text
stringlengths
2
1.04M
meta
dict
<?php namespace APPUser\Form; use Zend\Form\Form; class Vendedor extends Form { public function __construct($name = null, $options = array()) { parent::__construct('vendedor', $options); //add filters $this->setInputFilter(new VendedorFilter()); $this->setAttribute('method', 'post'); $this->setAttribute('class', "form-horizontal"); $id = new \Zend\Form\Element\Hidden('id'); $this->add($id); $nome = new \Zend\Form\Element\Text('nome'); $nome->setAttribute("placeholder", 'Entre com o Nome') ->setAttribute('class', 'form-control input-md'); $this->add($nome); $email = new \Zend\Form\Element\Text('email'); $email->setAttribute("placeholder", 'Entre com o Email') ->setAttribute('class', 'form-control input-md'); $this->add($email); $password = new \Zend\Form\Element\Password('password'); $password->setAttribute('class', 'form-control input-md') ->setAttribute("placeholder", 'Entre com a Senha'); $this->add($password); $confirmation = new \Zend\Form\Element\Password('confirmation'); $confirmation->setAttribute('class', 'form-control input-md') ->setAttribute("placeholder", 'Redegite a Senha'); // ->setAttribute('class', 'btn btn-success'); $this->add($confirmation); $csrf = new \Zend\Form\Element\Csrf('security'); $this->add($csrf); $this->add(array( 'name' => 'submit', 'type' => 'Zend\Form\Element\Submit', 'attributes' => array( 'value' => 'Salvar', 'class' => 'btn btn-primary' ) )); } }
{ "content_hash": "5e96d9321dc9a82c9d7ed7a29317f7b2", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 72, "avg_line_length": 30.46551724137931, "alnum_prop": 0.5495189586870401, "repo_name": "fabiopratta/zend2configurado", "id": "46c13af1490c8dfb14474d4e33dd92e3cc50a2e6", "size": "2125", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "module/APPUser/src/APPUser/Form/Vendedor.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1042" }, { "name": "PHP", "bytes": "62656" } ], "symlink_target": "" }
.class public abstract Landroid/support/v4/app/FragmentTransaction; .super Ljava/lang/Object; .source "FragmentTransaction.java" # static fields .field public static final TRANSIT_ENTER_MASK:I = 0x1000 .field public static final TRANSIT_EXIT_MASK:I = 0x2000 .field public static final TRANSIT_FRAGMENT_CLOSE:I = 0x2002 .field public static final TRANSIT_FRAGMENT_FADE:I = 0x1003 .field public static final TRANSIT_FRAGMENT_OPEN:I = 0x1001 .field public static final TRANSIT_NONE:I = 0x0 .field public static final TRANSIT_UNSET:I = -0x1 # direct methods .method public constructor <init>()V .registers 1 .prologue .line 40 invoke-direct {p0}, Ljava/lang/Object;-><init>()V .line 185 return-void .end method # virtual methods .method public abstract add(ILandroid/support/v4/app/Fragment;)Landroid/support/v4/app/FragmentTransaction; .param p1 # I .annotation build Landroid/support/annotation/IdRes; .end annotation .end param .end method .method public abstract add(ILandroid/support/v4/app/Fragment;Ljava/lang/String;)Landroid/support/v4/app/FragmentTransaction; .param p1 # I .annotation build Landroid/support/annotation/IdRes; .end annotation .end param .param p3 # Ljava/lang/String; .annotation build Landroid/support/annotation/Nullable; .end annotation .end param .end method .method public abstract add(Landroid/support/v4/app/Fragment;Ljava/lang/String;)Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract addSharedElement(Landroid/view/View;Ljava/lang/String;)Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract addToBackStack(Ljava/lang/String;)Landroid/support/v4/app/FragmentTransaction; .param p1 # Ljava/lang/String; .annotation build Landroid/support/annotation/Nullable; .end annotation .end param .end method .method public abstract attach(Landroid/support/v4/app/Fragment;)Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract commit()I .end method .method public abstract commitAllowingStateLoss()I .end method .method public abstract commitNow()V .end method .method public abstract commitNowAllowingStateLoss()V .end method .method public abstract detach(Landroid/support/v4/app/Fragment;)Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract disallowAddToBackStack()Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract hide(Landroid/support/v4/app/Fragment;)Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract isAddToBackStackAllowed()Z .end method .method public abstract isEmpty()Z .end method .method public abstract postOnCommit(Ljava/lang/Runnable;)Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract remove(Landroid/support/v4/app/Fragment;)Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract replace(ILandroid/support/v4/app/Fragment;)Landroid/support/v4/app/FragmentTransaction; .param p1 # I .annotation build Landroid/support/annotation/IdRes; .end annotation .end param .end method .method public abstract replace(ILandroid/support/v4/app/Fragment;Ljava/lang/String;)Landroid/support/v4/app/FragmentTransaction; .param p1 # I .annotation build Landroid/support/annotation/IdRes; .end annotation .end param .param p3 # Ljava/lang/String; .annotation build Landroid/support/annotation/Nullable; .end annotation .end param .end method .method public abstract setAllowOptimization(Z)Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract setBreadCrumbShortTitle(I)Landroid/support/v4/app/FragmentTransaction; .param p1 # I .annotation build Landroid/support/annotation/StringRes; .end annotation .end param .end method .method public abstract setBreadCrumbShortTitle(Ljava/lang/CharSequence;)Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract setBreadCrumbTitle(I)Landroid/support/v4/app/FragmentTransaction; .param p1 # I .annotation build Landroid/support/annotation/StringRes; .end annotation .end param .end method .method public abstract setBreadCrumbTitle(Ljava/lang/CharSequence;)Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract setCustomAnimations(II)Landroid/support/v4/app/FragmentTransaction; .param p1 # I .annotation build Landroid/support/annotation/AnimRes; .end annotation .end param .param p2 # I .annotation build Landroid/support/annotation/AnimRes; .end annotation .end param .end method .method public abstract setCustomAnimations(IIII)Landroid/support/v4/app/FragmentTransaction; .param p1 # I .annotation build Landroid/support/annotation/AnimRes; .end annotation .end param .param p2 # I .annotation build Landroid/support/annotation/AnimRes; .end annotation .end param .param p3 # I .annotation build Landroid/support/annotation/AnimRes; .end annotation .end param .param p4 # I .annotation build Landroid/support/annotation/AnimRes; .end annotation .end param .end method .method public abstract setPrimaryNavigationFragment(Landroid/support/v4/app/Fragment;)Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract setTransition(I)Landroid/support/v4/app/FragmentTransaction; .end method .method public abstract setTransitionStyle(I)Landroid/support/v4/app/FragmentTransaction; .param p1 # I .annotation build Landroid/support/annotation/StyleRes; .end annotation .end param .end method .method public abstract show(Landroid/support/v4/app/Fragment;)Landroid/support/v4/app/FragmentTransaction; .end method
{ "content_hash": "8c604637b936f78cdc210f683a502abf", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 131, "avg_line_length": 31.93617021276596, "alnum_prop": 0.7521652231845436, "repo_name": "AresS31/SCI", "id": "a54c629f7d0d23b2a6f0c767cfd2e5f7f03baca2", "size": "6004", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "payloads/smali/support/v4/app/FragmentTransaction.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "4276" }, { "name": "Python", "bytes": "48120" }, { "name": "Smali", "bytes": "15529276" } ], "symlink_target": "" }
class InvoiceModeration < ActiveRecord::Base belongs_to :worker belongs_to :assignment belongs_to :invoice belongs_to :hit has_many :responses, as: :trackable FIELDS = [:amount_due, :vendor_id, :tax, :due_date, :number, :other_fee, :date] enum status: [:not_submited, :submited] enum moderation_type: [:default, :for_second_review, :for_marked_through] enum items_marked: { not_marked: 0, marked: 1 } scope :second_review,-> { where(moderation_type: 1) } accepts_nested_attributes_for :worker normalize_attribute :amount_due, :vendor_id, :tax, :due_date, :number, :account_number, :other_fee, with: [:squish, :blank] def self.not_most_recent order('created_at ASC').submited end def self.not_submited_hits(hit_id) where(hit_id: hit_id).not_submited.first end def self.submited_hits(hit_id) where(hit_id: hit_id).submited end def self.get_invoices(hits) where(hit_id: hits).includes(:invoice).collect(&:invoice).uniq end def self.by_one(scope = :default) if count == 3 includes(invoice: [:uploads]).not_submited.send(scope) else includes(invoice: [:uploads]).not_submited.send(scope).to_a.uniq(&:invoice_id) end end alias_method :original_invoice, :invoice # Vendors name def selected @selected ||= Vendor.find_by(id: vendor_id).try(:name) if vendor_id end def pdf_url invoice.try(:pdf_url) end def attributes_for_invoice { amount_due: amount_due, vendor_id: vendor_id, tax: tax, due_date: due_date, number: number, account_number: account_number, other_fee: other_fee } end def sibling_record(scope = :default) @sibling_record ||= invoice.invoice_moderations.send(scope).order('created_at asc').where.not(id: id).first end end
{ "content_hash": "417ea5b97440d4c674fbda8bce729c29", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 111, "avg_line_length": 25.324324324324323, "alnum_prop": 0.6435432230522946, "repo_name": "sirius2013/BuildCore", "id": "d6cc44d9358b8de53133445143cde9f0c1fa7075", "size": "1874", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/invoice_moderation.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2722633" }, { "name": "CoffeeScript", "bytes": "29" }, { "name": "HTML", "bytes": "842234" }, { "name": "Java", "bytes": "5932370" }, { "name": "JavaScript", "bytes": "10874731" }, { "name": "Ruby", "bytes": "722735" }, { "name": "Smarty", "bytes": "798" } ], "symlink_target": "" }
* Su solicitud está siendo procesada, espere ...
{ "content_hash": "ed6a8b5c0184e9e3606d903eead3d713", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 48, "avg_line_length": 48, "alnum_prop": 0.75, "repo_name": "rahmatrasyidi/example-loading-text", "id": "0dc90db281e4dac2b68dfebc2ca89a913776fa74", "size": "49", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "es/loading_text_spanish.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "899" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_151) on Sun Mar 17 11:03:38 MST 2019 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>org.wildfly.swarm.swagger.deployment (BOM: * : All 2.4.0.Final API)</title> <meta name="date" content="2019-03-17"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <h1 class="bar"><a href="../../../../../org/wildfly/swarm/swagger/deployment/package-summary.html" target="classFrame">org.wildfly.swarm.swagger.deployment</a></h1> <div class="indexContainer"> <h2 title="Classes">Classes</h2> <ul title="Classes"> <li><a href="SwaggerExtension.html" title="class in org.wildfly.swarm.swagger.deployment" target="classFrame">SwaggerExtension</a></li> <li><a href="SwaggerRestApplicationInterceptor.html" title="class in org.wildfly.swarm.swagger.deployment" target="classFrame">SwaggerRestApplicationInterceptor</a></li> <li><a href="SwaggerServiceActivator.html" title="class in org.wildfly.swarm.swagger.deployment" target="classFrame">SwaggerServiceActivator</a></li> </ul> <h2 title="Annotation Types">Annotation Types</h2> <ul title="Annotation Types"> <li><a href="AddSwaggerResources.html" title="annotation in org.wildfly.swarm.swagger.deployment" target="classFrame">AddSwaggerResources</a></li> </ul> </div> </body> </html>
{ "content_hash": "9610e05052fbfb69570babfd386375c7", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 169, "avg_line_length": 57.592592592592595, "alnum_prop": 0.7157556270096463, "repo_name": "wildfly-swarm/wildfly-swarm-javadocs", "id": "a73798b8c4422079aacf6adb37608170c4b043b9", "size": "1555", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "2.4.0.Final/apidocs/org/wildfly/swarm/swagger/deployment/package-frame.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
namespace clutil { class ocl_ver { cl_ulong m; public: ocl_ver() : m(0) {} ocl_ver( const cl_uint major, const cl_uint minor) : m(cl_ulong(major) << 32 | minor) {} // primary relational ops bool operator ==( const ocl_ver& oth) const; bool operator <( const ocl_ver& oth) const; // derivative relational ops bool operator !=( const ocl_ver& oth) const; bool operator >( const ocl_ver& oth) const; bool operator <=( const ocl_ver& oth) const; bool operator >=( const ocl_ver& oth) const; }; inline bool ocl_ver::operator ==( const ocl_ver& oth) const { return m == oth.m; } inline bool ocl_ver::operator <( const ocl_ver& oth) const { return m < oth.m; } inline bool ocl_ver::operator !=( const ocl_ver& oth) const { return !this->operator ==(oth); } inline bool ocl_ver::operator >( const ocl_ver& oth) const { return oth.operator <(*this); } inline bool ocl_ver::operator <=( const ocl_ver& oth) const { return !oth.operator <(*this); } inline bool ocl_ver::operator >=( const ocl_ver& oth) const { return !this->operator <(oth); } bool clplatform_version( const cl_platform_id id, ocl_ver& version); bool cldevice_version( const cl_device_id id, ocl_ver& version); const char* cldevice_type_single_string( const cl_device_type type); bool reportCLError( const cl_int code, stream::out& out = stream::cerr); int reportCLCaps( const bool discard_platform_version, const bool discard_device_version, const size_t cascade_alignment = 5, const size_t value_alignment = 64); } // namespace clutil #endif // cl_util_H__
{ "content_hash": "009e92acc02a4c52a665c906d1ec398a", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 37, "avg_line_length": 13.767241379310345, "alnum_prop": 0.6656230432060113, "repo_name": "ChaosGroup/cg2_2014_demo", "id": "0e93d57cfca2ee770fd8814ce1d53adf27699610", "size": "1680", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "prob_7/cl_util.hpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "234509" }, { "name": "C++", "bytes": "1475870" }, { "name": "GLSL", "bytes": "16456" }, { "name": "Shell", "bytes": "38733" } ], "symlink_target": "" }
<?php namespace Geekhub\DreamBundle\EventListener; use Doctrine\Common\EventSubscriber; use Doctrine\Common\Persistence\Event\LifecycleEventArgs; use Geekhub\DreamBundle\Entity\AbstractContribute; use Geekhub\DreamBundle\Entity\Dream; use Geekhub\DreamBundle\Entity\Status; use Geekhub\UserBundle\Entity\User; use Hip\MandrillBundle\Dispatcher; use Hip\MandrillBundle\Message; use Symfony\Bridge\Monolog\Logger; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\HttpFoundation\Request; class DreamSubscriber implements EventSubscriber { /** @var Container $container */ protected $container; protected $mandrillDispatcher; /** * @param Container $container */ public function setContainer(Container $container) { $this->container = $container; } /** * @param Dispatcher $dispatcher */ public function setMandrillDispatcher(Dispatcher $dispatcher) { $this->mandrillDispatcher = $dispatcher; } public function getSubscribedEvents() { return array( 'prePersist', 'postPersist', 'preRemove', ); } public function preRemove(LifecycleEventArgs $args) { $object = $args->getObject(); /** @var Logger $logger */ $logger = $this->container->get('logger'); /** @var UserInterface $user */ $user = $this->container->get('security.context')->getToken()->getUser(); /** @var Request $request */ $request = $this->container->get('request'); if (!is_object($user) || !in_array('Symfony\Component\Security\Core\User\UserInterface', class_implements($user))) { $logger->addError( sprintf('Something that not user, try to delete object "%s", with id: "%s", from ip: "%s", from uri: "%s"', get_class($object), $object->getId(), $request->getClientIp(), $request->getUri()) ); throw new AccessDeniedException('Something went wrong, but don\'t worry - we already work on it!'); } $logger->addWarning( sprintf('User with username: "%s", delete object "%s", with id: "%s", from ip: "%s", from uri: "%s"', $user->getUsername(), get_class($object), $object->getId(), $request->getClientIp(), $request->getUri()) ); } public function prePersist(LifecycleEventArgs $args) { $object = $args->getObject(); if ($object instanceof Dream) { $object->addStatus(new Status(Status::SUBMITTED)); $token = $this->container->get('security.context')->getToken(); if (null != $token) { $object->setAuthor($token->getUser()); } elseif (!$object->getAuthor()) { throw new \Exception("Ooops! Something went wrong. We can't create dream without user. Please contact with administrator."); } } } public function postPersist(LifecycleEventArgs $args) { $object = $args->getObject(); if ($object instanceof Status) { $this->postStatusEmail($object->getTitle(), $object->getDream()); } if ('Geekhub\DreamBundle\Entity\AbstractContribute' == get_parent_class($object)) { $this->sendEmail( $this->getTemplate( 'GeekhubResourceBundle:Email:contribution.html.twig', array( 'dream' => $object->getDream(), 'contributor' => $object ) ), $object->getUser()->getEmail(), 'Підтримка мрії' ); } } protected function sendEmail($body, $to, $subject) { $message = new Message(); $message->setFromEmail('test@gmail.com') ->setFromName('Черкаська мрія') ->addTo($to) ->setSubject($subject) ->setHtml($body) ; $this->mandrillDispatcher->send($message); } protected function postStatusEmail($status, Dream $dream) { if (in_array($status, array('success', 'implementing'))) { $users = $this->container->get('doctrine') ->getRepository('GeekhubDreamBundle:Dream') ->getArrayContributorsByDream($dream) ; } if (in_array($status, array('submitted', 'completed'))) { $user = new User(); $user->setEmail($this->container->getParameter('admin.mail')); $users = array($user); } if (in_array($status, array('rejected', 'collecting-resources', 'fail'))) { $users = array($dream->getAuthor()); } if (isset($users)) { foreach ($users as $user) { $this->sendEmail( $this->getTemplate( 'GeekhubResourceBundle:Email:'.$status.'.html.twig', array( 'dream' => $dream, 'contributor' => $user ) ), $user->getEmail(), $status ); } } } protected function getTemplate($nameTwigTemplate, $options = array()) { return $this->container->get('templating')->render( $nameTwigTemplate, $options ); } }
{ "content_hash": "e9f43374b5101ff577bacead8f068d2a", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 218, "avg_line_length": 32.96449704142012, "alnum_prop": 0.5546580506192784, "repo_name": "geekhub-php/CheDream2", "id": "e1bdfb7cfb358245e936d2ac689f17e11e15da7b", "size": "5597", "binary": false, "copies": "1", "ref": "refs/heads/slicing", "path": "src/Geekhub/DreamBundle/EventListener/DreamSubscriber.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "2647" }, { "name": "CSS", "bytes": "435196" }, { "name": "Gherkin", "bytes": "13756" }, { "name": "HTML", "bytes": "153274" }, { "name": "JavaScript", "bytes": "116088" }, { "name": "PHP", "bytes": "323342" }, { "name": "Shell", "bytes": "4236" } ], "symlink_target": "" }
TMPFILE=/var/tmp/offline$$.log if [ -f .offline.pid ]; then echo "Found file .offline.pid. Not starting." exit 1 fi serverless offline start 2>1 > $TMPFILE & PID=$! echo $PID > .offline.pid while ! grep "Offline listening" $TMPFILE do sleep 1; done rm $TMPFILE
{ "content_hash": "b5010f3b7cb17acc30ee0151148d1a6f", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 49, "avg_line_length": 19.357142857142858, "alnum_prop": 0.6826568265682657, "repo_name": "SC5/sc5-serverless-boilerplate", "id": "b77535508009c5f0eeb3ad5a17dbcdf205ae5ca1", "size": "271", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".tools/startOffline.sh", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "565" }, { "name": "JavaScript", "bytes": "2623" }, { "name": "Shell", "bytes": "310" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd"> <entity name="Cierres" table="cierres"> <id name="codigo" type="integer" column="codigo"> <generator strategy="IDENTITY"/> </id> <field name="empresa" type="integer" column="empresa" nullable="false"/> <field name="fechaLl" type="date" column="fecha_ll" nullable="false"/> <field name="activo" type="integer" column="activo" nullable="false"/> <field name="modificado" type="string" column="modificado" length="50" nullable="false"/> <field name="fecMod" type="date" column="fec_mod" nullable="false"/> <field name="tipomov" type="integer" column="tipomov" nullable="true"/> <field name="bodega" type="integer" column="bodega" nullable="true"/> <field name="obs" type="text" column="obs" nullable="true"/> </entity> </doctrine-mapping>
{ "content_hash": "b7052fe23cca801c4498d1c5ab33d160", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 276, "avg_line_length": 68.875, "alnum_prop": 0.6978221415607986, "repo_name": "efraxpc/restaurante", "id": "0c4b9e21e1d373acbd1cda21af248aec233804aa", "size": "1102", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Proyecto/PrincipalBundle/Resources/config/doctrine/metadata/orm/Cierres.orm.xml", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "8799" }, { "name": "JavaScript", "bytes": "478232" }, { "name": "PHP", "bytes": "393362" }, { "name": "Perl", "bytes": "2621" }, { "name": "Ruby", "bytes": "660" } ], "symlink_target": "" }
/* * @test * @bug 8026844 * @summary Test constant negExact * @compile NegExactIConstantTest.java Verify.java * @run main NegExactIConstantTest -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockExperimentalVMOptions -XX:+UseMathExactIntrinsics * */ public class NegExactIConstantTest { public static void main(String[] args) { Verify.ConstantTest.verify(new Verify.UnaryToBinary(new Verify.NegExactI())); } }
{ "content_hash": "f4c0d8679b300434724a4847c65790a2", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 128, "avg_line_length": 26.8125, "alnum_prop": 0.7435897435897436, "repo_name": "rokn/Count_Words_2015", "id": "0a5e164ba68178917c7d36c22780bb2b9a6e5305", "size": "1479", "binary": false, "copies": "18", "ref": "refs/heads/master", "path": "testing/openjdk2/hotspot/test/compiler/intrinsics/mathexact/NegExactIConstantTest.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "61802" }, { "name": "Ruby", "bytes": "18888605" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true"> <ripple android:color="@color/grey" /> </item> <item android:state_activated="true" android:drawable="@color/primary_light"/> <item android:state_selected="true" android:drawable="@color/primary_light"/> <item android:drawable="@color/primary" /> </selector>
{ "content_hash": "4891e1dc5c9c0a69c6760f475e2e2174", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 69, "avg_line_length": 30.066666666666666, "alnum_prop": 0.656319290465632, "repo_name": "Gperez88/Sunshine", "id": "b67329b8249f7e20976146fc155d911159a68e9b", "size": "451", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "app/src/main/res/drawable-v21/today_touch_selector.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "150782" } ], "symlink_target": "" }
<!DOCTYPE frameset SYSTEM "frameset.dtd"> <frameset> <predicate lemma="contradict"> <note> Frames file for 'contradict' based on survey of sentences in the WSJ corpus. </note> <roleset id="contradict.01" name="to deny, negate, or oppose" vncls="-"> <roles> <role descr="entity contradicting" n="0"/> <role descr="entity denied or opposed to" n="1"/> </roles> <example name="transitive"> <inflection aspect="ns" form="full" person="ns" tense="present" voice="active"/> <text> It would contradict that objective if the appropriations clause ( technically a limitation on legislative power ) could be read [*-52] as [*-52] placing the president on Congress 's short leash , [*-52] making the executive consist of the president and every member of Congress . </text> <arg n="0">It</arg> <arg f="MOD" n="M">would</arg> <rel>contradict</rel> <arg n="1">that objective</arg> <arg f="ADV" n="M">if the appropriations clause ( technically a limitation on legislative power ) could be read [*-52] as [*-52] placing the president on Congress 's short leash , [*-52] making the executive consist of the president and every member of Congress</arg> </example> </roleset> </predicate> <note> frames created by Olga </note> </frameset>
{ "content_hash": "d57e0cb725cbb53c5c1f98209321c41f", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 299, "avg_line_length": 45.371428571428574, "alnum_prop": 0.5547858942065491, "repo_name": "keenon/jamr", "id": "6d72c26b9f281eb542f8e6047f30a3bb3d0275bc", "size": "1588", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/frames/contradict.xml", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Java", "bytes": "640454" }, { "name": "Perl", "bytes": "8697" }, { "name": "Python", "bytes": "76079" }, { "name": "Scala", "bytes": "353885" }, { "name": "Shell", "bytes": "41192" } ], "symlink_target": "" }
package org.zstack.sdk.iam2.api; import java.util.HashMap; import java.util.Map; import org.zstack.sdk.*; public class AddAttributesToIAM2VirtualIDGroupAction extends AbstractAction { private static final HashMap<String, Parameter> parameterMap = new HashMap<>(); private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>(); public static class Result { public ErrorCode error; public org.zstack.sdk.iam2.api.AddAttributesToIAM2VirtualIDGroupResult value; public Result throwExceptionIfError() { if (error != null) { throw new ApiException( String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details) ); } return this; } } @Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String uuid; @Param(required = true, nonempty = true, nullElements = false, emptyString = true, noTrim = false) public java.util.List attributes; @Param(required = false) public java.util.List systemTags; @Param(required = false) public java.util.List userTags; @Param(required = false) public String sessionId; @Param(required = false) public String accessKeyId; @Param(required = false) public String accessKeySecret; @Param(required = false) public String requestIp; @NonAPIParam public long timeout = -1; @NonAPIParam public long pollingInterval = -1; private Result makeResult(ApiResult res) { Result ret = new Result(); if (res.error != null) { ret.error = res.error; return ret; } org.zstack.sdk.iam2.api.AddAttributesToIAM2VirtualIDGroupResult value = res.getResult(org.zstack.sdk.iam2.api.AddAttributesToIAM2VirtualIDGroupResult.class); ret.value = value == null ? new org.zstack.sdk.iam2.api.AddAttributesToIAM2VirtualIDGroupResult() : value; return ret; } public Result call() { ApiResult res = ZSClient.call(this); return makeResult(res); } public void call(final Completion<Result> completion) { ZSClient.call(this, new InternalCompletion() { @Override public void complete(ApiResult res) { completion.complete(makeResult(res)); } }); } protected Map<String, Parameter> getParameterMap() { return parameterMap; } protected Map<String, Parameter> getNonAPIParameterMap() { return nonAPIParameterMap; } protected RestInfo getRestInfo() { RestInfo info = new RestInfo(); info.httpMethod = "POST"; info.path = "/iam2/projects/groups/{uuid}/attributes"; info.needSession = true; info.needPoll = true; info.parameterName = "params"; return info; } }
{ "content_hash": "09c352ce3b0910ad195b63ff810302eb", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 165, "avg_line_length": 28.951923076923077, "alnum_prop": 0.6343407505812022, "repo_name": "zstackorg/zstack", "id": "a5bb512701d861945cdf0827326af451608d0112", "size": "3011", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "sdk/src/main/java/org/zstack/sdk/iam2/api/AddAttributesToIAM2VirtualIDGroupAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AspectJ", "bytes": "54952" }, { "name": "Batchfile", "bytes": "1132" }, { "name": "Groovy", "bytes": "832169" }, { "name": "Java", "bytes": "15798995" }, { "name": "Shell", "bytes": "152829" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>de.rnd7</groupId> <artifactId>de.rnd7.kata.reversi.root</artifactId> <version>0.1</version> <packaging>pom</packaging> <modules> <module>de.rnd7.kata.reversi</module> </modules> </project>
{ "content_hash": "b55c94a548f5c1577e9d41143de09e69", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 67, "avg_line_length": 32.266666666666666, "alnum_prop": 0.6714876033057852, "repo_name": "ggsm/reversi", "id": "779b09345754af36635c09b93f191fd48202d1c2", "size": "484", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "59621" } ], "symlink_target": "" }
bootstrapit =========== Bootstrap skin generator Adds ----- - make css (build css only in ./css [default] ) - more flexibility in variables.less (auto calculate fluid grid var with the same non fluid grid ratio) - add non calculate page width, and calcule row insted Install ------- :: sudo apt-get install npm npm install recess uglify-js jshint -g
{ "content_hash": "6857a88be17683f3ae052cbad93ea0f3", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 107, "avg_line_length": 18, "alnum_prop": 0.6666666666666666, "repo_name": "h3/bootstrapit", "id": "b91a2a31273555217759063ffdae365897dca086", "size": "378", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.rst", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "JavaScript", "bytes": "600694" }, { "name": "Python", "bytes": "26500" } ], "symlink_target": "" }
<?php namespace Google\AdsApi\AdManager\v202211; /** * This file was generated from WSDL. DO NOT EDIT. */ class ReportErrorReason { const DEFAULT_VALUE = 'DEFAULT'; const REPORT_ACCESS_NOT_ALLOWED = 'REPORT_ACCESS_NOT_ALLOWED'; const DIMENSION_VIEW_NOT_ALLOWED = 'DIMENSION_VIEW_NOT_ALLOWED'; const ATTRIBUTE_VIEW_NOT_ALLOWED = 'ATTRIBUTE_VIEW_NOT_ALLOWED'; const COLUMN_VIEW_NOT_ALLOWED = 'COLUMN_VIEW_NOT_ALLOWED'; const TOO_MANY_CONCURRENT_REPORTS = 'TOO_MANY_CONCURRENT_REPORTS'; const REPORT_QUERY_TOO_LONG = 'REPORT_QUERY_TOO_LONG'; const INVALID_OPERATION_FOR_REPORT_STATE = 'INVALID_OPERATION_FOR_REPORT_STATE'; const INVALID_DIMENSIONS = 'INVALID_DIMENSIONS'; const INVALID_ATTRIBUTES = 'INVALID_ATTRIBUTES'; const INVALID_CMS_METADATA_DIMENSIONS = 'INVALID_CMS_METADATA_DIMENSIONS'; const INVALID_COLUMNS = 'INVALID_COLUMNS'; const INVALID_DIMENSION_FILTERS = 'INVALID_DIMENSION_FILTERS'; const INVALID_DATE = 'INVALID_DATE'; const END_DATE_TIME_NOT_AFTER_START_TIME = 'END_DATE_TIME_NOT_AFTER_START_TIME'; const START_DATE_MORE_THAN_THREE_YEARS_AGO = 'START_DATE_MORE_THAN_THREE_YEARS_AGO'; const NOT_NULL = 'NOT_NULL'; const ATTRIBUTES_NOT_SUPPORTED_FOR_REQUEST = 'ATTRIBUTES_NOT_SUPPORTED_FOR_REQUEST'; const COLUMNS_NOT_SUPPORTED_FOR_REQUESTED_DIMENSIONS = 'COLUMNS_NOT_SUPPORTED_FOR_REQUESTED_DIMENSIONS'; const DATE_RANGE_NOT_SUPPORTED_FOR_REQUESTED_REPORT = 'DATE_RANGE_NOT_SUPPORTED_FOR_REQUESTED_REPORT'; const TIME_ZONE_TYPE_NOT_SUPPORTED_FOR_REQUESTED_REPORT = 'TIME_ZONE_TYPE_NOT_SUPPORTED_FOR_REQUESTED_REPORT'; const CURRENCY_CODE_NOT_SUPPORTED_FOR_REQUESTED_REPORT = 'CURRENCY_CODE_NOT_SUPPORTED_FOR_REQUESTED_REPORT'; const FAILED_TO_STORE_REPORT = 'FAILED_TO_STORE_REPORT'; const REPORT_NOT_FOUND = 'REPORT_NOT_FOUND'; const SR_CANNOT_RUN_REPORT_IN_ANOTHER_NETWORK = 'SR_CANNOT_RUN_REPORT_IN_ANOTHER_NETWORK'; const AD_UNIT_VIEW_NOT_SUPPORTED_FOR_REQUESTED_REPORT = 'AD_UNIT_VIEW_NOT_SUPPORTED_FOR_REQUESTED_REPORT'; const UNKNOWN = 'UNKNOWN'; }
{ "content_hash": "8f0507fbe76797da9159a76c1dfd394b", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 114, "avg_line_length": 52.2, "alnum_prop": 0.7380268199233716, "repo_name": "googleads/googleads-php-lib", "id": "e8b6135812f137036dd0c484192538541fd651ac", "size": "2088", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/Google/AdsApi/AdManager/v202211/ReportErrorReason.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "11415914" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace NetUserMgt.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(); } } }
{ "content_hash": "80b051e49330570264ce46d2b29d8b02", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 71, "avg_line_length": 19.694444444444443, "alnum_prop": 0.5430183356840621, "repo_name": "dledanseur/net-resource-mgr", "id": "b842f4ccb15bf6115077fd10f50408fbcd039625", "size": "711", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ResourceManagerMvc/Controllers/HomeController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "59655" }, { "name": "CSS", "bytes": "3" }, { "name": "JavaScript", "bytes": "34" } ], "symlink_target": "" }
/* Contributed by Nicola Pero <nicola.pero@meta-innovation.com>, November 2010. */ /* { dg-do run } */ /* { dg-xfail-run-if "Needs OBJC2 ABI" { *-*-darwin* && { lp64 && { ! objc2 } } } { "-fnext-runtime" } { "" } } */ /* Test @synthesize with protocols of protocols. */ #include <stdlib.h> #include <objc/objc.h> #include <objc/runtime.h> @protocol ProtocolA @property int countA; @end @protocol ProtocolB <ProtocolA> @property int countB; @end @protocol ProtocolC <ProtocolB> @property int countC; @end @protocol ProtocolD @property int countD; @end @interface MyRootClass <ProtocolC> { Class isa; int countA; int countB; int countC; } + (id) initialize; + (id) alloc; - (id) init; @end @implementation MyRootClass + (id) initialize { return self; } + (id) alloc { return class_createInstance (self, 0); } - (id) init { return self; } @synthesize countA; @synthesize countB; @synthesize countC; @end @interface MySubClass : MyRootClass <ProtocolD> { int countD; } @end @implementation MySubClass @synthesize countD; @end int main (void) { MySubClass *object = [[MySubClass alloc] init]; int i; for (i = 0; i < 10; i++) { object.countA += i; object.countB += i + 1; object.countC += i + 2; object.countD += i + 3; } if (object.countA != 45) abort (); if (object.countB != 55) abort (); if (object.countC != 65) abort (); if (object.countD != 75) abort (); return 0; }
{ "content_hash": "4f3eeaf37c954e5518b294f41379ebd7", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 114, "avg_line_length": 17.011627906976745, "alnum_prop": 0.6261107313738893, "repo_name": "the-linix-project/linix-kernel-source", "id": "929e3803bf95215853eb29e481e1f8e0003104cc", "size": "1463", "binary": false, "copies": "361", "ref": "refs/heads/master", "path": "gccsrc/gcc-4.7.2/gcc/testsuite/objc.dg/property/synthesize-7.m", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ada", "bytes": "38139979" }, { "name": "Assembly", "bytes": "3723477" }, { "name": "Awk", "bytes": "83739" }, { "name": "C", "bytes": "103607293" }, { "name": "C#", "bytes": "55726" }, { "name": "C++", "bytes": "38577421" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "CSS", "bytes": "32588" }, { "name": "Emacs Lisp", "bytes": "13451" }, { "name": "FORTRAN", "bytes": "4294984" }, { "name": "GAP", "bytes": "13089" }, { "name": "Go", "bytes": "11277335" }, { "name": "Haskell", "bytes": "2415" }, { "name": "Java", "bytes": "45298678" }, { "name": "JavaScript", "bytes": "6265" }, { "name": "Matlab", "bytes": "56" }, { "name": "OCaml", "bytes": "148372" }, { "name": "Objective-C", "bytes": "995127" }, { "name": "Objective-C++", "bytes": "436045" }, { "name": "PHP", "bytes": "12361" }, { "name": "Pascal", "bytes": "40318" }, { "name": "Perl", "bytes": "358808" }, { "name": "Python", "bytes": "60178" }, { "name": "SAS", "bytes": "1711" }, { "name": "Scilab", "bytes": "258457" }, { "name": "Shell", "bytes": "2610907" }, { "name": "Tcl", "bytes": "17983" }, { "name": "TeX", "bytes": "1455571" }, { "name": "XSLT", "bytes": "156419" } ], "symlink_target": "" }
title: Grav Development taxonomy: category: docs --- If you want to develop with Grav, you will benefit from a more sophisticated setup than the one required for a regular Grav user. This includes just about any type of development, such as: **Grav Core**, **Grav Plugins**, **Grav Skeletons**, or even **Grav Themes**. First, let us breakdown the various types of development: ## Grav Core When we talk about the **Grav Core**, we are effectively talking about things in the `system` folder. This folder controls everything about Grav and is really the very essence of the [Grav workflow and lifecycle](../grav-lifecycle). Grav is intentionally focused on working with pages in an efficient manner. Manipulation of pages and extensive functionality are often best served by creating a plugin. We strongly encourage our community to contribute bug fixes, and even propose development of appropriate functionality within the core of Grav. ## Grav Plugins Most development effort will probably take the form of a **Grav Plugin**. Because Grav has plenty of [Event Hooks](../../plugins/event-hooks), it's very easy to provide enhanced and specific functionality via the creation of a plugin. We have already developed many plugins that work in a variety of ways using many different events to show off the power of this functionality. There are many benefits of providing functionality in plugins, but a couple of the key benefits are: 1. The Grav Core Remains Lean - You only need to add the plugins you need for a particular site. For example, a blog may need many more plugins than a simple landing page. 2. Third-Party Development of New Functionality - You don't have to wait until Grav gets a bit of functionality you want. You can simply create a plugin to extend Grav to do what you want it to do. #### Plugin Requirements A proper Grav plugin requires certain files in order to function properly, be listed in the Grav repository, and be visible in the Grav admin plugin. Please ensure your plugin contains all these files: * **yourplugin.php** - plugin PHP file that should be named the same as the folder * **yourplugin.yaml** - plugin configuration file that contains any options and stream inheritance information * **blueprints.yaml** - plugin definition file and form definition file * **CHANGELOG.md** - a changelog file that should be in the proper Grav format for consistent rendering * **README.md** - required file to explain and preview the plugin * **LICENSE** - license file, probably MIT if in line with Grav core * **languages.yaml** (optional) - a language definition file ## Grav Skeletons A **Grav Skeleton** is effectively an **all-in-one sample site**. They include the **Grav Core**, required **plugins**, as well as appropriate **pages** for content and a **theme** for pulling it all together. Grav was designed to make the process of creating a site as easy as possible. For that reason, everything you need for a site can be contained in the `user` folder. Each of the skeletons we currently have available are simply a `user` folder on GitHub that we package up with various dependencies (required plugins, and theme) into a package that can be simply unzipped to provide a working example. These skeletons are a base on which you can grow your site, quickly and efficiently. You aren't locked in to a specific set of features. It is every bit as flexible as any other Grav install. #### Skeleton Requirements A proper Grav plugin requires certain files in order to function properly, be listed in the Grav repository, and be visible in the Grav admin plugin. Please ensure your plugin contains all these files: * **.dependencies** - A file to define theme and plugin dependencies for this skeleton * **blueprints.yaml** - skeleton definition file and form definition file * **CHANGELOG.md** - a changelog file that should be in the proper Grav format for consistent rendering * **README.md** - required file to explain and preview the plugin * **LICENSE** - license file, probably MIT if in line with Grav core * **screenshot.jpg** - a 1:1 aspect ratio preview of the theme. Should be at least 800px x 800px ## Grav Themes Because of the tight coupling with Grav pages and themes, a **Grav Theme** is an integral and very important part of a Grav site. By this we mean that each Grav page references a template in the theme, so your theme needs to provide the appropriate **Twig templates** that your pages are using. The Twig templating engine is a very powerful system, and because there really are no restrictions by Grav itself, you are free to create any kind of design you wish. This is one of the great things that sets Grav apart from a traditional CMS that has a loose coupling between content and design. #### Theme Requirements A proper Grav theme requires certain files in order to function properly, be listed in the Grav repository, and be visible in the Grav admin plugin. Please ensure your theme contains all these files: * **yourtheme.php** - theme PHP file that should be named the same as the folder * **yourtheme.yaml** - theme configuration file that contains any options and stream inheritance information * **blueprints.yaml** - theme definition file and form definition file * **CHANGELOG.md** - a changelog file that should be in the proper Grav format for consistent rendering * **README.md** - required file to explain and preview the theme * **LICENSE** - license file, probably MIT if in line with Grav core * **screenshot.jpg** - a 1:1 aspect ratio preview of the theme. Should be at least 800px x 800px * **thumbnail.jpg** - a smaller thumbnail image used by the admin plug. 1:1 aspect ratio and should be at 300px x 300px * **languages.yaml** (optional) - a language definition file ## Demo Content With the release of Grav 0.9.18, you are now able to provide demo content as part of a plugin or theme package. This means that anything found in a folder called `_demo/` will be copied over to the `user/` folder as part of the installation procedure. This means you can provide **pages**, or **configuration** or anything else that sits in the `user/` folder. The user is prompted to do this, and it's purely optional. ## Theme/Plugin Release Process When you have created your new theme or plugin and would like to see it added to the [Grav Repository](http://getgrav.org/downloads) there are a few standard things that you need to ensure: 1. It is open source with a `LICENSE` file that provides an [MIT](http://en.wikipedia.org/wiki/MIT_License) compatible license [Example Here](https://github.com/getgrav/grav-theme-antimatter/blob/develop/LICENSE) 2. Contains a `README.md` file with a summary of functionality and instructions on how to install and configure it. [Example Here](https://github.com/getgrav/grav-theme-antimatter/blob/develop/README.md) 3. Contains a `blueprints.yaml` file with [all required fields](../blueprints). [Example Here](https://github.com/getgrav/grav-theme-antimatter/blob/develop/blueprints.yaml) 4. Provide a `CHANGELOG.md` in the [correct format](#changelog-format) an [Example Here](https://github.com/getgrav/grav-theme-antimatter/blob/develop/CHANGELOG.md) 5. Provides appropriate attribution if you use any other libraries, scripts, code. 6. [Create a release](https://help.github.com/articles/creating-releases) for your finished plugin/theme. The Grav repository system requires a release and will not find your plugin/theme unless there is a release that contains all of the above. 7. [Add an issue to the Grav issues tracker](https://github.com/getgrav/grav/issues/new?title=[add-resource]%20New%20Plugin/Theme&body=I%20would%20like%20to%20add%20my%20new%20plugin/theme%20to%20the%20Grav%20Repository.%0AHere%20are%20the%20project%20details:%20**user/repository**) with details about your plugin, and we will give it a quick test to ensure it functions, and then add it. ! Ensure your **naming for each tag is consistent**. GPM uses this information to determine if your plugin/theme is newer than the last. We recommend using [Semantic Version Numbers](http://semver.org/) for tags. E.g. `1.2.4`. Consistency for all tags is paramount! ## ChangeLog Format The GetGrav.org site uses a custom ChangeLog format that is written in standard markdown but can be manipulated with some simple CSS and [displayed in an attractive format](http://getgrav.org/downloads#changelog). In order to ensure your ChangeLogs can be parsed and formatted properly, please use this syntax: ``` # vX.Y.Z ## 01/01/2015 1. [](#new) * New features added * Another new feature 2. [](#improved) * Improvement made * Another improvement 3. [](#bugfix) * Bugfix implemented * Another bugfix ...repeat... ``` Each section `#new, #improved, #bugfix` are optional, just include the sections you need. ## GitHub Setup As is the way of things these days, GitHub is going to be your best friend when it comes to developing for Grav. We have created some tools to make this as easy as possible, but there are some development patterns that you should follow to make the process simpler. Clone all the repositories you plan to work with into a single `Projects` or `Development` folder on your computer. This will allow our provided tools to find the repositories they need. !! We use the [GitFlow](http://nvie.com/posts/a-successful-git-branching-model/) branching model for all our Grav development. The core concept of the GitFlow methodology is that development happens in the `develop` branch, but new features and functionality are created in seperate `feature` branches that are merged into `develop` when complete. Releases merge `develop` into `master`, and you can apply `hotfix` branches as needed during the release process. Most modern git clients support this. However, we recommend [Atlassian SourceTree](https://www.atlassian.com/software/sourcetree/overview) as it's free, cross-platform, and easy to use. Grav also has some dependencies (dictated by the `.dependencies` file) which include the **Error** and **Problems** plugins, as well as the **Antimatter** theme. You can follow these instructions to clone these bits on your own computer. !!!! If you wish to make additions or changes to any of the `getgrav` repositories, you will need to **fork** the appropriate repository and then clone **your fork's url** rather than the `getgrav` repository directly. The example below is using the direct `getgrav` repositories for example only. ``` $ cd $ mkdir Projects $ cd Projects $ mkdir Grav $ cd Grav $ git clone https://github.com/getgrav/grav.git $ git clone https://github.com/getgrav/grav-plugin-error.git $ git clone https://github.com/getgrav/grav-plugin-problems.git $ git clone https://github.com/getgrav/grav-theme-antimatter.git ``` This will clone **all 4 repositories** into your `~/Projects/Grav` folder. Usually, the normal procedure for setting up a test site for Grav is to use the `bin/grav new-project` command. This is true for development, except for one important difference. Because we want to to be able to develop from your web root, but have any changes show up in your cloned code, we need to **symbolically link** the relevant parts. We do this by passing a `-s` flag to the `bin/grav new-project` command. There is one extra step required. You must tell the command where it can find your repositories. So, follow these steps to create a configuration file in a new `.grav/` folder which you will need to create in the **root of your home directory**: ``` $ cd $ mkdir .grav $ vi .grav/config ``` In this file: provide a simple mapping of where the relevant files are located: ``` github_repos: /Users/your_user/Projects/Grav/ ``` Make sure you **save** this file and that it's readable. You can now set up your **symbolically linked** site where `~/www` is your webroot and `~/www/grav` is the location where your new grav test site will be created: ``` $ cd ~/Projects/Grav/grav $ bin/grav new-project -s ~/www/grav ``` You should see quite a bit of output like this: ``` rhukster@gibblets:~/Projects/Grav/grav(develop○) » bin/grav new-project -s ~/www/grav Creating Directories /cache /logs /images /assets /user/accounts /user/config /user/pages /user/data /user/plugins /user/themes Resetting Symbolic Links /index.php -> /Users/rhuk/www/grav/index.php /composer.json -> /Users/rhuk/www/grav/composer.json /bin -> /Users/rhuk/www/grav/bin /system -> /Users/rhuk/www/grav/system Pages Initializing /Users/rhuk/Projects/Grav/grav/user/pages -> Created File Initializing /.dependencies -> Created /.htaccess -> Created /user/config/site.yaml -> Created /user/config/system.yaml -> Created Permisions Initializing bin/grav permissions reset to 755 read local config from /Users/rhuk/.grav/config Symlinking Bits =============== SUCCESS symlinked grav-plugin-problems -> user/plugins/problems SUCCESS symlinked grav-plugin-error -> user/plugins/error SUCCESS symlinked grav-theme-antimatter -> user/themes/antimatter ``` As you can see, a number of default directories were created, and an initial `pages` folder was also created. After the base has been set up, the other dependencies are symbolically linked in. You should be able to point your browser to `http://localhost/grav` and see the test site you just setup. Now, any changes you make in your `~/www/grav` folder will show up ready to commit and push in your cloned repositories. ## Abandoned Resource Protocol People move on, and user-generated content like plugins and themes may become abandoned. If you wish to take over the maintenance of an existing theme or plugin, you must follow this protocol: 1. Submit a well-formed, tested pull request to the original repository. 2. If the maintainer does not respond *at all* after 30 days, or if the maintainer states that they are abandoning the resource and are not willing to grant someone else write access, then proceed to the next step. 3. [Submit a new issue to Grav's GitHub repository](https://github.com/getgrav/grav/issues/new?title=%5Bchange-resource%5D%20Take%20over%20Plugin%2FTheme&body=I%20would%20like%20to%20take%20over%20an%20existing%20plugin%2Ftheme.%0AHere%20are%20the%20project%20details%3A%20%2A%2Auser%2Frepository%2A%2A) with the following details: * Title: `[change-resource] Take over plugin/theme` * Provide the name of the plugin and link to the original repository. * Link to your pull request that went unanswered or link to the conversation in which the maintainer has abandoned the resource. 4. The Grav maintainers will review the case and let you know if the takeover is approved. If approval is granted, proceed to the next step. 5. Prepare your forked repository with a new release. 6. Add a note to the README that this repository is the new master and link back to the old repository. 7. Reply to the issue, giving the maintainers the new URL for the plugin. 8. The maintainers will update GPM and new and updated installs will now come from your forked repository.
{ "content_hash": "bd2ea9ed1c5f2b55121cc7531d4f1214", "timestamp": "", "source": "github", "line_count": 244, "max_line_length": 649, "avg_line_length": 62.14754098360656, "alnum_prop": 0.7615404906357162, "repo_name": "miljan-aleksic/grav-learn", "id": "79f36966b599d08c513b67d45297cd7c1874d299", "size": "15171", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "pages/08.advanced/09.grav-development/docs.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "148170" }, { "name": "HTML", "bytes": "17780" }, { "name": "JavaScript", "bytes": "6371" }, { "name": "PHP", "bytes": "2127" }, { "name": "Shell", "bytes": "99" } ], "symlink_target": "" }
package net.choas.android.ioiotree; import android.app.Activity; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.preference.Preference; import android.preference.PreferenceActivity; import android.view.Menu; import android.view.MenuItem; public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } }
{ "content_hash": "7aa08f286aa7a743eb5e8441a0d27721", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 70, "avg_line_length": 28.82608695652174, "alnum_prop": 0.7164404223227753, "repo_name": "choas/android-IOIO-tree", "id": "157d431d39adcd990d86aabf5724dd191f3a065a", "size": "663", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/net/choas/android/ioiotree/SettingsActivity.java", "mode": "33261", "license": "mit", "language": [ { "name": "Groovy", "bytes": "2504" }, { "name": "Java", "bytes": "306882" } ], "symlink_target": "" }
package com.dmdirc.parser.common; import com.dmdirc.parser.events.ParserEvent; import net.engio.mbassy.bus.MBassador; import net.engio.mbassy.bus.config.BusConfiguration; import net.engio.mbassy.bus.config.Feature; import net.engio.mbassy.bus.error.IPublicationErrorHandler; /** * Parser Callback Manager. * Manages adding/removing/calling callbacks. */ public class CallbackManager extends MBassador<ParserEvent> { public CallbackManager(final IPublicationErrorHandler errorHandler) { super(new BusConfiguration().addFeature(Feature.SyncPubSub.Default()) .addFeature(Feature.AsynchronousHandlerInvocation.Default(1, 1)) .addFeature(Feature.AsynchronousMessageDispatch.Default() .setNumberOfMessageDispatchers(1)) .addPublicationErrorHandler(errorHandler)); } }
{ "content_hash": "49ba35f9453fa316a79ebfcca3435589", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 80, "avg_line_length": 33.07692307692308, "alnum_prop": 0.7395348837209302, "repo_name": "greboid/Parser", "id": "3fa79331e13a1c17faca8e87b3996bdc70409a17", "size": "1986", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/src/main/java/com/dmdirc/parser/common/CallbackManager.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "773538" } ], "symlink_target": "" }
package org.psjava.ds.map; import java.util.HashMap; public class JavaHashMapFactory { public static MutableMapFactory getInstance() { return new MutableMapFactory() { @Override public <K, V> MutableMap<K, V> create() { return MutableMapUsingJavaMap.wrap(new HashMap<K, V>()); } }; } private JavaHashMapFactory() { } }
{ "content_hash": "0ac4473bd5bed777e0428da8f94fc81a", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 72, "avg_line_length": 22.61111111111111, "alnum_prop": 0.5896805896805897, "repo_name": "psjava/psjava", "id": "d6814405ee8b82b99df8ffa2386c88d145489cc6", "size": "407", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/psjava/ds/map/JavaHashMapFactory.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "493434" }, { "name": "Shell", "bytes": "136" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>cats-in-zfc: 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.1 / cats-in-zfc - 8.9.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> cats-in-zfc <small> 8.9.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-07-03 12:42:49 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-07-03 12:42:49 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base 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.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.03.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.03.0 Official 4.03.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.5 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/cats-in-zfc&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/CatsInZFC&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.9&quot; &amp; &lt; &quot;8.10~&quot;} ] tags: [ &quot;keyword: set theory&quot; &quot;keyword: ordinal numbers&quot; &quot;keyword: cardinal numbers&quot; &quot;keyword: category theory&quot; &quot;keyword: functors&quot; &quot;keyword: natural transformation&quot; &quot;keyword: limit&quot; &quot;keyword: colimit&quot; &quot;category: Mathematics/Logic/Set theory&quot; &quot;category: Mathematics/Category Theory&quot; &quot;date: 2004-10-10&quot; ] authors: [ &quot;Carlos Simpson &lt;carlos@math.unice.fr&gt; [http://math.unice.fr/~carlos/]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/cats-in-zfc/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/cats-in-zfc.git&quot; synopsis: &quot;Category theory in ZFC&quot; description: &quot;&quot;&quot; In a ZFC-like environment augmented by reference to the ambient type theory, we develop some basic set theory, ordinals, cardinals and transfinite induction, and category theory including functors, natural transformations, limits and colimits, functor categories, and the theorem that functor_cat a b has (co)limits if b does.&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/cats-in-zfc/archive/v8.9.0.tar.gz&quot; checksum: &quot;md5=c8be2400164ae30e17cb4b55a851c977&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-cats-in-zfc.8.9.0 coq.8.8.1</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.1). The following dependencies couldn&#39;t be met: - coq-cats-in-zfc -&gt; coq &gt;= 8.9 -&gt; ocaml &gt;= 4.05.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-cats-in-zfc.8.9.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": "4380747766ed4cfb6c69efc681191dfe", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 159, "avg_line_length": 41.15217391304348, "alnum_prop": 0.5561278394083465, "repo_name": "coq-bench/coq-bench.github.io", "id": "40376895fa530b2bbc4a7b6ba0ef541a226b6fb1", "size": "7597", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.03.0-2.0.5/released/8.8.1/cats-in-zfc/8.9.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
// Copyright (C) 2010 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.sshd; import com.google.gerrit.server.config.ConfigUtil; import com.google.gerrit.server.config.GerritServerConfig; import com.google.inject.Inject; import com.google.inject.Singleton; import org.eclipse.jgit.lib.Config; import java.util.concurrent.TimeUnit; @Singleton public class TransferConfig { private final int timeout; @Inject TransferConfig(@GerritServerConfig final Config cfg) { timeout = (int) ConfigUtil.getTimeUnit(cfg, "transfer", null, "timeout", // 0, TimeUnit.SECONDS); } /** @return configured timeout, in seconds. 0 if the timeout is infinite. */ public int getTimeout() { return timeout; } }
{ "content_hash": "71f382c2f39c12035a1d9b316d719608", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 79, "avg_line_length": 32.1, "alnum_prop": 0.7468847352024922, "repo_name": "skurfuerst/gerrit", "id": "c976e7fcf3a47744a7bcf07a223257a85a77809b", "size": "1284", "binary": false, "copies": "1", "ref": "refs/heads/stable", "path": "gerrit-sshd/src/main/java/com/google/gerrit/sshd/TransferConfig.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2928695" }, { "name": "JavaScript", "bytes": "29380" }, { "name": "Python", "bytes": "12214" }, { "name": "Shell", "bytes": "16307" } ], "symlink_target": "" }
struct Setup { float speed; float kp; float ki; float kd; }; struct Mark { float position; // distance in meters float acceleration; // mark acceleration Setup setup; // robot setup }; #endif
{ "content_hash": "cc675d5e239fb3f485567a9364b6273d", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 42, "avg_line_length": 14.857142857142858, "alnum_prop": 0.6682692307692307, "repo_name": "Project-Neon/Sloth", "id": "3371a9038a0b83f6eb6ebd8e415c45a5fe733b5b", "size": "240", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Firmware/Sloth/src/main.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4611" }, { "name": "C++", "bytes": "81093" }, { "name": "Objective-C", "bytes": "10579" }, { "name": "Python", "bytes": "972" } ], "symlink_target": "" }
require "rails_helper" RSpec.describe Alchemy::PictureVariant do let(:image_file) do File.new(File.expand_path("../../fixtures/500x500.png", __dir__)) end let(:alchemy_picture) { build_stubbed(:alchemy_picture, image_file: image_file) } it_behaves_like "has image transformations" do let(:picture) { described_class.new(alchemy_picture) } end subject { described_class.new(alchemy_picture, options).image } let(:options) { Hash.new } context "when no image is present" do let(:alchemy_picture) { nil } it "raises ArgumentError" do expect { subject }.to raise_error(ArgumentError) end end context "when a size is passed in" do let(:options) do { size: "120x160" } end it "resizes the image without upsampling it" do expect(subject.steps[0].arguments).to eq(["120x160>"]) end context "but upsample set to true" do let(:options) do { size: "1600x1200", upsample: true, } end it "resizes the image with upsampling it" do expect(subject.steps[0].arguments).to eq(["1600x1200"]) end end context "and crop is set to true" do let(:options) do { size: "160x120", crop: true, } end it "crops from center and resizes the picture" do expect(subject.steps[0].arguments).to eq(["160x120#"]) end context "and crop_from and crop_size is passed in" do let(:options) do { crop_size: "123x44", crop_from: "0x0", size: "160x120", crop: true, } end it "crops and resizes the picture" do expect(subject.steps[0].arguments).to eq(["123x44+0+0", "160x120>"]) end end end context "and crop is set to false" do let(:options) do { size: "160x120", crop: false, } end it "does not crop the picture" do expect(subject.steps[0].arguments).to eq(["160x120>"]) end context "and crop_from and crop_size is passed in" do let(:options) do { crop_size: "123x44", crop_from: "0x0", size: "160x120", crop: false, } end it "does not crop the picture" do expect(subject.steps[0].arguments).to eq(["160x120>"]) end end end context "with no height given" do let(:options) do { size: "40" } end it "resizes the image inferring the height" do expect(subject.steps[0].arguments).to eq(["40>"]) end end context "with no width given" do let(:options) do { size: "x30" } end it "resizes the image inferring the width" do expect(subject.steps[0].arguments).to eq(["x30>"]) end end end context "when no size is passed in" do it "does not process the image" do expect(subject.job.steps).to be_empty end end context "when a different format is requested" do let(:options) do { format: "gif" } end it "converts the format" do step = subject.steps[0] expect(step.name).to eq(:encode) expect(step.arguments).to include("gif") end context "but image has not a convertible format (svg)" do let(:image_file) do fixture_file_upload( File.expand_path("../../fixtures/icon.svg", __dir__), "image/svg+xml", ) end it "does not convert the picture format" do expect(subject.job.steps.size).to eq(0) end end context "for an animated gif" do let(:options) do { format: "png" } end let(:image_file) do fixture_file_upload( File.expand_path("../../fixtures/animated.gif", __dir__), "image/gif", ) end it "flattens the image." do step = subject.steps[0] expect(step.name).to eq(:encode) expect(step.arguments).to eq(["png", "-flatten"]) end end end context "requesting a not allowed format" do let(:options) do { format: "zip" } end it "returns nil" do expect(subject).to be_nil end it "logs warning" do expect(Alchemy::Logger).to receive(:warn) subject end end %w[jpg jpeg].each do |format| context "when #{format} format is requested" do let(:options) do { format: format } end context "and the image file format is not JPG" do it "sets the default quality" do step = subject.steps[0] expect(step.name).to eq(:encode) expect(step.arguments).to eq([format, "-quality 85"]) end context "and quality is passed" do let(:options) do { format: format, quality: "30" } end it "sets the quality" do step = subject.steps[0] expect(step.name).to eq(:encode) expect(step.arguments).to eq([format, "-quality 30"]) end end end context "and image has jpg format" do let(:alchemy_picture) do build_stubbed(:alchemy_picture, image_file: image_file, image_file_format: "jpg") end it "does not convert the picture format" do expect(subject).to_not respond_to(:steps) end context "and quality is passed in options" do let(:options) do { format: format, quality: "30" } end it "sets the quality" do step = subject.steps[0] expect(step.name).to eq(:encode) expect(step.arguments).to eq([format, "-quality 30"]) end end end context "and image has jpeg format" do let(:alchemy_picture) do build_stubbed(:alchemy_picture, image_file: image_file, image_file_format: "jpeg") end it "does not convert the picture format" do expect(subject).to_not respond_to(:steps) end context "and quality is passed in options" do let(:options) do { format: format, quality: "30" } end it "sets the quality" do step = subject.steps[0] expect(step.name).to eq(:encode) expect(step.arguments).to eq([format, "-quality 30"]) end end end end end end
{ "content_hash": "78e5871f6059f34a0aacc60b1516e300", "timestamp": "", "source": "github", "line_count": 261, "max_line_length": 92, "avg_line_length": 24.74712643678161, "alnum_prop": 0.5516333797801517, "repo_name": "robinboening/alchemy_cms", "id": "b042f679f0a022258749eeb878867cb3542c815e", "size": "6490", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "spec/models/alchemy/picture_variant_spec.rb", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "457" }, { "name": "CoffeeScript", "bytes": "70169" }, { "name": "HTML", "bytes": "205971" }, { "name": "Haml", "bytes": "1496" }, { "name": "Handlebars", "bytes": "1664" }, { "name": "JavaScript", "bytes": "61452" }, { "name": "Ruby", "bytes": "1411061" }, { "name": "SCSS", "bytes": "355685" }, { "name": "Sass", "bytes": "826" }, { "name": "Slim", "bytes": "1494" } ], "symlink_target": "" }
package com.amazonaws.services.config.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.config.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * ComplianceSummary JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ComplianceSummaryJsonUnmarshaller implements Unmarshaller<ComplianceSummary, JsonUnmarshallerContext> { public ComplianceSummary unmarshall(JsonUnmarshallerContext context) throws Exception { ComplianceSummary complianceSummary = new ComplianceSummary(); 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("CompliantResourceCount", targetDepth)) { context.nextToken(); complianceSummary.setCompliantResourceCount(ComplianceContributorCountJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("NonCompliantResourceCount", targetDepth)) { context.nextToken(); complianceSummary.setNonCompliantResourceCount(ComplianceContributorCountJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("ComplianceSummaryTimestamp", targetDepth)) { context.nextToken(); complianceSummary.setComplianceSummaryTimestamp(context.getUnmarshaller(java.util.Date.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 complianceSummary; } private static ComplianceSummaryJsonUnmarshaller instance; public static ComplianceSummaryJsonUnmarshaller getInstance() { if (instance == null) instance = new ComplianceSummaryJsonUnmarshaller(); return instance; } }
{ "content_hash": "70a83b8cf8c7fd581000a1474a97a9ba", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 145, "avg_line_length": 39.46478873239437, "alnum_prop": 0.6531049250535332, "repo_name": "dagnir/aws-sdk-java", "id": "06b3cdcc7d590346fc5026991aece60c8ef51fbd", "size": "3382", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "aws-java-sdk-config/src/main/java/com/amazonaws/services/config/model/transform/ComplianceSummaryJsonUnmarshaller.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "157317" }, { "name": "Gherkin", "bytes": "25556" }, { "name": "Java", "bytes": "165755153" }, { "name": "Scilab", "bytes": "3561" } ], "symlink_target": "" }
findMate.filter('dateFilter', function($filter) { return function (items) { var filtered = []; var todayDate = new Date(); var todayDay = todayDate.getDate(); for (var i = 0; i < items.length; i++) { var item = items[i]; var itemDate = item.startDate; if (itemDate.getDate() < todayDate) { filtered.push(item); } } return filtered; }; });
{ "content_hash": "19492da3889a49be1113d505ef3bb317", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 49, "avg_line_length": 28.6875, "alnum_prop": 0.49673202614379086, "repo_name": "Foirfeacht/findmates_postgre", "id": "6c2a03babdbd9b2c68d54674698bdba130f2a2cd", "size": "459", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "public/js/filters/dateFilter.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "7276" }, { "name": "JavaScript", "bytes": "74769" } ], "symlink_target": "" }
// // bridging-header.h // BlueCap // // Created by 박재유 on 2016. 6. 1.. // Copyright © 2016년 Troy Stribling. All rights reserved. // #ifndef bridging_header_h #define bridging_header_h #import "FMDB.h" #endif /* bridging_header_h */
{ "content_hash": "4c09fc3cf2e2ae501a76bc1c884b670c", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 58, "avg_line_length": 17.142857142857142, "alnum_prop": 0.6625, "repo_name": "cpuu/OTT", "id": "74a603ad328f0e9b0b76ee8a2b47883c3ee9c731", "size": "249", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OTT/bridging-header.h", "mode": "33261", "license": "mit", "language": [ { "name": "C++", "bytes": "4572" }, { "name": "Objective-C", "bytes": "788899" }, { "name": "Ruby", "bytes": "6003" }, { "name": "Shell", "bytes": "7707" }, { "name": "Swift", "bytes": "1643122" } ], "symlink_target": "" }
ACCEPTED #### According to GRIN Taxonomy for Plants #### Published in Fl. Algérie 1(1):126. 1888 #### Original name null ### Remarks null
{ "content_hash": "07e1fc831a77388a8db0c4cd5d108eab", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 26, "avg_line_length": 10.846153846153847, "alnum_prop": 0.6808510638297872, "repo_name": "mdoering/backbone", "id": "45ab7e324472efcbc5719e180c3270e61aaf8249", "size": "223", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Geraniales/Geraniaceae/Erodium/Erodium laciniatum/Erodium laciniatum pulverulentum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Don't you pay attention to the name of the directory? Ok, snarkiness aside, this directory contains little code samples done for my own sake and meant as tests, but not formal ones.
{ "content_hash": "073c7579c03903a24f2b14fd4425c43f", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 65, "avg_line_length": 45.5, "alnum_prop": 0.7912087912087912, "repo_name": "aroberge/easygui_qt", "id": "d8714bd8e3d3af876fdbf1a97300a4b92a71a666", "size": "182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ignore/readme.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "74719" } ], "symlink_target": "" }
import React from 'react' const Location = () => <div> The location page </div> const styles = { } export default Location
{ "content_hash": "23a1d194f412dff6cded9d208b75a66b", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 25, "avg_line_length": 11.166666666666666, "alnum_prop": 0.6417910447761194, "repo_name": "TUIHackfridays/tuise-poc", "id": "3591acef9afed66ac35a5b0cf225b94acbd5a587", "size": "134", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/containers/Location/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5965" }, { "name": "HTML", "bytes": "12011" }, { "name": "JavaScript", "bytes": "22531" } ], "symlink_target": "" }
'use strict'; /* global stripHash: true */ /** * ! This is a private undocumented service ! * * @name $browser * @requires $log * @description * This object has two goals: * * - hide all the global state in the browser caused by the window object * - abstract away all the browser specific features and inconsistencies * * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser` * service, which can be used for convenient testing of the application without the interaction with * the real browser apis. */ /** * @param {object} window The global window object. * @param {object} document jQuery wrapped document. * @param {object} $log window.console or an object with the same interface. * @param {object} $sniffer $sniffer service */ function Browser(window, document, $log, $sniffer) { var self = this, rawDocument = document[0], location = window.location, history = window.history, setTimeout = window.setTimeout, clearTimeout = window.clearTimeout, pendingDeferIds = {}; self.isMock = false; var outstandingRequestCount = 0; var outstandingRequestCallbacks = []; // TODO(vojta): remove this temporary api self.$$completeOutstandingRequest = completeOutstandingRequest; self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; }; /** * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks` * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed. */ function completeOutstandingRequest(fn) { try { fn.apply(null, sliceArgs(arguments, 1)); } finally { outstandingRequestCount--; if (outstandingRequestCount === 0) { while (outstandingRequestCallbacks.length) { try { outstandingRequestCallbacks.pop()(); } catch (e) { $log.error(e); } } } } } /** * @private * Note: this method is used only by scenario runner * TODO(vojta): prefix this method with $$ ? * @param {function()} callback Function that will be called when no outstanding request */ self.notifyWhenNoOutstandingRequests = function(callback) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach(pollFns, function(pollFn) { pollFn(); }); if (outstandingRequestCount === 0) { callback(); } else { outstandingRequestCallbacks.push(callback); } }; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [], pollTimeout; /** * @name $browser#addPollFn * * @param {function()} fn Poll function to add * * @description * Adds a function to the list of functions that poller periodically executes, * and starts polling if not started yet. * * @returns {function()} the added function */ self.addPollFn = function(fn) { if (isUndefined(pollTimeout)) startPoller(100, setTimeout); pollFns.push(fn); return fn; }; /** * @param {number} interval How often should browser call poll functions (ms) * @param {function()} setTimeout Reference to a real or fake `setTimeout` function. * * @description * Configures the poller to run in the specified intervals, using the specified * setTimeout fn and kicks it off. */ function startPoller(interval, setTimeout) { (function check() { forEach(pollFns, function(pollFn) { pollFn(); }); pollTimeout = setTimeout(check, interval); })(); } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var cachedState, lastHistoryState, lastBrowserUrl = location.href, baseElement = document.find('base'), reloadLocation = null; cacheState(); lastHistoryState = cachedState; /** * @name $browser#url * * @description * GETTER: * Without any argument, this method just returns current value of location.href. * * SETTER: * With at least one argument, this method sets url to new value. * If html5 history api supported, pushState/replaceState is used, otherwise * location.href/location.replace is used. * Returns its own instance to allow chaining * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to change url. * * @param {string} url New url (when used as setter) * @param {boolean=} replace Should new url replace current history record? * @param {object=} state object to use with pushState/replaceState */ self.url = function(url, replace, state) { // In modern browsers `history.state` is `null` by default; treating it separately // from `undefined` would cause `$browser.url('/foo')` to change `history.state` // to undefined via `pushState`. Instead, let's change `undefined` to `null` here. if (isUndefined(state)) { state = null; } // Android Browser BFCache causes location, history reference to become stale. if (location !== window.location) location = window.location; if (history !== window.history) history = window.history; // setter if (url) { var sameState = lastHistoryState === state; // Don't change anything if previous and current URLs and states match. This also prevents // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode. // See https://github.com/angular/angular.js/commit/ffb2701 if (lastBrowserUrl === url && (!$sniffer.history || sameState)) { return self; } var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url); lastBrowserUrl = url; lastHistoryState = state; // Don't use history API if only the hash changed // due to a bug in IE10/IE11 which leads // to not firing a `hashchange` nor `popstate` event // in some cases (see #9143). if ($sniffer.history && (!sameBase || !sameState)) { history[replace ? 'replaceState' : 'pushState'](state, '', url); cacheState(); // Do the assignment again so that those two variables are referentially identical. lastHistoryState = cachedState; } else { if (!sameBase) { reloadLocation = url; } if (replace) { location.replace(url); } else { location.href = url; } } return self; // getter } else { // - reloadLocation is needed as browsers don't allow to read out // the new location.href if a reload happened. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 return reloadLocation || location.href.replace(/%27/g,"'"); } }; /** * @name $browser#state * * @description * This method is a getter. * * Return history.state or null if history.state is undefined. * * @returns {object} state */ self.state = function() { return cachedState; }; var urlChangeListeners = [], urlChangeInit = false; function cacheStateAndFireUrlChange() { cacheState(); fireUrlChange(); } // This variable should be used *only* inside the cacheState function. var lastCachedState = null; function cacheState() { // This should be the only place in $browser where `history.state` is read. cachedState = window.history.state; cachedState = isUndefined(cachedState) ? null : cachedState; // Prevent callbacks fo fire twice if both hashchange & popstate were fired. if (equals(cachedState, lastCachedState)) { cachedState = lastCachedState; } lastCachedState = cachedState; } function fireUrlChange() { if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) { return; } lastBrowserUrl = self.url(); lastHistoryState = cachedState; forEach(urlChangeListeners, function(listener) { listener(self.url(), cachedState); }); } /** * @name $browser#onUrlChange * * @description * Register callback function that will be called, when url changes. * * It's only called when the url is changed from outside of angular: * - user types different url into address bar * - user clicks on history (forward/back) button * - user clicks on a link * * It's not called when url is changed by $browser.url() method * * The listener gets called with new url as parameter. * * NOTE: this api is intended for use only by the $location service. Please use the * {@link ng.$location $location service} to monitor url changes in angular apps. * * @param {function(string)} listener Listener function to be called when url changes. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous. */ self.onUrlChange = function(callback) { // TODO(vojta): refactor to use node's syntax for events if (!urlChangeInit) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange); // hashchange event jqLite(window).on('hashchange', cacheStateAndFireUrlChange); urlChangeInit = true; } urlChangeListeners.push(callback); return callback; }; /** * Checks whether the url has changed outside of Angular. * Needs to be exported to be able to check for changes that have been done in sync, * as hashchange/popstate events fire in async. */ self.$$checkUrlChange = fireUrlChange; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /** * @name $browser#baseHref * * @description * Returns current <base href> * (always relative - without domain) * * @returns {string} The current base href */ self.baseHref = function() { var href = baseElement.attr('href'); return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : ''; }; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = {}; var lastCookieString = ''; var cookiePath = self.baseHref(); function safeDecodeURIComponent(str) { try { return decodeURIComponent(str); } catch (e) { return str; } } /** * @name $browser#cookies * * @param {string=} name Cookie name * @param {string=} value Cookie value * * @description * The cookies method provides a 'private' low level access to browser cookies. * It is not meant to be used directly, use the $cookie service instead. * * The return values vary depending on the arguments that the method was called with as follows: * * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify * it * - cookies(name, value) -> set name to value, if value is undefined delete the cookie * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that * way) * * @returns {Object} Hash of all cookies (if called without any parameter) */ self.cookies = function(name, value) { var cookieLength, cookieArray, cookie, i, index; if (name) { if (value === undefined) { rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT"; } else { if (isString(value)) { cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + ';path=' + cookiePath).length + 1; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie if (cookieLength > 4096) { $log.warn("Cookie '" + name + "' possibly not set or overflowed because it was too large (" + cookieLength + " > 4096 bytes)!"); } } } } else { if (rawDocument.cookie !== lastCookieString) { lastCookieString = rawDocument.cookie; cookieArray = lastCookieString.split("; "); lastCookies = {}; for (i = 0; i < cookieArray.length; i++) { cookie = cookieArray[i]; index = cookie.indexOf('='); if (index > 0) { //ignore nameless cookies name = safeDecodeURIComponent(cookie.substring(0, index)); // the first value that is seen for a cookie is the most // specific one. values for the same cookie name that // follow are for less specific paths. if (lastCookies[name] === undefined) { lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1)); } } } } return lastCookies; } }; /** * @name $browser#defer * @param {function()} fn A function, who's execution should be deferred. * @param {number=} [delay=0] of milliseconds to defer the function execution. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`. * * @description * Executes a fn asynchronously via `setTimeout(fn, delay)`. * * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed * via `$browser.defer.flush()`. * */ self.defer = function(fn, delay) { var timeoutId; outstandingRequestCount++; timeoutId = setTimeout(function() { delete pendingDeferIds[timeoutId]; completeOutstandingRequest(fn); }, delay || 0); pendingDeferIds[timeoutId] = true; return timeoutId; }; /** * @name $browser#defer.cancel * * @description * Cancels a deferred task identified with `deferId`. * * @param {*} deferId Token returned by the `$browser.defer` function. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully * canceled. */ self.defer.cancel = function(deferId) { if (pendingDeferIds[deferId]) { delete pendingDeferIds[deferId]; clearTimeout(deferId); completeOutstandingRequest(noop); return true; } return false; }; } function $BrowserProvider() { this.$get = ['$window', '$log', '$sniffer', '$document', function($window, $log, $sniffer, $document) { return new Browser($window, $document, $log, $sniffer); }]; }
{ "content_hash": "38e980d7afe0f5bd3da5709d9e736a4b", "timestamp": "", "source": "github", "line_count": 456, "max_line_length": 107, "avg_line_length": 33.526315789473685, "alnum_prop": 0.6185243328100472, "repo_name": "yuichimaruyama/angular.js", "id": "a9299343778db0aec831e4a9d32deaf72e37d539", "size": "15288", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/ng/browser.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "21125" }, { "name": "JavaScript", "bytes": "5079426" }, { "name": "Shell", "bytes": "18589" } ], "symlink_target": "" }
package rss.feed.reader.ui.presenters; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import io.reactivex.Completable; import rss.feed.reader.managers.UserManager; import rss.feed.reader.ui.contracts.SignInContract; import rss.feed.reader.utils.validators.UserInfoValidator; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Created by omartynets on 29.03.2017. */ public class SignInPresenterTest { private static final String DEFAULT_EMAIL = "default_email"; private static final String DEFAULT_PASSWORD = "default_password"; private SignInPresenter mPresenter; @Mock private SignInContract.View mView; @Mock private UserManager mUserManager; @Mock private UserInfoValidator mValidator; @Before public void setUpDependencies() { MockitoAnnotations.initMocks(this); mPresenter = new SignInPresenter(mView, mUserManager, mValidator); } @Test public void signIn_ifCredentialsAreValid() { when(mValidator.isEmailValid(anyString())).thenReturn(true); when(mValidator.isPasswordValid(anyString())).thenReturn(true); when(mUserManager.signIn(anyString(), anyString())).thenReturn(Completable.complete()); mPresenter.signIn(DEFAULT_EMAIL, DEFAULT_PASSWORD); verify(mView).showProgress(anyInt()); verify(mUserManager).signIn(anyString(), anyString()); verify(mView).hideProgress(); verify(mView).navigateToMain(); } @Test public void signIn_ifEmailIsNotValid() { when(mValidator.isEmailValid(anyString())).thenReturn(false); when(mValidator.isPasswordValid(anyString())).thenReturn(true); mPresenter.signIn(DEFAULT_EMAIL, DEFAULT_PASSWORD); verify(mView).showEmailError(anyInt()); verify(mUserManager, never()).signIn(anyString(), anyString()); } @Test public void signIn_ifPasswordIsNotValid() { when(mValidator.isEmailValid(anyString())).thenReturn(true); when(mValidator.isPasswordValid(anyString())).thenReturn(false); mPresenter.signIn(DEFAULT_EMAIL, DEFAULT_PASSWORD); verify(mView).showPasswordError(anyInt()); verify(mUserManager, never()).signIn(anyString(), anyString()); } @Test public void signIn_ifCredentialsAreNotValid() { when(mValidator.isEmailValid(anyString())).thenReturn(true); when(mValidator.isPasswordValid(anyString())).thenReturn(true); when(mUserManager.signIn(anyString(), anyString())).thenReturn(Completable.error(new RuntimeException(anyString()))); mPresenter.signIn(DEFAULT_EMAIL, DEFAULT_PASSWORD); verify(mUserManager).signIn(anyString(), anyString()); verify(mView).showSnackBar(anyString()); } }
{ "content_hash": "826d87168c5817b733bc838edbec674b", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 125, "avg_line_length": 32.641304347826086, "alnum_prop": 0.7162837162837162, "repo_name": "Vovchyk/android-rss-feed-reader", "id": "a7a8e2ed074cc4ae61bfeafc20ba247834efe6c3", "size": "3003", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/test/java/rss/feed/reader/ui/presenters/SignInPresenterTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "3100" }, { "name": "Java", "bytes": "240432" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name Becium ctenodon Gilli ### Remarks null
{ "content_hash": "772193d0081b207c067207c0bb7c5191", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 11, "alnum_prop": 0.7272727272727273, "repo_name": "mdoering/backbone", "id": "391f30a1bbcb68af60d0c336ab59ab80b196822c", "size": "216", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Lamiaceae/Ocimum/Ocimum fimbriatum/Ocimum fimbriatum ctenodon/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.scalatest.events import org.scalatest._ import java.util.Date /** * A base class for the events that can be passed to the report function passed * to the <code>execute</code> method of a <code>Suite</code>. * * @author Bill Venners */ sealed abstract class Event extends Ordered[Event] with java.io.Serializable { /** * An <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run. */ val ordinal: Ordinal /** * An optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user. */ val formatter: Option[Formatter] /** * An optional location that provides information indicating where in the source code an event originated. * IDEs can use this information, for example, to allow the user to hop from an event report to the relevant * line of source code. */ val location: Option[Location] /** * An optional object that can be used to pass custom information to the reporter about this event. */ val payload: Option[Any] /** * A name for the <code>Thread</code> about whose activity this event was reported. */ val threadName: String /** * A <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": * January 1, 1970, 00:00:00 GMT. */ val timeStamp: Long /** * Comparing <code>this</code> event with the event passed as <code>that</code>. Returns * x, where x < 0 iff this < that, x == 0 iff this == that, x > 0 iff this > that. * * @param that the event to compare to this event * @param return an integer indicating whether this event is less than, equal to, or greater than * the passed event */ def compare(that: Event): Int = ordinal.compare(that.ordinal) } /** * Event that indicates a suite (or other entity) is about to start running a test. * * <p> * For example, trait <code>Suite</code> uses <code>TestStarting</code> to report * that a test method of a <code>Suite</code> is about to be invoked. * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="TestStarting$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>TestStarting</code> event like this: * </p> * * <pre class="stHighlight"> * report(TestStarting(ordinal, userFriendlyName, suiteName, Some(thisSuite.getClass.getName), testName)) * </pre> * * <p> * The suite class name parameter is optional, because suites in ScalaTest are an abstraction that * need not necessarily correspond to one class. Nevertheless, it most cases each suite will correspond * to a class, and when it does, the fully qualified name of that class should be reported by passing a * <code>Some</code> for <code>suiteClassName</code>. One use for this bit of information is JUnit integration, * because the "name" provided to a JUnit <code>org.junit.runner.Description</code> appears to usually include * a fully qualified class name by convention. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName a localized name identifying the suite containing the test that is starting, suitable for presenting to the user * @param suiteID a string ID for the suite containing the test that is starting, intended to be unique across all suites in a run * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that is starting * @param decodedSuiteName the decoded suite name, in case the suite name is put between backticks. None if it is same as suiteName. * @param testName the name of the test that is starting * @param testText the text of the test that is starting (may be the test name, or a suffix of the test name) * @param decodedTestName the decoded name of the test, in case the name is put between backticks. None if it is same as testName. * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the test that is starting (if <code>None</code> * is passed, the test cannot be rerun) * @param payload an optional object that can be used to pass custom information to the reporter about the <code>TestStarting</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class TestStarting ( ordinal: Ordinal, suiteName: String, suiteID: String, suiteClassName: Option[String], decodedSuiteName: Option[String], testName: String, testText: String, decodedTestName: Option[String], formatter: Option[Formatter] = None, location: Option[Location] = None, rerunner: Option[Rerunner] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (suiteName == null) throw new NullPointerException("suiteName was null") if (suiteID == null) throw new NullPointerException("suiteID was null") if (suiteClassName == null) throw new NullPointerException("suiteClassName was null") if (testName == null) throw new NullPointerException("testName was null") if (testText == null) throw new NullPointerException("testText was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (rerunner == null) throw new NullPointerException("rerunner was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates a suite (or other entity) has completed running a test that succeeded. * * <p> * For example, trait <code>Suite</code> uses <code>TestSucceeded</code> to report * that a test method of a <code>Suite</code> returned normally * (without throwing an <code>Exception</code>). * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="TestSucceeded$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>TestSucceeded</code> event like this: * </p> * * <pre class="stHighlight"> * report(TestSucceeded(ordinal, userFriendlyName, suiteName, Some(thisSuite.getClass.getName), testName)) * </pre> * * <p> * The suite class name parameter is optional, because suites in ScalaTest are an abstraction that * need not necessarily correspond to one class. Nevertheless, it most cases each suite will correspond * to a class, and when it does, the fully qualified name of that class should be reported by passing a * <code>Some</code> for <code>suiteClassName</code>. One use for this bit of information is JUnit integration, * because the "name" provided to a JUnit <code>org.junit.runner.Description</code> appears to usually include * a fully qualified class name by convention. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName a localized name identifying the suite containing the test that has succeeded, suitable for presenting to the user * @param suiteID a string ID for the suite containing the test that is starting, intended to be unique across all suites in a run * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that has succeeded * @param decodedSuiteName the decoded suite name, in case the suite name is put between backticks. None if it is same as suiteName. * @param testName the name of the test that has succeeded * @param testText the text of the test that has succeeded (may be the test name, or a suffix of the test name) * @param decodedTestName the decoded name of the test, in case the name is put between backticks. None if it is same as testName. * @param duration an optional amount of time, in milliseconds, that was required to run the test that has succeeded * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the test that has succeeded (if <code>None</code> * is passed, the test cannot be rerun) * @param payload an optional object that can be used to pass custom information to the reporter about the <code>TestSucceeded</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class TestSucceeded ( ordinal: Ordinal, suiteName: String, suiteID: String, suiteClassName: Option[String], decodedSuiteName: Option[String], testName: String, testText: String, decodedTestName: Option[String], duration: Option[Long] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, rerunner: Option[Rerunner] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (suiteName == null) throw new NullPointerException("suiteName was null") if (suiteID == null) throw new NullPointerException("suiteID was null") if (suiteClassName == null) throw new NullPointerException("suiteClassName was null") if (testName == null) throw new NullPointerException("testName was null") if (testText == null) throw new NullPointerException("testText was null") if (duration == null) throw new NullPointerException("duration was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (rerunner == null) throw new NullPointerException("rerunner was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates a suite (or other entity) has completed running a test that failed. * * <p> * For example, trait <code>Suite</code> uses <code>TestFailed</code> to report * that a test method of a <code>Suite</code> completed abruptly with an <code>Exception</code>. * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="TestFailed$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>TestFailed</code> event like this: * </p> * * <pre class="stHighlight"> * report(TestFailed(ordinal, userFriendlyName, message, suiteName, Some(thisSuite.getClass.getName), testName)) * </pre> * * <p> * The suite class name parameter is optional, because suites in ScalaTest are an abstraction that * need not necessarily correspond to one class. Nevertheless, it most cases each suite will correspond * to a class, and when it does, the fully qualified name of that class should be reported by passing a * <code>Some</code> for <code>suiteClassName</code>. One use for this bit of information is JUnit integration, * because the "name" provided to a JUnit <code>org.junit.runner.Description</code> appears to usually include * a fully qualified class name by convention. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param suiteName a localized name identifying the suite containing the test that has failed, suitable for presenting to the user * @param suiteID a string ID for the suite containing the test that is starting, intended to be unique across all suites in a run * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that has failed * @param decodedSuiteName the decoded suite name, in case the suite name is put between backticks. None if it is same as suiteName. * @param testName the name of the test that has failed * @param testText the text of the test that has failed (may be the test name, or a suffix of the test name) * @param decodedTestName the decoded name of the test, in case the name is put between backticks. None if it is same as testName. * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the test has failed, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required to run the test that has failed * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the test that has failed (if <code>None</code> * is passed, the test cannot be rerun) * @param payload an optional object that can be used to pass custom information to the reporter about the <code>TestFailed</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class TestFailed ( ordinal: Ordinal, message: String, suiteName: String, suiteID: String, suiteClassName: Option[String], decodedSuiteName: Option[String], testName: String, testText: String, decodedTestName: Option[String], throwable: Option[Throwable] = None, duration: Option[Long] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, rerunner: Option[Rerunner] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (message == null) throw new NullPointerException("message was null") if (suiteName == null) throw new NullPointerException("suiteName was null") if (suiteID == null) throw new NullPointerException("suiteID was null") if (suiteClassName == null) throw new NullPointerException("suiteClassName was null") if (testName == null) throw new NullPointerException("testName was null") if (testText == null) throw new NullPointerException("testText was null") if (throwable == null) throw new NullPointerException("throwable was null") if (duration == null) throw new NullPointerException("duration was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (rerunner == null) throw new NullPointerException("rerunner was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates a suite (or other entity) has ignored a test. * * <p> * For example, trait <code>Suite</code> uses <code>TestIgnored</code> to report * that a test method of a <code>Suite</code> was ignored because it was annotated with <code>@Ignore</code>. * Ignored tests will not be run, but will usually be reported as reminder to fix the broken test. * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="TestIgnored$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>TestIgnored</code> event like this: * </p> * * <pre class="stHighlight"> * report(TestIgnored(ordinal, userFriendlyName, suiteName, Some(thisSuite.getClass.getName), testName)) * </pre> * * <p> * The suite class name parameter is optional, because suites in ScalaTest are an abstraction that * need not necessarily correspond to one class. Nevertheless, it most cases each suite will correspond * to a class, and when it does, the fully qualified name of that class should be reported by passing a * <code>Some</code> for <code>suiteClassName</code>. One use for this bit of information is JUnit integration, * because the "name" provided to a JUnit <code>org.junit.runner.Description</code> appears to usually include * a fully qualified class name by convention. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName a localized name identifying the suite containing the test that was ignored, suitable for presenting to the user * @param suiteID a string ID for the suite containing the test that is starting, intended to be unique across all suites in a run * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that was ignored * @param decodedSuiteName the decoded suite name, in case the suite name is put between backticks. None if it is same as suiteName. * @param testName the name of the test that was ignored * @param testText the text of the test that was ignored (may be the test name, or a suffix of the test name) * @param decodedTestName the decoded name of the test, in case the name is put between backticks. None if it is same as testName. * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param payload an optional object that can be used to pass custom information to the reporter about the <code>TestIgnored</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class TestIgnored ( ordinal: Ordinal, suiteName: String, suiteID: String, suiteClassName: Option[String], decodedSuiteName: Option[String], testName: String, testText: String, decodedTestName: Option[String], formatter: Option[Formatter] = None, location: Option[Location] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (suiteName == null) throw new NullPointerException("suiteName was null") if (suiteID == null) throw new NullPointerException("suiteID was null") if (suiteClassName == null) throw new NullPointerException("suiteClassName was null") if (testName == null) throw new NullPointerException("testName was null") if (testText == null) throw new NullPointerException("testText was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates a test is pending, <em>i.e.</em>, it hasn't yet been implemented. * * <p> * To create instances of this class you may * use the factory method provided in its <a href="TestPending$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>TestPending</code> event like this: * </p> * * <pre class="stHighlight"> * report(TestPending(ordinal, userFriendlyName, suiteName, Some(thisSuite.getClass.getName), testName)) * </pre> * * <p> * The suite class name parameter is optional, because suites in ScalaTest are an abstraction that * need not necessarily correspond to one class. Nevertheless, it most cases each suite will correspond * to a class, and when it does, the fully qualified name of that class should be reported by passing a * <code>Some</code> for <code>suiteClassName</code>. One use for this bit of information is JUnit integration, * because the "name" provided to a JUnit <code>org.junit.runner.Description</code> appears to usually include * a fully qualified class name by convention. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName a localized name identifying the suite containing the test that is pending, suitable for presenting to the user * @param suiteID a string ID for the suite containing the test that is starting, intended to be unique across all suites in a run * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that is pending * @param decodedSuiteName the decoded suite name, in case the suite name is put between backticks. None if it is same as suiteName. * @param testName the name of the test that is pending * @param testText the text of the test that is pending (may be the test name, or a suffix of the test name) * @param decodedTestName the decoded name of the test, in case the name is put between backticks. None if it is same as testName. * @param duration an optional amount of time, in milliseconds, that was required to run the test that is pending * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param payload an optional object that can be used to pass custom information to the reporter about the <code>TestPending</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class TestPending ( ordinal: Ordinal, suiteName: String, suiteID: String, suiteClassName: Option[String], decodedSuiteName: Option[String], testName: String, testText: String, decodedTestName: Option[String], duration: Option[Long] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (suiteName == null) throw new NullPointerException("suiteName was null") if (suiteID == null) throw new NullPointerException("suiteID was null") if (suiteClassName == null) throw new NullPointerException("suiteClassName was null") if (testName == null) throw new NullPointerException("testName was null") if (testText == null) throw new NullPointerException("testText was null") if (duration == null) throw new NullPointerException("duration was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates a test was canceled, <em>i.e.</em>, it couldn't run because some precondition was not met. * * <p> * To create instances of this class you may * use the factory methods provided in its <a href="TestCanceled$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>TestCanceled</code> event like this: * </p> * * <pre class="stHighlight"> * report(TestPending(ordinal, userFriendlyName, suiteName, Some(thisSuite.getClass.getName), testName)) * </pre> * * <p> * The suite class name parameter is optional, because suites in ScalaTest are an abstraction that * need not necessarily correspond to one class. Nevertheless, it most cases each suite will correspond * to a class, and when it does, the fully qualified name of that class should be reported by passing a * <code>Some</code> for <code>suiteClassName</code>. One use for this bit of information is JUnit integration, * because the "name" provided to a JUnit <code>org.junit.runner.Description</code> appears to usually include * a fully qualified class name by convention. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName a localized name identifying the suite containing the test that was canceled, suitable for presenting to the user * @param suiteID a string ID for the suite containing the test that is starting, intended to be unique across all suites in a run * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that was canceled * @param decodedSuiteName the decoded suite name, in case the suite name is put between backticks. None if it is same as suiteName. * @param testName the name of the test that was canceled * @param testText the text of the test that was canceled (may be the test name, or a suffix of the test name) * @param decodedTestName the decoded name of the test, in case the name is put between backticks. None if it is same as testName. * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the test was canceled, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required to run the test that was canceled * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param payload an optional object that can be used to pass custom information to the reporter about the <code>TestCanceled</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ // TODO: Probably add a rerunnable to TestCanceled final case class TestCanceled ( ordinal: Ordinal, message: String, suiteName: String, suiteID: String, suiteClassName: Option[String], decodedSuiteName: Option[String], testName: String, testText: String, decodedTestName: Option[String], throwable: Option[Throwable] = None, duration: Option[Long] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (message == null) throw new NullPointerException("message was null") if (suiteName == null) throw new NullPointerException("suiteName was null") if (suiteID == null) throw new NullPointerException("suiteID was null") if (suiteClassName == null) throw new NullPointerException("suiteClassName was null") if (testName == null) throw new NullPointerException("testName was null") if (testText == null) throw new NullPointerException("testText was null") if (duration == null) throw new NullPointerException("duration was null") if (throwable == null) throw new NullPointerException("throwable was null") if (duration == null) throw new NullPointerException("duration was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates a suite of tests is about to start executing. * * <p> * For example, trait <code>Suite</code> and object <code>Runner</code> use <code>SuiteStarting</code> to report * that the <code>execute</code> method of a <code>Suite</code> is about to be invoked. * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="SuiteStarting$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>SuiteStarting</code> event like this: * </p> * * <pre class="stHighlight"> * report(SuiteStarting(ordinal, userFriendlyName, suiteName, Some(thisSuite.getClass.getName))) * </pre> * * <p> * The suite class name parameter is optional, because suites in ScalaTest are an abstraction that * need not necessarily correspond to one class. Nevertheless, it most cases each suite will correspond * to a class, and when it does, the fully qualified name of that class should be reported by passing a * <code>Some</code> for <code>suiteClassName</code>. One use for this bit of information is JUnit integration, * because the "name" provided to a JUnit <code>org.junit.runner.Description</code> appears to usually include * a fully qualified class name by convention. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName a localized name identifying the suite that is starting, suitable for presenting to the user * @param suiteID a string ID for the suite that is starting, intended to be unique across all suites in a run XXX * @param suiteClassName an optional fully qualifed <code>Suite</code> class name of the suite that is starting * @param decodedSuiteName the decoded suite name, in case the suite name is put between backticks. None if it is same as suiteName. * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the suite that is starting (if <code>None</code> * is passed, the suite cannot be rerun) * @param payload an optional object that can be used to pass custom information to the reporter about the <code>SuiteStarting</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class SuiteStarting ( ordinal: Ordinal, suiteName: String, suiteID: String, suiteClassName: Option[String], decodedSuiteName: Option[String], formatter: Option[Formatter] = None, location: Option[Location] = None, rerunner: Option[Rerunner] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (suiteName == null) throw new NullPointerException("suiteName was null") if (suiteID == null) throw new NullPointerException("suiteID was null") if (suiteClassName == null) throw new NullPointerException("suiteClassName was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (rerunner == null) throw new NullPointerException("rerunner was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates a suite of tests has completed executing. * * <p> * For example, trait <code>Suite</code> and object <code>Runner</code> use <code>SuiteCompleted</code> to report * that the <code>execute</code> method of a <code>Suite</code> * has returned normally (without throwing a <code>RuntimeException</code>). * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="SuiteCompleted$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>SuiteCompleted</code> event like this: * </p> * * <pre class="stHighlight"> * report(SuiteCompleted(ordinal, userFriendlyName, suiteName, Some(thisSuite.getClass.getName))) * </pre> * * <p> * The suite class name parameter is optional, because suites in ScalaTest are an abstraction that * need not necessarily correspond to one class. Nevertheless, it most cases each suite will correspond * to a class, and when it does, the fully qualified name of that class should be reported by passing a * <code>Some</code> for <code>suiteClassName</code>. One use for this bit of information is JUnit integration, * because the "name" provided to a JUnit <code>org.junit.runner.Description</code> appears to usually include * a fully qualified class name by convention. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName a localized name identifying the suite that has completed, suitable for presenting to the user * @param suiteID a string ID for the suite that has completed, intended to be unique across all suites in a run * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the suite that has completed * @param decodedSuiteName the decoded suite name, in case the suite name is put between backticks. None if it is same as suiteName. * @param duration an optional amount of time, in milliseconds, that was required to execute the suite that has completed * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the suite that has completed (if <code>None</code> * is passed, the suite cannot be rerun) * @param payload an optional object that can be used to pass custom information to the reporter about the <code>SuiteCompleted</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class SuiteCompleted ( ordinal: Ordinal, suiteName: String, suiteID: String, suiteClassName: Option[String], decodedSuiteName: Option[String], duration: Option[Long] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, rerunner: Option[Rerunner] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (suiteName == null) throw new NullPointerException("suiteName was null") if (suiteID == null) throw new NullPointerException("suiteID was null") if (suiteClassName == null) throw new NullPointerException("suiteClassName was null") if (duration == null) throw new NullPointerException("duration was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (rerunner == null) throw new NullPointerException("rerunner was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates the execution of a suite of tests has aborted, likely because of an error, prior * to completion. * * <p> * For example, trait <code>Suite</code> and object <code>Runner</code> use <code>SuiteAborted</code> to report * that the <code>execute</code> method of a <code>Suite</code> * has completed abruptly with a <code>RuntimeException</code>. * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="SuiteAborted$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>SuiteAborted</code> event like this: * </p> * * <pre class="stHighlight"> * report(SuiteAborted(ordinal, userFriendlyName, message, suiteName, Some(thisSuite.getClass.getName))) * </pre> * * <p> * The suite class name parameter is optional, because suites in ScalaTest are an abstraction that * need not necessarily correspond to one class. Nevertheless, it most cases each suite will correspond * to a class, and when it does, the fully qualified name of that class should be reported by passing a * <code>Some</code> for <code>suiteClassName</code>. One use for this bit of information is JUnit integration, * because the "name" provided to a JUnit <code>org.junit.runner.Description</code> appears to usually include * a fully qualified class name by convention. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param name a localized name identifying the suite that has aborted, which should include the * suite name, suitable for presenting to the user * @param message a localized message suitable for presenting to the user * @param suiteName a localized name identifying the suite that has aborted, suitable for presenting to the user * @param suiteID a string ID for the suite that has aborted, intended to be unique across all suites in a run * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the suite that has aborted * @param decodedSuiteName the decoded suite name, in case the suite name is put between backticks. None if it is same as suiteName. * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the suite has aborted, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required to execute the suite that has aborted * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the suite that has aborted (if <code>None</code> * is passed, the suite cannot be rerun) * @param payload an optional object that can be used to pass custom information to the reporter about the <code>SuiteAborted</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class SuiteAborted ( ordinal: Ordinal, message: String, suiteName: String, suiteID: String, suiteClassName: Option[String], decodedSuiteName: Option[String], throwable: Option[Throwable] = None, duration: Option[Long] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, rerunner: Option[Rerunner] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (message == null) throw new NullPointerException("message was null") if (suiteName == null) throw new NullPointerException("suiteName was null") if (suiteID == null) throw new NullPointerException("suiteID was null") if (suiteClassName == null) throw new NullPointerException("suiteClassName was null") if (throwable == null) throw new NullPointerException("throwable was null") if (duration == null) throw new NullPointerException("duration was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (rerunner == null) throw new NullPointerException("rerunner was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } // TODO: Put location as a val set to None /** * Event that indicates a runner is about run a suite of tests. * * <p> * For example, object <code>Runner</code> reports <code>RunStarting</code> to indicate * that the first <code>execute</code> method of a run's initial <code>Suite</code> * is about to be invoked. * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="RunStarting$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>RunStarting</code> event like this: * </p> * * <pre class="stHighlight"> * report(RunStarting(ordinal, testCount)) * </pre> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param testCount the number of tests expected during this run * @param configMap a <code>Map</code> of key-value pairs that can be used by custom <code>Reporter</code>s * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param payload an optional object that can be used to pass custom information to the reporter about the <code>RunStarting</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @throws IllegalArgumentException if <code>testCount</code> is less than zero. * * @author Bill Venners */ final case class RunStarting ( ordinal: Ordinal, testCount: Int, configMap: Map[String, Any], formatter: Option[Formatter] = None, location: Option[Location] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (testCount < 0) throw new IllegalArgumentException("testCount was less than zero: " + testCount) if (configMap == null) throw new NullPointerException("configMap was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates a runner has completed running a suite of tests. * * <p> * <code>Suite</code>'s <code>execute</code> method takes a <code>Stopper</code>, whose <code>stopRequested</code> * method indicates a stop was requested. If <code>true</code> is returned by * <code>stopRequested</code> while a suite of tests is running, the * <code>execute</code> method should promptly * return even if that suite hasn't finished running all of its tests. * </p> * * <p>If a stop was requested via the <code>Stopper</code>. * <code>Runner</code> will report <code>RunStopped</code> * when the <code>execute</code> method of the run's starting <code>Suite</code> returns. * If a stop is not requested, <code>Runner</code> will report <code>RunCompleted</code> * when the last <code>execute</code> method of the run's starting <code>Suite</code>s returns. * </p> * * <p> * ScalaTest's <code>Runner</code> fires a <code>RunCompleted</code> report with an empty <code>summary</code>, because * the reporter is responsible for keeping track of the total number of tests reported as succeeded, failed, ignored, and pending. * ScalaTest's internal reporter replaces the <code>RunCompleted</code> with a new one that is identical except that is * has a defined <code>summary</code>. * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="RunCompleted$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>RunCompleted</code> event like this: * </p> * * <pre class="stHighlight"> * report(RunCompleted(ordinal)) * </pre> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param duration an optional amount of time, in milliseconds, that was required by the run that has completed * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param payload an optional object that can be used to pass custom information to the reporter about the <code>RunCompleted</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class RunCompleted ( ordinal: Ordinal, duration: Option[Long] = None, summary: Option[Summary] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (duration == null) throw new NullPointerException("duration was null") if (summary == null) throw new NullPointerException("summary was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates a runner has stopped running a suite of tests prior to completion, likely * because of a stop request. * * <p> * <code>Suite</code>'s <code>execute</code> method takes a <code>Stopper</code>, whose <code>stopRequested</code> * method indicates a stop was requested. If <code>true</code> is returned by * <code>stopRequested</code> while a suite of tests is running, the * <code>execute</code> method should promptly * return even if that suite hasn't finished running all of its tests. * </p> * * <p>If a stop was requested via the <code>Stopper</code>. * <code>Runner</code> will report <code>RunStopped</code> * when the <code>execute</code> method of the run's starting <code>Suite</code> returns. * If a stop is not requested, <code>Runner</code> will report <code>RunCompleted</code> * when the last <code>execute</code> method of the run's starting <code>Suite</code>s returns. * </p> * * <p> * ScalaTest's <code>Runner</code> fires a <code>RunStopped</code> report with an empty <code>summary</code>, because * the reporter is responsible for keeping track of the total number of tests reported as succeeded, failed, ignored, and pending. * ScalaTest's internal reporter replaces the <code>RunStopped</code> with a new one that is identical except that is * has a defined <code>summary</code>. * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="RunStopped$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>RunStopped</code> event like this: * </p> * * <pre class="stHighlight"> * report(RunStopped(ordinal)) * </pre> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param duration an optional amount of time, in milliseconds, that was required by the run that has stopped * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param payload an optional object that can be used to pass custom information to the reporter about the <code>RunStopped</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class RunStopped ( ordinal: Ordinal, duration: Option[Long] = None, summary: Option[Summary] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (duration == null) throw new NullPointerException("duration was null") if (summary == null) throw new NullPointerException("summary was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates a runner encountered an error while attempting to run a suite of tests. * * <p> * For example, object <code>Runner</code> reports <code>RunAborted</code> if the * <code>execute</code> method of any of the run's starting <code>Suite</code>s completes * abruptly with a <code>Throwable</code>. * </p> * * <p> * ScalaTest's <code>Runner</code> fires a <code>RunAborted</code> report with an empty <code>summary</code>, because * the reporter is responsible for keeping track of the total number of tests reported as succeeded, failed, ignored, and pending. * ScalaTest's internal reporter replaces the <code>RunAborted</code> with a new one that is identical except that is * has a defined <code>summary</code>. * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="RunAborted$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>RunAborted</code> event like this: * </p> * * <pre class="stHighlight"> * report(RunAborted(ordinal, message, Some(exception))) * </pre> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the suite has aborted, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required by the run that has aborted * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param payload an optional object that can be used to pass custom information to the reporter about the <code>RunAborted</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class RunAborted ( ordinal: Ordinal, message: String, throwable: Option[Throwable], duration: Option[Long] = None, summary: Option[Summary] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (message == null) throw new NullPointerException("message was null") if (throwable == null) throw new NullPointerException("throwable was null") if (duration == null) throw new NullPointerException("duration was null") if (summary == null) throw new NullPointerException("summary was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event used to provide information that is not appropriate to report via any other <code>Event</code>. * * <p> * To create instances of this class you may * use the factory method provided in its <a href="InfoProvided$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>InfoProvided</code> event like this: * </p> * * <pre class="stHighlight"> * report(InfoProvided(ordinal, message, Some(NameInfo(suiteName, Some(thisSuite.getClass.getName), Some(testName))))) * </pre> * * <p> * An <code>InfoProvided</code> event may be fired from anywhere. In this respect <code>InfoProvided</code> is different * from the other events, for which it is defined whether they are fired in the context of a suite or test. * If fired in the context of a test, the <code>InfoProvided</code> event should include a <code>NameInfo</code> in which * <code>testName</code> is defined. If fired in the context of a suite, but not a test, the <code>InfoProvided</code> event * should include a <code>NameInfo</code> in which <code>testName</code> is <em>not</em> defined. If fired within the context * of neither a suite nor a test, the <code>nameInfo</code> of the <code>InfoProvided</code> event (an <code>Option[NameInfo]</code>) should be <code>None</code>. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param nameInfo an optional <code>NameInfo</code> that if defined, provides names for the suite and optionally the test * in the context of which the information was provided * @param aboutAPendingTest indicates whether the information being provided via this event is about a pending test * @param aboutACanceledTest indicates whether the information being provided via this event is about a canceled test * @param throwable an optional <code>Throwable</code> * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param payload an optional object that can be used to pass custom information to the reporter about the <code>InfoProvided</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class InfoProvided ( ordinal: Ordinal, message: String, nameInfo: Option[NameInfo], aboutAPendingTest: Option[Boolean] = None, aboutACanceledTest: Option[Boolean] = None, throwable: Option[Throwable] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (message == null) throw new NullPointerException("message was null") if (nameInfo == null) throw new NullPointerException("nameInfo was null") if (aboutAPendingTest == null) throw new NullPointerException("aboutAPendingTest was null") if (aboutACanceledTest == null) throw new NullPointerException("aboutACanceledTest was null") if (throwable == null) throw new NullPointerException("throwable was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event used to provide markup text for document-style reports. * * <p> * To create instances of this class you may * use the factory method provided in its <a href="MarkupProvided$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>MarkupProvided</code> event like this: * </p> * * <pre class="stHighlight"> * report(MarkupProvided(ordinal, text, Some(NameInfo(suiteName, Some(thisSuite.getClass.getName), Some(testName))))) * </pre> * * <p> * A <code>MarkupProvided</code> event may be fired from anywhere. In this respect <code>MarkupProvided</code> is different * from the other events, for which it is defined whether they are fired in the context of a suite or test. * If fired in the context of a test, the <code>MarkupProvided</code> event should include a <code>NameInfo</code> in which * <code>testName</code> is defined. If fired in the context of a suite, but not a test, the <code>MarkupProvided</code> event * should include a <code>NameInfo</code> in which <code>testName</code> is <em>not</em> defined. If fired within the context * of neither a suite nor a test, the <code>nameInfo</code> of the <code>MarkupProvided</code> event (an <code>Option[NameInfo]</code>) should be <code>None</code>. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param text a snippet of markup text (in Markdown format) * @param nameInfo an optional <code>NameInfo</code> that if defined, provides names for the suite and optionally the test * in the context of which the information was provided * @param aboutAPendingTest indicates whether the information being provided via this event is about a pending test * @param aboutACanceledTest indicates whether the information being provided via this event is about a canceled test * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param payload an optional object that can be used to pass custom information to the reporter about the <code>MarkupProvided</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class MarkupProvided ( ordinal: Ordinal, text: String, nameInfo: Option[NameInfo], aboutAPendingTest: Option[Boolean] = None, aboutACanceledTest: Option[Boolean] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (text == null) throw new NullPointerException("message was null") if (nameInfo == null) throw new NullPointerException("nameInfo was null") if (aboutAPendingTest == null) throw new NullPointerException("aboutAPendingTest was null") if (aboutACanceledTest == null) throw new NullPointerException("aboutACanceledTest was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates a new scope has been opened. * * <p> * To create instances of this class you may * use the factory method provided in its <a href="ScopeOpened$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>ScopeOpened</code> event like this: * </p> * * <pre class="stHighlight"> * report(ScopeOpened(ordinal, message, Some(NameInfo(suiteName, Some(thisSuite.getClass.getName), Some(testName))))) * </pre> * * <p> * A <code>ScopeOpened</code> event may be fired from within suites or tests. * If fired in the context of a test, the <code>ScopeOpened</code> event should include a <code>NameInfo</code> in which * <code>testName</code> is defined. If fired in the context of a suite, but not a test, the <code>ScopeOpened</code> event * should include a <code>NameInfo</code> in which <code>testName</code> is <em>not</em> defined. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param nameInfo a <code>NameInfo</code> that provides names for the suite and optionally the test * in the context of which the scope was opened * @param aboutAPendingTest indicates whether the scope was opened in the context of a pending test * @param aboutACanceledTest indicates whether the scope was opened in the context of a canceled test * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param payload an optional object that can be used to pass custom information to the reporter about the <code>ScopeOpened</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class ScopeOpened ( ordinal: Ordinal, message: String, nameInfo: NameInfo, aboutAPendingTest: Option[Boolean] = None, aboutACanceledTest: Option[Boolean] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (message == null) throw new NullPointerException("message was null") if (nameInfo == null) throw new NullPointerException("nameInfo was null") if (aboutAPendingTest == null) throw new NullPointerException("aboutAPendingTest was null") if (aboutACanceledTest == null) throw new NullPointerException("aboutACanceledTest was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /** * Event that indicates a scope has been closed. * * <p> * To create instances of this class you may * use the factory method provided in its <a href="ScopeClosed$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>ScopeClosed</code> event like this: * </p> * * <pre class="stHighlight"> * report(ScopeClosed(ordinal, message, Some(NameInfo(suiteName, Some(thisSuite.getClass.getName), Some(testName))))) * </pre> * * <p> * A <code>ScopeClosed</code> event may be fired from within suites or tests. * If fired in the context of a test, the <code>ScopeClosed</code> event should include a <code>NameInfo</code> in which * <code>testName</code> is defined. If fired in the context of a suite, but not a test, the <code>ScopeClosed</code> event * should include a <code>NameInfo</code> in which <code>testName</code> is <em>not</em> defined. * </p> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param nameInfo a <code>NameInfo</code> that provides names for the suite and optionally the test * in the context of which the scope was closed * @param aboutAPendingTest indicates whether the scope was closed in the context of a pending test * @param aboutACanceledTest indicates whether the scope was closed in the context of a canceled test * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param location An optional location that provides information indicating where in the source code an event originated. * @param payload an optional object that can be used to pass custom information to the reporter about the <code>ScopeClosed</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class ScopeClosed ( ordinal: Ordinal, message: String, nameInfo: NameInfo, aboutAPendingTest: Option[Boolean] = None, aboutACanceledTest: Option[Boolean] = None, formatter: Option[Formatter] = None, location: Option[Location] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (message == null) throw new NullPointerException("message was null") if (nameInfo == null) throw new NullPointerException("nameInfo was null") if (aboutAPendingTest == null) throw new NullPointerException("aboutAPendingTest was null") if (aboutACanceledTest == null) throw new NullPointerException("aboutACanceledTest was null") if (formatter == null) throw new NullPointerException("formatter was null") if (location == null) throw new NullPointerException("location was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") } /* /** * Event that indicates a runner is about run a suite of tests. * * <p> * For example, object <code>Runner</code> reports <code>RunStarting</code> to indicate * that the first <code>execute</code> method of a run's initial <code>Suite</code> * is about to be invoked. * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="RunStarting$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>RunStarting</code> event like this: * </p> * * <pre class="stHighlight"> * report(RunStarting(ordinal, testCount)) * </pre> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param testCount the number of tests expected during this run * @param configMap a <code>Map</code> of key-value pairs that can be used by custom <code>Reporter</code>s * @param payload an optional object that can be used to pass custom information to the reporter about the <code>RunStarting</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @throws IllegalArgumentException if <code>testCount</code> is less than zero. * * @author Bill Venners */ final case class DiscoveryStarting ( ordinal: Ordinal, testCount: Int, configMap: Map[String, Any], payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (testCount < 0) throw new IllegalArgumentException("testCount was less than zero: " + testCount) if (configMap == null) throw new NullPointerException("configMap was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") /** * Location in a <code>DiscoveryStarting</code> is always set to <code>None</code>. */ val location: Option[Location] = None /** * Formatter in a <code>DiscoveryStarting</code> is always set to <code>None</code>. */ val formatter: Option[Formatter] = None } /** * Event that indicates a runner has completed running a suite of tests. * * <p> * <code>Suite</code>'s <code>execute</code> method takes a <code>Stopper</code>, whose <code>stopRequested</code> * method indicates a stop was requested. If <code>true</code> is returned by * <code>stopRequested</code> while a suite of tests is running, the * <code>execute</code> method should promptly * return even if that suite hasn't finished running all of its tests. * </p> * * <p>If a stop was requested via the <code>Stopper</code>. * <code>Runner</code> will report <code>RunStopped</code> * when the <code>execute</code> method of the run's starting <code>Suite</code> returns. * If a stop is not requested, <code>Runner</code> will report <code>RunCompleted</code> * when the last <code>execute</code> method of the run's starting <code>Suite</code>s returns. * </p> * * <p> * ScalaTest's <code>Runner</code> fires a <code>RunCompleted</code> report with an empty <code>summary</code>, because * the reporter is responsible for keeping track of the total number of tests reported as succeeded, failed, ignored, and pending. * ScalaTest's internal reporter replaces the <code>RunCompleted</code> with a new one that is identical except that is * has a defined <code>summary</code>. * </p> * * <p> * To create instances of this class you may * use the factory method provided in its <a href="RunCompleted$.html">companion object</a>. For example, given a * report function named <code>report</code>, you could fire a <code>RunCompleted</code> event like this: * </p> * * <pre class="stHighlight"> * report(RunCompleted(ordinal)) * </pre> * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param duration an optional amount of time, in milliseconds, that was required by the run that has completed * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * @param payload an optional object that can be used to pass custom information to the reporter about the <code>RunCompleted</code> event * @param threadName a name for the <code>Thread</code> about whose activity this event was reported * @param timeStamp a <code>Long</code> indicating the time this event was reported, expressed in terms of the * number of milliseconds since the standard base time known as "the epoch": January 1, 1970, 00:00:00 GMT * * @author Bill Venners */ final case class DiscoveryCompleted ( ordinal: Ordinal, duration: Option[Long] = None, summary: Option[Summary] = None, payload: Option[Any] = None, threadName: String = Thread.currentThread.getName, timeStamp: Long = (new Date).getTime ) extends Event { if (ordinal == null) throw new NullPointerException("ordinal was null") if (duration == null) throw new NullPointerException("duration was null") if (summary == null) throw new NullPointerException("summary was null") if (payload == null) throw new NullPointerException("payload was null") if (threadName == null) throw new NullPointerException("threadName was null") /** * Location in a <code>DiscoveryCompleted</code> is always set to <code>None</code>. */ val location: Option[Location] = None /** * Formatter in a <code>DiscoveryCompleted</code> is always set to <code>None</code>. */ val formatter: Option[Formatter] = None } */ /** * Deprecated singleton object for the <a href="TestStarting.html"><code>TestStarting</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>TestStarting</code> objects. * This object contains methods that were in the <code>TestStarting</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>. * </p> * * @author Bill Venners */ @deprecated("Use TestStarting with named and/or default parameters instead.") object DeprecatedTestStarting { /** * Constructs a new <code>TestStarting</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that is starting * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that is starting * @param testName the name of the test that is starting * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the test that is starting (if <code>None</code> * is passed, the test cannot be rerun) * @param payload an optional object that can be used to pass custom information to the reporter about the <code>TestStarting</code> event * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestStarting</code> instance initialized with the passed and default values * */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String, formatter: Option[Formatter], rerunner: Option[Rerunner], payload: Option[Any] ): TestStarting = { TestStarting(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, formatter, None, rerunner, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestStarting</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that is starting * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that is starting * @param testName the name of the test that is starting * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the test that is starting (if <code>None</code> * is passed, the test cannot be rerun) * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestStarting</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String, formatter: Option[Formatter], rerunner: Option[Rerunner] ): TestStarting = { TestStarting(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, formatter, None, rerunner, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestStarting</code> event with the passed parameters, passing <code>None</code> as the * <code>rerunner</code>, <code>None</code> as the <code>payload</code>, the current threads name as <code>threadname</code>, * and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that is starting * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that is starting * @param testName the name of the test that is starting * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestStarting</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String, formatter: Option[Formatter] ): TestStarting = { TestStarting(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, formatter, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestStarting</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>rerunner</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that is starting * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that is starting * @param testName the name of the test that is starting * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestStarting</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String ): TestStarting = { TestStarting(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } } /** * Deprecated singleton object for the <a href="TestSucceeded.html"><code>TestSucceeded</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>TestSucceeded</code> objects. * This object contains methods that were in the <code>TestSucceeded</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>. * </p> * * @author Bill Venners */ @deprecated("Use TestSucceeded with named and/or default parameters instead.") object DeprecatedTestSucceeded { /** * Constructs a new <code>TestSucceeded</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that has succeeded * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that has succeeded * @param testName the name of the test that has succeeded * @param duration an optional amount of time, in milliseconds, that was required to run the test that has succeeded * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the test that has succeeded (if <code>None</code> * is passed, the test cannot be rerun) * @param payload an optional object that can be used to pass custom information to the reporter about the <code>TestSucceeded</code> event * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestSucceeded</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String, duration: Option[Long], formatter: Option[Formatter], rerunner: Option[Rerunner], payload: Option[Any] ): TestSucceeded = { TestSucceeded(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, duration, formatter, None, rerunner, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestSucceeded</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that has succeeded * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that has succeeded * @param testName the name of the test that has succeeded * @param duration an optional amount of time, in milliseconds, that was required to run the test that has succeeded * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the test that has succeeded (if <code>None</code> * is passed, the test cannot be rerun) * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestSucceeded</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String, duration: Option[Long], formatter: Option[Formatter], rerunner: Option[Rerunner] ): TestSucceeded = { TestSucceeded(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, duration, formatter, None, rerunner, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestSucceeded</code> event with the passed parameters, passing <code>None</code> as the * <code>rerunner</code>, <code>None</code> as the <code>payload</code>, the current threads name as <code>threadname</code>, * and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that has succeeded * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that has succeeded * @param testName the name of the test that has succeeded * @param duration an optional amount of time, in milliseconds, that was required to run the test that has succeeded * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestSucceeded</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String, duration: Option[Long], formatter: Option[Formatter] ): TestSucceeded = { TestSucceeded(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, duration, formatter, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestSucceeded</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>rerunner</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that has succeeded * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that has succeeded * @param testName the name of the test that has succeeded * @param duration an optional amount of time, in milliseconds, that was required to run the test that has succeeded * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestSucceeded</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String, duration: Option[Long] ): TestSucceeded = { TestSucceeded(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, duration, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestSucceeded</code> event with the passed parameters, passing <code>None</code> for <code>duration</code>, * <code>None</code> for <code>formatter</code>, <code>None</code> as the <code>rerunner</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that has succeeded * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that has succeeded * @param testName the name of the test that has succeeded * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestSucceeded</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String ): TestSucceeded = { TestSucceeded(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, None, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } } /** * Deprecated singleton object for the <a href="TestFailed.html"><code>TestFailed</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>TestFailed</code> objects. * This object contains methods that were in the <code>TestFailed</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>. * </p> * * @author Bill Venners */ @deprecated("Use TestFailed with named and/or default parameters instead.") object DeprecatedTestFailed { /** * Constructs a new <code>TestFailed</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param suiteName the name of the suite containing the test that has failed * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that has failed * @param testName the name of the test that has failed * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the test has failed, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required to run the test that has failed * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the test that has failed (if <code>None</code> * is passed, the test cannot be rerun) * @param payload an optional object that can be used to pass custom information to the reporter about the <code>TestFailed</code> event * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestFailed</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, suiteName: String, suiteClassName: Option[String], testName: String, throwable: Option[Throwable], duration: Option[Long], formatter: Option[Formatter], rerunner: Option[Rerunner], payload: Option[Any] ): TestFailed = { TestFailed(ordinal, message, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, throwable, duration, formatter, None, rerunner, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestFailed</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param suiteName the name of the suite containing the test that has failed * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that has failed * @param testName the name of the test that has failed * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the test has failed, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required to run the test that has failed * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the test that has failed (if <code>None</code> * is passed, the test cannot be rerun) * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestFailed</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, suiteName: String, suiteClassName: Option[String], testName: String, throwable: Option[Throwable], duration: Option[Long], formatter: Option[Formatter], rerunner: Option[Rerunner] ): TestFailed = { TestFailed(ordinal, message, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, throwable, duration, formatter, None, rerunner, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestFailed</code> event with the passed parameters, passing <code>None</code> as the * <code>rerunner</code>, <code>None</code> as the <code>payload</code>, the current threads name as <code>threadname</code>, * and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param suiteName the name of the suite containing the test that has failed * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that has failed * @param testName the name of the test that has failed * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the test has failed, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required to run the test that has failed * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestFailed</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, suiteName: String, suiteClassName: Option[String], testName: String, throwable: Option[Throwable], duration: Option[Long], formatter: Option[Formatter] ): TestFailed = { TestFailed(ordinal, message, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, throwable, duration, formatter, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestFailed</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>rerunner</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param suiteName the name of the suite containing the test that has failed * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that has failed * @param testName the name of the test that has failed * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the test has failed, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required to run the test that has failed * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestFailed</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, suiteName: String, suiteClassName: Option[String], testName: String, throwable: Option[Throwable], duration: Option[Long] ): TestFailed = { TestFailed(ordinal, message, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, throwable, duration, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestFailed</code> event with the passed parameters, passing <code>None</code> for <code>duration</code>, * <code>None</code> for <code>formatter</code>, <code>None</code> as the <code>rerunner</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param suiteName the name of the suite containing the test that has failed * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that has failed * @param testName the name of the test that has failed * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the test has failed, * or a <code>Throwable</code> created to capture stack trace information about the problem. * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestFailed</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, suiteName: String, suiteClassName: Option[String], testName: String, throwable: Option[Throwable] ): TestFailed = { TestFailed(ordinal, message, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, throwable, None, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } } /** * Deprecated singleton object for the <a href="TestIgnored.html"><code>TestIgnored</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>TestIgnored</code> objects. * This object contains methods that were in the <code>TestIgnored</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>. * </p> * * @author Bill Venners */ @deprecated("Use TestIgnored with named and/or default parameters instead.") object DeprecatedTestIgnored { /** * Constructs a new <code>TestIgnored</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that was ignored * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that was ignored * @param testName the name of the test that was ignored * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param payload an optional object that can be used to pass custom information to the reporter about the <code>TestIgnored</code> event * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestIgnored</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String, formatter: Option[Formatter], payload: Option[Any] ): TestIgnored = { TestIgnored(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, formatter, None, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestIgnored</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that was ignored * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that was ignored * @param testName the name of the test that was ignored * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestIgnored</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String, formatter: Option[Formatter] ): TestIgnored = { TestIgnored(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, formatter, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestIgnored</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that was ignored * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that was ignored * @param testName the name of the test that was ignored * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestIgnored</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String ): TestIgnored = { TestIgnored(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } } /** * Deprecated singleton object for the <a href="TestPending.html"><code>TestPending</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>TestPending</code> objects. * This object contains methods that were in the <code>TestPending</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>. * </p> * * @author Bill Venners */ @deprecated("Use TestPending with named and/or default parameters instead.") object DeprecatedTestPending { /** * Constructs a new <code>TestPending</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that is pending * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that is pending * @param testName the name of the test that is pending * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param payload an optional object that can be used to pass custom information to the reporter about the <code>TestPending</code> event * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestPending</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String, formatter: Option[Formatter], payload: Option[Any] ): TestPending = { TestPending(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, None, formatter, None, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestPending</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that is pending * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that is pending * @param testName the name of the test that is pending * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestPending</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String, formatter: Option[Formatter] ): TestPending = { TestPending(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, None, formatter, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>TestPending</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the test that is pending * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the test that is pending * @param testName the name of the test that is pending * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>TestPending</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], testName: String ): TestPending = { TestPending(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, testName, testName, None, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } } /** * Deprecated singleton object for the <a href="SuiteStarting.html"><code>SuiteStarting</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>SuiteStarting</code> objects. * This object contains methods that were in the <code>SuiteStarting</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>. * </p> * * @author Bill Venners */ @deprecated("Use SuiteStarting with named and/or default parameters instead.") object DeprecatedSuiteStarting { /** * Constructs a new <code>SuiteStarting</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName a localized name identifying the suite that is starting, which should include the * suite name, suitable for presenting to the user * @param suiteClassName an optional fully qualifed <code>Suite</code> class name of the suite that is starting * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the suite that is starting (if <code>None</code> * is passed, the suite cannot be rerun) * @param payload an optional object that can be used to pass custom information to the reporter about the <code>SuiteStarting</code> event * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteStarting</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], formatter: Option[Formatter], rerunner: Option[Rerunner], payload: Option[Any] ): SuiteStarting = { SuiteStarting(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, formatter, None, rerunner, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>SuiteStarting</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName a localized name identifying the suite that is starting, which should include the * suite name, suitable for presenting to the user * @param suiteClassName an optional fully qualifed <code>Suite</code> class name of the suite that is starting * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the suite that is starting (if <code>None</code> * is passed, the suite cannot be rerun) * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteStarting</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], formatter: Option[Formatter], rerunner: Option[Rerunner] ): SuiteStarting = { SuiteStarting(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, formatter, None, rerunner, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>SuiteStarting</code> event with the passed parameters, passing <code>None</code> as the * <code>rerunner</code>, <code>None</code> as the <code>payload</code>, the current threads name as <code>threadname</code>, * and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName a localized name identifying the suite that is starting, which should include the * suite name, suitable for presenting to the user * @param suiteClassName an optional fully qualifed <code>Suite</code> class name of the suite that is starting * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteStarting</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], formatter: Option[Formatter] ): SuiteStarting = { SuiteStarting(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, formatter, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>SuiteStarting</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>rerunner</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName a localized name identifying the suite that is starting, which should include the * suite name, suitable for presenting to the user * @param suiteClassName an optional fully qualifed <code>Suite</code> class name of the suite that is starting * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteStarting</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String] ): SuiteStarting = { SuiteStarting(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } } /** * Deprecated singleton object for the <a href="SuiteCompleted.html"><code>SuiteCompleted</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>SuiteCompleted</code> objects. * This object contains methods that were in the <code>SuiteCompleted</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>. * </p> * * @author Bill Venners */ @deprecated("Use SuiteCompleted with named and/or default parameters instead.") object DeprecatedSuiteCompleted { /** * Constructs a new <code>SuiteCompleted</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the suite that has completed * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the suite that has completed * @param duration an optional amount of time, in milliseconds, that was required to execute the suite that has completed * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the suite that has completed (if <code>None</code> * is passed, the suite cannot be rerun) * @param payload an optional object that can be used to pass custom information to the reporter about the <code>SuiteCompleted</code> event * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteCompleted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], duration: Option[Long], formatter: Option[Formatter], rerunner: Option[Rerunner], payload: Option[Any] ): SuiteCompleted = { SuiteCompleted(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, duration, formatter, None, rerunner, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>SuiteCompleted</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the suite that has completed * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the suite that has completed * @param duration an optional amount of time, in milliseconds, that was required to execute the suite that has completed * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the suite that has completed (if <code>None</code> * is passed, the suite cannot be rerun) * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteCompleted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], duration: Option[Long], formatter: Option[Formatter], rerunner: Option[Rerunner] ): SuiteCompleted = { SuiteCompleted(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, duration, formatter, None, rerunner, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>SuiteCompleted</code> event with the passed parameters, passing <code>None</code> as the * <code>rerunner</code>, <code>None</code> as the <code>payload</code>, the current threads name as <code>threadname</code>, * and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the suite that has completed * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the suite that has completed * @param duration an optional amount of time, in milliseconds, that was required to execute the suite that has completed * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteCompleted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], duration: Option[Long], formatter: Option[Formatter] ): SuiteCompleted = { SuiteCompleted(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, duration, formatter, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>SuiteCompleted</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>rerunner</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param suiteName the name of the suite containing the suite that has completed * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the suite that has completed * @param duration an optional amount of time, in milliseconds, that was required to execute the suite that has completed * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteCompleted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String], duration: Option[Long] ): SuiteCompleted = { SuiteCompleted(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, duration, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>SuiteCompleted</code> event with the passed parameters, passing <code>None</code> for <code>duration</code>, * <code>None</code> for <code>formatter</code>, <code>None</code> as the <code>rerunner</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param name a localized name identifying the suite that has completed, which should include the * suite name, suitable for presenting to the user * @param suiteName the name of the suite containing the suite that has completed * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the suite that has completed * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteCompleted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, suiteName: String, suiteClassName: Option[String] ): SuiteCompleted = { SuiteCompleted(ordinal, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, None, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } } /** * Deprecated singleton object for the <a href="SuiteAborted.html"><code>SuiteAborted</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>SuiteAborted</code> objects. * This object contains methods that were in the <code>SuiteAborted</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>. * </p> * * @author Bill Venners */ @deprecated("Use SuiteAborted with named and/or default parameters instead.") object DeprecatedSuiteAborted { /** * Constructs a new <code>SuiteAborted</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param name a localized name identifying the suite that has aborted, which should include the * suite name, suitable for presenting to the user * @param message a localized message suitable for presenting to the user * @param suiteName the name of the suite containing the suite that has aborted * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the suite that has aborted * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the suite has aborted, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required to execute the suite that has aborted * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the suite that has aborted (if <code>None</code> * is passed, the suite cannot be rerun) * @param payload an optional object that can be used to pass custom information to the reporter about the <code>SuiteAborted</code> event * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteAborted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, suiteName: String, suiteClassName: Option[String], throwable: Option[Throwable], duration: Option[Long], formatter: Option[Formatter], rerunner: Option[Rerunner], payload: Option[Any] ): SuiteAborted = { SuiteAborted(ordinal, message, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, throwable, duration, formatter, None, rerunner, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>SuiteAborted</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param suiteName the name of the suite containing the suite that has aborted * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the suite that has aborted * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the suite has aborted, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required to execute the suite that has aborted * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param rerunner an optional <code>Rerunner</code> that can be used to rerun the suite that has aborted (if <code>None</code> * is passed, the suite cannot be rerun) * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteAborted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, suiteName: String, suiteClassName: Option[String], throwable: Option[Throwable], duration: Option[Long], formatter: Option[Formatter], rerunner: Option[Rerunner] ): SuiteAborted = { SuiteAborted(ordinal, message, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, throwable, duration, formatter, None, rerunner, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>SuiteAborted</code> event with the passed parameters, passing <code>None</code> as the * <code>rerunner</code>, <code>None</code> as the <code>payload</code>, the current threads name as <code>threadname</code>, * and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the suite has aborted, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required to execute the suite that has aborted * @param suiteName the name of the suite containing the suite that has aborted * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the suite that has aborted * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteAborted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, suiteName: String, suiteClassName: Option[String], throwable: Option[Throwable], duration: Option[Long], formatter: Option[Formatter] ): SuiteAborted = { SuiteAborted(ordinal, message, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, throwable, duration, formatter, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>SuiteAborted</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>rerunner</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param suiteName the name of the suite containing the suite that has aborted * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the suite that has aborted * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the suite has aborted, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required to execute the suite that has aborted * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteAborted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, suiteName: String, suiteClassName: Option[String], throwable: Option[Throwable], duration: Option[Long] ): SuiteAborted = { SuiteAborted(ordinal, message, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, throwable, duration, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>SuiteAborted</code> event with the passed parameters, passing <code>None</code> for <code>duration</code>, * <code>None</code> for <code>formatter</code>, <code>None</code> as the <code>rerunner</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param suiteName the name of the suite containing the suite that has aborted * @param suiteClassName an optional fully qualifed <code>Suite</code> class name containing the suite that has aborted * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the suite has aborted, * or a <code>Throwable</code> created to capture stack trace information about the problem. * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>SuiteAborted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, suiteName: String, suiteClassName: Option[String], throwable: Option[Throwable] ): SuiteAborted = { SuiteAborted(ordinal, message, suiteName, suiteClassName getOrElse suiteName, suiteClassName, None, throwable, None, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } } /** * Deprecated singleton object for the <a href="RunStarting.html"><code>RunStarting</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>RunStarting</code> objects. * This object contains methods that were in the <code>RunStarting</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>, and <code>IllegalArgumentException</code> if * <code>testCount</code> is less than zero. * </p> * * @author Bill Venners */ @deprecated("Use RunStarting with named and/or default parameters instead.") object DeprecatedRunStarting { /** * Constructs a new <code>RunStarting</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param testCount the number of tests expected during this run * @param configMap a <code>Map</code> of key-value pairs that can be used by custom <code>Reporter</code>s * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param payload an optional object that can be used to pass custom information to the reporter about the <code>RunStarting</code> event * * @throws IllegalArgumentException if <code>testCount</code> is less than zero. * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunStarting</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, testCount: Int, configMap: Map[String, Any], formatter: Option[Formatter], payload: Option[Any] ): RunStarting = { RunStarting(ordinal, testCount, configMap, formatter, None, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunStarting</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, * and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param testCount the number of tests expected during this run * @param configMap a <code>Map</code> of key-value pairs that can be used by custom <code>Reporter</code>s * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunStarting</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, testCount: Int, configMap: Map[String, Any], formatter: Option[Formatter] ): RunStarting = { RunStarting(ordinal, testCount, configMap, formatter, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunStarting</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param testCount the number of tests expected during this run * @param configMap a <code>Map</code> of key-value pairs that can be used by custom <code>Reporter</code>s * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunStarting</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, testCount: Int, configMap: Map[String, Any] ): RunStarting = { RunStarting(ordinal, testCount, configMap, None, None, None, Thread.currentThread.getName, (new Date).getTime) } } /** * Deprecated singleton object for the <a href="RunCompleted.html"><code>RunCompleted</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>RunCompleted</code> objects. * This object contains methods that were in the <code>RunCompleted</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>. * </p> * * @author Bill Venners */ @deprecated("Use RunCompleted with named and/or default parameters instead.") object DeprecatedRunCompleted { /** * Constructs a new <code>RunCompleted</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param duration an optional amount of time, in milliseconds, that was required by the run that has completed * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param payload an optional object that can be used to pass custom information to the reporter about the <code>RunCompleted</code> event * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunCompleted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, duration: Option[Long], summary: Option[Summary], formatter: Option[Formatter], payload: Option[Any] ): RunCompleted = { RunCompleted(ordinal, duration, summary, formatter, None, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunCompleted</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, * and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param duration an optional amount of time, in milliseconds, that was required by the run that has completed * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunCompleted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, duration: Option[Long], summary: Option[Summary], formatter: Option[Formatter] ): RunCompleted = { RunCompleted(ordinal, duration, summary, formatter, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunCompleted</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param duration an optional amount of time, in milliseconds, that was required by the run that has completed * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunCompleted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, duration: Option[Long], summary: Option[Summary] ): RunCompleted = { RunCompleted(ordinal, duration, summary, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunCompleted</code> event with the passed parameters, passing <code>None</code> for <code>summary</code>, * <code>None</code> for <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param duration an optional amount of time, in milliseconds, that was required by the run that has completed * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunCompleted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, duration: Option[Long] ): RunCompleted = { RunCompleted(ordinal, duration, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunCompleted</code> event with the passed parameters, passing <code>None</code> for <code>duration</code>, * <code>None</code> for <code>summary</code>, <code>None</code> for <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunCompleted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal ): RunCompleted = { RunCompleted(ordinal, None, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } } /** * Deprecated singleton object for the <a href="RunStopped.html"><code>RunStopped</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>RunStopped</code> objects. * This object contains methods that were in the <code>RunStopped</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>. * </p> * * @author Bill Venners */ @deprecated("Use RunStopped with named and/or default parameters instead.") object DeprecatedRunStopped { /** * Constructs a new <code>RunStopped</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param duration an optional amount of time, in milliseconds, that was required by the run that has stopped * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param payload an optional object that can be used to pass custom information to the reporter about the <code>RunStopped</code> event * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunStopped</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, duration: Option[Long], summary: Option[Summary], formatter: Option[Formatter], payload: Option[Any] ): RunStopped = { RunStopped(ordinal, duration, summary, formatter, None, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunStopped</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, * and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param duration an optional amount of time, in milliseconds, that was required by the run that has stopped * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunStopped</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, duration: Option[Long], summary: Option[Summary], formatter: Option[Formatter] ): RunStopped = { RunStopped(ordinal, duration, summary, formatter, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunStopped</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param duration an optional amount of time, in milliseconds, that was required by the run that has stopped * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunStopped</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, duration: Option[Long], summary: Option[Summary] ): RunStopped = { RunStopped(ordinal, duration, summary, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunStopped</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param duration an optional amount of time, in milliseconds, that was required by the run that has stopped * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunStopped</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, duration: Option[Long] ): RunStopped = { RunStopped(ordinal, duration, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunStopped</code> event with the passed parameters, passing <code>None</code> for <code>duration</code>, * <code>None</code> for <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunStopped</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal ): RunStopped = { RunStopped(ordinal, None, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } } /** * Deprecated singleton object for the <a href="RunAborted.html"><code>RunAborted</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>RunAborted</code> objects. * This object contains methods that were in the <code>RunAborted</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>. * </p> * * @author Bill Venners */ @deprecated("Use RunAborted with named and/or default parameters instead.") object DeprecatedRunAborted { /** * Constructs a new <code>RunAborted</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the suite has aborted, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required by the run that has aborted * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param payload an optional object that can be used to pass custom information to the reporter about the <code>RunAborted</code> event * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunAborted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, throwable: Option[Throwable], duration: Option[Long], summary: Option[Summary], formatter: Option[Formatter], payload: Option[Any] ): RunAborted = { RunAborted(ordinal, message, throwable, duration, summary, formatter, None, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunAborted</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, * and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the suite has aborted, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required by the run that has aborted * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunAborted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, throwable: Option[Throwable], duration: Option[Long], summary: Option[Summary], formatter: Option[Formatter] ): RunAborted = { RunAborted(ordinal, message, throwable, duration, summary, formatter, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunAborted</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the suite has aborted, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required by the run that has aborted * @param summary an optional summary of the number of tests that were reported as succeeded, failed, ignored, and pending * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunAborted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, throwable: Option[Throwable], duration: Option[Long], summary: Option[Summary] ): RunAborted = { RunAborted(ordinal, message, throwable, duration, summary, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunAborted</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the suite has aborted, * or a <code>Throwable</code> created to capture stack trace information about the problem. * @param duration an optional amount of time, in milliseconds, that was required by the run that has aborted * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunAborted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, throwable: Option[Throwable], duration: Option[Long] ): RunAborted = { RunAborted(ordinal, message, throwable, duration, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>RunAborted</code> event with the passed parameters, passing <code>None</code> for <code>duration</code>, * <code>None</code> for <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param throwable an optional <code>Throwable</code> that, if a <code>Some</code>, indicates why the suite has aborted, * or a <code>Throwable</code> created to capture stack trace information about the problem. * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>RunAborted</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, throwable: Option[Throwable] ): RunAborted = { RunAborted(ordinal, message, throwable, None, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } } /** * Deprecated singleton object for the <a href="InfoProvided.html"><code>InfoProvided</code></a> event, which contains overloaded factory methods * and an extractor method to facilitate pattern matching on <code>InfoProvided</code> objects. * This object contains methods that were in the <code>InfoProvided</code> companion object prior to ScalaTest 2.0. If you get a compiler error when upgrading * to 2.0 for one of the methods formerly in the companion object, a quick way to fix it is to put <code>Deprecated</code> in front of your call. * Eventually you will need to fix it properly, as this singleton object is deprecated and will be removed in a future version of ScalaTest, but * this will work as a quick fix to get you compiling again. * * <p> * All factory methods throw <code>NullPointerException</code> if any of the passed values are <code>null</code>. * </p> * * @author Bill Venners */ @deprecated("Use InfoProvided with named and/or default parameters instead.") object DeprecatedInfoProvided { /** * Constructs a new <code>InfoProvided</code> event with the passed parameters, passing the current thread's * name as <code>threadname</code> and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param nameInfo an optional <code>NameInfo</code> that if defined, provides names for the suite and optionally the test * in the context of which the information was provided * @param aboutAPendingTest indicates whether the information being provided via this event is about a pending test * @param throwable an optional <code>Throwable</code> * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * @param payload an optional object that can be used to pass custom information to the reporter about the <code>InfoProvided</code> event * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>InfoProvided</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, nameInfo: Option[NameInfo], aboutAPendingTest: Option[Boolean], throwable: Option[Throwable], formatter: Option[Formatter], payload: Option[Any] ): InfoProvided = { InfoProvided(ordinal, message, nameInfo, aboutAPendingTest, Some(false), throwable, formatter, None, payload, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>InfoProvided</code> event with the passed parameters, passing <code>None</code> as the * <code>payload</code>, the current threads name as <code>threadname</code>, * and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param nameInfo an optional <code>NameInfo</code> that if defined, provides names for the suite and optionally the test * in the context of which the information was provided * @param aboutAPendingTest indicates whether the information being provided via this event is about a pending test * @param throwable an optional <code>Throwable</code> * @param formatter an optional formatter that provides extra information that can be used by reporters in determining * how to present this event to the user * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>InfoProvided</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, nameInfo: Option[NameInfo], aboutAPendingTest: Option[Boolean], throwable: Option[Throwable], formatter: Option[Formatter] ): InfoProvided = { InfoProvided(ordinal, message, nameInfo, aboutAPendingTest, Some(false), throwable, formatter, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>InfoProvided</code> event with the passed parameters, passing <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param nameInfo an optional <code>NameInfo</code> that if defined, provides names for the suite and optionally the test * in the context of which the information was provided * @param aboutAPendingTest indicates whether the information being provided via this event is about a pending test * @param throwable an optional <code>Throwable</code> * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>InfoProvided</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, nameInfo: Option[NameInfo], aboutAPendingTest: Option[Boolean], throwable: Option[Throwable] ): InfoProvided = { InfoProvided(ordinal, message, nameInfo, aboutAPendingTest, Some(false), throwable, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>InfoProvided</code> event with the passed parameters, passing <code>None</code> for * the <code>throwable</code>, <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param nameInfo an optional <code>NameInfo</code> that if defined, provides names for the suite and optionally the test * in the context of which the information was provided * @param aboutAPendingTest indicates whether the information being provided via this event is about a pending test * @param throwable an optional <code>Throwable</code> * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>InfoProvided</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, nameInfo: Option[NameInfo], aboutAPendingTest: Option[Boolean] ): InfoProvided = { InfoProvided(ordinal, message, nameInfo, aboutAPendingTest, Some(false), None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } /** * Constructs a new <code>InfoProvided</code> event with the passed parameters, passing <code>None</code> for * the <code>throwable</code>, <code>None</code> for * <code>formatter</code>, <code>None</code> as the <code>payload</code>, * the current threads name as <code>threadname</code>, and the current time as <code>timeStamp</code>. * * @param ordinal an <code>Ordinal</code> that can be used to place this event in order in the context of * other events reported during the same run * @param message a localized message suitable for presenting to the user * @param nameInfo an optional <code>NameInfo</code> that if defined, provides names for the suite and optionally the test * in the context of which the information was provided * @param throwable an optional <code>Throwable</code> * * @throws NullPointerException if any of the passed values are <code>null</code> * * @return a new <code>InfoProvided</code> instance initialized with the passed and default values */ def apply( ordinal: Ordinal, message: String, nameInfo: Option[NameInfo] ): InfoProvided = { InfoProvided(ordinal, message, nameInfo, None, None, None, None, None, None, Thread.currentThread.getName, (new Date).getTime) } }
{ "content_hash": "169922fd510597f2ca2e8a1ff209656e", "timestamp": "", "source": "github", "line_count": 3378, "max_line_length": 234, "avg_line_length": 53.19034931912374, "alnum_prop": 0.7281288089182255, "repo_name": "epishkin/scalatest-google-code", "id": "86c521459e00ec0fd445765fb0025add507226ea", "size": "180277", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/org/scalatest/events/Event.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "18703" }, { "name": "Scala", "bytes": "6184744" }, { "name": "Shell", "bytes": "100" } ], "symlink_target": "" }
<HTML> <BODY BGCOLOR="white"> <PRE> <FONT color="green">001</FONT> <a name="line.17"></a> <FONT color="green">018</FONT> <a name="line.18"></a> <FONT color="green">019</FONT> package org.apache.commons.exec;<a name="line.19"></a> <FONT color="green">020</FONT> <a name="line.20"></a> <FONT color="green">021</FONT> import org.apache.commons.exec.util.DebugUtils;<a name="line.21"></a> <FONT color="green">022</FONT> <a name="line.22"></a> <FONT color="green">023</FONT> import java.io.IOException;<a name="line.23"></a> <FONT color="green">024</FONT> import java.io.InputStream;<a name="line.24"></a> <FONT color="green">025</FONT> import java.io.OutputStream;<a name="line.25"></a> <FONT color="green">026</FONT> <a name="line.26"></a> <FONT color="green">027</FONT> /**<a name="line.27"></a> <FONT color="green">028</FONT> * Copies standard output and error of subprocesses to standard output and error<a name="line.28"></a> <FONT color="green">029</FONT> * of the parent process. If output or error stream are set to null, any feedback<a name="line.29"></a> <FONT color="green">030</FONT> * from that stream will be lost. <a name="line.30"></a> <FONT color="green">031</FONT> */<a name="line.31"></a> <FONT color="green">032</FONT> public class PumpStreamHandler implements ExecuteStreamHandler {<a name="line.32"></a> <FONT color="green">033</FONT> <a name="line.33"></a> <FONT color="green">034</FONT> private Thread outputThread;<a name="line.34"></a> <FONT color="green">035</FONT> <a name="line.35"></a> <FONT color="green">036</FONT> private Thread errorThread;<a name="line.36"></a> <FONT color="green">037</FONT> <a name="line.37"></a> <FONT color="green">038</FONT> private Thread inputThread;<a name="line.38"></a> <FONT color="green">039</FONT> <a name="line.39"></a> <FONT color="green">040</FONT> private final OutputStream out;<a name="line.40"></a> <FONT color="green">041</FONT> <a name="line.41"></a> <FONT color="green">042</FONT> private final OutputStream err;<a name="line.42"></a> <FONT color="green">043</FONT> <a name="line.43"></a> <FONT color="green">044</FONT> private final InputStream input;<a name="line.44"></a> <FONT color="green">045</FONT> <a name="line.45"></a> <FONT color="green">046</FONT> private InputStreamPumper inputStreamPumper;<a name="line.46"></a> <FONT color="green">047</FONT> <a name="line.47"></a> <FONT color="green">048</FONT> /**<a name="line.48"></a> <FONT color="green">049</FONT> * Construct a new &lt;CODE&gt;PumpStreamHandler&lt;/CODE&gt;.<a name="line.49"></a> <FONT color="green">050</FONT> */<a name="line.50"></a> <FONT color="green">051</FONT> public PumpStreamHandler() {<a name="line.51"></a> <FONT color="green">052</FONT> this(System.out, System.err);<a name="line.52"></a> <FONT color="green">053</FONT> }<a name="line.53"></a> <FONT color="green">054</FONT> <a name="line.54"></a> <FONT color="green">055</FONT> /**<a name="line.55"></a> <FONT color="green">056</FONT> * Construct a new &lt;CODE&gt;PumpStreamHandler&lt;/CODE&gt;.<a name="line.56"></a> <FONT color="green">057</FONT> *<a name="line.57"></a> <FONT color="green">058</FONT> * @param outAndErr<a name="line.58"></a> <FONT color="green">059</FONT> * the output/error &lt;CODE&gt;OutputStream&lt;/CODE&gt;.<a name="line.59"></a> <FONT color="green">060</FONT> */<a name="line.60"></a> <FONT color="green">061</FONT> public PumpStreamHandler(final OutputStream outAndErr) {<a name="line.61"></a> <FONT color="green">062</FONT> this(outAndErr, outAndErr);<a name="line.62"></a> <FONT color="green">063</FONT> }<a name="line.63"></a> <FONT color="green">064</FONT> <a name="line.64"></a> <FONT color="green">065</FONT> /**<a name="line.65"></a> <FONT color="green">066</FONT> * Construct a new &lt;CODE&gt;PumpStreamHandler&lt;/CODE&gt;.<a name="line.66"></a> <FONT color="green">067</FONT> *<a name="line.67"></a> <FONT color="green">068</FONT> * @param out<a name="line.68"></a> <FONT color="green">069</FONT> * the output &lt;CODE&gt;OutputStream&lt;/CODE&gt;.<a name="line.69"></a> <FONT color="green">070</FONT> * @param err<a name="line.70"></a> <FONT color="green">071</FONT> * the error &lt;CODE&gt;OutputStream&lt;/CODE&gt;.<a name="line.71"></a> <FONT color="green">072</FONT> */<a name="line.72"></a> <FONT color="green">073</FONT> public PumpStreamHandler(final OutputStream out, final OutputStream err) {<a name="line.73"></a> <FONT color="green">074</FONT> this(out, err, null);<a name="line.74"></a> <FONT color="green">075</FONT> }<a name="line.75"></a> <FONT color="green">076</FONT> <a name="line.76"></a> <FONT color="green">077</FONT> /**<a name="line.77"></a> <FONT color="green">078</FONT> * Construct a new &lt;CODE&gt;PumpStreamHandler&lt;/CODE&gt;.<a name="line.78"></a> <FONT color="green">079</FONT> * <a name="line.79"></a> <FONT color="green">080</FONT> * @param out<a name="line.80"></a> <FONT color="green">081</FONT> * the output &lt;CODE&gt;OutputStream&lt;/CODE&gt;.<a name="line.81"></a> <FONT color="green">082</FONT> * @param err<a name="line.82"></a> <FONT color="green">083</FONT> * the error &lt;CODE&gt;OutputStream&lt;/CODE&gt;.<a name="line.83"></a> <FONT color="green">084</FONT> * @param input<a name="line.84"></a> <FONT color="green">085</FONT> * the input &lt;CODE&gt;InputStream&lt;/CODE&gt;.<a name="line.85"></a> <FONT color="green">086</FONT> */<a name="line.86"></a> <FONT color="green">087</FONT> public PumpStreamHandler(final OutputStream out, final OutputStream err,<a name="line.87"></a> <FONT color="green">088</FONT> final InputStream input) {<a name="line.88"></a> <FONT color="green">089</FONT> <a name="line.89"></a> <FONT color="green">090</FONT> this.out = out;<a name="line.90"></a> <FONT color="green">091</FONT> this.err = err;<a name="line.91"></a> <FONT color="green">092</FONT> this.input = input;<a name="line.92"></a> <FONT color="green">093</FONT> }<a name="line.93"></a> <FONT color="green">094</FONT> <a name="line.94"></a> <FONT color="green">095</FONT> /**<a name="line.95"></a> <FONT color="green">096</FONT> * Set the &lt;CODE&gt;InputStream&lt;/CODE&gt; from which to read the standard output<a name="line.96"></a> <FONT color="green">097</FONT> * of the process.<a name="line.97"></a> <FONT color="green">098</FONT> * <a name="line.98"></a> <FONT color="green">099</FONT> * @param is<a name="line.99"></a> <FONT color="green">100</FONT> * the &lt;CODE&gt;InputStream&lt;/CODE&gt;.<a name="line.100"></a> <FONT color="green">101</FONT> */<a name="line.101"></a> <FONT color="green">102</FONT> public void setProcessOutputStream(final InputStream is) {<a name="line.102"></a> <FONT color="green">103</FONT> if (out != null) {<a name="line.103"></a> <FONT color="green">104</FONT> createProcessOutputPump(is, out);<a name="line.104"></a> <FONT color="green">105</FONT> }<a name="line.105"></a> <FONT color="green">106</FONT> }<a name="line.106"></a> <FONT color="green">107</FONT> <a name="line.107"></a> <FONT color="green">108</FONT> /**<a name="line.108"></a> <FONT color="green">109</FONT> * Set the &lt;CODE&gt;InputStream&lt;/CODE&gt; from which to read the standard error<a name="line.109"></a> <FONT color="green">110</FONT> * of the process.<a name="line.110"></a> <FONT color="green">111</FONT> * <a name="line.111"></a> <FONT color="green">112</FONT> * @param is<a name="line.112"></a> <FONT color="green">113</FONT> * the &lt;CODE&gt;InputStream&lt;/CODE&gt;.<a name="line.113"></a> <FONT color="green">114</FONT> */<a name="line.114"></a> <FONT color="green">115</FONT> public void setProcessErrorStream(final InputStream is) {<a name="line.115"></a> <FONT color="green">116</FONT> if (err != null) {<a name="line.116"></a> <FONT color="green">117</FONT> createProcessErrorPump(is, err);<a name="line.117"></a> <FONT color="green">118</FONT> }<a name="line.118"></a> <FONT color="green">119</FONT> }<a name="line.119"></a> <FONT color="green">120</FONT> <a name="line.120"></a> <FONT color="green">121</FONT> /**<a name="line.121"></a> <FONT color="green">122</FONT> * Set the &lt;CODE&gt;OutputStream&lt;/CODE&gt; by means of which input can be sent<a name="line.122"></a> <FONT color="green">123</FONT> * to the process.<a name="line.123"></a> <FONT color="green">124</FONT> * <a name="line.124"></a> <FONT color="green">125</FONT> * @param os<a name="line.125"></a> <FONT color="green">126</FONT> * the &lt;CODE&gt;OutputStream&lt;/CODE&gt;.<a name="line.126"></a> <FONT color="green">127</FONT> */<a name="line.127"></a> <FONT color="green">128</FONT> public void setProcessInputStream(final OutputStream os) {<a name="line.128"></a> <FONT color="green">129</FONT> if (input != null) {<a name="line.129"></a> <FONT color="green">130</FONT> if (input == System.in) {<a name="line.130"></a> <FONT color="green">131</FONT> inputThread = createSystemInPump(input, os);<a name="line.131"></a> <FONT color="green">132</FONT> } else {<a name="line.132"></a> <FONT color="green">133</FONT> inputThread = createPump(input, os, true);<a name="line.133"></a> <FONT color="green">134</FONT> } } <a name="line.134"></a> <FONT color="green">135</FONT> else {<a name="line.135"></a> <FONT color="green">136</FONT> try {<a name="line.136"></a> <FONT color="green">137</FONT> os.close();<a name="line.137"></a> <FONT color="green">138</FONT> } catch (IOException e) {<a name="line.138"></a> <FONT color="green">139</FONT> String msg = "Got exception while closing output stream";<a name="line.139"></a> <FONT color="green">140</FONT> DebugUtils.handleException(msg ,e);<a name="line.140"></a> <FONT color="green">141</FONT> }<a name="line.141"></a> <FONT color="green">142</FONT> }<a name="line.142"></a> <FONT color="green">143</FONT> }<a name="line.143"></a> <FONT color="green">144</FONT> <a name="line.144"></a> <FONT color="green">145</FONT> /**<a name="line.145"></a> <FONT color="green">146</FONT> * Start the &lt;CODE&gt;Thread&lt;/CODE&gt;s.<a name="line.146"></a> <FONT color="green">147</FONT> */<a name="line.147"></a> <FONT color="green">148</FONT> public void start() {<a name="line.148"></a> <FONT color="green">149</FONT> if (outputThread != null) {<a name="line.149"></a> <FONT color="green">150</FONT> outputThread.start();<a name="line.150"></a> <FONT color="green">151</FONT> }<a name="line.151"></a> <FONT color="green">152</FONT> if (errorThread != null) {<a name="line.152"></a> <FONT color="green">153</FONT> errorThread.start();<a name="line.153"></a> <FONT color="green">154</FONT> }<a name="line.154"></a> <FONT color="green">155</FONT> if (inputThread != null) {<a name="line.155"></a> <FONT color="green">156</FONT> inputThread.start();<a name="line.156"></a> <FONT color="green">157</FONT> }<a name="line.157"></a> <FONT color="green">158</FONT> }<a name="line.158"></a> <FONT color="green">159</FONT> <a name="line.159"></a> <FONT color="green">160</FONT> /**<a name="line.160"></a> <FONT color="green">161</FONT> * Stop pumping the streams.<a name="line.161"></a> <FONT color="green">162</FONT> */<a name="line.162"></a> <FONT color="green">163</FONT> public void stop() {<a name="line.163"></a> <FONT color="green">164</FONT> <a name="line.164"></a> <FONT color="green">165</FONT> if (inputStreamPumper != null) {<a name="line.165"></a> <FONT color="green">166</FONT> inputStreamPumper.stopProcessing();<a name="line.166"></a> <FONT color="green">167</FONT> }<a name="line.167"></a> <FONT color="green">168</FONT> <a name="line.168"></a> <FONT color="green">169</FONT> if (outputThread != null) {<a name="line.169"></a> <FONT color="green">170</FONT> try {<a name="line.170"></a> <FONT color="green">171</FONT> outputThread.join();<a name="line.171"></a> <FONT color="green">172</FONT> outputThread = null;<a name="line.172"></a> <FONT color="green">173</FONT> } catch (InterruptedException e) {<a name="line.173"></a> <FONT color="green">174</FONT> // ignore<a name="line.174"></a> <FONT color="green">175</FONT> }<a name="line.175"></a> <FONT color="green">176</FONT> }<a name="line.176"></a> <FONT color="green">177</FONT> <a name="line.177"></a> <FONT color="green">178</FONT> if (errorThread != null) {<a name="line.178"></a> <FONT color="green">179</FONT> try {<a name="line.179"></a> <FONT color="green">180</FONT> errorThread.join();<a name="line.180"></a> <FONT color="green">181</FONT> errorThread = null;<a name="line.181"></a> <FONT color="green">182</FONT> } catch (InterruptedException e) {<a name="line.182"></a> <FONT color="green">183</FONT> // ignore<a name="line.183"></a> <FONT color="green">184</FONT> }<a name="line.184"></a> <FONT color="green">185</FONT> }<a name="line.185"></a> <FONT color="green">186</FONT> <a name="line.186"></a> <FONT color="green">187</FONT> if (inputThread != null) {<a name="line.187"></a> <FONT color="green">188</FONT> try {<a name="line.188"></a> <FONT color="green">189</FONT> inputThread.join();<a name="line.189"></a> <FONT color="green">190</FONT> inputThread = null;<a name="line.190"></a> <FONT color="green">191</FONT> } catch (InterruptedException e) {<a name="line.191"></a> <FONT color="green">192</FONT> // ignore<a name="line.192"></a> <FONT color="green">193</FONT> }<a name="line.193"></a> <FONT color="green">194</FONT> }<a name="line.194"></a> <FONT color="green">195</FONT> <a name="line.195"></a> <FONT color="green">196</FONT> if (err != null &amp;&amp; err != out) {<a name="line.196"></a> <FONT color="green">197</FONT> try {<a name="line.197"></a> <FONT color="green">198</FONT> err.flush();<a name="line.198"></a> <FONT color="green">199</FONT> } catch (IOException e) {<a name="line.199"></a> <FONT color="green">200</FONT> String msg = "Got exception while flushing the error stream : " + e.getMessage();<a name="line.200"></a> <FONT color="green">201</FONT> DebugUtils.handleException(msg ,e);<a name="line.201"></a> <FONT color="green">202</FONT> }<a name="line.202"></a> <FONT color="green">203</FONT> }<a name="line.203"></a> <FONT color="green">204</FONT> <a name="line.204"></a> <FONT color="green">205</FONT> if (out != null) {<a name="line.205"></a> <FONT color="green">206</FONT> try {<a name="line.206"></a> <FONT color="green">207</FONT> out.flush();<a name="line.207"></a> <FONT color="green">208</FONT> } catch (IOException e) {<a name="line.208"></a> <FONT color="green">209</FONT> String msg = "Got exception while flushing the output stream";<a name="line.209"></a> <FONT color="green">210</FONT> DebugUtils.handleException(msg ,e);<a name="line.210"></a> <FONT color="green">211</FONT> }<a name="line.211"></a> <FONT color="green">212</FONT> }<a name="line.212"></a> <FONT color="green">213</FONT> }<a name="line.213"></a> <FONT color="green">214</FONT> <a name="line.214"></a> <FONT color="green">215</FONT> /**<a name="line.215"></a> <FONT color="green">216</FONT> * Get the error stream.<a name="line.216"></a> <FONT color="green">217</FONT> * <a name="line.217"></a> <FONT color="green">218</FONT> * @return &lt;CODE&gt;OutputStream&lt;/CODE&gt;.<a name="line.218"></a> <FONT color="green">219</FONT> */<a name="line.219"></a> <FONT color="green">220</FONT> protected OutputStream getErr() {<a name="line.220"></a> <FONT color="green">221</FONT> return err;<a name="line.221"></a> <FONT color="green">222</FONT> }<a name="line.222"></a> <FONT color="green">223</FONT> <a name="line.223"></a> <FONT color="green">224</FONT> /**<a name="line.224"></a> <FONT color="green">225</FONT> * Get the output stream.<a name="line.225"></a> <FONT color="green">226</FONT> * <a name="line.226"></a> <FONT color="green">227</FONT> * @return &lt;CODE&gt;OutputStream&lt;/CODE&gt;.<a name="line.227"></a> <FONT color="green">228</FONT> */<a name="line.228"></a> <FONT color="green">229</FONT> protected OutputStream getOut() {<a name="line.229"></a> <FONT color="green">230</FONT> return out;<a name="line.230"></a> <FONT color="green">231</FONT> }<a name="line.231"></a> <FONT color="green">232</FONT> <a name="line.232"></a> <FONT color="green">233</FONT> /**<a name="line.233"></a> <FONT color="green">234</FONT> * Create the pump to handle process output.<a name="line.234"></a> <FONT color="green">235</FONT> * <a name="line.235"></a> <FONT color="green">236</FONT> * @param is<a name="line.236"></a> <FONT color="green">237</FONT> * the &lt;CODE&gt;InputStream&lt;/CODE&gt;.<a name="line.237"></a> <FONT color="green">238</FONT> * @param os<a name="line.238"></a> <FONT color="green">239</FONT> * the &lt;CODE&gt;OutputStream&lt;/CODE&gt;.<a name="line.239"></a> <FONT color="green">240</FONT> */<a name="line.240"></a> <FONT color="green">241</FONT> protected void createProcessOutputPump(final InputStream is,<a name="line.241"></a> <FONT color="green">242</FONT> final OutputStream os) {<a name="line.242"></a> <FONT color="green">243</FONT> outputThread = createPump(is, os);<a name="line.243"></a> <FONT color="green">244</FONT> }<a name="line.244"></a> <FONT color="green">245</FONT> <a name="line.245"></a> <FONT color="green">246</FONT> /**<a name="line.246"></a> <FONT color="green">247</FONT> * Create the pump to handle error output.<a name="line.247"></a> <FONT color="green">248</FONT> * <a name="line.248"></a> <FONT color="green">249</FONT> * @param is<a name="line.249"></a> <FONT color="green">250</FONT> * the &lt;CODE&gt;InputStream&lt;/CODE&gt;.<a name="line.250"></a> <FONT color="green">251</FONT> * @param os<a name="line.251"></a> <FONT color="green">252</FONT> * the &lt;CODE&gt;OutputStream&lt;/CODE&gt;.<a name="line.252"></a> <FONT color="green">253</FONT> */<a name="line.253"></a> <FONT color="green">254</FONT> protected void createProcessErrorPump(final InputStream is,<a name="line.254"></a> <FONT color="green">255</FONT> final OutputStream os) {<a name="line.255"></a> <FONT color="green">256</FONT> errorThread = createPump(is, os);<a name="line.256"></a> <FONT color="green">257</FONT> }<a name="line.257"></a> <FONT color="green">258</FONT> <a name="line.258"></a> <FONT color="green">259</FONT> /**<a name="line.259"></a> <FONT color="green">260</FONT> * Creates a stream pumper to copy the given input stream to the given<a name="line.260"></a> <FONT color="green">261</FONT> * output stream.<a name="line.261"></a> <FONT color="green">262</FONT> *<a name="line.262"></a> <FONT color="green">263</FONT> * @param is the input stream to copy from<a name="line.263"></a> <FONT color="green">264</FONT> * @param os the output stream to copy into<a name="line.264"></a> <FONT color="green">265</FONT> * @return the stream pumper thread<a name="line.265"></a> <FONT color="green">266</FONT> */<a name="line.266"></a> <FONT color="green">267</FONT> protected Thread createPump(final InputStream is, final OutputStream os) {<a name="line.267"></a> <FONT color="green">268</FONT> return createPump(is, os, false);<a name="line.268"></a> <FONT color="green">269</FONT> }<a name="line.269"></a> <FONT color="green">270</FONT> <a name="line.270"></a> <FONT color="green">271</FONT> /**<a name="line.271"></a> <FONT color="green">272</FONT> * Creates a stream pumper to copy the given input stream to the given<a name="line.272"></a> <FONT color="green">273</FONT> * output stream.<a name="line.273"></a> <FONT color="green">274</FONT> *<a name="line.274"></a> <FONT color="green">275</FONT> * @param is the input stream to copy from<a name="line.275"></a> <FONT color="green">276</FONT> * @param os the output stream to copy into<a name="line.276"></a> <FONT color="green">277</FONT> * @param closeWhenExhausted close the output stream when the input stream is exhausted<a name="line.277"></a> <FONT color="green">278</FONT> * @return the stream pumper thread<a name="line.278"></a> <FONT color="green">279</FONT> */<a name="line.279"></a> <FONT color="green">280</FONT> protected Thread createPump(final InputStream is, final OutputStream os,<a name="line.280"></a> <FONT color="green">281</FONT> final boolean closeWhenExhausted) {<a name="line.281"></a> <FONT color="green">282</FONT> final Thread result = new Thread(new StreamPumper(is, os,<a name="line.282"></a> <FONT color="green">283</FONT> closeWhenExhausted));<a name="line.283"></a> <FONT color="green">284</FONT> result.setDaemon(true);<a name="line.284"></a> <FONT color="green">285</FONT> return result;<a name="line.285"></a> <FONT color="green">286</FONT> }<a name="line.286"></a> <FONT color="green">287</FONT> <a name="line.287"></a> <FONT color="green">288</FONT> <a name="line.288"></a> <FONT color="green">289</FONT> /**<a name="line.289"></a> <FONT color="green">290</FONT> * Creates a stream pumper to copy the given input stream to the given<a name="line.290"></a> <FONT color="green">291</FONT> * output stream.<a name="line.291"></a> <FONT color="green">292</FONT> *<a name="line.292"></a> <FONT color="green">293</FONT> * @param is the System.in input stream to copy from<a name="line.293"></a> <FONT color="green">294</FONT> * @param os the output stream to copy into<a name="line.294"></a> <FONT color="green">295</FONT> * @return the stream pumper thread<a name="line.295"></a> <FONT color="green">296</FONT> */<a name="line.296"></a> <FONT color="green">297</FONT> private Thread createSystemInPump(InputStream is, OutputStream os) {<a name="line.297"></a> <FONT color="green">298</FONT> inputStreamPumper = new InputStreamPumper(is, os);<a name="line.298"></a> <FONT color="green">299</FONT> final Thread result = new Thread(inputStreamPumper);<a name="line.299"></a> <FONT color="green">300</FONT> result.setDaemon(true);<a name="line.300"></a> <FONT color="green">301</FONT> return result;<a name="line.301"></a> <FONT color="green">302</FONT> }<a name="line.302"></a> <FONT color="green">303</FONT> <a name="line.303"></a> <FONT color="green">304</FONT> }<a name="line.304"></a> </PRE> </BODY> </HTML>
{ "content_hash": "71412e85bd4c11344e80a9ce061108b1", "timestamp": "", "source": "github", "line_count": 354, "max_line_length": 155, "avg_line_length": 69.12994350282486, "alnum_prop": 0.5780075187969925, "repo_name": "dunarel/dunphd-thesis", "id": "6227ea05ba087f31f0d4a5b607f772452bce9da4", "size": "26175", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Chapter4/Supplementary/proc-hom-ex/lib/commons-exec-1.1/apidocs/src-html/org/apache/commons/exec/PumpStreamHandler.html", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "1445" }, { "name": "C", "bytes": "28637" }, { "name": "C++", "bytes": "2109180" }, { "name": "CMake", "bytes": "3746" }, { "name": "CSS", "bytes": "4559" }, { "name": "CoffeeScript", "bytes": "458" }, { "name": "Cuda", "bytes": "181" }, { "name": "Gnuplot", "bytes": "378696" }, { "name": "HTML", "bytes": "4640709" }, { "name": "Java", "bytes": "569697" }, { "name": "JavaScript", "bytes": "641" }, { "name": "Makefile", "bytes": "122509" }, { "name": "Perl", "bytes": "627207" }, { "name": "Python", "bytes": "5789" }, { "name": "R", "bytes": "181791" }, { "name": "Ruby", "bytes": "1426161" }, { "name": "SQLPL", "bytes": "7302" }, { "name": "Shell", "bytes": "107908" }, { "name": "TeX", "bytes": "9788" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using TrueSync.Physics2D; using FP = TrueSync.FP; namespace TrueSync.Physics2D { /// <summary> /// Put a limit on the linear (translation - the movespeed) and angular (rotation) velocity /// of bodies added to this controller. /// </summary> public class VelocityLimitController : Controller { public bool LimitAngularVelocity = true; public bool LimitLinearVelocity = true; private List<Body> _bodies = new List<Body>(); private FP _maxAngularSqared; private FP _maxAngularVelocity; private FP _maxLinearSqared; private FP _maxLinearVelocity; /// <summary> /// Initializes a new instance of the <see cref="VelocityLimitController"/> class. /// Sets the max linear velocity to Settings.MaxTranslation /// Sets the max angular velocity to Settings.MaxRotation /// </summary> public VelocityLimitController() : base(ControllerType.VelocityLimitController) { MaxLinearVelocity = Settings.MaxTranslation; MaxAngularVelocity = Settings.MaxRotation; } /// <summary> /// Initializes a new instance of the <see cref="VelocityLimitController"/> class. /// Pass in 0 or FP.MaxValue to disable the limit. /// maxAngularVelocity = 0 will disable the angular velocity limit. /// </summary> /// <param name="maxLinearVelocity">The max linear velocity.</param> /// <param name="maxAngularVelocity">The max angular velocity.</param> public VelocityLimitController(FP maxLinearVelocity, FP maxAngularVelocity) : base(ControllerType.VelocityLimitController) { if (maxLinearVelocity == 0 || maxLinearVelocity == FP.MaxValue) LimitLinearVelocity = false; if (maxAngularVelocity == 0 || maxAngularVelocity == FP.MaxValue) LimitAngularVelocity = false; MaxLinearVelocity = maxLinearVelocity; MaxAngularVelocity = maxAngularVelocity; } /// <summary> /// Gets or sets the max angular velocity. /// </summary> /// <value>The max angular velocity.</value> public FP MaxAngularVelocity { get { return _maxAngularVelocity; } set { _maxAngularVelocity = value; _maxAngularSqared = _maxAngularVelocity * _maxAngularVelocity; } } /// <summary> /// Gets or sets the max linear velocity. /// </summary> /// <value>The max linear velocity.</value> public FP MaxLinearVelocity { get { return _maxLinearVelocity; } set { _maxLinearVelocity = value; _maxLinearSqared = _maxLinearVelocity * _maxLinearVelocity; } } public override void Update(FP dt) { foreach (Body body in _bodies) { if (!IsActiveOn(body)) continue; if (LimitLinearVelocity) { //Translation // Check for large velocities. FP translationX = dt * body._linearVelocity.x; FP translationY = dt * body._linearVelocity.y; FP result = translationX * translationX + translationY * translationY; if (result > dt * _maxLinearSqared) { FP sq = FP.Sqrt(result); FP ratio = _maxLinearVelocity / sq; body._linearVelocity.x *= ratio; body._linearVelocity.y *= ratio; } } if (LimitAngularVelocity) { //Rotation FP rotation = dt * body._angularVelocity; if (rotation * rotation > _maxAngularSqared) { FP ratio = _maxAngularVelocity / FP.Abs(rotation); body._angularVelocity *= ratio; } } } } public void AddBody(Body body) { _bodies.Add(body); } public void RemoveBody(Body body) { _bodies.Remove(body); } } }
{ "content_hash": "50da4aaaf550e8b65f1112a08bdd2641", "timestamp": "", "source": "github", "line_count": 130, "max_line_length": 95, "avg_line_length": 34.46923076923077, "alnum_prop": 0.5331399241240794, "repo_name": "Xaer033/YellowSign", "id": "08eb9425dfe4b99d9de6c798977d3f23c3431211", "size": "4483", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "YellowSignUnity/Assets/ThirdParty/Networking/TrueSync/Physics/Farseer/Controllers/VelocityLimitController.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "15347196" }, { "name": "HLSL", "bytes": "2893" }, { "name": "HTML", "bytes": "161990" }, { "name": "ShaderLab", "bytes": "4810" }, { "name": "Smalltalk", "bytes": "148037" } ], "symlink_target": "" }
/** * Generated with Acceleo */ package org.wso2.developerstudio.eclipse.gmf.esb.parts; // Start of user code for imports // End of user code /** * * */ public interface EntitlementOnAcceptContainerPropertiesEditionPart { /** * Returns the internationalized title text. * * @return the internationalized title text. * */ public String getTitle(); // Start of user code for additional methods // End of user code }
{ "content_hash": "b5308dae59d54e31b45db9eca9244734", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 68, "avg_line_length": 13.636363636363637, "alnum_prop": 0.6844444444444444, "repo_name": "wso2/devstudio-tooling-esb", "id": "119dc600cb62a955ced30632b143e6a82b4072fd", "size": "450", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "plugins/org.wso2.developerstudio.eclipse.gmf.esb.edit/src-gen/org/wso2/developerstudio/eclipse/gmf/esb/parts/EntitlementOnAcceptContainerPropertiesEditionPart.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "41098" }, { "name": "HTML", "bytes": "731356" }, { "name": "Java", "bytes": "77354104" }, { "name": "JavaScript", "bytes": "475592" }, { "name": "Shell", "bytes": "7727" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "167476fde47ca646ffcb1d2b78d14b3e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "cd19fe9b90e882ef91f14fcbd989f59a4d122488", "size": "192", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Bryophyta/Bryopsida/Bryales/Bartramiaceae/Breutelia/Breutelia aristifolia/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package ar.com.javacuriosities.algorithms.disjointset.v1; import java.util.Arrays; /* * Esta es la version mas simple de DisjointSet que podemos obtener * Dos mejoras típicas son: * * PathCompression * Union by Rank */ public class DisjointSet { private int[] parent; public DisjointSet(int numberOfElements) { parent = new int[numberOfElements]; for (int i = 0; i < numberOfElements; i++) { parent[i] = i; } } public int find(int x) { if (parent[x] == x) { return x; } else { return find(parent[x]); } } public void union(int x, int y) { parent[find(x)] = find(y); } @Override public String toString() { return Arrays.toString(parent); } }
{ "content_hash": "1b94eae75d5ca031a891b1abadbb515e", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 67, "avg_line_length": 20.358974358974358, "alnum_prop": 0.5717884130982368, "repo_name": "ldebello/algorithms", "id": "93c96a9a3e82eb2456a8ab2244101873c75c21ce", "size": "795", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DisjointSet/src/ar/com/javacuriosities/algorithms/disjointset/v1/DisjointSet.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "56418" } ], "symlink_target": "" }
using System; using System.Threading; using Hyena; using DBus; using org.freedesktop.DBus; using Banshee.Collection.Indexer; namespace Banshee.Collection.Indexer.RemoteHelper { public abstract class IndexerClient { private const string application_bus_name = "org.bansheeproject.Banshee"; private const string indexer_bus_name = "org.bansheeproject.CollectionIndexer"; private const string service_interface = "org.bansheeproject.CollectionIndexer.Service"; private static ObjectPath service_path = new ObjectPath ("/org/bansheeproject/Banshee/CollectionIndexerService"); private IBus session_bus; private bool listening; private ICollectionIndexerService service; private bool cleanup_and_shutdown; private bool index_when_collection_changed = true; public void Start () { ShowDebugMessages = true; Debug ("Acquiring org.freedesktop.DBus session instance"); session_bus = Bus.Session.GetObject<IBus> ("org.freedesktop.DBus", new ObjectPath ("/org/freedesktop/DBus")); session_bus.NameOwnerChanged += OnBusNameOwnerChanged; if (Bus.Session.NameHasOwner (indexer_bus_name)) { Debug ("{0} is already started", indexer_bus_name); ConnectToIndexerService (); } else { Debug ("Starting {0}", indexer_bus_name); Bus.Session.StartServiceByName (indexer_bus_name); } } private void OnBusNameOwnerChanged (string name, string oldOwner, string newOwner) { if (name == indexer_bus_name) { Debug ("NameOwnerChanged: {0}, '{1}' => '{2}'", name, oldOwner, newOwner); if (service == null && !String.IsNullOrEmpty (newOwner)) { ConnectToIndexerService (); } } } private void Index () { if (HasCollectionChanged) { ICollectionIndexer indexer = CreateIndexer (); indexer.IndexingFinished += delegate { _UpdateIndex (indexer); }; indexer.Index (); } } private void _UpdateIndex (ICollectionIndexer indexer) { ThreadPool.QueueUserWorkItem (delegate { Debug ("Running indexer"); try { UpdateIndex (indexer); } catch (Exception e) { Console.Error.WriteLine (e); } Debug ("Indexer finished"); indexer.Dispose (); if (!ApplicationAvailable || !listening) { DisconnectFromIndexerService (); } }); } private void ConnectToIndexerService () { DisconnectFromIndexerService (); ResolveIndexerService (); if (service == null) { Log.Error ("Failed to connect to {0}, bailing.", service_interface); return; } else { Debug ("Connected to {0}", service_interface); } service.CleanupAndShutdown += OnCleanupAndShutdown; if (ApplicationAvailable) { Debug ("Listening to service's CollectionChanged signal (full-app is running)"); listening = true; service.CollectionChanged += OnCollectionChanged; } Index (); } private void DisconnectFromIndexerService () { if (service == null) { return; } Debug ("Disconnecting from service"); if (listening) { try { listening = false; service.CollectionChanged -= OnCollectionChanged; } catch (Exception e) { Debug (e.ToString ()); } } try { service.CleanupAndShutdown -= OnCleanupAndShutdown; } catch (Exception e) { Debug (e.ToString ()); } try { service.Shutdown (); } catch (Exception e) { Debug (e.ToString ()); } ResetInternalState (); } private void ResetInternalState () { if (service == null) { return; } Debug ("Resetting internal state - service is no longer available or not needed"); service = null; listening = false; cleanup_and_shutdown = false; ResetState (); } private void ResolveIndexerService () { int attempts = 0; while (attempts++ < 4) { try { Debug ("Resolving {0} (attempt {1})", service_interface, attempts); service = Bus.Session.GetObject<ICollectionIndexerService> (indexer_bus_name, service_path); service.Hello (); return; } catch { service = null; System.Threading.Thread.Sleep (2000); } } } private void OnCollectionChanged () { if (IndexWhenCollectionChanged) { Index (); } } private void OnCleanupAndShutdown () { cleanup_and_shutdown = true; } protected void Debug (string message, params object [] args) { Log.DebugFormat (message, args); } protected abstract bool HasCollectionChanged { get; } protected abstract void UpdateIndex (ICollectionIndexer indexer); protected abstract void ResetState (); protected ICollectionIndexer CreateIndexer () { ObjectPath object_path = service.CreateIndexer (); Debug ("Creating an ICollectionIndexer ({0})", object_path); return Bus.Session.GetObject<ICollectionIndexer> (indexer_bus_name, object_path); } public bool ShowDebugMessages { get { return Log.Debugging; } set { Log.Debugging = value; } } protected bool CleanupAndShutdown { get { return cleanup_and_shutdown; } } public bool IndexWhenCollectionChanged { get { return index_when_collection_changed; } set { index_when_collection_changed = value; } } protected ICollectionIndexerService Service { get { return service; } } protected bool ApplicationAvailable { get { return Bus.Session.NameHasOwner (application_bus_name); } } } }
{ "content_hash": "bdede0886ebc547636034aeb64d532b8", "timestamp": "", "source": "github", "line_count": 220, "max_line_length": 121, "avg_line_length": 31.068181818181817, "alnum_prop": 0.5268471104608632, "repo_name": "dufoli/banshee", "id": "e880b6a700af136b87edfeadc5c2c9b4471767d3", "size": "8035", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "src/Core/Banshee.CollectionIndexer/Banshee.Collection.Indexer.RemoteHelper/IndexerClient.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Boo", "bytes": "3305" }, { "name": "C", "bytes": "208038" }, { "name": "C#", "bytes": "5858734" }, { "name": "C++", "bytes": "21486" }, { "name": "JavaScript", "bytes": "7855" }, { "name": "Perl", "bytes": "6386" }, { "name": "Python", "bytes": "6954" }, { "name": "R", "bytes": "3362" }, { "name": "Shell", "bytes": "59777" } ], "symlink_target": "" }
namespace open_spiel { std::vector<double> EvaluateBots(State* state, const std::vector<Bot*>& bots, int seed) { const int num_players = bots.size(); std::mt19937 rng(seed); std::vector<Action> joint_actions(bots.size()); if (state->History().empty()) { for (auto bot : bots) bot->Restart(); } else { for (auto bot : bots) bot->RestartAt(*state); } while (!state->IsTerminal()) { if (state->IsChanceNode()) { Action action = SampleAction(state->ChanceOutcomes(), rng).first; for (auto bot : bots) bot->InformAction(*state, kChancePlayerId, action); state->ApplyAction(action); } else if (state->IsSimultaneousNode()) { for (Player p = 0; p < num_players; ++p) { if (state->LegalActions(p).empty()) { joint_actions[p] = kInvalidAction; } else { joint_actions[p] = bots[p]->Step(*state); } } state->ApplyActions(joint_actions); } else { Player current_player = state->CurrentPlayer(); Action action = bots[current_player]->Step(*state); for (Player p = 0; p < num_players; ++p) { if (p != current_player) { bots[p]->InformAction(*state, current_player, action); } } state->ApplyAction(action); } } // Return terminal utility. return state->Returns(); } std::vector<double> EvaluateBots(const Game& game, const std::vector<Bot*>& bots, int seed) { std::unique_ptr<State> state = game.NewInitialState(); return EvaluateBots(state.get(), bots, seed); } std::vector<double> EvaluateBots(const Game& game, const std::vector<Bot*>& bots) { absl::Duration time_gap = absl::Now() - absl::UnixEpoch(); std::mt19937 rng(absl::ToInt64Nanoseconds(time_gap)); const int seed = absl::Uniform<int>(rng, std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); return EvaluateBots(game, bots, seed); } } // namespace open_spiel
{ "content_hash": "87fc541ad9b041bc62c9bfb3a82d91b1", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 79, "avg_line_length": 35.43103448275862, "alnum_prop": 0.5819951338199514, "repo_name": "deepmind/open_spiel", "id": "f8ffba5b6c13499d1f7466e9719ac072663c4c94", "size": "2945", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "open_spiel/algorithms/evaluate_bots.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "6640" }, { "name": "C++", "bytes": "4649139" }, { "name": "CMake", "bytes": "78467" }, { "name": "Go", "bytes": "18010" }, { "name": "Julia", "bytes": "16727" }, { "name": "Jupyter Notebook", "bytes": "148663" }, { "name": "Python", "bytes": "2823600" }, { "name": "Rust", "bytes": "18562" }, { "name": "Shell", "bytes": "51087" } ], "symlink_target": "" }
#!/usr/bin/env bash # # # # Runs a Hadoop hbase command as a daemon. # # Environment Variables # # HBASE_CONF_DIR Alternate hbase conf dir. Default is ${HBASE_HOME}/conf. # HBASE_LOG_DIR Where log files are stored. PWD by default. # HBASE_PID_DIR The pid files are stored. /tmp by default. # HBASE_IDENT_STRING A string representing this instance of hadoop. $USER by default # HBASE_NICENESS The scheduling priority for daemons. Defaults to 0. # # Modelled after $HADOOP_HOME/bin/hadoop-daemon.sh usage="Usage: hbase-daemon.sh [--config <conf-dir>]\ (start|stop) <hbase-command> \ <args...>" # if no args specified, show usage if [ $# -le 1 ]; then echo $usage exit 1 fi bin=`dirname "$0"` bin=`cd "$bin"; pwd` . "$bin"/hbase-config.sh # get arguments startStop=$1 shift command=$1 shift hbase_rotate_log () { log=$1; num=5; if [ -n "$2" ]; then num=$2 fi if [ -f "$log" ]; then # rotate logs while [ $num -gt 1 ]; do prev=`expr $num - 1` [ -f "$log.$prev" ] && mv "$log.$prev" "$log.$num" num=$prev done mv "$log" "$log.$num"; fi } if [ -f "${HBASE_CONF_DIR}/hbase-env.sh" ]; then . "${HBASE_CONF_DIR}/hbase-env.sh" fi # get log directory if [ "$HBASE_LOG_DIR" = "" ]; then export HBASE_LOG_DIR="$HBASE_HOME/logs" fi mkdir -p "$HBASE_LOG_DIR" if [ "$HBASE_PID_DIR" = "" ]; then HBASE_PID_DIR=/tmp fi if [ "$HBASE_IDENT_STRING" = "" ]; then export HBASE_IDENT_STRING="$USER" fi # Some variables # Work out java location so can print version into log. if [ "$JAVA_HOME" != "" ]; then #echo "run java in $JAVA_HOME" JAVA_HOME=$JAVA_HOME fi if [ "$JAVA_HOME" = "" ]; then echo "Error: JAVA_HOME is not set." exit 1 fi JAVA=$JAVA_HOME/bin/java export HBASE_LOGFILE=hbase-$HBASE_IDENT_STRING-$command-$HOSTNAME.log export HBASE_ROOT_LOGGER="INFO,DRFA" logout=$HBASE_LOG_DIR/hbase-$HBASE_IDENT_STRING-$command-$HOSTNAME.out loglog="${HBASE_LOG_DIR}/${HBASE_LOGFILE}" pid=$HBASE_PID_DIR/hbase-$HBASE_IDENT_STRING-$command.pid # Set default scheduling priority if [ "$HBASE_NICENESS" = "" ]; then export HBASE_NICENESS=0 fi case $startStop in (start) mkdir -p "$HBASE_PID_DIR" if [ -f $pid ]; then if kill -0 `cat $pid` > /dev/null 2>&1; then echo $command running as process `cat $pid`. Stop it first. exit 1 fi fi hbase_rotate_log $logout echo starting $command, logging to $logout # Add to the command log file vital stats on our environment. echo "`date` Starting $command on `hostname`" >> $loglog echo "ulimit -n `ulimit -n`" >> $loglog 2>&1 nohup nice -n $HBASE_NICENESS "$HBASE_HOME"/bin/hbase \ --config "${HBASE_CONF_DIR}" \ $command $startStop "$@" > "$logout" 2>&1 < /dev/null & echo $! > $pid sleep 1; head "$logout" ;; (stop) if [ -f $pid ]; then if kill -0 `cat $pid` > /dev/null 2>&1; then echo -n stopping $command echo "`date` Stopping $command" >> $loglog if [ "$command" = "master" ]; then nohup nice -n $HBASE_NICENESS "$HBASE_HOME"/bin/hbase \ --config "${HBASE_CONF_DIR}" \ $command $startStop "$@" > "$logout" 2>&1 < /dev/null & else echo "`date` Killing $command" >> $loglog kill `cat $pid` > /dev/null 2>&1 fi while kill -0 `cat $pid` > /dev/null 2>&1; do echo -n "." sleep 1; done echo else retval=$? echo no $command to stop because kill of pid `cat $pid` failed with status $retval fi else echo no $command to stop because no pid file $pid fi ;; (*) echo $usage exit 1 ;; esac
{ "content_hash": "04afc3a9c424934ffcac475e0c0cd024", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 90, "avg_line_length": 24.7682119205298, "alnum_prop": 0.5890374331550802, "repo_name": "adragomir/hbaseindex", "id": "f7be654de0bd223cb63683066a48b8235165f3d3", "size": "4616", "binary": false, "copies": "1", "ref": "refs/heads/trunk", "path": "bin/hbase-daemon.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "9334" }, { "name": "Java", "bytes": "4746474" }, { "name": "JavaScript", "bytes": "17630" }, { "name": "PHP", "bytes": "7341" }, { "name": "Python", "bytes": "207735" }, { "name": "Ruby", "bytes": "58002" }, { "name": "Shell", "bytes": "21036" } ], "symlink_target": "" }
package main import ( "flag" "fmt" "os" "github.com/davyxu/gosproto/meta" ) var paramGoOut = flag.String("go_out", "", "golang output filename") var paramLuaOut = flag.String("lua_out", "", "lua output filename") var paramCSOut = flag.String("cs_out", "", "csharp output filename") var paramJavaOut = flag.String("java_out", "", "java output filename") var paramSprotoOut = flag.String("sproto_out", "", "standard sproto output filename") var paramPackage = flag.String("package", "", "package name in go files") var paramCellnetReg = flag.Bool("cellnet_reg", false, "for type go, generate sproto auto register entry for github.com/davyxu/cellnet") //var paramForceAutoTag = flag.Bool("forceatag", false, "no ouput field tag in sp mode") var paramCSClassAttr = flag.String("cs_classattr", "", "add given string to class header as attribute in c sharp file") var paramCSFieldAttr = flag.String("cs_fieldattr", "", "add given string to class private field as attribute in c sharp file") var paramVersion = flag.Bool("version", false, "Show version") var paramEnumValueGroup = flag.Bool("enumvalgroup", false, "enum value into group") func mergeSchema(filelist []string) *meta.FileDescriptorSet { if len(filelist) == 0 { fmt.Println("require sproto file") os.Exit(1) } fileSet := meta.NewFileDescriptorSet() errorFileName, err := meta.ParseFileList(fileSet, filelist) if err != nil { fmt.Println(errorFileName, err.Error()) os.Exit(1) } return fileSet } const Version = "0.1.0" func genFile(fileset *meta.FileDescriptorSet, generator func(*fileModel, string), filename string) { fm := &fileModel{ FileDescriptorSet: fileset, PackageName: *paramPackage, CellnetReg: *paramCellnetReg, CSClassAttr: *paramCSClassAttr, CSFieldAttr: *paramCSFieldAttr, EnumValueGroup: *paramEnumValueGroup, } if *paramEnumValueGroup { enumValueGroup(fm) } generator(fm, filename) } func main() { flag.Parse() // 版本 if *paramVersion { fmt.Println(Version) return } fileset := mergeSchema(flag.Args()) if *paramGoOut != "" { genFile(fileset, gen_go, *paramGoOut) } if *paramLuaOut != "" { genFile(fileset, gen_lua, *paramLuaOut) } if *paramCSOut != "" { genFile(fileset, gen_csharp, *paramCSOut) } if *paramSprotoOut != "" { genFile(fileset, gen_sproto, *paramSprotoOut) } if *paramJavaOut != "" { genFile(fileset, gen_java, *paramJavaOut) } }
{ "content_hash": "acb4b64430a3e4be000a91c4fa6ab6b5", "timestamp": "", "source": "github", "line_count": 96, "max_line_length": 135, "avg_line_length": 25.385416666666668, "alnum_prop": 0.6975789905621665, "repo_name": "uin57/sproto-java", "id": "5567f2d9263682dea069d1e925f21d288d677bd3", "size": "2441", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sprotogen/main.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "33263" }, { "name": "Java", "bytes": "16232" } ], "symlink_target": "" }
package com.wuest.prefab.structures.messages; import com.wuest.prefab.blocks.entities.StructureScannerBlockEntity; import com.wuest.prefab.config.StructureScannerConfig; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraftforge.network.NetworkEvent; import java.util.function.Supplier; public class StructureScannerSyncHandler { public static void handle(final StructureScannerSyncMessage message, Supplier<NetworkEvent.Context> ctx) { NetworkEvent.Context context = ctx.get(); context.enqueueWork(() -> { StructureScannerConfig config = (new StructureScannerConfig()).ReadFromCompoundTag(message.getMessageTag()); BlockEntity blockEntity = context.getSender().getLevel().getBlockEntity(config.blockPos); if (blockEntity instanceof StructureScannerBlockEntity) { StructureScannerBlockEntity actualEntity = (StructureScannerBlockEntity) blockEntity; actualEntity.setConfig(config); } }); context.setPacketHandled(true); } }
{ "content_hash": "c01c26e331f5467ba8286a83f68e2c44", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 120, "avg_line_length": 39.888888888888886, "alnum_prop": 0.7390900649953575, "repo_name": "Brian-Wuest/MC-Prefab", "id": "03369f03d29ced7ff5447cc469d9a58ffa35012d", "size": "1077", "binary": false, "copies": "1", "ref": "refs/heads/Main", "path": "src/main/java/com/wuest/prefab/structures/messages/StructureScannerSyncHandler.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "131" }, { "name": "GLSL", "bytes": "464" }, { "name": "Java", "bytes": "762374" } ], "symlink_target": "" }
<aside id="contact" class="pt-4 border-t-2 border-green-500"> <h2 class="text-xl font-display font-bold mb-4"> Contact Me </h2> <form name="contact" method="POST" data-netlify="true" netlify-honeypot="bot" class="md:inline-flex space-x-4 container justify-center"> <p class="hidden"> <label for="honeypot">Are you a bot?</label> <input type="text" name="bot" /> </p> <p> <label for="name">Name:</label><br/> <input type="text" name="name" placeholder="Cortana" class="border-0 rounded focus:ring-2 focus:ring-green-200 h-10" /> </p> <p> <label for="email">Email:</label><br/> <input type="email" name="email" placeholder="rogue@ai.com" class="border-0 rounded focus:ring-2 focus:ring-green-200 h-10" /> </p> <p> <label for="message">Message:</label><br/> <textarea name="message" placeholder="Turn it off and on again" class="border-0 border-none rounded focus:ring-2 focus:ring-green-200 h-10" required></textarea> </p> <p class="mt-4 text-center"> <button type="submit" class="shadow-md text-white font-semibold border-0 bg-green-500 hover:bg-green-600 p-2 rounded">Submit</button> </p> </form> </aside>
{ "content_hash": "80bb1462330fd8e706ff1e05fb9fd8cd", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 172, "avg_line_length": 50.73076923076923, "alnum_prop": 0.5898407884761183, "repo_name": "michaelknowles/mikeknowles", "id": "8ee9a63ff2d0def8618999a0a66e7c5abdcf5c72", "size": "1319", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "layouts/partials/contact.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SSW.DataOnion.UserGroupDemo.VanillaEF.IntegrationTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SSW.DataOnion.UserGroupDemo.VanillaEF.IntegrationTests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7b53119c-1d86-47ba-a4dd-2929a952e22c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
{ "content_hash": "2780636e861f700afb75988b1fa1d103", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 85, "avg_line_length": 41.138888888888886, "alnum_prop": 0.7542201215395004, "repo_name": "brendan-ssw/SSW.DataOnion.UserGroupDemo", "id": "b7c62ca252e4354adfa79d46fec3fe8890e1ae81", "size": "1484", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SSW.DataOnion.UserGroupDemo/SSW.DataOnion.UserGroupDemo.VanillaEF.IntegrationTests/Properties/AssemblyInfo.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "124" }, { "name": "Batchfile", "bytes": "290" }, { "name": "C#", "bytes": "168685" }, { "name": "CSS", "bytes": "513" }, { "name": "HTML", "bytes": "5127" }, { "name": "JavaScript", "bytes": "10714" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- dao --> <!-- 系统管理 数据接口实现 --> <import resource="spring-examw-oa-dao-security.xml"/> <!-- 组织架构 数据接口实现 --> <import resource="spring-examw-oa-dao-org.xml"/> <!-- 计划总结 数据接口实现 --> <import resource="spring-examw-oa-dao-plan.xml"/> <!-- 行政事务 数据接口实现 --> <import resource="spring-examw-oa-dao-adm.xml"/> <!-- 奖惩管理 数据接口实现 --> <import resource="spring-examw-oa-dao-check.xml"/> </beans>
{ "content_hash": "c578c0624d2dae7bc8c25c71d4961f39", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 131, "avg_line_length": 46.53333333333333, "alnum_prop": 0.66189111747851, "repo_name": "jeasonyoung/examw-oa", "id": "9ffa0e2d02d7767656fe0d223dbd180b628ace01", "size": "798", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/resources/spring-examw-oa-dao.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "35708" }, { "name": "Java", "bytes": "520567" }, { "name": "JavaScript", "bytes": "957227" } ], "symlink_target": "" }
package org.jboss.resteasy.plugins.providers.atom; import org.jboss.resteasy.plugins.providers.jaxb.JAXBContextFinder; import org.jboss.resteasy.plugins.providers.jaxb.JAXBXmlTypeProvider; import org.w3c.dom.Element; import javax.ws.rs.core.MediaType; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.XmlType; import java.net.URI; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * <p>Per RFC4287:</p> * <pre> * The "atom:entry" element represents an individual entry, acting as a * container for metadata and data associated with the entry. This * element can appear as a child of the atom:feed element, or it can * appear as the document (i.e., top-level) element of a stand-alone * Atom Entry Document. * <p/> * atomEntry = * element atom:entry { * atomCommonAttributes, * (atomAuthor* * &amp; atomCategory* * &amp; atomContent? * &amp; atomContributor* * &amp; atomId * &amp; atomLink* * &amp; atomPublished? * &amp; atomRights? * &amp; atomSource? * &amp; atomSummary? * &amp; atomTitle * &amp; atomUpdated * &amp; extensionElement*) * } * <p/> * This specification assigns no significance to the order of appearance * of the child elements of atom:entry. * <p/> * The following child elements are defined by this specification (note * that it requires the presence of some of these elements): * <p/> * o atom:entry elements MUST contain one or more atom:author elements, * unless the atom:entry contains an atom:source element that * contains an atom:author element or, in an Atom Feed Document, the * atom:feed element contains an atom:author element itself. * o atom:entry elements MAY contain any number of atom:category * elements. * o atom:entry elements MUST NOT contain more than one atom:content * element. * o atom:entry elements MAY contain any number of atom:contributor * elements. * o atom:entry elements MUST contain exactly one atom:id element. * o atom:entry elements that contain no child atom:content element * MUST contain at least one atom:link element with a rel attribute * value of "alternate". * o atom:entry elements MUST NOT contain more than one atom:link * element with a rel attribute value of "alternate" that has the * same combination of type and hreflang attribute values. * o atom:entry elements MAY contain additional atom:link elements * beyond those described above. * o atom:entry elements MUST NOT contain more than one atom:published * element. * o atom:entry elements MUST NOT contain more than one atom:rights * element. * o atom:entry elements MUST NOT contain more than one atom:source * element. * o atom:entry elements MUST contain an atom:summary element in either * of the following cases: * * the atom:entry contains an atom:content that has a "src" * attribute (and is thus empty). * * the atom:entry contains content that is encoded in Base64; * i.e., the "type" attribute of atom:content is a MIME media type * [MIMEREG], but is not an XML media type [RFC3023], does not * begin with "text/", and does not end with "/xml" or "+xml". * o atom:entry elements MUST NOT contain more than one atom:summary * element. * o atom:entry elements MUST contain exactly one atom:title element. * o atom:entry elements MUST contain exactly one atom:updated element. * </pre> * * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ @XmlRootElement(name = "entry") @XmlAccessorType(XmlAccessType.PROPERTY) @XmlType(propOrder = {"titleElement", "links", "categories", "updated", "id", "published", "authors", "contributors", "source", "rightsElement", "content", "summaryElement", "anyOther"}) public class Entry extends CommonAttributes { private List<Person> authors = new ArrayList<Person>(); private List<Category> categories = new ArrayList<Category>(); private Content content; private List<Person> contributors = new ArrayList<Person>(); private URI id; private List<Link> links = new ArrayList<Link>(); private Date published; private Text title; private Date updated; private Text rights; private Source source; private Text summary; private Element anyOtherElement; private List<Object> anyOther; private Object anyOtherJaxbObject; protected JAXBContextFinder finder; protected void setFinder(JAXBContextFinder finder) { this.finder = finder; } @XmlElement public URI getId() { return id; } public void setId(URI id) { this.id = id; } @XmlElement(name = "title") public Text getTitleElement() { return title; } public void setTitleElement(Text title) { this.title = title; } @XmlTransient public String getTitle() { if (this.title == null) { return null; } return title.getText(); } public void setTitle(String title) { if (this.title == null) { this.title = new Text(); } this.title.setText(title); } @XmlElement public Date getUpdated() { return updated; } public void setUpdated(Date updated) { this.updated = updated; } public Link getLinkByRel(String name) { for (Link link : links) if (link.getRel().equals(name)) return link; return null; } @XmlElementRef public List<Link> getLinks() { return links; } @XmlElementRef public Content getContent() { return content; } public void setContent(Content content) { this.content = content; } @XmlElement(name = "author") public List<Person> getAuthors() { return authors; } @XmlElementRef public List<Category> getCategories() { return categories; } @XmlElement(name = "contributor") public List<Person> getContributors() { return contributors; } @XmlElement public Date getPublished() { return published; } public void setPublished(Date published) { this.published = published; } @XmlElement(name = "rights") public Text getRightsElement() { return rights; } public void setRightsElement(Text rights) { this.rights = rights; } @XmlTransient public String getRights() { if (rights == null) { return null; } return rights.getText(); } public void setRights(String rights) { if (this.rights == null) { this.rights = new Text(); } this.rights.setText(rights); } @XmlElement public Source getSource() { return source; } public void setSource(Source source) { this.source = source; } @XmlElement(name = "summary") public Text getSummaryElement() { return summary; } public void setSummaryElement(Text summary) { this.summary = summary; } @XmlTransient public String getSummary() { if (rights == null) { return null; } return rights.getText(); } public void setSummary(String summary) { if (this.summary == null) { this.summary = new Text(); } this.summary.setText(summary); } /** * Get content as an XML Element if the content is XML. Otherwise, this will just return null. * * @return */ @XmlTransient public Element getAnyOtherElement() { if (anyOther == null) return null; if (anyOtherElement != null) return anyOtherElement; for (Object obj : anyOther) { if (obj instanceof Element) { anyOtherElement = (Element) obj; return anyOtherElement; } } return null; } @XmlMixed @XmlAnyElement(lax = true) public List<Object> getAnyOther() { if (anyOther == null) { anyOther = new ArrayList<Object>(); } return this.anyOther; } /** * Extract the content as the provided JAXB annotated type. * <p/> * This method will use a cached JAXBContext used by the Resteasy JAXB providers * or, if those are not existent, it will create a new JAXBContext from scratch * using the class. * * @param clazz class type you are expecting * @param otherPossibleClasses Other classe you want to create the JAXBContext with * @return null if there is no XML content * @throws JAXBException */ @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T getAnyOtherJAXBObject(Class<T> clazz, Class... otherPossibleClasses) throws JAXBException { JAXBContext ctx = null; Class[] classes = {clazz}; if (otherPossibleClasses != null && otherPossibleClasses.length > 0) { classes = new Class[1 + otherPossibleClasses.length]; classes[0] = clazz; for (int i = 0; i < otherPossibleClasses.length; i++) classes[i + 1] = otherPossibleClasses[i]; } if (finder != null) { ctx = finder.findCacheContext(MediaType.APPLICATION_XML_TYPE, null, classes); } else { ctx = JAXBContext.newInstance(classes); } Object obj = null; if (getAnyOtherElement() != null) { obj = ctx.createUnmarshaller().unmarshal(getAnyOtherElement()); } else { if (getAnyOther().size() == 0) return null; for (Object _obj : getAnyOther()) { for (Class _clazz : classes) { if (_obj.getClass().equals(_clazz)) { obj = _obj; break; } } } if (obj == null) return null; } if (obj instanceof JAXBElement) { anyOtherJaxbObject = ((JAXBElement) obj).getValue(); return (T) anyOtherJaxbObject; } else { anyOtherJaxbObject = obj; return (T) obj; } } /** * Returns previous extracted jaxbobject from a call to getJAXBObject(Class<T> clazz) * or value passed in through a previous setJAXBObject(). * * @return */ @XmlTransient public Object getAnyOtherJAXBObject() { return anyOtherJaxbObject; } public void setAnyOtherJAXBObject(Object obj) { if (anyOther == null) anyOther = new ArrayList(); if (anyOtherJaxbObject != null && anyOther != null) anyOther.clear(); if (!obj.getClass().isAnnotationPresent(XmlRootElement.class) && obj.getClass().isAnnotationPresent(XmlType.class)) { anyOther.add(JAXBXmlTypeProvider.wrapInJAXBElement(obj, obj.getClass())); } else { anyOther.add(obj); } anyOtherJaxbObject = obj; } }
{ "content_hash": "687b57dbda5a9533673d32f2c7578381", "timestamp": "", "source": "github", "line_count": 426, "max_line_length": 127, "avg_line_length": 26.920187793427232, "alnum_prop": 0.6326299267527031, "repo_name": "rankinc/Resteasy", "id": "7777700a1a86d0ffa2f775e0e83d3ba45cad648c", "size": "11468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "providers/resteasy-atom/src/main/java/org/jboss/resteasy/plugins/providers/atom/Entry.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "373" }, { "name": "Java", "bytes": "8349021" }, { "name": "JavaScript", "bytes": "17786" }, { "name": "Python", "bytes": "4868" } ], "symlink_target": "" }
from __future__ import print_function, division import decimal import fractions import math import re as regex from collections import defaultdict from .core import C from .containers import Tuple from .sympify import converter, sympify, _sympify, SympifyError from .singleton import S, Singleton from .expr import Expr, AtomicExpr from .decorators import _sympifyit, deprecated from .cache import cacheit, clear_cache from sympy.core.compatibility import ( as_int, integer_types, long, string_types, with_metaclass, HAS_GMPY, SYMPY_INTS) import sympy.mpmath as mpmath import sympy.mpmath.libmp as mlib from sympy.mpmath.libmp import mpf_pow, mpf_pi, mpf_e, phi_fixed from sympy.mpmath.ctx_mp import mpnumeric from sympy.mpmath.libmp.libmpf import ( finf as _mpf_inf, fninf as _mpf_ninf, fnan as _mpf_nan, fzero as _mpf_zero, _normalize as mpf_normalize, prec_to_dps) rnd = mlib.round_nearest _LOG2 = math.log(2) def mpf_norm(mpf, prec): """Return the mpf tuple normalized appropriately for the indicated precision after doing a check to see if zero should be returned or not when the mantissa is 0. ``mpf_normlize`` always assumes that this is zero, but it may not be since the mantissa for mpf's values "+inf", "-inf" and "nan" have a mantissa of zero, too. Note: this is not intended to validate a given mpf tuple, so sending mpf tuples that were not created by mpmath may produce bad results. This is only a wrapper to ``mpf_normalize`` which provides the check for non- zero mpfs that have a 0 for the mantissa. """ sign, man, expt, bc = mpf if not man: # hack for mpf_normalize which does not do this; # it assumes that if man is zero the result is 0 # (see issue 6639) if not bc: return _mpf_zero else: # don't change anything; this should already # be a well formed mpf tuple return mpf rv = mpf_normalize(sign, man, expt, bc, prec, rnd) return rv # TODO: we should use the warnings module _errdict = {"divide": False} def seterr(divide=False): """ Should sympy raise an exception on 0/0 or return a nan? divide == True .... raise an exception divide == False ... return nan """ if _errdict["divide"] != divide: clear_cache() _errdict["divide"] = divide def _decimal_to_Rational_prec(dec): """Convert an ordinary decimal instance to a Rational.""" if not dec.is_finite(): # NOTE: this is_finite is not SymPy's raise TypeError("dec must be finite, got %s." % dec) s, d, e = dec.as_tuple() prec = len(d) if e >= 0: # it's an integer rv = Integer(int(dec)) else: s = (-1)**s d = sum([di*10**i for i, di in enumerate(reversed(d))]) rv = Rational(s*d, 10**-e) return rv, prec def _literal_float(f): """Return True if n can be interpreted as a floating point number.""" pat = r"[-+]?((\d*\.\d+)|(\d+\.?))(eE[-+]?\d+)?" return bool(regex.match(pat, f)) # (a,b) -> gcd(a,b) _gcdcache = {} # TODO caching with decorator, but not to degrade performance def igcd(*args): """Computes positive integer greatest common divisor. The algorithm is based on the well known Euclid's algorithm. To improve speed, igcd() has its own caching mechanism implemented. Examples ======== >>> from sympy.core.numbers import igcd >>> igcd(2, 4) 2 >>> igcd(5, 10, 15) 5 """ a = args[0] for b in args[1:]: try: a = _gcdcache[(a, b)] except KeyError: a, b = as_int(a), as_int(b) if a and b: if b < 0: b = -b while b: a, b = b, a % b else: a = abs(a or b) _gcdcache[(a, b)] = a if a == 1 or b == 1: return 1 return a def ilcm(*args): """Computes integer least common multiple. Examples ======== >>> from sympy.core.numbers import ilcm >>> ilcm(5, 10) 10 >>> ilcm(7, 3) 21 >>> ilcm(5, 10, 15) 30 """ if 0 in args: return 0 a = args[0] for b in args[1:]: a = a*b // igcd(a, b) return a def igcdex(a, b): """Returns x, y, g such that g = x*a + y*b = gcd(a, b). >>> from sympy.core.numbers import igcdex >>> igcdex(2, 3) (-1, 1, 1) >>> igcdex(10, 12) (-1, 1, 2) >>> x, y, g = igcdex(100, 2004) >>> x, y, g (-20, 1, 4) >>> x*100 + y*2004 4 """ if (not a) and (not b): return (0, 1, 0) if not a: return (0, b//abs(b), abs(b)) if not b: return (a//abs(a), 0, abs(a)) if a < 0: a, x_sign = -a, -1 else: x_sign = 1 if b < 0: b, y_sign = -b, -1 else: y_sign = 1 x, y, r, s = 1, 0, 0, 1 while b: (c, q) = (a % b, a // b) (a, b, r, s, x, y) = (b, c, x - q*r, y - q*s, r, s) return (x*x_sign, y*y_sign, a) class Number(AtomicExpr): """ Represents any kind of number in sympy. Floating point numbers are represented by the Float class. Integer numbers (of any size), together with rational numbers (again, there is no limit on their size) are represented by the Rational class. If you want to represent, for example, ``1+sqrt(2)``, then you need to do:: Rational(1) + sqrt(Rational(2)) """ is_commutative = True is_number = True __slots__ = [] # Used to make max(x._prec, y._prec) return x._prec when only x is a float _prec = -1 is_Number = True def __new__(cls, *obj): if len(obj) == 1: obj = obj[0] if isinstance(obj, Number): return obj if isinstance(obj, SYMPY_INTS): return Integer(obj) if isinstance(obj, tuple) and len(obj) == 2: return Rational(*obj) if isinstance(obj, (float, mpmath.mpf, decimal.Decimal)): return Float(obj) if isinstance(obj, string_types): val = sympify(obj) if isinstance(val, Number): return val else: raise ValueError('String "%s" does not denote a Number' % obj) if isinstance(obj, Number): return obj msg = "expected str|int|long|float|Decimal|Number object but got %r" raise TypeError(msg % type(obj).__name__) def __divmod__(self, other): from .containers import Tuple from sympy.functions.elementary.complexes import sign try: other = Number(other) except TypeError: msg = "unsupported operand type(s) for divmod(): '%s' and '%s'" raise TypeError(msg % (type(self).__name__, type(other).__name__)) if not other: raise ZeroDivisionError('modulo by zero') if self.is_Integer and other.is_Integer: return Tuple(*divmod(self.p, other.p)) else: rat = self/other w = sign(rat)*int(abs(rat)) # = rat.floor() r = self - other*w #w*other + r == self return Tuple(w, r) def __rdivmod__(self, other): try: other = Number(other) except TypeError: msg = "unsupported operand type(s) for divmod(): '%s' and '%s'" raise TypeError(msg % (type(other).__name__, type(self).__name__)) return divmod(other, self) def __round__(self, *args): return round(float(self), *args) def _as_mpf_val(self, prec): """Evaluation of mpf tuple accurate to at least prec bits.""" raise NotImplementedError('%s needs ._as_mpf_val() method' % (self.__class__.__name__)) def _eval_evalf(self, prec): return Float._new(self._as_mpf_val(prec), prec) def _as_mpf_op(self, prec): prec = max(prec, self._prec) return self._as_mpf_val(prec), prec def __float__(self): return mlib.to_float(self._as_mpf_val(53)) def _eval_conjugate(self): return self def _eval_order(self, *symbols): # Order(5, x, y) -> Order(1,x,y) return C.Order(S.One, *symbols) def _eval_subs(self, old, new): if old == -self: return -new return self # there is no other possibility def _eval_is_bounded(self): return True def _eval_is_finite(self): return True @classmethod def class_key(cls): return 1, 0, 'Number' @cacheit def sort_key(self, order=None): return self.class_key(), (0, ()), (), self @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number): if other is S.NaN: return S.NaN elif other is S.Infinity: return S.Infinity elif other is S.NegativeInfinity: return S.NegativeInfinity return AtomicExpr.__add__(self, other) @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number): if other is S.NaN: return S.NaN elif other is S.Infinity: return S.NegativeInfinity elif other is S.NegativeInfinity: return S.Infinity return AtomicExpr.__sub__(self, other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number): if other is S.NaN: return S.NaN elif other is S.Infinity: if self.is_zero: return S.NaN elif self.is_positive: return S.Infinity else: return S.NegativeInfinity elif other is S.NegativeInfinity: if self.is_zero: return S.NaN elif self.is_positive: return S.NegativeInfinity else: return S.Infinity elif isinstance(other, Tuple): return NotImplemented return AtomicExpr.__mul__(self, other) @_sympifyit('other', NotImplemented) def __div__(self, other): if isinstance(other, Number): if other is S.NaN: return S.NaN elif other is S.Infinity or other is S.NegativeInfinity: return S.Zero return AtomicExpr.__div__(self, other) __truediv__ = __div__ def __eq__(self, other): raise NotImplementedError('%s needs .__eq__() method' % (self.__class__.__name__)) def __ne__(self, other): raise NotImplementedError('%s needs .__ne__() method' % (self.__class__.__name__)) def __lt__(self, other): raise NotImplementedError('%s needs .__lt__() method' % (self.__class__.__name__)) def __le__(self, other): raise NotImplementedError('%s needs .__le__() method' % (self.__class__.__name__)) def __gt__(self, other): return _sympify(other).__lt__(self) def __ge__(self, other): return _sympify(other).__le__(self) def __hash__(self): return super(Number, self).__hash__() def is_constant(self, *wrt, **flags): return True def as_coeff_mul(self, *deps): # a -> c*t if self.is_Rational: return self, tuple() elif self.is_negative: return S.NegativeOne, (-self,) return S.One, (self,) def as_coeff_add(self, *deps): # a -> c + t if self.is_Rational: return self, tuple() return S.Zero, (self,) def as_coeff_Mul(self, rational=False): """Efficiently extract the coefficient of a product. """ if rational and not self.is_Rational: return S.One, self return self, S.One def as_coeff_Add(self): """Efficiently extract the coefficient of a summation. """ return self, S.Zero def gcd(self, other): """Compute GCD of `self` and `other`. """ from sympy.polys import gcd return gcd(self, other) def lcm(self, other): """Compute LCM of `self` and `other`. """ from sympy.polys import lcm return lcm(self, other) def cofactors(self, other): """Compute GCD and cofactors of `self` and `other`. """ from sympy.polys import cofactors return cofactors(self, other) class Float(Number): """ Represents a floating point number. It is capable of representing arbitrary-precision floating-point numbers. Examples ======== >>> from sympy import Float >>> Float(3.5) 3.50000000000000 >>> Float(3) 3.00000000000000 Floats can be created from a string representations of Python floats to force ints to Float or to enter high-precision (> 15 significant digits) values: >>> Float('.0010') 0.00100000000000000 >>> Float('1e-3') 0.00100000000000000 >>> Float('1e-3', 3) 0.00100 Float can automatically count significant figures if a null string is sent for the precision; space are also allowed in the string. (Auto- counting is only allowed for strings, ints and longs). >>> Float('123 456 789 . 123 456', '') 123456789.123456 >>> Float('12e-3', '') 0.012 >>> Float(3, '') 3. If a number is written in scientific notation, only the digits before the exponent are considered significant if a decimal appears, otherwise the "e" signifies only how to move the decimal: >>> Float('60.e2', '') # 2 digits significant 6.0e+3 >>> Float('60e2', '') # 4 digits significant 6000. >>> Float('600e-2', '') # 3 digits significant 6.00 Notes ===== Floats are inexact by their nature unless their value is a binary-exact value. >>> approx, exact = Float(.1, 1), Float(.125, 1) For calculation purposes, evalf needs to be able to change the precision but this will not increase the accuracy of the inexact value. The following is the most accurate 5-digit approximation of a value of 0.1 that had only 1 digit of precision: >>> approx.evalf(5) 0.099609 By contrast, 0.125 is exact in binary (as it is in base 10) and so it can be passed to Float or evalf to obtain an arbitrary precision with matching accuracy: >>> Float(exact, 5) 0.12500 >>> exact.evalf(20) 0.12500000000000000000 Trying to make a high-precision Float from a float is not disallowed, but one must keep in mind that the *underlying float* (not the apparent decimal value) is being obtained with high precision. For example, 0.3 does not have a finite binary representation. The closest rational is the fraction 5404319552844595/2**54. So if you try to obtain a Float of 0.3 to 20 digits of precision you will not see the same thing as 0.3 followed by 19 zeros: >>> Float(0.3, 20) 0.29999999999999998890 If you want a 20-digit value of the decimal 0.3 (not the floating point approximation of 0.3) you should send the 0.3 as a string. The underlying representation is still binary but a higher precision than Python's float is used: >>> Float('0.3', 20) 0.30000000000000000000 Although you can increase the precision of an existing Float using Float it will not increase the accuracy -- the underlying value is not changed: >>> def show(f): # binary rep of Float ... from sympy import Mul, Pow ... s, m, e, b = f._mpf_ ... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False) ... print('%s at prec=%s' % (v, f._prec)) ... >>> t = Float('0.3', 3) >>> show(t) 4915/2**14 at prec=13 >>> show(Float(t, 20)) # higher prec, not higher accuracy 4915/2**14 at prec=70 >>> show(Float(t, 2)) # lower prec 307/2**10 at prec=10 The same thing happens when evalf is used on a Float: >>> show(t.evalf(20)) 4915/2**14 at prec=70 >>> show(t.evalf(2)) 307/2**10 at prec=10 Finally, Floats can be instantiated with an mpf tuple (n, c, p) to produce the number (-1)**n*c*2**p: >>> n, c, p = 1, 5, 0 >>> (-1)**n*c*2**p -5 >>> Float((1, 5, 0)) -5.00000000000000 An actual mpf tuple also contains the number of bits in c as the last element of the tuple: >>> _._mpf_ (1, 5, 0, 3) This is not needed for instantiation and is not the same thing as the precision. The mpf tuple and the precision are two separate quantities that Float tracks. """ __slots__ = ['_mpf_', '_prec'] is_rational = True is_real = True is_Float = True def __new__(cls, num, prec=15): if isinstance(num, string_types): num = num.replace(' ', '') if num.startswith('.') and len(num) > 1: num = '0' + num elif num.startswith('-.') and len(num) > 2: num = '-0.' + num[2:] elif isinstance(num, float) and num == 0: num = '0' elif isinstance(num, (SYMPY_INTS, Integer)): num = str(num) # faster than mlib.from_int elif isinstance(num, mpmath.mpf): num = num._mpf_ if prec == '': if not isinstance(num, string_types): raise ValueError('The null string can only be used when ' 'the number to Float is passed as a string or an integer.') ok = None if _literal_float(num): try: Num = decimal.Decimal(num) except decimal.InvalidOperation: pass else: isint = '.' not in num num, dps = _decimal_to_Rational_prec(Num) if num.is_Integer and isint: dps = max(dps, len(str(num).lstrip('-'))) ok = True if ok is None: raise ValueError('string-float not recognized: %s' % num) else: dps = prec prec = mlib.libmpf.dps_to_prec(dps) if isinstance(num, float): _mpf_ = mlib.from_float(num, prec, rnd) elif isinstance(num, str): _mpf_ = mlib.from_str(num, prec, rnd) elif isinstance(num, decimal.Decimal): _mpf_ = mlib.from_str(str(num), prec, rnd) elif isinstance(num, Rational): _mpf_ = mlib.from_rational(num.p, num.q, prec, rnd) elif isinstance(num, tuple) and len(num) in (3, 4): if type(num[1]) is str: # it's a hexadecimal (coming from a pickled object) # assume that it is in standard form num = list(num) num[1] = long(num[1], 16) _mpf_ = tuple(num) else: if not num[1] and len(num) == 4: # handle normalization hack return Float._new(num, prec) else: _mpf_ = mpmath.mpf( S.NegativeOne**num[0]*num[1]*2**num[2])._mpf_ elif isinstance(num, Float): _mpf_ = num._mpf_ if prec < num._prec: _mpf_ = mpf_norm(_mpf_, prec) else: _mpf_ = mpmath.mpf(num)._mpf_ # special cases if _mpf_ == _mpf_zero: pass # we want a Float elif _mpf_ == _mpf_nan: return S.NaN obj = Expr.__new__(cls) obj._mpf_ = _mpf_ obj._prec = prec return obj @classmethod def _new(cls, _mpf_, _prec): # special cases if _mpf_ == _mpf_zero: return S.Zero # XXX this is different from Float which gives 0.0 elif _mpf_ == _mpf_nan: return S.NaN obj = Expr.__new__(cls) obj._mpf_ = mpf_norm(_mpf_, _prec) obj._prec = _prec return obj # mpz can't be pickled def __getnewargs__(self): return (mlib.to_pickable(self._mpf_),) def __getstate__(self): return {'_prec': self._prec} def _hashable_content(self): return (self._mpf_, self._prec) def floor(self): return C.Integer(int(mlib.to_int( mlib.mpf_floor(self._mpf_, self._prec)))) def ceiling(self): return C.Integer(int(mlib.to_int( mlib.mpf_ceil(self._mpf_, self._prec)))) @property def num(self): return mpmath.mpf(self._mpf_) def _as_mpf_val(self, prec): rv = mpf_norm(self._mpf_, prec) # uncomment to see failures #if rv != self._mpf_ and self._prec == prec: # print self._mpf_, rv return rv def _as_mpf_op(self, prec): return self._mpf_, max(prec, self._prec) def _eval_is_bounded(self): if self._mpf_ in (_mpf_inf, _mpf_ninf): return False return True def _eval_is_finite(self): if self._mpf_ in (_mpf_inf, _mpf_ninf, _mpf_zero): return False return True def _eval_is_integer(self): return self._mpf_ == _mpf_zero def _eval_is_negative(self): if self._mpf_ == _mpf_ninf: return True if self._mpf_ == _mpf_inf: return False return self.num < 0 def _eval_is_positive(self): if self._mpf_ == _mpf_inf: return True if self._mpf_ == _mpf_ninf: return False return self.num > 0 def _eval_is_zero(self): return self._mpf_ == _mpf_zero def __nonzero__(self): return self._mpf_ != _mpf_zero __bool__ = __nonzero__ def __neg__(self): return Float._new(mlib.mpf_neg(self._mpf_), self._prec) @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number): rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_add(self._mpf_, rhs, prec, rnd), prec) return Number.__add__(self, other) @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number): rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_sub(self._mpf_, rhs, prec, rnd), prec) return Number.__sub__(self, other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number): rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_mul(self._mpf_, rhs, prec, rnd), prec) return Number.__mul__(self, other) @_sympifyit('other', NotImplemented) def __div__(self, other): if isinstance(other, Number) and other != 0: rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_div(self._mpf_, rhs, prec, rnd), prec) return Number.__div__(self, other) __truediv__ = __div__ @_sympifyit('other', NotImplemented) def __mod__(self, other): if isinstance(other, Rational) and other.q != 1: # calculate mod with Rationals, *then* round the result return Float(Rational.__mod__(Rational(self), other), prec_to_dps(self._prec)) if isinstance(other, Float): r = self/other if r == int(r): prec = max([prec_to_dps(i) for i in (self._prec, other._prec)]) return Float(0, prec) if isinstance(other, Number): rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_mod(self._mpf_, rhs, prec, rnd), prec) return Number.__mod__(self, other) @_sympifyit('other', NotImplemented) def __rmod__(self, other): if isinstance(other, Float): return other.__mod__(self) if isinstance(other, Number): rhs, prec = other._as_mpf_op(self._prec) return Float._new(mlib.mpf_mod(rhs, self._mpf_, prec, rnd), prec) return Number.__rmod__(self, other) def _eval_power(self, expt): """ expt is symbolic object but not equal to 0, 1 (-p)**r -> exp(r*log(-p)) -> exp(r*(log(p) + I*Pi)) -> -> p**r*(sin(Pi*r) + cos(Pi*r)*I) """ if self == 0: if expt.is_positive: return S.Zero if expt.is_negative: return Float('inf') if isinstance(expt, Number): if isinstance(expt, Integer): prec = self._prec return Float._new( mlib.mpf_pow_int(self._mpf_, expt.p, prec, rnd), prec) expt, prec = expt._as_mpf_op(self._prec) self = self._mpf_ try: y = mpf_pow(self, expt, prec, rnd) return Float._new(y, prec) except mlib.ComplexResult: re, im = mlib.mpc_pow( (self, _mpf_zero), (expt, _mpf_zero), prec, rnd) return Float._new(re, prec) + \ Float._new(im, prec)*S.ImaginaryUnit def __abs__(self): return Float._new(mlib.mpf_abs(self._mpf_), self._prec) def __int__(self): if self._mpf_ == _mpf_zero: return 0 return int(mlib.to_int(self._mpf_)) # uses round_fast = round_down __long__ = __int__ def __eq__(self, other): if isinstance(other, float): # coerce to Float at same precision o = Float(other) try: ompf = o._as_mpf_val(self._prec) except ValueError: return False return bool(mlib.mpf_eq(self._mpf_, ompf)) try: other = _sympify(other) except SympifyError: return False # sympy != other --> not == if isinstance(other, NumberSymbol): if other.is_irrational: return False return other.__eq__(self) if isinstance(other, Float): return bool(mlib.mpf_eq(self._mpf_, other._mpf_)) if isinstance(other, Number): # numbers should compare at the same precision; # all _as_mpf_val routines should be sure to abide # by the request to change the prec if necessary; if # they don't, the equality test will fail since it compares # the mpf tuples ompf = other._as_mpf_val(self._prec) return bool(mlib.mpf_eq(self._mpf_, ompf)) return False # Float != non-Number def __ne__(self, other): return not self.__eq__(other) def __gt__(self, other): try: other = _sympify(other) except SympifyError: return S.false # sympy > other if isinstance(other, NumberSymbol): return other.__le__(self) if other.is_comparable: other = other.evalf() if isinstance(other, Number): return _sympify(bool( mlib.mpf_gt(self._mpf_, other._as_mpf_val(self._prec)))) return Expr.__gt__(self, other) def __ge__(self, other): try: other = _sympify(other) except SympifyError: return S.false # sympy > other --> ! <= if isinstance(other, NumberSymbol): return other.__lt__(self) if other.is_comparable: other = other.evalf() if isinstance(other, Number): return _sympify(bool( mlib.mpf_ge(self._mpf_, other._as_mpf_val(self._prec)))) return Expr.__ge__(self, other) def __lt__(self, other): try: other = _sympify(other) except SympifyError: return S.false # sympy > other if isinstance(other, NumberSymbol): return other.__ge__(self) if other.is_real and other.is_number: other = other.evalf() if isinstance(other, Number): return _sympify(bool( mlib.mpf_lt(self._mpf_, other._as_mpf_val(self._prec)))) return Expr.__lt__(self, other) def __le__(self, other): try: other = _sympify(other) except SympifyError: return S.false # sympy > other --> ! <= if isinstance(other, NumberSymbol): return other.__gt__(self) if other.is_real and other.is_number: other = other.evalf() if isinstance(other, Number): return _sympify(bool( mlib.mpf_le(self._mpf_, other._as_mpf_val(self._prec)))) return Expr.__le__(self, other) def __hash__(self): return super(Float, self).__hash__() def epsilon_eq(self, other, epsilon="1e-15"): return abs(self - other) < Float(epsilon) def _sage_(self): import sage.all as sage return sage.RealNumber(str(self)) # Add sympify converters converter[float] = converter[decimal.Decimal] = Float # this is here to work nicely in Sage RealNumber = Float class Rational(Number): """Represents integers and rational numbers (p/q) of any size. Examples ======== >>> from sympy import Rational, nsimplify, S, pi >>> Rational(3) 3 >>> Rational(1, 2) 1/2 Rational is unprejudiced in accepting input. If a float is passed, the underlying value of the binary representation will be returned: >>> Rational(.5) 1/2 >>> Rational(.2) 3602879701896397/18014398509481984 If the simpler representation of the float is desired then consider limiting the denominator to the desired value or convert the float to a string (which is roughly equivalent to limiting the denominator to 10**12): >>> Rational(str(.2)) 1/5 >>> Rational(.2).limit_denominator(10**12) 1/5 An arbitrarily precise Rational is obtained when a string literal is passed: >>> Rational("1.23") 123/100 >>> Rational('1e-2') 1/100 >>> Rational(".1") 1/10 >>> Rational('1e-2/3.2') 1/320 The conversion of other types of strings can be handled by the sympify() function, and conversion of floats to expressions or simple fractions can be handled with nsimplify: >>> S('.[3]') # repeating digits in brackets 1/3 >>> S('3**2/10') # general expressions 9/10 >>> nsimplify(.3) # numbers that have a simple form 3/10 But if the input does not reduce to a literal Rational, an error will be raised: >>> Rational(pi) Traceback (most recent call last): ... TypeError: invalid input: pi Low-level --------- Access numerator and denominator as .p and .q: >>> r = Rational(3, 4) >>> r 3/4 >>> r.p 3 >>> r.q 4 Note that p and q return integers (not SymPy Integers) so some care is needed when using them in expressions: >>> r.p/r.q 0.75 See Also ======== sympify, sympy.simplify.simplify.nsimplify """ is_real = True is_integer = False is_rational = True __slots__ = ['p', 'q'] is_Rational = True @cacheit def __new__(cls, p, q=None): if q is None: if isinstance(p, Rational): return p if isinstance(p, string_types): p = p.replace(' ', '') try: # we might have a Float neg_pow, digits, expt = decimal.Decimal(p).as_tuple() p = [1, -1][neg_pow]*int("".join(str(x) for x in digits)) if expt > 0: # TODO: this branch needs a test return Rational(p*Pow(10, expt), 1) return Rational(p, Pow(10, -expt)) except decimal.InvalidOperation: f = regex.match('^([-+]?[0-9]+)/([0-9]+)$', p) if f: n, d = f.groups() return Rational(int(n), int(d)) elif p.count('/') == 1: p, q = p.split('/') return Rational(Rational(p), Rational(q)) else: pass # error will raise below else: try: if isinstance(p, fractions.Fraction): return Rational(p.numerator, p.denominator) except NameError: pass # error will raise below if isinstance(p, (float, Float)): return Rational(*float(p).as_integer_ratio()) if not isinstance(p, SYMPY_INTS + (Rational,)): raise TypeError('invalid input: %s' % p) q = S.One else: p = Rational(p) q = Rational(q) if isinstance(q, Rational): p *= q.q q = q.p if isinstance(p, Rational): q *= p.q p = p.p # p and q are now integers if q == 0: if p == 0: if _errdict["divide"]: raise ValueError("Indeterminate 0/0") else: return S.NaN if p < 0: return S.NegativeInfinity return S.Infinity if q < 0: q = -q p = -p n = igcd(abs(p), q) if n > 1: p //= n q //= n if q == 1: return Integer(p) if p == 1 and q == 2: return S.Half obj = Expr.__new__(cls) obj.p = p obj.q = q #obj._args = (p, q) return obj def limit_denominator(self, max_denominator=1000000): """Closest Rational to self with denominator at most max_denominator. >>> from sympy import Rational >>> Rational('3.141592653589793').limit_denominator(10) 22/7 >>> Rational('3.141592653589793').limit_denominator(100) 311/99 """ # Algorithm notes: For any real number x, define a *best upper # approximation* to x to be a rational number p/q such that: # # (1) p/q >= x, and # (2) if p/q > r/s >= x then s > q, for any rational r/s. # # Define *best lower approximation* similarly. Then it can be # proved that a rational number is a best upper or lower # approximation to x if, and only if, it is a convergent or # semiconvergent of the (unique shortest) continued fraction # associated to x. # # To find a best rational approximation with denominator <= M, # we find the best upper and lower approximations with # denominator <= M and take whichever of these is closer to x. # In the event of a tie, the bound with smaller denominator is # chosen. If both denominators are equal (which can happen # only when max_denominator == 1 and self is midway between # two integers) the lower bound---i.e., the floor of self, is # taken. if max_denominator < 1: raise ValueError("max_denominator should be at least 1") if self.q <= max_denominator: return self p0, q0, p1, q1 = 0, 1, 1, 0 n, d = self.p, self.q while True: a = n//d q2 = q0 + a*q1 if q2 > max_denominator: break p0, q0, p1, q1 = p1, q1, p0 + a*p1, q2 n, d = d, n - a*d k = (max_denominator - q0)//q1 bound1 = Rational(p0 + k*p1, q0 + k*q1) bound2 = Rational(p1, q1) if abs(bound2 - self) <= abs(bound1 - self): return bound2 else: return bound1 def __getnewargs__(self): return (self.p, self.q) def _hashable_content(self): return (self.p, self.q) def _eval_is_positive(self): return self.p > 0 def _eval_is_zero(self): return self.p == 0 def __neg__(self): return Rational(-self.p, self.q) @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Rational): return Rational(self.p*other.q + self.q*other.p, self.q*other.q) elif isinstance(other, Float): return other + self else: return Number.__add__(self, other) @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Rational): return Rational(self.p*other.q - self.q*other.p, self.q*other.q) elif isinstance(other, Float): return -other + self else: return Number.__sub__(self, other) @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Rational): return Rational(self.p*other.p, self.q*other.q) elif isinstance(other, Float): return other*self else: return Number.__mul__(self, other) @_sympifyit('other', NotImplemented) def __div__(self, other): if isinstance(other, Rational): if self.p and other.p == S.Zero: return S.ComplexInfinity else: return Rational(self.p*other.q, self.q*other.p) elif isinstance(other, Float): return self*(1/other) else: return Number.__div__(self, other) __truediv__ = __div__ @_sympifyit('other', NotImplemented) def __mod__(self, other): if isinstance(other, Rational): n = (self.p*other.q) // (other.p*self.q) return Rational(self.p*other.q - n*other.p*self.q, self.q*other.q) if isinstance(other, Float): # calculate mod with Rationals, *then* round the answer return Float(self.__mod__(Rational(other)), prec_to_dps(other._prec)) return Number.__mod__(self, other) @_sympifyit('other', NotImplemented) def __rmod__(self, other): if isinstance(other, Rational): return Rational.__mod__(other, self) return Number.__rmod__(self, other) def _eval_power(self, expt): if isinstance(expt, Number): if isinstance(expt, Float): return self._eval_evalf(expt._prec)**expt if expt.is_negative: # (3/4)**-2 -> (4/3)**2 ne = -expt if (ne is S.One): return Rational(self.q, self.p) if self.is_negative: if expt.q != 1: return -(S.NegativeOne)**((expt.p % expt.q) / S(expt.q))*Rational(self.q, -self.p)**ne else: return S.NegativeOne**ne*Rational(self.q, -self.p)**ne else: return Rational(self.q, self.p)**ne if expt is S.Infinity: # -oo already caught by test for negative if self.p > self.q: # (3/2)**oo -> oo return S.Infinity if self.p < -self.q: # (-3/2)**oo -> oo + I*oo return S.Infinity + S.Infinity*S.ImaginaryUnit return S.Zero if isinstance(expt, Integer): # (4/3)**2 -> 4**2 / 3**2 return Rational(self.p**expt.p, self.q**expt.p) if isinstance(expt, Rational): if self.p != 1: # (4/3)**(5/6) -> 4**(5/6)*3**(-5/6) return Integer(self.p)**expt*Integer(self.q)**(-expt) # as the above caught negative self.p, now self is positive return Integer(self.q)**Rational( expt.p*(expt.q - 1), expt.q) / \ Integer(self.q)**Integer(expt.p) if self.is_negative and expt.is_even: return (-self)**expt return def _as_mpf_val(self, prec): return mlib.from_rational(self.p, self.q, prec, rnd) def _mpmath_(self, prec, rnd): return mpmath.make_mpf(mlib.from_rational(self.p, self.q, prec, rnd)) def __abs__(self): return Rational(abs(self.p), self.q) def __int__(self): p, q = self.p, self.q if p < 0: return -(-p//q) return p//q __long__ = __int__ def __eq__(self, other): try: other = _sympify(other) except SympifyError: return False # sympy != other --> not == if isinstance(other, NumberSymbol): if other.is_irrational: return False return other.__eq__(self) if isinstance(other, Number): if isinstance(other, Rational): # a Rational is always in reduced form so will never be 2/4 # so we can just check equivalence of args return self.p == other.p and self.q == other.q if isinstance(other, Float): return mlib.mpf_eq(self._as_mpf_val(other._prec), other._mpf_) return False def __ne__(self, other): return not self.__eq__(other) def __gt__(self, other): try: other = _sympify(other) except SympifyError: return S.false # sympy > other --> not < if isinstance(other, NumberSymbol): return other.__le__(self) if other.is_real and other.is_number and not isinstance(other, Rational): other = other.evalf() if isinstance(other, Number): if isinstance(other, Rational): return _sympify(bool(self.p*other.q > self.q*other.p)) if isinstance(other, Float): return _sympify(bool(mlib.mpf_gt( self._as_mpf_val(other._prec), other._mpf_))) if other is S.NaN: return other.__le__(self) return Expr.__gt__(self, other) def __ge__(self, other): try: other = _sympify(other) except SympifyError: return S.false # sympy > other --> not <= if isinstance(other, NumberSymbol): return other.__lt__(self) if other.is_real and other.is_number and not isinstance(other, Rational): other = other.evalf() if isinstance(other, Number): if isinstance(other, Rational): return _sympify(bool(self.p*other.q >= self.q*other.p)) if isinstance(other, Float): return _sympify(bool(mlib.mpf_ge( self._as_mpf_val(other._prec), other._mpf_))) if other is S.NaN: return other.__lt__(self) return Expr.__ge__(self, other) def __lt__(self, other): try: other = _sympify(other) except SympifyError: return S.false # sympy > other --> not < if isinstance(other, NumberSymbol): return other.__ge__(self) if other.is_real and other.is_number and not isinstance(other, Rational): other = other.evalf() if isinstance(other, Number): if isinstance(other, Rational): return _sympify(bool(self.p*other.q < self.q*other.p)) if isinstance(other, Float): return _sympify(bool(mlib.mpf_lt( self._as_mpf_val(other._prec), other._mpf_))) if other is S.NaN: return other.__ge__(self) return Expr.__lt__(self, other) def __le__(self, other): try: other = _sympify(other) except SympifyError: return S.false # sympy > other --> not <= if isinstance(other, NumberSymbol): return other.__gt__(self) if other.is_real and other.is_number and not isinstance(other, Rational): other = other.evalf() if isinstance(other, Number): if isinstance(other, Rational): return _sympify(bool(self.p*other.q <= self.q*other.p)) if isinstance(other, Float): return _sympify(bool(mlib.mpf_le( self._as_mpf_val(other._prec), other._mpf_))) if other is S.NaN: return other.__gt__(self) return Expr.__le__(self, other) def __hash__(self): return super(Rational, self).__hash__() def factors(self, limit=None, use_trial=True, use_rho=False, use_pm1=False, verbose=False, visual=False): """A wrapper to factorint which return factors of self that are smaller than limit (or cheap to compute). Special methods of factoring are disabled by default so that only trial division is used. """ from sympy.ntheory import factorint f = factorint(self.p, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose).copy() f = defaultdict(int, f) for p, e in factorint(self.q, limit=limit, use_trial=use_trial, use_rho=use_rho, use_pm1=use_pm1, verbose=verbose).items(): f[p] += -e if len(f) > 1 and 1 in f: del f[1] if not f: f = {1: 1} if not visual: return dict(f) else: if -1 in f: f.pop(-1) args = [S.NegativeOne] else: args = [] args.extend([Pow(*i, evaluate=False) for i in sorted(f.items())]) return Mul(*args, evaluate=False) @_sympifyit('other', NotImplemented) def gcd(self, other): if isinstance(other, Rational): if other is S.Zero: return other return Rational( Integer(igcd(self.p, other.p)), Integer(ilcm(self.q, other.q))) return Number.gcd(self, other) @_sympifyit('other', NotImplemented) def lcm(self, other): if isinstance(other, Rational): return Rational( self.p*other.p//igcd(self.p, other.p), igcd(self.q, other.q)) return Number.lcm(self, other) def as_numer_denom(self): return Integer(self.p), Integer(self.q) def _sage_(self): import sage.all as sage return sage.Integer(self.p)/sage.Integer(self.q) def as_content_primitive(self, radical=False): """Return the tuple (R, self/R) where R is the positive Rational extracted from self. Examples ======== >>> from sympy import S >>> (S(-3)/2).as_content_primitive() (3/2, -1) See docstring of Expr.as_content_primitive for more examples. """ if self: if self.is_positive: return self, S.One return -self, S.NegativeOne return S.One, self # int -> Integer _intcache = {} # TODO move this tracing facility to sympy/core/trace.py ? def _intcache_printinfo(): ints = sorted(_intcache.keys()) nhit = _intcache_hits nmiss = _intcache_misses if nhit == 0 and nmiss == 0: print() print('Integer cache statistic was not collected') return miss_ratio = float(nmiss) / (nhit + nmiss) print() print('Integer cache statistic') print('-----------------------') print() print('#items: %i' % len(ints)) print() print(' #hit #miss #total') print() print('%5i %5i (%7.5f %%) %5i' % ( nhit, nmiss, miss_ratio*100, nhit + nmiss) ) print() print(ints) _intcache_hits = 0 _intcache_misses = 0 def int_trace(f): import os if os.getenv('SYMPY_TRACE_INT', 'no').lower() != 'yes': return f def Integer_tracer(cls, i): global _intcache_hits, _intcache_misses try: _intcache_hits += 1 return _intcache[i] except KeyError: _intcache_hits -= 1 _intcache_misses += 1 return f(cls, i) # also we want to hook our _intcache_printinfo into sys.atexit import atexit atexit.register(_intcache_printinfo) return Integer_tracer class Integer(Rational): q = 1 is_integer = True is_Integer = True __slots__ = ['p'] def _as_mpf_val(self, prec): return mlib.from_int(self.p, prec) def _mpmath_(self, prec, rnd): return mpmath.make_mpf(self._as_mpf_val(prec)) # TODO caching with decorator, but not to degrade performance @int_trace def __new__(cls, i): if isinstance(i, string_types): i = i.replace(' ', '') # whereas we cannot, in general, make a Rational from an # arbitrary expression, we can make an Integer unambiguously # (except when a non-integer expression happens to round to # an integer). So we proceed by taking int() of the input and # let the int routines determine whether the expression can # be made into an int or whether an error should be raised. try: ival = int(i) except TypeError: raise TypeError( 'Integer can only work with integer expressions.') try: return _intcache[ival] except KeyError: # We only work with well-behaved integer types. This converts, for # example, numpy.int32 instances. obj = Expr.__new__(cls) obj.p = ival _intcache[ival] = obj return obj def __getnewargs__(self): return (self.p,) # Arithmetic operations are here for efficiency def __int__(self): return self.p __long__ = __int__ def __neg__(self): return Integer(-self.p) def __abs__(self): if self.p >= 0: return self else: return Integer(-self.p) def __divmod__(self, other): from .containers import Tuple if isinstance(other, Integer): return Tuple(*(divmod(self.p, other.p))) else: return Number.__divmod__(self, other) def __rdivmod__(self, other): from .containers import Tuple if isinstance(other, integer_types): return Tuple(*(divmod(other, self.p))) else: try: other = Number(other) except TypeError: msg = "unsupported operand type(s) for divmod(): '%s' and '%s'" oname = type(other).__name__ sname = type(self).__name__ raise TypeError(msg % (oname, sname)) return Number.__divmod__(other, self) # TODO make it decorator + bytecodehacks? def __add__(self, other): if isinstance(other, integer_types): return Integer(self.p + other) elif isinstance(other, Integer): return Integer(self.p + other.p) return Rational.__add__(self, other) def __radd__(self, other): if isinstance(other, integer_types): return Integer(other + self.p) return Rational.__add__(self, other) def __sub__(self, other): if isinstance(other, integer_types): return Integer(self.p - other) elif isinstance(other, Integer): return Integer(self.p - other.p) return Rational.__sub__(self, other) def __rsub__(self, other): if isinstance(other, integer_types): return Integer(other - self.p) return Rational.__rsub__(self, other) def __mul__(self, other): if isinstance(other, integer_types): return Integer(self.p*other) elif isinstance(other, Integer): return Integer(self.p*other.p) return Rational.__mul__(self, other) def __rmul__(self, other): if isinstance(other, integer_types): return Integer(other*self.p) return Rational.__mul__(self, other) def __mod__(self, other): if isinstance(other, integer_types): return Integer(self.p % other) elif isinstance(other, Integer): return Integer(self.p % other.p) return Rational.__mod__(self, other) def __rmod__(self, other): if isinstance(other, integer_types): return Integer(other % self.p) elif isinstance(other, Integer): return Integer(other.p % self.p) return Rational.__rmod__(self, other) def __eq__(self, other): if isinstance(other, integer_types): return (self.p == other) elif isinstance(other, Integer): return (self.p == other.p) return Rational.__eq__(self, other) def __ne__(self, other): return not self.__eq__(other) def __gt__(self, other): if isinstance(other, integer_types): return _sympify(self.p > other) elif isinstance(other, Integer): return _sympify(self.p > other.p) return Rational.__gt__(self, other) def __lt__(self, other): if isinstance(other, integer_types): return _sympify(self.p < other) elif isinstance(other, Integer): return _sympify(self.p < other.p) return Rational.__lt__(self, other) def __ge__(self, other): if isinstance(other, integer_types): return _sympify(self.p >= other) elif isinstance(other, Integer): return _sympify(self.p >= other.p) return Rational.__ge__(self, other) def __le__(self, other): if isinstance(other, integer_types): return _sympify(self.p <= other) elif isinstance(other, Integer): return _sympify(self.p <= other.p) return Rational.__le__(self, other) def __hash__(self): return super(Integer, self).__hash__() def __index__(self): return self.p ######################################## def _eval_is_odd(self): return bool(self.p % 2) def _eval_power(self, expt): """ Tries to do some simplifications on self**expt Returns None if no further simplifications can be done When exponent is a fraction (so we have for example a square root), we try to find a simpler representation by factoring the argument up to factors of 2**15, e.g. - sqrt(4) becomes 2 - sqrt(-4) becomes 2*I - (2**(3+7)*3**(6+7))**Rational(1,7) becomes 6*18**(3/7) Further simplification would require a special call to factorint on the argument which is not done here for sake of speed. """ from sympy import perfect_power if expt is S.Infinity: if self.p > S.One: return S.Infinity # cases -1, 0, 1 are done in their respective classes return S.Infinity + S.ImaginaryUnit*S.Infinity if expt is S.NegativeInfinity: return Rational(1, self)**S.Infinity if not isinstance(expt, Number): # simplify when expt is even # (-2)**k --> 2**k if self.is_negative and expt.is_even: return (-self)**expt if not isinstance(expt, Rational): return if expt is S.Half and self.is_negative: # we extract I for this special case since everyone is doing so return S.ImaginaryUnit*Pow(-self, expt) if expt.is_negative: # invert base and change sign on exponent ne = -expt if self.is_negative: if expt.q != 1: return -(S.NegativeOne)**((expt.p % expt.q) / S(expt.q))*Rational(1, -self)**ne else: return (S.NegativeOne)**ne*Rational(1, -self)**ne else: return Rational(1, self.p)**ne # see if base is a perfect root, sqrt(4) --> 2 x, xexact = integer_nthroot(abs(self.p), expt.q) if xexact: # if it's a perfect root we've finished result = Integer(x**abs(expt.p)) if self.is_negative: result *= S.NegativeOne**expt return result # The following is an algorithm where we collect perfect roots # from the factors of base. # if it's not an nth root, it still might be a perfect power b_pos = int(abs(self.p)) p = perfect_power(b_pos) if p is not False: dict = {p[0]: p[1]} else: dict = Integer(self).factors(limit=2**15) # now process the dict of factors if self.is_negative: dict[-1] = 1 out_int = 1 # integer part out_rad = 1 # extracted radicals sqr_int = 1 sqr_gcd = 0 sqr_dict = {} for prime, exponent in dict.items(): exponent *= expt.p # remove multiples of expt.q: (2**12)**(1/10) -> 2*(2**2)**(1/10) div_e, div_m = divmod(exponent, expt.q) if div_e > 0: out_int *= prime**div_e if div_m > 0: # see if the reduced exponent shares a gcd with e.q # (2**2)**(1/10) -> 2**(1/5) g = igcd(div_m, expt.q) if g != 1: out_rad *= Pow(prime, Rational(div_m//g, expt.q//g)) else: sqr_dict[prime] = div_m # identify gcd of remaining powers for p, ex in sqr_dict.items(): if sqr_gcd == 0: sqr_gcd = ex else: sqr_gcd = igcd(sqr_gcd, ex) if sqr_gcd == 1: break for k, v in sqr_dict.items(): sqr_int *= k**(v//sqr_gcd) if sqr_int == self and out_int == 1 and out_rad == 1: result = None else: result = out_int*out_rad*Pow(sqr_int, Rational(sqr_gcd, expt.q)) return result def _eval_is_prime(self): from sympy.ntheory import isprime return isprime(self) def as_numer_denom(self): return self, S.One def __floordiv__(self, other): return Integer(self.p // Integer(other).p) def __rfloordiv__(self, other): return Integer(Integer(other).p // self.p) # Add sympify converters for i_type in integer_types: converter[i_type] = Integer class RationalConstant(Rational): """ Abstract base class for rationals with specific behaviors Derived classes must define class attributes p and q and should probably all be singletons. """ __slots__ = [] def __new__(cls): return AtomicExpr.__new__(cls) class IntegerConstant(Integer): __slots__ = [] def __new__(cls): return AtomicExpr.__new__(cls) class Zero(with_metaclass(Singleton, IntegerConstant)): """The number zero. Zero is a singleton, and can be accessed by ``S.Zero`` Examples ======== >>> from sympy import S, Integer, zoo >>> Integer(0) is S.Zero True >>> 1/S.Zero zoo References ========== .. [1] http://en.wikipedia.org/wiki/Zero """ p = 0 q = 1 is_positive = False is_negative = False is_finite = False is_zero = True is_composite = False __slots__ = [] @staticmethod def __abs__(): return S.Zero @staticmethod def __neg__(): return S.Zero def _eval_power(self, expt): if expt.is_positive: return self if expt.is_negative: return S.ComplexInfinity if expt.is_real is False: return S.NaN # infinities are already handled with pos and neg # tests above; now throw away leading numbers on Mul # exponent coeff, terms = expt.as_coeff_Mul() if coeff.is_negative: return S.ComplexInfinity**terms if coeff is not S.One: # there is a Number to discard return self**terms def _eval_order(self, *symbols): # Order(0,x) -> 0 return self def __nonzero__(self): return False __bool__ = __nonzero__ class One(with_metaclass(Singleton, IntegerConstant)): """The number one. One is a singleton, and can be accessed by ``S.One``. Examples ======== >>> from sympy import S, Integer >>> Integer(1) is S.One True References ========== .. [1] http://en.wikipedia.org/wiki/1_%28number%29 """ p = 1 q = 1 __slots__ = [] @staticmethod def __abs__(): return S.One @staticmethod def __neg__(): return S.NegativeOne def _eval_power(self, expt): return self def _eval_order(self, *symbols): return @staticmethod def factors(limit=None, use_trial=True, use_rho=False, use_pm1=False, verbose=False, visual=False): if visual: return S.One return {1: 1} class NegativeOne(with_metaclass(Singleton, IntegerConstant)): """The number negative one. NegativeOne is a singleton, and can be accessed by ``S.NegativeOne``. Examples ======== >>> from sympy import S, Integer >>> Integer(-1) is S.NegativeOne True See Also ======== One References ========== .. [1] http://en.wikipedia.org/wiki/%E2%88%921_%28number%29 """ p = -1 q = 1 __slots__ = [] @staticmethod def __abs__(): return S.One @staticmethod def __neg__(): return S.One def _eval_power(self, expt): if expt.is_odd: return S.NegativeOne if expt.is_even: return S.One if isinstance(expt, Number): if isinstance(expt, Float): return Float(-1.0)**expt if expt is S.NaN: return S.NaN if expt is S.Infinity or expt is S.NegativeInfinity: return S.NaN if expt is S.Half: return S.ImaginaryUnit if isinstance(expt, Rational): if expt.q == 2: return S.ImaginaryUnit**Integer(expt.p) i, r = divmod(expt.p, expt.q) if i: return self**i*self**Rational(r, expt.q) return class Half(with_metaclass(Singleton, RationalConstant)): """The rational number 1/2. Half is a singleton, and can be accessed by ``S.Half``. Examples ======== >>> from sympy import S, Rational >>> Rational(1, 2) is S.Half True References ========== .. [1] http://en.wikipedia.org/wiki/One_half """ p = 1 q = 2 __slots__ = [] @staticmethod def __abs__(): return S.Half class Infinity(with_metaclass(Singleton, Number)): r"""Positive infinite quantity. In real analysis the symbol `\infty` denotes an unbounded limit: `x\to\infty` means that `x` grows without bound. Infinity is often used not only to define a limit but as a value in the affinely extended real number system. Points labeled `+\infty` and `-\infty` can be added to the topological space of the real numbers, producing the two-point compactification of the real numbers. Adding algebraic properties to this gives us the extended real numbers. Infinity is a singleton, and can be accessed by ``S.Infinity``, or can be imported as ``oo``. Examples ======== >>> from sympy import oo, exp, limit, Symbol >>> 1 + oo oo >>> 42/oo 0 >>> x = Symbol('x') >>> limit(exp(x), x, oo) oo See Also ======== NegativeInfinity, NaN References ========== .. [1] http://en.wikipedia.org/wiki/Infinity """ is_commutative = True is_positive = True is_bounded = False is_finite = False is_infinitesimal = False is_integer = None is_rational = None is_odd = None __slots__ = [] def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"\infty" @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number): if other is S.NegativeInfinity or other is S.NaN: return S.NaN elif other.is_Float: if other == Float('-inf'): return S.NaN else: return Float('inf') else: return S.Infinity return NotImplemented __radd__ = __add__ @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number): if other is S.Infinity or other is S.NaN: return S.NaN elif other.is_Float: if other == Float('inf'): return S.NaN else: return Float('inf') else: return S.Infinity return NotImplemented @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number): if other is S.Zero or other is S.NaN: return S.NaN elif other.is_Float: if other == 0: return S.NaN if other > 0: return Float('inf') else: return Float('-inf') else: if other > 0: return S.Infinity else: return S.NegativeInfinity return NotImplemented __rmul__ = __mul__ @_sympifyit('other', NotImplemented) def __div__(self, other): if isinstance(other, Number): if other is S.Infinity or \ other is S.NegativeInfinity or \ other is S.NaN: return S.NaN elif other.is_Float: if other == Float('-inf') or \ other == Float('inf'): return S.NaN elif other.is_nonnegative: return Float('inf') else: return Float('-inf') else: if other >= 0: return S.Infinity else: return S.NegativeInfinity return NotImplemented __truediv__ = __div__ def __abs__(self): return S.Infinity def __neg__(self): return S.NegativeInfinity def _eval_power(self, expt): """ ``expt`` is symbolic object but not equal to 0 or 1. ================ ======= ============================== Expression Result Notes ================ ======= ============================== ``oo ** nan`` ``nan`` ``oo ** -p`` ``0`` ``p`` is number, ``oo`` ================ ======= ============================== See Also ======== Pow NaN NegativeInfinity """ if expt.is_positive: return S.Infinity if expt.is_negative: return S.Zero if expt is S.NaN: return S.NaN if expt.is_number: return self**expt.evalf() def _as_mpf_val(self, prec): return mlib.finf def _sage_(self): import sage.all as sage return sage.oo def __hash__(self): return super(Infinity, self).__hash__() def __eq__(self, other): return other is S.Infinity def __ne__(self, other): return other is not S.Infinity @_sympifyit('other', NotImplemented) def __lt__(self, other): if other.is_number and other.is_real is False: raise TypeError("Invalid comparison of %s and %s" % (self, other)) return S.false @_sympifyit('other', NotImplemented) def __le__(self, other): if other.is_number and other.is_real is False: raise TypeError("Invalid comparison of %s and %s" % (self, other)) return _sympify(other is S.Infinity) @_sympifyit('other', NotImplemented) def __gt__(self, other): if other.is_number and other.is_real is False: raise TypeError("Invalid comparison of %s and %s" % (self, other)) return _sympify(other is not S.Infinity) @_sympifyit('other', NotImplemented) def __ge__(self, other): if other.is_number and other.is_real is False: raise TypeError("Invalid comparison of %s and %s" % (self, other)) return S.true def __mod__(self, other): return S.NaN __rmod__ = __mod__ oo = S.Infinity class NegativeInfinity(with_metaclass(Singleton, Number)): """Negative infinite quantity. NegativeInfinity is a singleton, and can be accessed by ``S.NegativeInfinity``. See Also ======== Infinity """ is_commutative = True is_real = True is_positive = False is_bounded = False is_finite = False is_infinitesimal = False is_integer = None is_rational = None __slots__ = [] def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"-\infty" @_sympifyit('other', NotImplemented) def __add__(self, other): if isinstance(other, Number): if other is S.Infinity or other is S.NaN: return S.NaN elif other.is_Float: if other == Float('inf'): return Float('nan') else: return Float('-inf') else: return S.NegativeInfinity return NotImplemented __radd__ = __add__ @_sympifyit('other', NotImplemented) def __sub__(self, other): if isinstance(other, Number): if other is S.NegativeInfinity or other is S.NaN: return S.NaN elif other.is_Float: if other == Float('-inf'): return Float('nan') else: return Float('-inf') else: return S.NegativeInfinity return NotImplemented @_sympifyit('other', NotImplemented) def __mul__(self, other): if isinstance(other, Number): if other is S.Zero or other is S.NaN: return S.NaN elif other.is_Float: if other is S.NaN or other.is_zero: return S.NaN elif other.is_positive: return Float('-inf') else: return Float('inf') else: if other.is_positive: return S.NegativeInfinity else: return S.Infinity return NotImplemented __rmul__ = __mul__ @_sympifyit('other', NotImplemented) def __div__(self, other): if isinstance(other, Number): if other is S.Infinity or \ other is S.NegativeInfinity or \ other is S.NaN: return S.NaN elif other.is_Float: if other == Float('-inf') or \ other == Float('inf') or \ other is S.NaN: return S.NaN elif other.is_nonnegative: return Float('-inf') else: return Float('inf') else: if other >= 0: return S.NegativeInfinity else: return S.Infinity return NotImplemented __truediv__ = __div__ def __abs__(self): return S.Infinity def __neg__(self): return S.Infinity def _eval_power(self, expt): """ ``expt`` is symbolic object but not equal to 0 or 1. ================ ======= ============================== Expression Result Notes ================ ======= ============================== ``(-oo) ** nan`` ``nan`` ``(-oo) ** oo`` ``nan`` ``(-oo) ** -oo`` ``nan`` ``(-oo) ** e`` ``oo`` ``e`` is positive even integer ``(-oo) ** o`` ``-oo`` ``o`` is positive odd integer ================ ======= ============================== See Also ======== Infinity Pow NaN """ if isinstance(expt, Number): if expt is S.NaN or \ expt is S.Infinity or \ expt is S.NegativeInfinity: return S.NaN if isinstance(expt, Integer) and expt.is_positive: if expt.is_odd: return S.NegativeInfinity else: return S.Infinity return S.NegativeOne**expt*S.Infinity**expt def _as_mpf_val(self, prec): return mlib.fninf def _sage_(self): import sage.all as sage return -(sage.oo) def __hash__(self): return super(NegativeInfinity, self).__hash__() def __eq__(self, other): return other is S.NegativeInfinity def __ne__(self, other): return other is not S.NegativeInfinity @_sympifyit('other', NotImplemented) def __lt__(self, other): if other.is_number and other.is_real is False: raise TypeError("Invalid comparison of %s and %s" % (self, other)) return _sympify(other is not S.NegativeInfinity) @_sympifyit('other', NotImplemented) def __le__(self, other): if other.is_number and other.is_real is False: raise TypeError("Invalid comparison of %s and %s" % (self, other)) return S.true @_sympifyit('other', NotImplemented) def __gt__(self, other): if other.is_number and other.is_real is False: raise TypeError("Invalid comparison of %s and %s" % (self, other)) return S.false @_sympifyit('other', NotImplemented) def __ge__(self, other): if other.is_number and other.is_real is False: raise TypeError("Invalid comparison of %s and %s" % (self, other)) return _sympify(other is S.NegativeInfinity) class NaN(with_metaclass(Singleton, Number)): """ Not a Number. This represents the corresponding data type to floating point nan, which is defined in the IEEE 754 floating point standard, and corresponds to the Python ``float('nan')``. NaN serves as a place holder for numeric values that are indeterminate. Most operations on nan, produce another nan. Most indeterminate forms, such as ``0/0`` or ``oo - oo` produce nan. Two exceptions are ``0**0`` and ``oo**0``, which all produce ``1`` (this is consistent with Python's float). NaN is a singleton, and can be accessed by ``S.NaN``, or can be imported as ``nan``. Examples ======== >>> from sympy import nan, S, oo >>> nan is S.NaN True >>> oo - oo nan >>> nan + 1 nan References ========== .. [1] http://en.wikipedia.org/wiki/NaN """ is_commutative = True is_real = None is_rational = None is_integer = None is_comparable = False is_finite = None is_bounded = None is_zero = None is_prime = None is_positive = None is_negative = None __slots__ = [] def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"\mathrm{NaN}" @_sympifyit('other', NotImplemented) def __add__(self, other): return self @_sympifyit('other', NotImplemented) def __sub__(self, other): return self @_sympifyit('other', NotImplemented) def __mul__(self, other): return self @_sympifyit('other', NotImplemented) def __div__(self, other): return self __truediv__ = __div__ def _as_mpf_val(self, prec): return _mpf_nan def _sage_(self): import sage.all as sage return sage.NaN def __hash__(self): return super(NaN, self).__hash__() def __eq__(self, other): return other is S.NaN def __ne__(self, other): return other is not S.NaN def __gt__(self, other): return S.false def __ge__(self, other): return S.false def __lt__(self, other): return S.false def __le__(self, other): return S.false nan = S.NaN class ComplexInfinity(with_metaclass(Singleton, AtomicExpr)): r"""Complex infinity. In complex analysis the symbol `\tilde\infty`, called "complex infinity", represents a quantity with infinite magnitude, but undetermined complex phase. ComplexInfinity is a singleton, and can be accessed by ``S.ComplexInfinity``, or can be imported as ``zoo``. Examples ======== >>> from sympy import zoo, oo >>> zoo + 42 zoo >>> 42/zoo 0 >>> zoo + zoo nan >>> zoo*zoo zoo See Also ======== Infinity """ is_commutative = True is_bounded = False is_real = None is_number = True __slots__ = [] def __new__(cls): return AtomicExpr.__new__(cls) def _latex(self, printer): return r"\tilde{\infty}" @staticmethod def __abs__(): return S.Infinity @staticmethod def __neg__(): return S.ComplexInfinity def _eval_power(self, expt): if expt is S.ComplexInfinity: return S.NaN if isinstance(expt, Number): if expt is S.Zero: return S.NaN else: if expt.is_positive: return S.ComplexInfinity else: return S.Zero zoo = S.ComplexInfinity class NumberSymbol(AtomicExpr): is_commutative = True is_bounded = True is_finite = True is_number = True __slots__ = [] is_NumberSymbol = True def __new__(cls): return AtomicExpr.__new__(cls) def approximation(self, number_cls): """ Return an interval with number_cls endpoints that contains the value of NumberSymbol. If not implemented, then return None. """ def _eval_evalf(self, prec): return Float._new(self._as_mpf_val(prec), prec) def __eq__(self, other): try: other = _sympify(other) except SympifyError: return False # sympy != other --> not == if self is other: return True if isinstance(other, Number) and self.is_irrational: return False return False # NumberSymbol != non-(Number|self) def __ne__(self, other): return not self.__eq__(other) def __lt__(self, other): try: other = _sympify(other) except SympifyError: return S.false # sympy > other --> not < if self is other: return S.false if isinstance(other, Number): approx = self.approximation_interval(other.__class__) if approx is not None: l, u = approx if other < l: return S.false if other > u: return S.true return _sympify(self.evalf() < other) if other.is_real and other.is_number: other = other.evalf() return _sympify(self.evalf() < other) return Expr.__lt__(self, other) def __le__(self, other): try: other = _sympify(other) except SympifyError: return S.false # sympy > other --> not <= if self is other: return S.true if other.is_real and other.is_number: other = other.evalf() if isinstance(other, Number): return _sympify(self.evalf() <= other) return Expr.__le__(self, other) def __gt__(self, other): return _sympify((-self) < (-other)) def __ge__(self, other): return _sympify((-self) <= (-other)) def __int__(self): # subclass with appropriate return value raise NotImplementedError def __long__(self): return self.__int__() def __hash__(self): return super(NumberSymbol, self).__hash__() class Exp1(with_metaclass(Singleton, NumberSymbol)): r"""The `e` constant. The transcendental number `e = 2.718281828\dots` is the base of the natural logarithm and of the exponential function, `e = \exp(1)`. Sometimes called Euler's number or Napier's constant. Exp1 is a singleton, and can be accessed by ``S.Exp1``, or can be imported as ``E``. Examples ======== >>> from sympy import exp, log, E >>> E is exp(1) True >>> log(E) 1 References ========== .. [1] http://en.wikipedia.org/wiki/E_%28mathematical_constant%29 """ is_real = True is_positive = True is_negative = False # XXX Forces is_negative/is_nonnegative is_irrational = True __slots__ = [] def _latex(self, printer): return r"e" @staticmethod def __abs__(): return S.Exp1 def __int__(self): return 2 def _as_mpf_val(self, prec): return mpf_e(prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (Integer(2), Integer(3)) elif issubclass(number_cls, Rational): pass def _eval_power(self, expt): return C.exp(expt) def _eval_rewrite_as_sin(self): I = S.ImaginaryUnit return C.sin(I + S.Pi/2) - I*C.sin(I) def _eval_rewrite_as_cos(self): I = S.ImaginaryUnit return C.cos(I) + I*C.cos(I + S.Pi/2) def _sage_(self): import sage.all as sage return sage.e E = S.Exp1 class Pi(with_metaclass(Singleton, NumberSymbol)): r"""The `\pi` constant. The transcendental number `\pi = 3.141592654\dots` represents the ratio of a circle's circumference to its diameter, the area of the unit circle, the half-period of trigonometric functions, and many other things in mathematics. Pi is a singleton, and can be accessed by ``S.Pi``, or can be imported as ``pi``. Examples ======== >>> from sympy import S, pi, oo, sin, exp, integrate, Symbol >>> S.Pi pi >>> pi > 3 True >>> pi.is_irrational True >>> x = Symbol('x') >>> sin(x + 2*pi) sin(x) >>> integrate(exp(-x**2), (x, -oo, oo)) sqrt(pi) References ========== .. [1] http://en.wikipedia.org/wiki/Pi """ is_real = True is_positive = True is_negative = False is_irrational = True __slots__ = [] def _latex(self, printer): return r"\pi" @staticmethod def __abs__(): return S.Pi def __int__(self): return 3 def _as_mpf_val(self, prec): return mpf_pi(prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (Integer(3), Integer(4)) elif issubclass(number_cls, Rational): return (Rational(223, 71), Rational(22, 7)) def _sage_(self): import sage.all as sage return sage.pi pi = S.Pi class GoldenRatio(with_metaclass(Singleton, NumberSymbol)): r"""The golden ratio, `\phi`. `\phi = \frac{1 + \sqrt{5}}{2}` is algebraic number. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities, i.e. their maximum. GoldenRatio is a singleton, and can be accessed by ``S.GoldenRatio``. Examples ======== >>> from sympy import S >>> S.GoldenRatio > 1 True >>> S.GoldenRatio.expand(func=True) 1/2 + sqrt(5)/2 >>> S.GoldenRatio.is_irrational True References ========== .. [1] http://en.wikipedia.org/wiki/Golden_ratio """ is_real = True is_positive = True is_negative = False is_irrational = True __slots__ = [] def _latex(self, printer): return r"\phi" def __int__(self): return 1 def _as_mpf_val(self, prec): # XXX track down why this has to be increased rv = mlib.from_man_exp(phi_fixed(prec + 10), -prec - 10) return mpf_norm(rv, prec) def _eval_expand_func(self, **hints): from sympy import sqrt return S.Half + S.Half*sqrt(5) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.One, Rational(2)) elif issubclass(number_cls, Rational): pass def _sage_(self): import sage.all as sage return sage.golden_ratio class EulerGamma(with_metaclass(Singleton, NumberSymbol)): r"""The Euler-Mascheroni constant. `\gamma = 0.5772157\dots` (also called Euler's constant) is a mathematical constant recurring in analysis and number theory. It is defined as the limiting difference between the harmonic series and the natural logarithm: .. math:: \gamma = \lim\limits_{n\to\infty} \left(\sum\limits_{k=1}^n\frac{1}{k} - \ln n\right) EulerGamma is a singleton, and can be accessed by ``S.EulerGamma``. Examples ======== >>> from sympy import S >>> S.EulerGamma.is_irrational >>> S.EulerGamma > 0 True >>> S.EulerGamma > 1 False References ========== .. [1] http://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant """ is_real = True is_positive = True is_negative = False is_irrational = None __slots__ = [] def _latex(self, printer): return r"\gamma" def __int__(self): return 0 def _as_mpf_val(self, prec): # XXX track down why this has to be increased v = mlib.libhyper.euler_fixed(prec + 10) rv = mlib.from_man_exp(v, -prec - 10) return mpf_norm(rv, prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.Zero, S.One) elif issubclass(number_cls, Rational): return (S.Half, Rational(3, 5)) def _sage_(self): import sage.all as sage return sage.euler_gamma class Catalan(with_metaclass(Singleton, NumberSymbol)): r"""Catalan's constant. `K = 0.91596559\dots` is given by the infinite series .. math:: K = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2} Catalan is a singleton, and can be accessed by ``S.Catalan``. Examples ======== >>> from sympy import S >>> S.Catalan.is_irrational >>> S.Catalan > 0 True >>> S.Catalan > 1 False References ========== .. [1] http://en.wikipedia.org/wiki/Catalan%27s_constant """ is_real = True is_positive = True is_negative = False is_irrational = None __slots__ = [] def __int__(self): return 0 def _as_mpf_val(self, prec): # XXX track down why this has to be increased v = mlib.catalan_fixed(prec + 10) rv = mlib.from_man_exp(v, -prec - 10) return mpf_norm(rv, prec) def approximation_interval(self, number_cls): if issubclass(number_cls, Integer): return (S.Zero, S.One) elif issubclass(number_cls, Rational): return (Rational(9, 10), S.One) def _sage_(self): import sage.all as sage return sage.catalan class ImaginaryUnit(with_metaclass(Singleton, AtomicExpr)): r"""The imaginary unit, `i = \sqrt{-1}`. I is a singleton, and can be accessed by ``S.I``, or can be imported as ``I``. Examples ======== >>> from sympy import I, sqrt >>> sqrt(-1) I >>> I*I -1 >>> 1/I -I References ========== .. [1] http://en.wikipedia.org/wiki/Imaginary_unit """ is_commutative = True is_imaginary = True is_bounded = True is_finite = True is_number = True __slots__ = [] def _latex(self, printer): return r"i" @staticmethod def __abs__(): return S.One def _eval_evalf(self, prec): return self def _eval_conjugate(self): return -S.ImaginaryUnit def _eval_power(self, expt): """ b is I = sqrt(-1) e is symbolic object but not equal to 0, 1 I**r -> (-1)**(r/2) -> exp(r/2*Pi*I) -> sin(Pi*r/2) + cos(Pi*r/2)*I, r is decimal I**0 mod 4 -> 1 I**1 mod 4 -> I I**2 mod 4 -> -1 I**3 mod 4 -> -I """ if isinstance(expt, Number): if isinstance(expt, Integer): expt = expt.p % 4 if expt == 0: return S.One if expt == 1: return S.ImaginaryUnit if expt == 2: return -S.One return -S.ImaginaryUnit return (S.NegativeOne)**(expt*S.Half) return def as_base_exp(self): return S.NegativeOne, S.Half def _sage_(self): import sage.all as sage return sage.I I = S.ImaginaryUnit def sympify_fractions(f): return Rational(f.numerator, f.denominator) converter[fractions.Fraction] = sympify_fractions try: if HAS_GMPY == 2: import gmpy2 as gmpy elif HAS_GMPY == 1: import gmpy else: raise ImportError def sympify_mpz(x): return Integer(long(x)) def sympify_mpq(x): return Rational(long(x.numerator), long(x.denominator)) converter[type(gmpy.mpz(1))] = sympify_mpz converter[type(gmpy.mpq(1, 2))] = sympify_mpq except ImportError: pass def sympify_mpmath(x): return Expr._from_mpmath(x, x.context.prec) converter[mpnumeric] = sympify_mpmath def sympify_complex(a): real, imag = list(map(sympify, (a.real, a.imag))) return real + S.ImaginaryUnit*imag converter[complex] = sympify_complex _intcache[0] = S.Zero _intcache[1] = S.One _intcache[-1] = S.NegativeOne from .power import Pow, integer_nthroot from .mul import Mul Mul.identity = One() from .add import Add Add.identity = Zero()
{ "content_hash": "e99da789929ef2c87c7d75903bf7671b", "timestamp": "", "source": "github", "line_count": 3147, "max_line_length": 89, "avg_line_length": 28.74642516682555, "alnum_prop": 0.5301055656883877, "repo_name": "ojengwa/sympy", "id": "0cc780da272f7c8554bcdd7f2985217f981aa6dc", "size": "90465", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sympy/core/numbers.py", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package kr.ac.kaist.jsaf.nodes; import java.lang.Double; import java.lang.String; import java.math.BigInteger; import java.io.Writer; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.ArrayList; import java.util.LinkedList; import kr.ac.kaist.jsaf.nodes_util.*; import kr.ac.kaist.jsaf.useful.*; import edu.rice.cs.plt.tuple.Option; /** * Class WEAConst, a component of the ASTGen-generated composite hierarchy. * Note: null is not allowed as a value for any field. * @version Generated automatically by ASTGen at Mon Nov 21 18:10:57 CET 2016 */ @SuppressWarnings("unused") public class WEAConst extends WEAttribute { /** * Constructs a WEAConst. * @throws java.lang.IllegalArgumentException If any parameter to the constructor is null. */ public WEAConst() { super(); } public <RetType> RetType accept(WNodeVisitor<RetType> visitor) { return visitor.forWEAConst(this); } public void accept(WNodeVisitor_void visitor) { visitor.forWEAConst(this); } /** * Implementation of equals that is based on the values of the fields of the * object. Thus, two objects created with identical parameters will be equal. */ public boolean equals(Object obj) { if (obj == null) return false; if ((obj.getClass() != this.getClass()) || (obj.hashCode() != this.hashCode())) { return false; } else { WEAConst casted = (WEAConst) obj; return true; } } /** * Implementation of hashCode that is consistent with equals. The value of * the hashCode is formed by XORing the hashcode of the class object with * the hashcodes of all the fields of the object. */ public int generateHashCode() { int code = getClass().hashCode(); return code; } public void walk(TreeWalker w) { if (w.visitNode(this, "WEAConst", 0)) { w.endNode(this, "WEAConst", 0); } } }
{ "content_hash": "0e2c67322e62b334fa4da9af949a519b", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 95, "avg_line_length": 27.958904109589042, "alnum_prop": 0.6462518373346399, "repo_name": "darkrsw/safe", "id": "39d48b9e52b18c1a8acba5a3cd2e45c447cb3869", "size": "2041", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/kr/ac/kaist/jsaf/nodes/WEAConst.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "932" }, { "name": "C", "bytes": "391844" }, { "name": "C++", "bytes": "23560186" }, { "name": "CSS", "bytes": "3580565" }, { "name": "Emacs Lisp", "bytes": "9812" }, { "name": "GAP", "bytes": "4956" }, { "name": "HTML", "bytes": "12360645" }, { "name": "Jasmin", "bytes": "46" }, { "name": "Java", "bytes": "5647454" }, { "name": "JavaScript", "bytes": "23686582" }, { "name": "Lex", "bytes": "57542" }, { "name": "Makefile", "bytes": "30159" }, { "name": "Objective-C", "bytes": "360597" }, { "name": "Objective-J", "bytes": "4500028" }, { "name": "PHP", "bytes": "10002" }, { "name": "Perl", "bytes": "10556" }, { "name": "Python", "bytes": "229823" }, { "name": "Roff", "bytes": "52732" }, { "name": "Ruby", "bytes": "17326" }, { "name": "Scala", "bytes": "6529375" }, { "name": "Shell", "bytes": "153495" }, { "name": "Vim script", "bytes": "6985" }, { "name": "XSLT", "bytes": "21507" }, { "name": "Yacc", "bytes": "297844" } ], "symlink_target": "" }
<style> .blocos{ border:1px dashed grey; margin:5px 5px 1px; } .blocos:first-child{margin-top: 0px} </style> <script> $(document).ready(function(){ var options = { target: '.resultado_busca', // target element(s) to be updated with server response resetForm: false, beforeSubmit: showRequest, // pre-submit callback success: refreshPage, // post-submit callback }; $('form').on("submit",function(){ $(this).ajaxSubmit(options); return false; }); $(".btn_busca").on('click',function(){ var form = $(this).parents("form"); form.ajaxSubmit(options); //alert(form.attr('action')); }); if ($("#autor").val() != ""){ var form = $("#autor").parents('form'); $(form).ajaxSubmit(options); } if ($("#editora").val() != ""){ var form = $("#editora").parents('form'); $(form).ajaxSubmit(options); } $("#btnUpdateFoto").on("click", function() { var options = { target: '#conteudo_upFoto', // target element(s) to be updated with server response resetForm: true, beforeSubmit: showRequest, // pre-submit callback success: refreshPage // post-submit callback }; $('#formUpload').ajaxSubmit(options); }); }) </script> <div class="container-alternate"> <div class="container"> {view_lateral} <div class="col-md-9" style="background: transparent"> <div class="col-md-12 blocos"> <div class="col-lg-6 "> <form action="{base_url}livro/getlivro/titulo" method="post"> <div class="input-group"> <input type="text" name="titulo" class="form-control" placeholder="buscar por Titulo"> <span class="input-group-btn"> <button class="btn btn-default btn_busca " type="button"><i class="glyphicon glyphicon-search"></i></button> </span> </div><!-- /input-group --> </form> </div><!-- /.col-lg-6 --> <div class="col-lg-6 "> <form action="{base_url}livro/getlivro/autor" method="post"> <div class="input-group"> <input type="text" name="autor" id="autor" class="form-control" placeholder="buscar por Autor" value="<?= isset($campo_autor)? $campo_autor:"" ?>"> <span class="input-group-btn"> <button class="btn btn-default btn_busca" type="button"><i class="glyphicon glyphicon-search"></i></button> </span> </div><!-- /input-group --> </form> </div><!-- /.col-lg-6 --> <div class="col-lg-6 "> <form action="{base_url}livro/getlivro/editora" method="post"> <div class="input-group"> <input type="text" name="editora" id="editora" class="form-control" placeholder="buscar por Editora" value="<?= isset($campo_editora)? $campo_editora:"" ?>"> <span class="input-group-btn"> <button class="btn btn-default btn_busca" type="button"><i class="glyphicon glyphicon-search"></i></button> </span> </div><!-- /input-group --> </form> </div><!-- /.col-lg-6 --> <div class="col-lg-6 "> <form action="{base_url}livro/getlivro/isbn" method="post"> <div class="input-group"> <input type="text" name="isbn" class="form-control" placeholder="buscar por ISBN"> <span class="input-group-btn"> <button class="btn btn-default btn_busca " type="button"><i class="glyphicon glyphicon-search"></i></button> </span> </div><!-- /input-group --> </form> </div><!-- /.col-lg-6 --> </div> <div class="col-md-12 resultado_busca blocos"> </div> </div> </div> <br> </div> <div class="col-md-12"> <footer> Direitos reservados </footer> </div>
{ "content_hash": "a7f4085de00c320ea3b1dc02b2b7c9fd", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 181, "avg_line_length": 41.4054054054054, "alnum_prop": 0.4623585726718886, "repo_name": "ivanrufino/permutaLivro", "id": "b182e3eafb50fc46319e773829ef67c48ec4f044", "size": "4596", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "application/views/telas/buscarLivro.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "536" }, { "name": "CSS", "bytes": "173288" }, { "name": "HTML", "bytes": "26987" }, { "name": "JavaScript", "bytes": "61377" }, { "name": "PHP", "bytes": "4325404" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hobsoft.entangle; import java.util.Collections; import org.hobsoft.entangle.test.TestValidators; import org.junit.Test; import static org.hobsoft.entangle.test.BindingAssert.assertBinding; import static org.hobsoft.entangle.test.TestConverters.toStringConverter; import static org.junit.Assert.assertEquals; /** * Tests {@code DefaultBinding}. * * @author Mark Hobson * @see DefaultBinding */ public class DefaultBindingTest extends BindingTest { // TODO: pull up toString tests when format standardised // TODO: does it make sense to pull up constructor tests? // tests ------------------------------------------------------------------ @Test public void newDefaultBinding() { Observable<String> source = Observables.instance(); Observable<String> target = Observables.instance(); Converter<String, String> converter = Converters.identity(); DefaultBinding<String, String, String> binding = new DefaultBinding<String, String, String>(source, converter, target); assertBinding(source, converter, target, binding); assertEquals(Collections.emptyList(), binding.getValue()); } @Test public void newDefaultBindingWithValidators() { Observable<String> source = Observables.instance(); Observable<String> target = Observables.instance(); Converter<String, String> converter = Converters.identity(); Validator<String, String> sourceValidator = TestValidators.validString(); Validator<String, String> targetValidator = TestValidators.validString(); DefaultBinding<String, String, String> binding = new DefaultBinding<String, String, String>(source, sourceValidator, converter, targetValidator, target); assertBinding(source, sourceValidator, converter, targetValidator, target, binding); assertEquals(Collections.emptyList(), binding.getValue()); } @Test(expected = NullPointerException.class) public void newDefaultBindingWithNullSource() { Observable<String> target = Observables.instance(); Converter<String, String> converter = Converters.identity(); new DefaultBinding<String, String, String>(null, converter, target); } @Test(expected = NullPointerException.class) public void newDefaultBindingWithNullTarget() { Observable<String> source = Observables.instance(); Converter<String, String> converter = Converters.identity(); new DefaultBinding<String, String, String>(source, converter, null); } @Test(expected = NullPointerException.class) public void newDefaultBindingWithNullConverter() { Observable<String> source = Observables.instance(); Observable<String> target = Observables.instance(); new DefaultBinding<String, String, String>(source, null, target); } @Test public void toStringTest() { DefaultBinding<Object, Object, Object> binding = new DefaultBinding<Object, Object, Object>( Observables.instance(), Converters.identity(), Observables.instance()); String expected = "org.hobsoft.entangle.DefaultBinding[" + "source=" + binding.getSource() + "," + "target=" + binding.getTarget() + "]"; assertEquals(expected, binding.toString()); } @Test public void toStringWithConverter() { Observable<Integer> source = Observables.instance(); Observable<String> target = Observables.instance(); Converter<Integer, String> converter = toStringConverter(); DefaultBinding<Integer, String, String> binding = new DefaultBinding<Integer, String, String>(source, converter, target); String expected = "org.hobsoft.entangle.DefaultBinding[" + "source=" + source + "," + "target=" + target + "," + "converter=" + converter + "]"; assertEquals(expected, binding.toString()); } // BindingTest methods ---------------------------------------------------- /** * {@inheritDoc} */ @Override protected <S, T, V> Binding<S, T, V> createBinding(Observable<S> source, Validator<? super S, V> sourceValidator, Converter<S, T> converter, Validator<? super T, V> targetValidator, Observable<T> target) { return new DefaultBinding<S, T, V>(source, sourceValidator, converter, targetValidator, target); } }
{ "content_hash": "00e2980288c4c5c0731e6430eedca0f8", "timestamp": "", "source": "github", "line_count": 137, "max_line_length": 114, "avg_line_length": 34.02919708029197, "alnum_prop": 0.7198627198627199, "repo_name": "markhobson/entangle", "id": "95935c39aba29d142ab2223784f35f8c7c37e3c7", "size": "4662", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/hobsoft/entangle/DefaultBindingTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "205188" } ], "symlink_target": "" }
ACCEPTED #### According to Integrated Taxonomic Information System #### Published in null #### Original name null ### Remarks null
{ "content_hash": "2e085dabf0c995f4170e508ff86fcb72", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.7238805970149254, "repo_name": "mdoering/backbone", "id": "dd221c3b97146b522c919b9ed84ec3ae54d09d47", "size": "188", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Chlorophyta/Chlorophyceae/Chlorococcales/Hydrodictyaceae/Pediastrum/Pediastrum tetras/Pediastrum tetras evoluta/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
import json import unittest2 from unittest2 import SkipTest from uuid import uuid4 from test.functional import check_response, cluster_info, retry, \ requires_acls, load_constraint, requires_policies import test.functional as tf from six.moves import range def setUpModule(): tf.setup_package() def tearDownModule(): tf.teardown_package() class TestContainer(unittest2.TestCase): def setUp(self): if tf.skip: raise SkipTest self.name = uuid4().hex # this container isn't created by default, but will be cleaned up self.container = uuid4().hex def put(url, token, parsed, conn): conn.request('PUT', parsed.path + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(put) resp.read() self.assertEqual(resp.status, 201) self.max_meta_count = load_constraint('max_meta_count') self.max_meta_name_length = load_constraint('max_meta_name_length') self.max_meta_overall_size = load_constraint('max_meta_overall_size') self.max_meta_value_length = load_constraint('max_meta_value_length') def tearDown(self): if tf.skip: raise SkipTest def get(url, token, parsed, conn, container): conn.request( 'GET', parsed.path + '/' + container + '?format=json', '', {'X-Auth-Token': token}) return check_response(conn) def delete(url, token, parsed, conn, container, obj): conn.request( 'DELETE', '/'.join([parsed.path, container, obj['name']]), '', {'X-Auth-Token': token}) return check_response(conn) for container in (self.name, self.container): while True: resp = retry(get, container) body = resp.read() if resp.status == 404: break self.assertEqual(resp.status // 100, 2, resp.status) objs = json.loads(body) if not objs: break for obj in objs: resp = retry(delete, container, obj) resp.read() self.assertEqual(resp.status, 204) def delete(url, token, parsed, conn, container): conn.request('DELETE', parsed.path + '/' + container, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(delete, self.name) resp.read() self.assertEqual(resp.status, 204) # container may have not been created resp = retry(delete, self.container) resp.read() self.assertIn(resp.status, (204, 404)) def test_multi_metadata(self): if tf.skip: raise SkipTest def post(url, token, parsed, conn, name, value): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, name: value}) return check_response(conn) def head(url, token, parsed, conn): conn.request('HEAD', parsed.path + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(post, 'X-Container-Meta-One', '1') resp.read() self.assertEqual(resp.status, 204) resp = retry(head) resp.read() self.assertIn(resp.status, (200, 204)) self.assertEqual(resp.getheader('x-container-meta-one'), '1') resp = retry(post, 'X-Container-Meta-Two', '2') resp.read() self.assertEqual(resp.status, 204) resp = retry(head) resp.read() self.assertIn(resp.status, (200, 204)) self.assertEqual(resp.getheader('x-container-meta-one'), '1') self.assertEqual(resp.getheader('x-container-meta-two'), '2') def test_unicode_metadata(self): if tf.skip: raise SkipTest def post(url, token, parsed, conn, name, value): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, name: value}) return check_response(conn) def head(url, token, parsed, conn): conn.request('HEAD', parsed.path + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) uni_key = u'X-Container-Meta-uni\u0E12' uni_value = u'uni\u0E12' if (tf.web_front_end == 'integral'): resp = retry(post, uni_key, '1') resp.read() self.assertEqual(resp.status, 204) resp = retry(head) resp.read() self.assertIn(resp.status, (200, 204)) self.assertEqual(resp.getheader(uni_key.encode('utf-8')), '1') resp = retry(post, 'X-Container-Meta-uni', uni_value) resp.read() self.assertEqual(resp.status, 204) resp = retry(head) resp.read() self.assertIn(resp.status, (200, 204)) self.assertEqual(resp.getheader('X-Container-Meta-uni'), uni_value.encode('utf-8')) if (tf.web_front_end == 'integral'): resp = retry(post, uni_key, uni_value) resp.read() self.assertEqual(resp.status, 204) resp = retry(head) resp.read() self.assertIn(resp.status, (200, 204)) self.assertEqual(resp.getheader(uni_key.encode('utf-8')), uni_value.encode('utf-8')) def test_PUT_metadata(self): if tf.skip: raise SkipTest def put(url, token, parsed, conn, name, value): conn.request('PUT', parsed.path + '/' + name, '', {'X-Auth-Token': token, 'X-Container-Meta-Test': value}) return check_response(conn) def head(url, token, parsed, conn, name): conn.request('HEAD', parsed.path + '/' + name, '', {'X-Auth-Token': token}) return check_response(conn) def get(url, token, parsed, conn, name): conn.request('GET', parsed.path + '/' + name, '', {'X-Auth-Token': token}) return check_response(conn) def delete(url, token, parsed, conn, name): conn.request('DELETE', parsed.path + '/' + name, '', {'X-Auth-Token': token}) return check_response(conn) name = uuid4().hex resp = retry(put, name, 'Value') resp.read() self.assertEqual(resp.status, 201) resp = retry(head, name) resp.read() self.assertIn(resp.status, (200, 204)) self.assertEqual(resp.getheader('x-container-meta-test'), 'Value') resp = retry(get, name) resp.read() self.assertIn(resp.status, (200, 204)) self.assertEqual(resp.getheader('x-container-meta-test'), 'Value') resp = retry(delete, name) resp.read() self.assertEqual(resp.status, 204) name = uuid4().hex resp = retry(put, name, '') resp.read() self.assertEqual(resp.status, 201) resp = retry(head, name) resp.read() self.assertIn(resp.status, (200, 204)) self.assertIsNone(resp.getheader('x-container-meta-test')) resp = retry(get, name) resp.read() self.assertIn(resp.status, (200, 204)) self.assertIsNone(resp.getheader('x-container-meta-test')) resp = retry(delete, name) resp.read() self.assertEqual(resp.status, 204) def test_POST_metadata(self): if tf.skip: raise SkipTest def post(url, token, parsed, conn, value): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, 'X-Container-Meta-Test': value}) return check_response(conn) def head(url, token, parsed, conn): conn.request('HEAD', parsed.path + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) def get(url, token, parsed, conn): conn.request('GET', parsed.path + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(head) resp.read() self.assertIn(resp.status, (200, 204)) self.assertIsNone(resp.getheader('x-container-meta-test')) resp = retry(get) resp.read() self.assertIn(resp.status, (200, 204)) self.assertIsNone(resp.getheader('x-container-meta-test')) resp = retry(post, 'Value') resp.read() self.assertEqual(resp.status, 204) resp = retry(head) resp.read() self.assertIn(resp.status, (200, 204)) self.assertEqual(resp.getheader('x-container-meta-test'), 'Value') resp = retry(get) resp.read() self.assertIn(resp.status, (200, 204)) self.assertEqual(resp.getheader('x-container-meta-test'), 'Value') def test_PUT_bad_metadata(self): if tf.skip: raise SkipTest def put(url, token, parsed, conn, name, extra_headers): headers = {'X-Auth-Token': token} headers.update(extra_headers) conn.request('PUT', parsed.path + '/' + name, '', headers) return check_response(conn) def delete(url, token, parsed, conn, name): conn.request('DELETE', parsed.path + '/' + name, '', {'X-Auth-Token': token}) return check_response(conn) name = uuid4().hex resp = retry( put, name, {'X-Container-Meta-' + ('k' * self.max_meta_name_length): 'v'}) resp.read() self.assertEqual(resp.status, 201) resp = retry(delete, name) resp.read() self.assertEqual(resp.status, 204) name = uuid4().hex resp = retry( put, name, {'X-Container-Meta-' + ( 'k' * (self.max_meta_name_length + 1)): 'v'}) resp.read() self.assertEqual(resp.status, 400) resp = retry(delete, name) resp.read() self.assertEqual(resp.status, 404) name = uuid4().hex resp = retry( put, name, {'X-Container-Meta-Too-Long': 'k' * self.max_meta_value_length}) resp.read() self.assertEqual(resp.status, 201) resp = retry(delete, name) resp.read() self.assertEqual(resp.status, 204) name = uuid4().hex resp = retry( put, name, {'X-Container-Meta-Too-Long': 'k' * ( self.max_meta_value_length + 1)}) resp.read() self.assertEqual(resp.status, 400) resp = retry(delete, name) resp.read() self.assertEqual(resp.status, 404) name = uuid4().hex headers = {} for x in range(self.max_meta_count): headers['X-Container-Meta-%d' % x] = 'v' resp = retry(put, name, headers) resp.read() self.assertEqual(resp.status, 201) resp = retry(delete, name) resp.read() self.assertEqual(resp.status, 204) name = uuid4().hex headers = {} for x in range(self.max_meta_count + 1): headers['X-Container-Meta-%d' % x] = 'v' resp = retry(put, name, headers) resp.read() self.assertEqual(resp.status, 400) resp = retry(delete, name) resp.read() self.assertEqual(resp.status, 404) name = uuid4().hex headers = {} header_value = 'k' * self.max_meta_value_length size = 0 x = 0 while size < (self.max_meta_overall_size - 4 - self.max_meta_value_length): size += 4 + self.max_meta_value_length headers['X-Container-Meta-%04d' % x] = header_value x += 1 if self.max_meta_overall_size - size > 1: headers['X-Container-Meta-k'] = \ 'v' * (self.max_meta_overall_size - size - 1) resp = retry(put, name, headers) resp.read() self.assertEqual(resp.status, 201) resp = retry(delete, name) resp.read() self.assertEqual(resp.status, 204) name = uuid4().hex headers['X-Container-Meta-k'] = \ 'v' * (self.max_meta_overall_size - size) resp = retry(put, name, headers) resp.read() self.assertEqual(resp.status, 400) resp = retry(delete, name) resp.read() self.assertEqual(resp.status, 404) def test_POST_bad_metadata(self): if tf.skip: raise SkipTest def post(url, token, parsed, conn, extra_headers): headers = {'X-Auth-Token': token} headers.update(extra_headers) conn.request('POST', parsed.path + '/' + self.name, '', headers) return check_response(conn) resp = retry( post, {'X-Container-Meta-' + ('k' * self.max_meta_name_length): 'v'}) resp.read() self.assertEqual(resp.status, 204) resp = retry( post, {'X-Container-Meta-' + ( 'k' * (self.max_meta_name_length + 1)): 'v'}) resp.read() self.assertEqual(resp.status, 400) resp = retry( post, {'X-Container-Meta-Too-Long': 'k' * self.max_meta_value_length}) resp.read() self.assertEqual(resp.status, 204) resp = retry( post, {'X-Container-Meta-Too-Long': 'k' * ( self.max_meta_value_length + 1)}) resp.read() self.assertEqual(resp.status, 400) def test_POST_bad_metadata2(self): if tf.skip: raise SkipTest def post(url, token, parsed, conn, extra_headers): headers = {'X-Auth-Token': token} headers.update(extra_headers) conn.request('POST', parsed.path + '/' + self.name, '', headers) return check_response(conn) headers = {} for x in range(self.max_meta_count): headers['X-Container-Meta-%d' % x] = 'v' resp = retry(post, headers) resp.read() self.assertEqual(resp.status, 204) headers = {} for x in range(self.max_meta_count + 1): headers['X-Container-Meta-%d' % x] = 'v' resp = retry(post, headers) resp.read() self.assertEqual(resp.status, 400) def test_POST_bad_metadata3(self): if tf.skip: raise SkipTest if tf.in_process: tf.skip_if_no_xattrs() def post(url, token, parsed, conn, extra_headers): headers = {'X-Auth-Token': token} headers.update(extra_headers) conn.request('POST', parsed.path + '/' + self.name, '', headers) return check_response(conn) headers = {} header_value = 'k' * self.max_meta_value_length size = 0 x = 0 while size < (self.max_meta_overall_size - 4 - self.max_meta_value_length): size += 4 + self.max_meta_value_length headers['X-Container-Meta-%04d' % x] = header_value x += 1 if self.max_meta_overall_size - size > 1: headers['X-Container-Meta-k'] = \ 'v' * (self.max_meta_overall_size - size - 1) resp = retry(post, headers) resp.read() self.assertEqual(resp.status, 204) # this POST includes metadata size that is over limit headers['X-Container-Meta-k'] = \ 'x' * (self.max_meta_overall_size - size) resp = retry(post, headers) resp.read() self.assertEqual(resp.status, 400) # this POST would be ok and the aggregate backend metadata # size is on the border headers = {'X-Container-Meta-k': 'y' * (self.max_meta_overall_size - size - 1)} resp = retry(post, headers) resp.read() self.assertEqual(resp.status, 204) # this last POST would be ok by itself but takes the aggregate # backend metadata size over limit headers = {'X-Container-Meta-k': 'z' * (self.max_meta_overall_size - size)} resp = retry(post, headers) resp.read() self.assertEqual(resp.status, 400) def test_public_container(self): if tf.skip: raise SkipTest def get(url, token, parsed, conn): conn.request('GET', parsed.path + '/' + self.name) return check_response(conn) try: resp = retry(get) raise Exception('Should not have been able to GET') except Exception as err: self.assertTrue(str(err).startswith('No result after '), err) def post(url, token, parsed, conn): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, 'X-Container-Read': '.r:*,.rlistings'}) return check_response(conn) resp = retry(post) resp.read() self.assertEqual(resp.status, 204) resp = retry(get) resp.read() self.assertEqual(resp.status, 204) def post(url, token, parsed, conn): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, 'X-Container-Read': ''}) return check_response(conn) resp = retry(post) resp.read() self.assertEqual(resp.status, 204) try: resp = retry(get) raise Exception('Should not have been able to GET') except Exception as err: self.assertTrue(str(err).startswith('No result after '), err) def test_cross_account_container(self): if tf.skip or tf.skip2: raise SkipTest # Obtain the first account's string first_account = ['unknown'] def get1(url, token, parsed, conn): first_account[0] = parsed.path conn.request('HEAD', parsed.path + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(get1) resp.read() # Ensure we can't access the container with the second account def get2(url, token, parsed, conn): conn.request('GET', first_account[0] + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(get2, use_account=2) resp.read() self.assertEqual(resp.status, 403) # Make the container accessible by the second account def post(url, token, parsed, conn): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, 'X-Container-Read': tf.swift_test_perm[1], 'X-Container-Write': tf.swift_test_perm[1]}) return check_response(conn) resp = retry(post) resp.read() self.assertEqual(resp.status, 204) # Ensure we can now use the container with the second account resp = retry(get2, use_account=2) resp.read() self.assertEqual(resp.status, 204) # Make the container private again def post(url, token, parsed, conn): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, 'X-Container-Read': '', 'X-Container-Write': ''}) return check_response(conn) resp = retry(post) resp.read() self.assertEqual(resp.status, 204) # Ensure we can't access the container with the second account again resp = retry(get2, use_account=2) resp.read() self.assertEqual(resp.status, 403) def test_cross_account_public_container(self): if tf.skip or tf.skip2: raise SkipTest if tf.in_process: tf.skip_if_no_xattrs() # Obtain the first account's string first_account = ['unknown'] def get1(url, token, parsed, conn): first_account[0] = parsed.path conn.request('HEAD', parsed.path + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(get1) resp.read() # Ensure we can't access the container with the second account def get2(url, token, parsed, conn): conn.request('GET', first_account[0] + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(get2, use_account=2) resp.read() self.assertEqual(resp.status, 403) # Make the container completely public def post(url, token, parsed, conn): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, 'X-Container-Read': '.r:*,.rlistings'}) return check_response(conn) resp = retry(post) resp.read() self.assertEqual(resp.status, 204) # Ensure we can now read the container with the second account resp = retry(get2, use_account=2) resp.read() self.assertEqual(resp.status, 204) # But we shouldn't be able to write with the second account def put2(url, token, parsed, conn): conn.request('PUT', first_account[0] + '/' + self.name + '/object', 'test object', {'X-Auth-Token': token}) return check_response(conn) resp = retry(put2, use_account=2) resp.read() self.assertEqual(resp.status, 403) # Now make the container also writable by the second account def post(url, token, parsed, conn): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, 'X-Container-Write': tf.swift_test_perm[1]}) return check_response(conn) resp = retry(post) resp.read() self.assertEqual(resp.status, 204) # Ensure we can still read the container with the second account resp = retry(get2, use_account=2) resp.read() self.assertEqual(resp.status, 204) # And that we can now write with the second account resp = retry(put2, use_account=2) resp.read() self.assertEqual(resp.status, 201) def test_nonadmin_user(self): if tf.skip or tf.skip3: raise SkipTest if tf.in_process: tf.skip_if_no_xattrs() # Obtain the first account's string first_account = ['unknown'] def get1(url, token, parsed, conn): first_account[0] = parsed.path conn.request('HEAD', parsed.path + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(get1) resp.read() # Ensure we can't access the container with the third account def get3(url, token, parsed, conn): conn.request('GET', first_account[0] + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(get3, use_account=3) resp.read() self.assertEqual(resp.status, 403) # Make the container accessible by the third account def post(url, token, parsed, conn): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, 'X-Container-Read': tf.swift_test_perm[2]}) return check_response(conn) resp = retry(post) resp.read() self.assertEqual(resp.status, 204) # Ensure we can now read the container with the third account resp = retry(get3, use_account=3) resp.read() self.assertEqual(resp.status, 204) # But we shouldn't be able to write with the third account def put3(url, token, parsed, conn): conn.request('PUT', first_account[0] + '/' + self.name + '/object', 'test object', {'X-Auth-Token': token}) return check_response(conn) resp = retry(put3, use_account=3) resp.read() self.assertEqual(resp.status, 403) # Now make the container also writable by the third account def post(url, token, parsed, conn): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, 'X-Container-Write': tf.swift_test_perm[2]}) return check_response(conn) resp = retry(post) resp.read() self.assertEqual(resp.status, 204) # Ensure we can still read the container with the third account resp = retry(get3, use_account=3) resp.read() self.assertEqual(resp.status, 204) # And that we can now write with the third account resp = retry(put3, use_account=3) resp.read() self.assertEqual(resp.status, 201) @requires_acls def test_read_only_acl_listings(self): if tf.skip3: raise SkipTest def get(url, token, parsed, conn): conn.request('GET', parsed.path, '', {'X-Auth-Token': token}) return check_response(conn) def post_account(url, token, parsed, conn, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path, '', new_headers) return check_response(conn) def put(url, token, parsed, conn, name): conn.request('PUT', parsed.path + '/%s' % name, '', {'X-Auth-Token': token}) return check_response(conn) # cannot list containers resp = retry(get, use_account=3) resp.read() self.assertEqual(resp.status, 403) # grant read-only access acl_user = tf.swift_test_user[2] acl = {'read-only': [acl_user]} headers = {'x-account-access-control': json.dumps(acl)} resp = retry(post_account, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) # read-only can list containers resp = retry(get, use_account=3) listing = resp.read() self.assertEqual(resp.status, 200) self.assertIn(self.name, listing) # read-only can not create containers new_container_name = str(uuid4()) resp = retry(put, new_container_name, use_account=3) resp.read() self.assertEqual(resp.status, 403) # but it can see newly created ones resp = retry(put, new_container_name, use_account=1) resp.read() self.assertEqual(resp.status, 201) resp = retry(get, use_account=3) listing = resp.read() self.assertEqual(resp.status, 200) self.assertIn(new_container_name, listing) @requires_acls def test_read_only_acl_metadata(self): if tf.skip3: raise SkipTest def get(url, token, parsed, conn, name): conn.request('GET', parsed.path + '/%s' % name, '', {'X-Auth-Token': token}) return check_response(conn) def post_account(url, token, parsed, conn, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path, '', new_headers) return check_response(conn) def post(url, token, parsed, conn, name, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path + '/%s' % name, '', new_headers) return check_response(conn) # add some metadata value = str(uuid4()) headers = {'x-container-meta-test': value} resp = retry(post, self.name, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=1) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), value) # cannot see metadata resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 403) # grant read-only access acl_user = tf.swift_test_user[2] acl = {'read-only': [acl_user]} headers = {'x-account-access-control': json.dumps(acl)} resp = retry(post_account, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) # read-only can NOT write container metadata new_value = str(uuid4()) headers = {'x-container-meta-test': new_value} resp = retry(post, self.name, headers=headers, use_account=3) resp.read() self.assertEqual(resp.status, 403) # read-only can read container metadata resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), value) @requires_acls def test_read_write_acl_listings(self): if tf.skip3: raise SkipTest def get(url, token, parsed, conn): conn.request('GET', parsed.path, '', {'X-Auth-Token': token}) return check_response(conn) def post(url, token, parsed, conn, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path, '', new_headers) return check_response(conn) def put(url, token, parsed, conn, name): conn.request('PUT', parsed.path + '/%s' % name, '', {'X-Auth-Token': token}) return check_response(conn) def delete(url, token, parsed, conn, name): conn.request('DELETE', parsed.path + '/%s' % name, '', {'X-Auth-Token': token}) return check_response(conn) # cannot list containers resp = retry(get, use_account=3) resp.read() self.assertEqual(resp.status, 403) # grant read-write access acl_user = tf.swift_test_user[2] acl = {'read-write': [acl_user]} headers = {'x-account-access-control': json.dumps(acl)} resp = retry(post, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) # can list containers resp = retry(get, use_account=3) listing = resp.read() self.assertEqual(resp.status, 200) self.assertIn(self.name, listing) # can create new containers new_container_name = str(uuid4()) resp = retry(put, new_container_name, use_account=3) resp.read() self.assertEqual(resp.status, 201) resp = retry(get, use_account=3) listing = resp.read() self.assertEqual(resp.status, 200) self.assertIn(new_container_name, listing) # can also delete them resp = retry(delete, new_container_name, use_account=3) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, use_account=3) listing = resp.read() self.assertEqual(resp.status, 200) self.assertNotIn(new_container_name, listing) # even if they didn't create them empty_container_name = str(uuid4()) resp = retry(put, empty_container_name, use_account=1) resp.read() self.assertEqual(resp.status, 201) resp = retry(delete, empty_container_name, use_account=3) resp.read() self.assertEqual(resp.status, 204) @requires_acls def test_read_write_acl_metadata(self): if tf.skip3: raise SkipTest def get(url, token, parsed, conn, name): conn.request('GET', parsed.path + '/%s' % name, '', {'X-Auth-Token': token}) return check_response(conn) def post_account(url, token, parsed, conn, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path, '', new_headers) return check_response(conn) def post(url, token, parsed, conn, name, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path + '/%s' % name, '', new_headers) return check_response(conn) # add some metadata value = str(uuid4()) headers = {'x-container-meta-test': value} resp = retry(post, self.name, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=1) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), value) # cannot see metadata resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 403) # grant read-write access acl_user = tf.swift_test_user[2] acl = {'read-write': [acl_user]} headers = {'x-account-access-control': json.dumps(acl)} resp = retry(post_account, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) # read-write can read container metadata resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), value) # read-write can also write container metadata new_value = str(uuid4()) headers = {'x-container-meta-test': new_value} resp = retry(post, self.name, headers=headers, use_account=3) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), new_value) # and remove it headers = {'x-remove-container-meta-test': 'true'} resp = retry(post, self.name, headers=headers, use_account=3) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertIsNone(resp.getheader('X-Container-Meta-Test')) @requires_acls def test_admin_acl_listing(self): if tf.skip3: raise SkipTest def get(url, token, parsed, conn): conn.request('GET', parsed.path, '', {'X-Auth-Token': token}) return check_response(conn) def post(url, token, parsed, conn, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path, '', new_headers) return check_response(conn) def put(url, token, parsed, conn, name): conn.request('PUT', parsed.path + '/%s' % name, '', {'X-Auth-Token': token}) return check_response(conn) def delete(url, token, parsed, conn, name): conn.request('DELETE', parsed.path + '/%s' % name, '', {'X-Auth-Token': token}) return check_response(conn) # cannot list containers resp = retry(get, use_account=3) resp.read() self.assertEqual(resp.status, 403) # grant admin access acl_user = tf.swift_test_user[2] acl = {'admin': [acl_user]} headers = {'x-account-access-control': json.dumps(acl)} resp = retry(post, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) # can list containers resp = retry(get, use_account=3) listing = resp.read() self.assertEqual(resp.status, 200) self.assertIn(self.name, listing) # can create new containers new_container_name = str(uuid4()) resp = retry(put, new_container_name, use_account=3) resp.read() self.assertEqual(resp.status, 201) resp = retry(get, use_account=3) listing = resp.read() self.assertEqual(resp.status, 200) self.assertIn(new_container_name, listing) # can also delete them resp = retry(delete, new_container_name, use_account=3) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, use_account=3) listing = resp.read() self.assertEqual(resp.status, 200) self.assertNotIn(new_container_name, listing) # even if they didn't create them empty_container_name = str(uuid4()) resp = retry(put, empty_container_name, use_account=1) resp.read() self.assertEqual(resp.status, 201) resp = retry(delete, empty_container_name, use_account=3) resp.read() self.assertEqual(resp.status, 204) @requires_acls def test_admin_acl_metadata(self): if tf.skip3: raise SkipTest def get(url, token, parsed, conn, name): conn.request('GET', parsed.path + '/%s' % name, '', {'X-Auth-Token': token}) return check_response(conn) def post_account(url, token, parsed, conn, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path, '', new_headers) return check_response(conn) def post(url, token, parsed, conn, name, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path + '/%s' % name, '', new_headers) return check_response(conn) # add some metadata value = str(uuid4()) headers = {'x-container-meta-test': value} resp = retry(post, self.name, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=1) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), value) # cannot see metadata resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 403) # grant access acl_user = tf.swift_test_user[2] acl = {'admin': [acl_user]} headers = {'x-account-access-control': json.dumps(acl)} resp = retry(post_account, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) # can read container metadata resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), value) # can also write container metadata new_value = str(uuid4()) headers = {'x-container-meta-test': new_value} resp = retry(post, self.name, headers=headers, use_account=3) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), new_value) # and remove it headers = {'x-remove-container-meta-test': 'true'} resp = retry(post, self.name, headers=headers, use_account=3) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertIsNone(resp.getheader('X-Container-Meta-Test')) @requires_acls def test_protected_container_sync(self): if tf.skip3: raise SkipTest def get(url, token, parsed, conn, name): conn.request('GET', parsed.path + '/%s' % name, '', {'X-Auth-Token': token}) return check_response(conn) def post_account(url, token, parsed, conn, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path, '', new_headers) return check_response(conn) def post(url, token, parsed, conn, name, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path + '/%s' % name, '', new_headers) return check_response(conn) # add some metadata value = str(uuid4()) headers = { 'x-container-sync-key': 'secret', 'x-container-meta-test': value, } resp = retry(post, self.name, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=1) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Sync-Key'), 'secret') self.assertEqual(resp.getheader('X-Container-Meta-Test'), value) # grant read-only access acl_user = tf.swift_test_user[2] acl = {'read-only': [acl_user]} headers = {'x-account-access-control': json.dumps(acl)} resp = retry(post_account, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) # can read container metadata resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), value) # but not sync-key self.assertIsNone(resp.getheader('X-Container-Sync-Key')) # and can not write headers = {'x-container-sync-key': str(uuid4())} resp = retry(post, self.name, headers=headers, use_account=3) resp.read() self.assertEqual(resp.status, 403) # grant read-write access acl_user = tf.swift_test_user[2] acl = {'read-write': [acl_user]} headers = {'x-account-access-control': json.dumps(acl)} resp = retry(post_account, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) # can read container metadata resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), value) # but not sync-key self.assertIsNone(resp.getheader('X-Container-Sync-Key')) # sanity check sync-key w/ account1 resp = retry(get, self.name, use_account=1) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Sync-Key'), 'secret') # and can write new_value = str(uuid4()) headers = { 'x-container-sync-key': str(uuid4()), 'x-container-meta-test': new_value, } resp = retry(post, self.name, headers=headers, use_account=3) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=1) # validate w/ account1 resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), new_value) # but can not write sync-key self.assertEqual(resp.getheader('X-Container-Sync-Key'), 'secret') # grant admin access acl_user = tf.swift_test_user[2] acl = {'admin': [acl_user]} headers = {'x-account-access-control': json.dumps(acl)} resp = retry(post_account, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) # admin can read container metadata resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), new_value) # and ALSO sync-key self.assertEqual(resp.getheader('X-Container-Sync-Key'), 'secret') # admin tester3 can even change sync-key new_secret = str(uuid4()) headers = {'x-container-sync-key': new_secret} resp = retry(post, self.name, headers=headers, use_account=3) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Sync-Key'), new_secret) @requires_acls def test_protected_container_acl(self): if tf.skip3: raise SkipTest def get(url, token, parsed, conn, name): conn.request('GET', parsed.path + '/%s' % name, '', {'X-Auth-Token': token}) return check_response(conn) def post_account(url, token, parsed, conn, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path, '', new_headers) return check_response(conn) def post(url, token, parsed, conn, name, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path + '/%s' % name, '', new_headers) return check_response(conn) # add some container acls value = str(uuid4()) headers = { 'x-container-read': 'jdoe', 'x-container-write': 'jdoe', 'x-container-meta-test': value, } resp = retry(post, self.name, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=1) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Read'), 'jdoe') self.assertEqual(resp.getheader('X-Container-Write'), 'jdoe') self.assertEqual(resp.getheader('X-Container-Meta-Test'), value) # grant read-only access acl_user = tf.swift_test_user[2] acl = {'read-only': [acl_user]} headers = {'x-account-access-control': json.dumps(acl)} resp = retry(post_account, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) # can read container metadata resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), value) # but not container acl self.assertIsNone(resp.getheader('X-Container-Read')) self.assertIsNone(resp.getheader('X-Container-Write')) # and can not write headers = { 'x-container-read': 'frank', 'x-container-write': 'frank', } resp = retry(post, self.name, headers=headers, use_account=3) resp.read() self.assertEqual(resp.status, 403) # grant read-write access acl_user = tf.swift_test_user[2] acl = {'read-write': [acl_user]} headers = {'x-account-access-control': json.dumps(acl)} resp = retry(post_account, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) # can read container metadata resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), value) # but not container acl self.assertIsNone(resp.getheader('X-Container-Read')) self.assertIsNone(resp.getheader('X-Container-Write')) # sanity check container acls with account1 resp = retry(get, self.name, use_account=1) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Read'), 'jdoe') self.assertEqual(resp.getheader('X-Container-Write'), 'jdoe') # and can write new_value = str(uuid4()) headers = { 'x-container-read': 'frank', 'x-container-write': 'frank', 'x-container-meta-test': new_value, } resp = retry(post, self.name, headers=headers, use_account=3) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=1) # validate w/ account1 resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), new_value) # but can not write container acls self.assertEqual(resp.getheader('X-Container-Read'), 'jdoe') self.assertEqual(resp.getheader('X-Container-Write'), 'jdoe') # grant admin access acl_user = tf.swift_test_user[2] acl = {'admin': [acl_user]} headers = {'x-account-access-control': json.dumps(acl)} resp = retry(post_account, headers=headers, use_account=1) resp.read() self.assertEqual(resp.status, 204) # admin can read container metadata resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Meta-Test'), new_value) # and ALSO container acls self.assertEqual(resp.getheader('X-Container-Read'), 'jdoe') self.assertEqual(resp.getheader('X-Container-Write'), 'jdoe') # admin tester3 can even change container acls new_value = str(uuid4()) headers = { 'x-container-read': '.r:*', } resp = retry(post, self.name, headers=headers, use_account=3) resp.read() self.assertEqual(resp.status, 204) resp = retry(get, self.name, use_account=3) resp.read() self.assertEqual(resp.status, 204) self.assertEqual(resp.getheader('X-Container-Read'), '.r:*') def test_long_name_content_type(self): if tf.skip: raise SkipTest def put(url, token, parsed, conn): container_name = 'X' * 2048 conn.request('PUT', '%s/%s' % (parsed.path, container_name), 'there', {'X-Auth-Token': token}) return check_response(conn) resp = retry(put) resp.read() self.assertEqual(resp.status, 400) self.assertEqual(resp.getheader('Content-Type'), 'text/html; charset=UTF-8') def test_null_name(self): if tf.skip: raise SkipTest def put(url, token, parsed, conn): conn.request('PUT', '%s/abc%%00def' % parsed.path, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(put) if (tf.web_front_end == 'apache2'): self.assertEqual(resp.status, 404) else: self.assertEqual(resp.read(), 'Invalid UTF8 or contains NULL') self.assertEqual(resp.status, 412) def test_create_container_gets_default_policy_by_default(self): try: default_policy = \ tf.FunctionalStoragePolicyCollection.from_info().default except AssertionError: raise SkipTest() def put(url, token, parsed, conn): # using the empty storage policy header value here to ensure # that the default policy is chosen in case policy_specified is set # see __init__.py for details on policy_specified conn.request('PUT', parsed.path + '/' + self.container, '', {'X-Auth-Token': token, 'X-Storage-Policy': ''}) return check_response(conn) resp = retry(put) resp.read() self.assertEqual(resp.status // 100, 2) def head(url, token, parsed, conn): conn.request('HEAD', parsed.path + '/' + self.container, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(head) resp.read() headers = dict((k.lower(), v) for k, v in resp.getheaders()) self.assertEqual(headers.get('x-storage-policy'), default_policy['name']) def test_error_invalid_storage_policy_name(self): def put(url, token, parsed, conn, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('PUT', parsed.path + '/' + self.container, '', new_headers) return check_response(conn) # create resp = retry(put, {'X-Storage-Policy': uuid4().hex}) resp.read() self.assertEqual(resp.status, 400) @requires_policies def test_create_non_default_storage_policy_container(self): policy = self.policies.exclude(default=True).select() def put(url, token, parsed, conn, headers=None): base_headers = {'X-Auth-Token': token} if headers: base_headers.update(headers) conn.request('PUT', parsed.path + '/' + self.container, '', base_headers) return check_response(conn) headers = {'X-Storage-Policy': policy['name']} resp = retry(put, headers=headers) resp.read() self.assertEqual(resp.status, 201) def head(url, token, parsed, conn): conn.request('HEAD', parsed.path + '/' + self.container, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(head) resp.read() headers = dict((k.lower(), v) for k, v in resp.getheaders()) self.assertEqual(headers.get('x-storage-policy'), policy['name']) # and test recreate with-out specifying Storage Policy resp = retry(put) resp.read() self.assertEqual(resp.status, 202) # should still be original storage policy resp = retry(head) resp.read() headers = dict((k.lower(), v) for k, v in resp.getheaders()) self.assertEqual(headers.get('x-storage-policy'), policy['name']) # delete it def delete(url, token, parsed, conn): conn.request('DELETE', parsed.path + '/' + self.container, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(delete) resp.read() self.assertEqual(resp.status, 204) # verify no policy header resp = retry(head) resp.read() headers = dict((k.lower(), v) for k, v in resp.getheaders()) self.assertIsNone(headers.get('x-storage-policy')) @requires_policies def test_conflict_change_storage_policy_with_put(self): def put(url, token, parsed, conn, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('PUT', parsed.path + '/' + self.container, '', new_headers) return check_response(conn) # create policy = self.policies.select() resp = retry(put, {'X-Storage-Policy': policy['name']}) resp.read() self.assertEqual(resp.status, 201) # can't change it other_policy = self.policies.exclude(name=policy['name']).select() resp = retry(put, {'X-Storage-Policy': other_policy['name']}) resp.read() self.assertEqual(resp.status, 409) def head(url, token, parsed, conn): conn.request('HEAD', parsed.path + '/' + self.container, '', {'X-Auth-Token': token}) return check_response(conn) # still original policy resp = retry(head) resp.read() headers = dict((k.lower(), v) for k, v in resp.getheaders()) self.assertEqual(headers.get('x-storage-policy'), policy['name']) @requires_policies def test_noop_change_storage_policy_with_post(self): def put(url, token, parsed, conn, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('PUT', parsed.path + '/' + self.container, '', new_headers) return check_response(conn) # create policy = self.policies.select() resp = retry(put, {'X-Storage-Policy': policy['name']}) resp.read() self.assertEqual(resp.status, 201) def post(url, token, parsed, conn, headers): new_headers = dict({'X-Auth-Token': token}, **headers) conn.request('POST', parsed.path + '/' + self.container, '', new_headers) return check_response(conn) # attempt update for header in ('X-Storage-Policy', 'X-Storage-Policy-Index'): other_policy = self.policies.exclude(name=policy['name']).select() resp = retry(post, {header: other_policy['name']}) resp.read() self.assertEqual(resp.status, 204) def head(url, token, parsed, conn): conn.request('HEAD', parsed.path + '/' + self.container, '', {'X-Auth-Token': token}) return check_response(conn) # still original policy resp = retry(head) resp.read() headers = dict((k.lower(), v) for k, v in resp.getheaders()) self.assertEqual(headers.get('x-storage-policy'), policy['name']) def test_container_quota_bytes(self): if 'container_quotas' not in cluster_info: raise SkipTest('Container quotas not enabled') if tf.in_process: tf.skip_if_no_xattrs() def post(url, token, parsed, conn, name, value): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, name: value}) return check_response(conn) def head(url, token, parsed, conn): conn.request('HEAD', parsed.path + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) # set X-Container-Meta-Quota-Bytes is 10 resp = retry(post, 'X-Container-Meta-Quota-Bytes', '10') resp.read() self.assertEqual(resp.status, 204) resp = retry(head) resp.read() self.assertIn(resp.status, (200, 204)) # confirm X-Container-Meta-Quota-Bytes self.assertEqual(resp.getheader('X-Container-Meta-Quota-Bytes'), '10') def put(url, token, parsed, conn, data): conn.request('PUT', parsed.path + '/' + self.name + '/object', data, {'X-Auth-Token': token}) return check_response(conn) # upload 11 bytes object resp = retry(put, '01234567890') resp.read() self.assertEqual(resp.status, 413) # upload 10 bytes object resp = retry(put, '0123456789') resp.read() self.assertEqual(resp.status, 201) def get(url, token, parsed, conn): conn.request('GET', parsed.path + '/' + self.name + '/object', '', {'X-Auth-Token': token}) return check_response(conn) # download 10 bytes object resp = retry(get) body = resp.read() self.assertEqual(resp.status, 200) self.assertEqual(body, '0123456789') class BaseTestContainerACLs(unittest2.TestCase): # subclasses can change the account in which container # is created/deleted by setUp/tearDown account = 1 def _get_account(self, url, token, parsed, conn): return parsed.path def _get_tenant_id(self, url, token, parsed, conn): account = parsed.path return account.replace('/v1/AUTH_', '', 1) def setUp(self): if tf.skip or tf.skip2 or tf.skip_if_not_v3: raise SkipTest('AUTH VERSION 3 SPECIFIC TEST') self.name = uuid4().hex def put(url, token, parsed, conn): conn.request('PUT', parsed.path + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(put, use_account=self.account) resp.read() self.assertEqual(resp.status, 201) def tearDown(self): if tf.skip or tf.skip2 or tf.skip_if_not_v3: raise SkipTest def get(url, token, parsed, conn): conn.request('GET', parsed.path + '/' + self.name + '?format=json', '', {'X-Auth-Token': token}) return check_response(conn) def delete(url, token, parsed, conn, obj): conn.request('DELETE', '/'.join([parsed.path, self.name, obj['name']]), '', {'X-Auth-Token': token}) return check_response(conn) while True: resp = retry(get, use_account=self.account) body = resp.read() self.assertEqual(resp.status // 100, 2, resp.status) objs = json.loads(body) if not objs: break for obj in objs: resp = retry(delete, obj, use_account=self.account) resp.read() self.assertEqual(resp.status, 204) def delete(url, token, parsed, conn): conn.request('DELETE', parsed.path + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(delete, use_account=self.account) resp.read() self.assertEqual(resp.status, 204) def _assert_cross_account_acl_granted(self, granted, grantee_account, acl): ''' Check whether a given container ACL is granted when a user specified by account_b attempts to access a container. ''' # Obtain the first account's string first_account = retry(self._get_account, use_account=self.account) # Ensure we can't access the container with the grantee account def get2(url, token, parsed, conn): conn.request('GET', first_account + '/' + self.name, '', {'X-Auth-Token': token}) return check_response(conn) resp = retry(get2, use_account=grantee_account) resp.read() self.assertEqual(resp.status, 403) def put2(url, token, parsed, conn): conn.request('PUT', first_account + '/' + self.name + '/object', 'test object', {'X-Auth-Token': token}) return check_response(conn) resp = retry(put2, use_account=grantee_account) resp.read() self.assertEqual(resp.status, 403) # Post ACL to the container def post(url, token, parsed, conn): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, 'X-Container-Read': acl, 'X-Container-Write': acl}) return check_response(conn) resp = retry(post, use_account=self.account) resp.read() self.assertEqual(resp.status, 204) # Check access to container from grantee account with ACL in place resp = retry(get2, use_account=grantee_account) resp.read() expected = 204 if granted else 403 self.assertEqual(resp.status, expected) resp = retry(put2, use_account=grantee_account) resp.read() expected = 201 if granted else 403 self.assertEqual(resp.status, expected) # Make the container private again def post(url, token, parsed, conn): conn.request('POST', parsed.path + '/' + self.name, '', {'X-Auth-Token': token, 'X-Container-Read': '', 'X-Container-Write': ''}) return check_response(conn) resp = retry(post, use_account=self.account) resp.read() self.assertEqual(resp.status, 204) # Ensure we can't access the container with the grantee account again resp = retry(get2, use_account=grantee_account) resp.read() self.assertEqual(resp.status, 403) resp = retry(put2, use_account=grantee_account) resp.read() self.assertEqual(resp.status, 403) class TestContainerACLsAccount1(BaseTestContainerACLs): def test_cross_account_acl_names_with_user_in_non_default_domain(self): # names in acls are disallowed when grantee is in a non-default domain acl = '%s:%s' % (tf.swift_test_tenant[3], tf.swift_test_user[3]) self._assert_cross_account_acl_granted(False, 4, acl) def test_cross_account_acl_ids_with_user_in_non_default_domain(self): # ids are allowed in acls when grantee is in a non-default domain tenant_id = retry(self._get_tenant_id, use_account=4) acl = '%s:%s' % (tenant_id, '*') self._assert_cross_account_acl_granted(True, 4, acl) def test_cross_account_acl_names_in_default_domain(self): # names are allowed in acls when grantee and project are in # the default domain acl = '%s:%s' % (tf.swift_test_tenant[1], tf.swift_test_user[1]) self._assert_cross_account_acl_granted(True, 2, acl) def test_cross_account_acl_ids_in_default_domain(self): # ids are allowed in acls when grantee and project are in # the default domain tenant_id = retry(self._get_tenant_id, use_account=2) acl = '%s:%s' % (tenant_id, '*') self._assert_cross_account_acl_granted(True, 2, acl) class TestContainerACLsAccount4(BaseTestContainerACLs): account = 4 def test_cross_account_acl_names_with_project_in_non_default_domain(self): # names in acls are disallowed when project is in a non-default domain acl = '%s:%s' % (tf.swift_test_tenant[0], tf.swift_test_user[0]) self._assert_cross_account_acl_granted(False, 1, acl) def test_cross_account_acl_ids_with_project_in_non_default_domain(self): # ids are allowed in acls when project is in a non-default domain tenant_id = retry(self._get_tenant_id, use_account=1) acl = '%s:%s' % (tenant_id, '*') self._assert_cross_account_acl_granted(True, 1, acl) if __name__ == '__main__': unittest2.main()
{ "content_hash": "a4fed08b16ff64097d19c5cb5f82da34", "timestamp": "", "source": "github", "line_count": 1782, "max_line_length": 79, "avg_line_length": 37.5942760942761, "alnum_prop": 0.5565059036018688, "repo_name": "nadeemsyed/swift", "id": "6853d45e369d67bd4714d053b826edd860924e0b", "size": "67607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/functional/test_container.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "248" }, { "name": "PHP", "bytes": "377" }, { "name": "Python", "bytes": "8547418" }, { "name": "Shell", "bytes": "1804" } ], "symlink_target": "" }
function [X_norm, mu, sigma] = featureNormalize(X) %FEATURENORMALIZE Normalizes the features in X % FEATURENORMALIZE(X) returns a normalized version of X where % the mean value of each feature is 0 and the standard deviation % is 1. This is often a good preprocessing step to do when % working with learning algorithms. mu = mean(X); X_norm = bsxfun(@minus, X, mu); sigma = std(X_norm); X_norm = bsxfun(@rdivide, X_norm, sigma); % ============================================================ end
{ "content_hash": "368f9ed1592967f5a54e5a055a767a8f", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 66, "avg_line_length": 31.75, "alnum_prop": 0.6318897637795275, "repo_name": "ganesshkumar/cs229-ml-assignment", "id": "89aef06221e459bc7a6fdfb569433505e4daa906", "size": "508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "machine-learning-ex7/ex7/featureNormalize.m", "mode": "33188", "license": "mit", "language": [ { "name": "Matlab", "bytes": "812587" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "a05c009e0de18709304c097a480f07a4", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "20b7bafd54594cbb7a27606a4c5e7a9b5cd88316", "size": "183", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Anacardiaceae/Phlebochiton/Phlebochiton philippinensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
#ifndef CORE_ALGORITHMS_FINITEELEMENTS_BUILDTDCSMATRIX_H #define CORE_ALGORITHMS_FINITEELEMENTS_BUILDTDCSMATRIX_H 1 #include <Core/Datatypes/MatrixFwd.h> #include <Core/Algorithms/Base/AlgorithmBase.h> // for Windows support #include <Core/Algorithms/Legacy/FiniteElements/share.h> namespace SCIRun { namespace Core { namespace Algorithms { namespace FiniteElements { class SCISHARE BuildTDCSMatrixAlgo : public AlgorithmBase { public: static AlgorithmInputName FEM_Stiffness_Matrix; static AlgorithmInputName FEM_Mesh; static AlgorithmInputName Electrode_Element; static AlgorithmInputName Electrode_Element_Type; static AlgorithmInputName Electrode_Element_Definition; static AlgorithmInputName Contact_Impedance; static AlgorithmOutputName TDCSMatrix; bool run(Datatypes::SparseRowMatrixHandle stiff, FieldHandle mesh, Datatypes::DenseMatrixHandle ElectrodeElements, Datatypes::DenseMatrixHandle ElectrodeElementType, Datatypes::DenseMatrixHandle ElectrodeElementDefinition, Datatypes::DenseMatrixHandle contactimpedance, Datatypes::SparseRowMatrixHandle& output) const; virtual AlgorithmOutput run(const AlgorithmInput &) const; }; }}}} #endif
{ "content_hash": "27fd9ef9c5451b28e34bc23d4a91dfab", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 321, "avg_line_length": 34.371428571428574, "alnum_prop": 0.8129675810473815, "repo_name": "collint8/SCIRun", "id": "f094e97a8ea76572d6022d2e850558a48d59a286", "size": "2457", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Core/Algorithms/Legacy/FiniteElements/BuildMatrix/BuildTDCSMatrix.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "13240423" }, { "name": "C++", "bytes": "29987282" }, { "name": "CMake", "bytes": "780445" }, { "name": "CSS", "bytes": "5578" }, { "name": "Cuda", "bytes": "131738" }, { "name": "DIGITAL Command Language", "bytes": "8092" }, { "name": "Fortran", "bytes": "1326303" }, { "name": "GLSL", "bytes": "58737" }, { "name": "HTML", "bytes": "29427" }, { "name": "JavaScript", "bytes": "36777" }, { "name": "M4", "bytes": "85976" }, { "name": "Makefile", "bytes": "637928" }, { "name": "Mercury", "bytes": "347" }, { "name": "Objective-C", "bytes": "109973" }, { "name": "Perl", "bytes": "7210" }, { "name": "Perl 6", "bytes": "2651" }, { "name": "Python", "bytes": "429910" }, { "name": "Roff", "bytes": "2817" }, { "name": "Shell", "bytes": "1228236" }, { "name": "XSLT", "bytes": "14273" } ], "symlink_target": "" }
@import Foundation; @class Database; @class FeedCredentials; @class Folder; @interface RefreshManager : NSObject <NSURLSessionTaskDelegate> { NSUInteger countOfNewArticles; NSMutableArray * authQueue; FeedCredentials * credentialsController; BOOL hasStarted; NSString * statusMessageDuringRefresh; NSOperationQueue *networkQueue; dispatch_queue_t _queue; } @property (class, readonly, nonatomic) RefreshManager *sharedManager; @property (readonly, copy) NSString *statusMessage; @property (nonatomic, getter=isConnecting, readonly) BOOL connecting; @property (nonatomic, readonly) NSUInteger countOfNewArticles; -(void)refreshFolderIconCacheForSubscriptions:(NSArray *)foldersArray; -(void)refreshSubscriptions:(NSArray *)foldersArray ignoringSubscriptionStatus:(BOOL)ignoreSubStatus; -(void)forceRefreshSubscriptionForFolders:(NSArray*)foldersArray; -(void)cancelAll; -(void)refreshFavIconForFolder:(Folder *)folder; -(NSOperation *)addConnection:(NSURLRequest *)conn completionHandler:(void (^)(NSData *data, NSURLResponse *response, NSError *error))completionHandler; -(void)suspendConnectionsQueue; -(void)resumeConnectionsQueue; @end // Refresh types typedef NS_ENUM(int, RefreshTypes) { MA_Refresh_NilType = -1, MA_Refresh_Feed, MA_Refresh_FavIcon, MA_Refresh_GoogleFeed, MA_ForceRefresh_Google_Feed };
{ "content_hash": "801d544896baf6f8d66aca8d171ff185", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 152, "avg_line_length": 33.175, "alnum_prop": 0.8055764883195177, "repo_name": "ViennaRSS/vienna-rss", "id": "09aa9a26938de5b551541ff2d58532fe9bd67709", "size": "2108", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Vienna/Sources/Fetching/RefreshManager.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "8016" }, { "name": "CSS", "bytes": "30881" }, { "name": "HTML", "bytes": "570969" }, { "name": "Makefile", "bytes": "995" }, { "name": "Objective-C", "bytes": "1243448" }, { "name": "Rich Text Format", "bytes": "7915" }, { "name": "Ruby", "bytes": "760" }, { "name": "Shell", "bytes": "12247" }, { "name": "Swift", "bytes": "212965" } ], "symlink_target": "" }
require('normalize.css/normalize.css'); require ('styles/login.css'); import React from 'react'; class Login extends React.Component{ getInitialState = ()=>{ return{ username:' ', password:' ' }; } handleChange = (e)=>{ let newState ={}; newState[e.target.name]=e.target.value; this.setState(newState); } handleOnclickReset =()=>{ let newState={}; this.setState(newState); } // 获取提交数据 // handleClick = ()=>{ // let data = { // username:this.state.username, // password:this.state.password // } // } //提交数据 // $.ajax({}) render(){ return( <div className="g_login" > <div className="g_login_right" > <div className="usrname" > <input type="text" placeholder="请输入你的名字" onChange={this.handleChange}/> <label>{}</label> </div> <div className="password" > <input type="password" placeholder="请输入你的密码" /> </div> <div> <input type="submit" value="确认" /> <input type="reset" value="重置" /> </div> </div> </div> ); } } export default Login;
{ "content_hash": "5d864bd2856b3e5458ffa284fd35376b", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 96, "avg_line_length": 27.923076923076923, "alnum_prop": 0.424931129476584, "repo_name": "ThinkDuan/react-webpack-onetry", "id": "6b05977324d86d482ab909273b07c0e34bfbc1d1", "size": "1508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/components/login.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "705" }, { "name": "HTML", "bytes": "508" }, { "name": "JavaScript", "bytes": "17458" } ], "symlink_target": "" }
class Survey < ActiveRecord::Base has_many :questions # has_many :participants, through: :questions, through: :responses, source: :participants has_many :responses, through: :questions belongs_to :author, class_name: "User" # Remember to create a migration! def takers self.questions.first.participants end end
{ "content_hash": "32c7a2a368ee5b00f52acc6e78e26ed6", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 91, "avg_line_length": 23.785714285714285, "alnum_prop": 0.7297297297297297, "repo_name": "wolves-2014/rmmn-survey-gorilla", "id": "7c173bbccd957657cfc9e4840dd8c322fabe0954", "size": "333", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/models/survey.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1059" }, { "name": "JavaScript", "bytes": "534" }, { "name": "Ruby", "bytes": "13619" } ], "symlink_target": "" }
import React, { Component } from 'react' import { connect } from 'react-redux' import { PermissionsAndroid } from 'react-native' import styles from '../styles/stylesheet' import strings from '../resources/translations' import StartViewButtons from '../components/StartViewButtons' import AccessibilityView from '../components/AccessibilityView' import { resetState } from '../actions/resetStateAction' import { getGpsLocation } from '../actions/gpsLocationActions' import { getBeaconData } from '../actions/beaconLocationActions' class StartView extends Component { constructor() { super() this.state = {locationPermissionsError: false} this.sceneName = 'start' } async requestLocationPermission() { try { const granted = await PermissionsAndroid.requestPermission( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, { 'title': strings.locationPermissionTitle, 'message': strings.locationPermissionMessage } ) if (granted) { this.props.getGpsLocation(navigator.geolocation.getCurrentPosition) } else { this.setState({locationPermissionsError: true}) } } catch (error) { this.setState({locationError: true}) } } componentWillMount = () => { this.props.resetState() this.requestLocationPermission() this.props.getBeaconData() } render() { return ( <AccessibilityView style={styles.start} name={this.sceneName}> <StartViewButtons /> </AccessibilityView> ) } } StartView.propTypes = { gettingGpsLocation: React.PropTypes.bool.isRequired, locationError: React.PropTypes.string, locationPermissionError: React.PropTypes.string, getGpsLocation: React.PropTypes.func.isRequired, getBeaconData: React.PropTypes.func.isRequired, resetState: React.PropTypes.func.isRequired } const mapStateToProps = (state) => { return { gettingGpsLocation: state.gpsLocation.gettingGpsLocation, locationError: state.gpsLocation.error, locationPermissionError: state.gpsLocation.locationPermissionError } } const mapDispatchToProps = (dispatch) => { return { getGpsLocation: () => { dispatch(getGpsLocation(navigator.geolocation.getCurrentPosition)) }, getBeaconData: () => { dispatch(getBeaconData()) }, resetState: () => { dispatch(resetState()) } } } export default connect(mapStateToProps, mapDispatchToProps)(StartView)
{ "content_hash": "bef76b05844724abf071999e2364f744", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 83, "avg_line_length": 27.048076923076923, "alnum_prop": 0.6160682545325276, "repo_name": "STOP2/stop2.0-traveller-client", "id": "79a8ef77e44d23c22a9d3b7743a439335bc45f77", "size": "2813", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/pages/StartPage.js", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "1686" }, { "name": "JavaScript", "bytes": "133863" }, { "name": "Objective-C", "bytes": "4434" }, { "name": "Python", "bytes": "1665" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_16) on Thu Oct 02 15:35:31 BST 2008 --> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <TITLE> Uses of Package org.springframework.security.ui.session (Spring Security 2.0.4 API) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Package org.springframework.security.ui.session (Spring Security 2.0.4 API)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> Spring Security Framework</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/springframework/security/ui/session/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Package<br>org.springframework.security.ui.session</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../org/springframework/security/ui/session/package-summary.html">org.springframework.security.ui.session</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.springframework.security.providers.jaas"><B>org.springframework.security.providers.jaas</B></A></TD> <TD>An authentication provider for JAAS.&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.springframework.security.ui.session"><B>org.springframework.security.ui.session</B></A></TD> <TD>HttpSession events and publisher classes.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.springframework.security.providers.jaas"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Classes in <A HREF="../../../../../org/springframework/security/ui/session/package-summary.html">org.springframework.security.ui.session</A> used by <A HREF="../../../../../org/springframework/security/providers/jaas/package-summary.html">org.springframework.security.providers.jaas</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../org/springframework/security/ui/session/class-use/HttpSessionDestroyedEvent.html#org.springframework.security.providers.jaas"><B>HttpSessionDestroyedEvent</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Published by the <A HREF="../../../../../org/springframework/security/ui/session/HttpSessionEventPublisher.html" title="class in org.springframework.security.ui.session"><CODE>HttpSessionEventPublisher</CODE></A> when a HttpSession is created in the container</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.springframework.security.ui.session"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Classes in <A HREF="../../../../../org/springframework/security/ui/session/package-summary.html">org.springframework.security.ui.session</A> used by <A HREF="../../../../../org/springframework/security/ui/session/package-summary.html">org.springframework.security.ui.session</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../org/springframework/security/ui/session/class-use/HttpSessionApplicationEvent.html#org.springframework.security.ui.session"><B>HttpSessionApplicationEvent</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Parent class for published HttpSession events</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> Spring Security Framework</EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/springframework/security/ui/session/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2004-2008 <a href="http://www.springsource.com/">SpringSource, Inc</a>. All Rights Reserved. </BODY> </HTML>
{ "content_hash": "41a0bf85f301ac5912a04e1216ded7e3", "timestamp": "", "source": "github", "line_count": 186, "max_line_length": 324, "avg_line_length": 46.376344086021504, "alnum_prop": 0.6512868073266868, "repo_name": "imondragon/spring-security-2.0.4", "id": "968ef759866103b7685d2dbb0730c2ea196e2757", "size": "8626", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/apidocs/org/springframework/security/ui/session/package-use.html", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
Public Class _2PlayerSnakeEnd Private Sub _2PlayerSnakeEnd_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load _2PlayerSnake.Close() lblWinner.Text = GlobalVariables.SnakeWinner lblPlayer.Text = GlobalVariables.PlayerName lblPlayer2.Text = GlobalVariables.PlayerName2 lblScore1.Text = GlobalVariables.SFinal1 lblScore2.Text = GlobalVariables.SFinal2 End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click Me.Close() End Sub Private Sub btnRestart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRestart.Click GlobalVariables.SnakeWinner = "" GlobalVariables.SFinal1 = 0 GlobalVariables.SFinal2 = 0 _2PlayerSnake.Show() End Sub End Class
{ "content_hash": "81c504cfb7411881944a2fab8086057c", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 117, "avg_line_length": 39.77272727272727, "alnum_prop": 0.7188571428571429, "repo_name": "XIAOAGE/mini-game-centre", "id": "e367ea43e665c0ee8ed5d4699a84f668081cfd65", "size": "877", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Mouse Labyrinth/2PlayerSnakeEnd.vb", "mode": "33188", "license": "mit", "language": [ { "name": "Visual Basic", "bytes": "215936" } ], "symlink_target": "" }
// This example uses the Seeed Studio Grove Starter Kit Plus - Intel IoT Edition // This example incorporates examples from the Johnny-Five API examples at // http://johnny-five.io/examples/grove-lcd-rgb-temperature-display-edison/ 'use strict'; // Define the objects you will be working with var five = require('johnny-five'); var Edison = require('edison-io'); var device = require('azure-iot-device'); // Define the client object that communicates with Azure IoT Hubs var Client = require('azure-iot-device').Client; // Define the message object that will define the message format going into Azure IoT Hubs var Message = require('azure-iot-device').Message; // Define the protocol that will be used to send messages to Azure IoT Hub // For this lab we will use AMQP over Web Sockets. // If you want to use a different protocol, comment out the protocol you want to replace, // and uncomment one of the other transports. // var Protocol = require('azure-iot-device-amqp-ws').AmqpWs; var Protocol = require('azure-iot-device-amqp').Amqp; // var Protocol = require('azure-iot-device-http').Http; // var Protocol = require('azure-iot-device-mqtt').Mqtt; // The device-specific connection string to your Azure IoT Hub var connectionString = process.env.IOTHUB_DEVICE_CONN || 'YOUR IOT HUB DEVICE-SPECIFIC CONNECTION STRING HERE'; // Create the client instanxe that will manage the connection to your IoT Hub // The client is created in the context of an Azure IoT device. var client = Client.fromConnectionString(connectionString, Protocol); // Extract the Azure IoT Hub device ID from the connection string var deviceId = device.ConnectionString.parse(connectionString).DeviceId; // location is simply a string that you can filter on later var location = process.env.DEVICE_LOCATION || 'GIVE A NAME TO THE LOCATION OF THE THING'; // Define the sensors you will use var th02, lcd, led, button; // Define some variable for holding sensor values var tempC, tempF, humidity, r, g, b = 0; // Define the board, which is an abstraction of the Intel Edison var board = new five.Board({ io: new Edison() }); // ********************************************* // Send a messae to Azure IoT Hub. // Always send the same message format (to // ensure the StreamAnalytics job doesn't fail) // includng deviceId, location and the sensor // type/value combination. // ********************************************* function sendMessage(src, val){ // Define the message body var payload = JSON.stringify({ deviceId: deviceId, location: location, sensorType: src, sensorValue: val }); // Create the message based on the payload JSON var message = new Message(payload); // For debugging purposes, write out the message payload to the console console.log('Sending message: ' + message.getData()); // Send the message to Azure IoT Hub client.sendEvent(message, printResultFor('send')); console.log('- - - -'); } // ********************************************* // Helper function to print results in the console // ********************************************* function printResultFor(op) { return function printResult(err, res) { if (err) console.log(op + ' error: ' + err.toString()); if (res) console.log(op + ' status: ' + res.constructor.name); }; } // ********************************************* // Open the connection to Azure IoT Hub. // When the connection respondes (either open or // error) the anonymous function is executed. // ********************************************* var connectCallback = function (err) { console.log('Open Azure IoT connection...'); // ********************************************* // If there is a connection error, display it // in the console. // ********************************************* if(err) { console.error('...could not connect: ' + err); // ********************************************* // If there is no error, send and receive // messages, and process completed messages. // ********************************************* } else { console.log('...client connected'); // ********************************************* // Create a message and send it to the IoT Hub // every two-seconds // ********************************************* var sendInterval = setInterval(function () { sendMessage('temperature', tempC); }, 2000); // ********************************************* // Listen for incoming messages // ********************************************* client.on('message', function (msg) { console.log('*********************************************'); console.log('**** Message Received - Id: ' + msg.messageId + ' Body: ' + msg.data); console.log('*********************************************'); // Split the message on a delimiter. var body = msg.data.split(':'); // Look for the 'ledl' indicator. var indexOfLed = body.indexOf('led'); // If 'led' is found, look at the next node in // the message body, and turn the led on or off // accordingly. if(indexOfLed >= 0) { if(body[indexOfLed+1] === 'on') led.on(); else if(body[indexOfLed+1] === 'off') led.off(); } // ********************************************* // Process completed messages and remove them // from the message queue. // ********************************************* client.complete(msg, printResultFor('completed')); // reject and abandon follow the same pattern. // /!\ reject and abandon are not available with MQTT }); // ********************************************* // If the client gets an error, dsiplay it in // the console. // ********************************************* client.on('error', function (err) { console.error(err.message); }); // ********************************************* // If the client gets disconnected, cleanup and // reconnect. // ********************************************* client.on('disconnect', function () { clearInterval(sendInterval); client.removeAllListeners(); client.connect(connectCallback); }); } } // ********************************************* // The board.on() executes the anonymous // function when the 'board' reports back that // it is initialized and ready. // ********************************************* board.on('ready', function() { console.log('Board connected...'); // Plug the Temperature sensor module // into the Grove Shield's I2C jack th02 = new five.Multi({ controller: "TH02" }); // Plug the LCD module into any of the // Grove Shield's I2C jacks. lcd = new five.LCD({ controller: 'JHD1313M1' }); // Plug the LED module into the // Grove Shield's D6 jack. led = new five.Led(13); // Plug the Button module into the // Grove Shield's D4 jack. button = new five.Button(4); // ********************************************* // The thermometer object will invoke a callback // everytime it reads data as fast as every 25ms // or whatever the 'freq' argument is set to. // ********************************************* th02.on('data', function() { // Set the state of the variables based on the // value read from the thermometer // 'this' scope is the thermometer tempC = this.temperature.celsius; tempF = this.temperature.fahrenheit; humidity = this. hygrometer.relativeHumidity; // Use a simple linear function to determine // the RGB color to paint the LCD screen. // The LCD's background will change color // according to the temperature. // Hot -> Moderate -> Cold // 122°F -> 77°F -> 32°F // 50°C -> 25°C -> 0°C // Red -> Violet -> Blue r = linear(0x00, 0xFF, tempC, 50); g = linear(0x00, 0x00, tempC, 50); b = linear(0xFF, 0x00, tempC, 50); // Paint the LCD and print the temperture // (rounded up to the nearest whole integer) lcd.bgColor(r, g, b).cursor(0, 0).print('Fahrenheit: ' + Math.ceil(tempF) +'\nHumidity: ' + humidity); }); // ********************************************* // The button.on('press') invokes the anonymous // callback when the button is pressed. // ********************************************* button.on('press', function() { led.on(); console.log('*********************************************'); sendMessage('led', 'on'); console.log('*********************************************'); }); // ********************************************* // The button.on('release') invokes the // anonymous callback when the button is // released. // ********************************************* button.on('release', function() { led.off(); console.log('*********************************************'); sendMessage('led', 'off'); console.log('*********************************************'); }); // ********************************************* // Open the connection to Azure IoT Hubs and // begin sending messages. // ********************************************* client.open(connectCallback); }); // ********************************************* // Helper method for painting the LCD. // Linear Interpolation // (https://en.wikipedia.org/wiki/Linear_interpolation) // ********************************************* function linear(start, end, step, steps) { return (end - start) * step / steps + start; }
{ "content_hash": "92d986b2127ed88639ade7673d981dfa", "timestamp": "", "source": "github", "line_count": 297, "max_line_length": 111, "avg_line_length": 34.78114478114478, "alnum_prop": 0.4915779283639884, "repo_name": "ThingLabsIo/IoTLabs", "id": "f8e3434de561f217d423c4f7f12910018eeddc39", "size": "11465", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Edison/azure-iot/iot-starter-kit.js", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "2878" }, { "name": "C#", "bytes": "48014" }, { "name": "C++", "bytes": "45709" }, { "name": "HTML", "bytes": "181" }, { "name": "JavaScript", "bytes": "116457" } ], "symlink_target": "" }
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { stripBanners: true, banner: '/* \n * <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy") %> \n * \n * <%= pkg.author %>, and the web community.\n * Licensed under the <%= pkg.license %> license. \n * \n * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice. \n *\n */\n\n', }, patternlab: { src: './builder/patternlab.js', dest: './builder/patternlab.js' }, object_factory: { src: './builder/object_factory.js', dest: './builder/object_factory.js' }, lineage: { src: './builder/lineage_hunter.js', dest: './builder/lineage_hunter.js' }, media_hunter: { src: './builder/media_hunter.js', dest: './builder/media_hunter.js' }, patternlab_grunt: { src: './builder/patternlab_grunt.js', dest: './builder/patternlab_grunt.js' }, patternlab_gulp: { src: './builder/patternlab_gulp.js', dest: './builder/patternlab_gulp.js' }, parameter_hunter: { src: './builder/parameter_hunter.js', dest: './builder/parameter_hunter.js' }, pattern_exporter: { src: './builder/pattern_exporter.js', dest: './builder/pattern_exporter.js' }, pattern_assembler: { src: './builder/pattern_assembler.js', dest: './builder/pattern_assembler.js' }, pseudopattern_hunter: { src: './builder/pseudopattern_hunter.js', dest: './builder/pseudopattern_hunter.js' }, list_item_hunter: { src: './builder/list_item_hunter.js', dest: './builder/list_item_hunter.js' }, style_modifier_hunter: { src: './builder/style_modifier_hunter.js', dest: './builder/style_modifier_hunter.js' } }, copy: { main: { files: [ { expand: true, cwd: './source/js/', src: '*', dest: './public/js/'}, { expand: true, cwd: './source/css/', src: '*.css', dest: './public/css/' }, { expand: true, cwd: './source/images/', src: ['*.png', '*.jpg', '*.gif', '*.jpeg'], dest: './public/images/' }, { expand: true, cwd: './source/images/sample/', src: ['*.png', '*.jpg', '*.gif', '*.jpeg'], dest: './public/images/sample/'}, { expand: true, cwd: './source/fonts/', src: '*', dest: './public/fonts/'}, { expand: true, cwd: './source/_data/', src: 'annotations.js', dest: './public/data/' } ] }, css: { files: [ { expand: true, cwd: './source/css/', src: '*.css', dest: './public/css/' } ] } }, watch: { all: { files: [ 'source/css/**/*.css', 'public/styleguide/css/*.css', 'source/_patterns/**/*.mustache', 'source/_patterns/**/*.json', 'source/_data/*.json' ], tasks: ['default'] }, // scss: { // files: ['source/css/**/*.scss', 'public/styleguide/css/*.scss'], // tasks: ['sass', 'copy:css','bsReload:css'] // }, patterns: { files: [ 'source/_patterns/**/*.mustache', 'source/_patterns/**/*.json', 'source/_data/*.json' ], tasks: ['default'] } }, // sass: { // build: { // options: { // style: 'expanded', // precision: 8 // }, // files: { // './source/css/style.css': './source/css/style.scss', // './public/styleguide/css/static.css': './public/styleguide/css/static.scss', // './public/styleguide/css/styleguide.css': './public/styleguide/css/styleguide.scss', // './public/styleguide/css/styleguide-specific.css': './public/styleguide/css/styleguide-specific.scss' // } // } // }, nodeunit: { all: ['test/*_tests.js'] }, browserSync: { dev: { options: { server: './public', watchTask: true, plugins: [ { module: 'bs-html-injector', options: { files: './public/index.html' } } ] } } }, bsReload: { css: './public/**/*.css' } }); // load all grunt tasks require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); //load the patternlab task grunt.task.loadTasks('./builder/'); //if you choose to use scss, or any preprocessor, you can add it here grunt.registerTask('default', ['patternlab', /*'sass',*/ 'copy:main']); //travis CI task grunt.registerTask('travis', ['nodeunit', 'patternlab']); //TODO: this line is more efficient, but you cannot run concurrent watch tasks without another dependency. //grunt.registerTask('serve', ['patternlab', /*'sass',*/ 'copy:main', 'browserSync', 'watch:patterns', 'watch:scss']); grunt.registerTask('serve', ['patternlab', /*'sass',*/ 'copy:main', 'browserSync', 'watch:all']); grunt.registerTask('build', ['nodeunit', 'concat']); };
{ "content_hash": "80cc771f63c78a622a3c172fb02bb492", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 310, "avg_line_length": 31.121019108280255, "alnum_prop": 0.5523945968072043, "repo_name": "freshcodellc/pattern-labs-node-scaffold", "id": "dac041822078bdd86e3be5b4784f19a74b657a4f", "size": "4886", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Gruntfile.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "77857" }, { "name": "HTML", "bytes": "64088" }, { "name": "JavaScript", "bytes": "695358" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- | Licensed to the Apache Software Foundation (ASF) under one | or more contributor license agreements. See the NOTICE file | distributed with this work for additional information | regarding copyright ownership. The ASF licenses this file | to you under the Apache License, Version 2.0 (the | "License"); you may not use this file except in compliance | with the License. You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, | software distributed under the License is distributed on an | "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | KIND, either express or implied. See the License for the | specific language governing permissions and limitations | under the License. --> <project xmlns="http://maven.apache.org/DECORATION/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/DECORATION/1.1.0 http://maven.apache.org/xsd/decoration-1.1.0.xsd" name="${project.name}"> <body> <head> <link rel="meta" title="DOAP" href="${project.url}/doap.rdf" type="application/rdf+xml" /> </head> <menu name="Apache Onami™ Lifecycle"> <item name="Home" href="index.html" /> </menu> <menu ref="modules" /> <menu ref="reports" /> <footer> <div class="row span12"> Apache Onami, Apache Onami Lifecycle, Apache, the Apache feather logo, and the Apache Onami project logos are trademarks of The Apache Software Foundation. All other marks mentioned may be trademarks or registered trademarks of their respective owners. </div> </footer> </body> </project>
{ "content_hash": "25e9211276805e16233523c009b9568a", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 260, "avg_line_length": 40.46511627906977, "alnum_prop": 0.7051724137931035, "repo_name": "e2000y/onami.lifecycle", "id": "43d436a61f0eec402b6a91194ff031198d5e0528", "size": "1742", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/site/site.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "135520" }, { "name": "Shell", "bytes": "858" } ], "symlink_target": "" }
<?php namespace VideoGamesRecords\ProofBundle\Repository; use Doctrine\ORM\EntityRepository; class RequestRepository extends EntityRepository { /** * @param $idPlayer * @return mixed */ public function getNbRequestFromToDay($idPlayer) { $qb = $this->createQueryBuilder('request') ->select('COUNT(request.idRequest)') ->where('request.idPlayerRequesting = :idPlayer') ->setParameter('idPlayer', $idPlayer) ->andWhere('request.createdAt LIKE :now') ->setParameter('now', date('Y-m-d') . '%'); return $qb->getQuery() ->getSingleScalarResult(); } }
{ "content_hash": "bac07456d9925d5d9daeb88e522a437c", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 61, "avg_line_length": 25.73076923076923, "alnum_prop": 0.6068759342301944, "repo_name": "video-games-records/ProofBundle", "id": "00536235eb7330cb38d813fac0991d4c3bb1c954", "size": "669", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "Repository/RequestRepository.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "7829" }, { "name": "PHP", "bytes": "47148" } ], "symlink_target": "" }
Simple-HTTP-Poster ===================== <pre> Simple HTTP POST Requester usage: post.py [-h] [--header [HEADER [HEADER ...]]] [--fheader FHEADER] [--ua UA] [--ct CT] [--data DATA] [--fdata FDATA] url positional arguments: url URL to send the POST request optional arguments: -h, --help show this help message and exit --header [HEADER [HEADER ...]] Specify required request headers --fheader HEADER_FILE Specify a file containing the required request headers --ua UA Specify User-Agent header --ct CT Specify Content-Type header --data DATA Data to be sent inside the request body --fdata DATA_FILE Specify a file containing the data to be sent inside the request body </pre>
{ "content_hash": "b3b45724fc54f48fd57fe3b340f91115", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 78, "avg_line_length": 35.416666666666664, "alnum_prop": 0.571764705882353, "repo_name": "DarkLighting/Simple-HTTP-Poster", "id": "00e3c4aa1a44cd4e5447bb3a39c195de2bad71b0", "size": "850", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "4793" } ], "symlink_target": "" }
""" ==================================================== Using Sparse Autoencoder features for classification ==================================================== This compares the performance of stochastic gradient descent (SGD) on raw image pixels and on Autoencoder extracted features . """ import random import numpy as np from sklearn.datasets import fetch_mldata from sklearn.linear_model import SGDClassifier from multilayer_perceptron import MultilayerPerceptronAutoencoder from sklearn.utils import shuffle random.seed(100) # Download the MNIST dataset and grab 200 images for testing mnist = fetch_mldata('MNIST original') X, y = mnist.data, mnist.target X, y = shuffle(X, y, random_state=0) indices = np.array(random.sample(range(70000), 2000)) X, y = X[indices].astype('float64'), y[indices] X = X / 255 ae = MultilayerPerceptronAutoencoder( algorithm='l-bfgs', verbose=True, max_iter=200, hidden_layer_sizes=100, random_state=3, batch_size=X.shape[0]) # Train autoencoder and extract features ae_features = ae.fit_transform(X) clf = SGDClassifier(random_state=3) # Train Classifier on raw pixel features and report score clf.fit(X, y) print 'SGD on raw pixels score: ', clf.score(X, y) # Train Classifier on Autoencoder features and report score clf.fit(ae_features, y) print 'SGD on extracted features score: ', clf.score(ae_features, y)
{ "content_hash": "0c3c7eef629f43b51847fedf0ac707f8", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 74, "avg_line_length": 28.367346938775512, "alnum_prop": 0.6956834532374101, "repo_name": "M-R-Houghton/euroscipy_2015", "id": "4c6e950986dcbceb723d88f36c1f7862bc7feb09", "size": "1390", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modelling/multilayer_perceptron/autoencoder_example.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "10590" }, { "name": "CSS", "bytes": "455819" }, { "name": "CoffeeScript", "bytes": "1974794" }, { "name": "HTML", "bytes": "1552875" }, { "name": "JavaScript", "bytes": "8032" }, { "name": "Makefile", "bytes": "14762" }, { "name": "Python", "bytes": "1909253" }, { "name": "Shell", "bytes": "15485" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- ~ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION ~ Copyright (c) 2008, Nationwide Health Information Network (NHIN) Connect. 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. ~ - Neither the name of the NHIN Connect Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. ~ ~ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ~ ~ END OF TERMS AND CONDITIONS --> <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd"> <sun-web-app error-url=""> <context-root>/XDSManagerWeb</context-root> <class-loader delegate="true"/> <jsp-config> <property name="keepgenerated" value="true"> <description>Keep a copy of the generated servlet class' java code.</description> </property> </jsp-config> </sun-web-app>
{ "content_hash": "cd5dc835b1d969b32d68d9026ad07fd7", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 757, "avg_line_length": 87.2, "alnum_prop": 0.7678899082568807, "repo_name": "TATRC/KMR2", "id": "9f898e1282163fe063d3b9be7e807c7f81a2b3c5", "size": "2180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Services/XDSManagerWeb/src/main/webapp/WEB-INF/sun-web.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "3767453" }, { "name": "JavaScript", "bytes": "2184689" } ], "symlink_target": "" }
import pytest from flask import url_for @pytest.mark.usefixtures('user') class TestResendConfirmation: def test_email_required(self, api_client): r = api_client.post(url_for('api.resend_confirmation_email')) assert r.status_code == 400 assert 'email' in r.errors def test_cannot_reconfirm(self, user, api_client): r = api_client.post(url_for('api.resend_confirmation_email'), data=dict(email=user.email)) assert r.status_code == 400 assert 'Your email has already been confirmed.' in r.errors['email'] @pytest.mark.options(SECURITY_CONFIRMABLE=True) def test_instructions_resent(self, api_client, outbox, templates): from backend.security.models import User from backend.security.views.user_resource import register_user user = User(username='test', email='test@example.com', password='password', first_name='the', last_name='user') register_user(user) r = api_client.post(url_for('api.resend_confirmation_email'), data=dict(email=user.email)) assert r.status_code == 204 assert len(outbox) == len(templates) == 2 assert templates[0].template.name == 'security/email/welcome.html' assert templates[1].template.name == 'security/email/confirmation_instructions.html' assert templates[0].context.get('confirmation_link') != templates[1].context.get('confirmation_link')
{ "content_hash": "27236e64451301f0a559c7eedfa6f8ec", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 109, "avg_line_length": 43.166666666666664, "alnum_prop": 0.6274131274131274, "repo_name": "briancappello/flask-react-spa", "id": "14749d2b2bc8e9fc3e6441eb31b226fa9365a09b", "size": "1554", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/security/views/test_resend_confirmation_email.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8579" }, { "name": "Dockerfile", "bytes": "1009" }, { "name": "HTML", "bytes": "18126" }, { "name": "JavaScript", "bytes": "169637" }, { "name": "Makefile", "bytes": "685" }, { "name": "Mako", "bytes": "509" }, { "name": "Python", "bytes": "282850" }, { "name": "Ruby", "bytes": "5065" }, { "name": "Shell", "bytes": "5231" } ], "symlink_target": "" }
using UnityEngine; [RequireComponent(typeof(AudioSource))] //------------------------------------------------------------------------------------- // ***** OVRLipSyncContext // /// <summary> /// OVRLipSyncContext interfaces into the Oculus phoneme recognizer. /// This component should be added into the scene once for each Audio Source. /// /// </summary> public class OVRLipSyncContext : OVRLipSyncContextBase { // * * * * * * * * * * * * * // Public members [Tooltip("Allow capturing of keyboard input to control operation.")] public bool enableKeyboardInput = false; [Tooltip("Register a mouse/touch callback to control loopback and gain (requires script restart).")] public bool enableTouchInput = false; [Tooltip("Play input audio back through audio output.")] public bool audioLoopback = false; [Tooltip("Key to toggle audio loopback.")] public KeyCode loopbackKey = KeyCode.L; [Tooltip("Show viseme scores in an OVRLipSyncDebugConsole display.")] public bool showVisemes = false; [Tooltip("Key to toggle viseme score display.")] public KeyCode debugVisemesKey = KeyCode.D; [Tooltip("Skip data from the Audio Source. Use if you intend to pass audio data in manually.")] public bool skipAudioSource = false; [Tooltip("Adjust the linear audio gain multiplier before processing lipsync")] public float gain = 1.0f; private bool hasDebugConsole = false; public KeyCode debugLaughterKey = KeyCode.H; public bool showLaughter = false; public float laughterScore = 0.0f; // * * * * * * * * * * * * * // Private members /// <summary> /// Start this instance. /// Note: make sure to always have a Start function for classes that have editor scripts. /// </summary> void Start() { // Add a listener to the OVRTouchpad for touch events if (enableTouchInput) { OVRTouchpad.AddListener(LocalTouchEventCallback); } // Find console OVRLipSyncDebugConsole[] consoles = FindObjectsOfType<OVRLipSyncDebugConsole>(); if (consoles.Length > 0) { hasDebugConsole = consoles[0]; } } /// <summary> /// Handle keyboard input /// </summary> void HandleKeyboard() { // Turn loopback on/off if (Input.GetKeyDown(loopbackKey)) { ToggleAudioLoopback(); } else if (Input.GetKeyDown(debugVisemesKey)) { showVisemes = !showVisemes; if (showVisemes) { if (hasDebugConsole) { Debug.Log("DEBUG SHOW VISEMES: ENABLED"); } else { Debug.LogWarning("Warning: No OVRLipSyncDebugConsole in the scene!"); showVisemes = false; } } else { if (hasDebugConsole) { OVRLipSyncDebugConsole.Clear(); } Debug.Log("DEBUG SHOW VISEMES: DISABLED"); } } else if (Input.GetKeyDown(debugLaughterKey)) { showLaughter = !showLaughter; if (showLaughter) { if (hasDebugConsole) { Debug.Log("DEBUG SHOW LAUGHTER: ENABLED"); } else { Debug.LogWarning("Warning: No OVRLipSyncDebugConsole in the scene!"); showLaughter = false; } } else { if (hasDebugConsole) { OVRLipSyncDebugConsole.Clear(); } Debug.Log("DEBUG SHOW LAUGHTER: DISABLED"); } } else if (Input.GetKeyDown(KeyCode.LeftArrow)) { gain -= 1.0f; if (gain < 1.0f) gain = 1.0f; string g = "LINEAR GAIN: "; g += gain; if (hasDebugConsole) { OVRLipSyncDebugConsole.Clear(); OVRLipSyncDebugConsole.Log(g); OVRLipSyncDebugConsole.ClearTimeout(1.5f); } } else if (Input.GetKeyDown(KeyCode.RightArrow)) { gain += 1.0f; if (gain > 15.0f) gain = 15.0f; string g = "LINEAR GAIN: "; g += gain; if (hasDebugConsole) { OVRLipSyncDebugConsole.Clear(); OVRLipSyncDebugConsole.Log(g); OVRLipSyncDebugConsole.ClearTimeout(1.5f); } } } /// <summary> /// Run processes that need to be updated in our game thread /// </summary> void Update() { if (enableKeyboardInput) { HandleKeyboard(); } laughterScore = this.Frame.laughterScore; DebugShowVisemesAndLaughter(); } /// <summary> /// Preprocess F32 PCM audio buffer /// </summary> /// <param name="data">Data.</param> /// <param name="channels">Channels.</param> public void PreprocessAudioSamples(float[] data, int channels) { // Increase the gain of the input for (int i = 0; i < data.Length; ++i) { data[i] = data[i] * gain; } } /// <summary> /// Postprocess F32 PCM audio buffer /// </summary> /// <param name="data">Data.</param> /// <param name="channels">Channels.</param> public void PostprocessAudioSamples(float[] data, int channels) { // Turn off output (so that we don't get feedback from mics too close to speakers) if (!audioLoopback) { for (int i = 0; i < data.Length; ++i) data[i] = data[i] * 0.0f; } } /// <summary> /// Pass F32 PCM audio buffer to the lip sync module /// </summary> /// <param name="data">Data.</param> /// <param name="channels">Channels.</param> public void ProcessAudioSamplesRaw(float[] data, int channels) { // Send data into Phoneme context for processing (if context is not 0) lock (this) { if (Context == 0 || OVRLipSync.IsInitialized() != OVRLipSync.Result.Success) { return; } var frame = this.Frame; OVRLipSync.ProcessFrame(Context, data, frame, channels == 2); } } /// <summary> /// Pass S16 PCM audio buffer to the lip sync module /// </summary> /// <param name="data">Data.</param> /// <param name="channels">Channels.</param> public void ProcessAudioSamplesRaw(short[] data, int channels) { // Send data into Phoneme context for processing (if context is not 0) lock (this) { if (Context == 0 || OVRLipSync.IsInitialized() != OVRLipSync.Result.Success) { return; } var frame = this.Frame; OVRLipSync.ProcessFrame(Context, data, frame, channels == 2); } } /// <summary> /// Process F32 audio sample and pass it to the lip sync module for computation /// </summary> /// <param name="data">Data.</param> /// <param name="channels">Channels.</param> public void ProcessAudioSamples(float[] data, int channels) { // Do not process if we are not initialized, or if there is no // audio source attached to game object if ((OVRLipSync.IsInitialized() != OVRLipSync.Result.Success) || audioSource == null) { return; } PreprocessAudioSamples(data, channels); ProcessAudioSamplesRaw(data, channels); PostprocessAudioSamples(data, channels); } /// <summary> /// Raises the audio filter read event. /// </summary> /// <param name="data">Data.</param> /// <param name="channels">Channels.</param> void OnAudioFilterRead(float[] data, int channels) { if (!skipAudioSource) { ProcessAudioSamples(data, channels); } } /// <summary> /// Print the visemes and laughter score to game window /// </summary> void DebugShowVisemesAndLaughter() { if (hasDebugConsole) { string seq = ""; if (showLaughter) { seq += "Laughter:"; int count = (int)(50.0f * this.Frame.laughterScore); for (int c = 0; c < count; c++) seq += "*"; seq += "\n"; } if (showVisemes) { for (int i = 0; i < this.Frame.Visemes.Length; i++) { seq += ((OVRLipSync.Viseme)i).ToString(); seq += ":"; int count = (int)(50.0f * this.Frame.Visemes[i]); for (int c = 0; c < count; c++) seq += "*"; seq += "\n"; } } OVRLipSyncDebugConsole.Clear(); if (seq != "") { OVRLipSyncDebugConsole.Log(seq); } } } void ToggleAudioLoopback() { audioLoopback = !audioLoopback; if (hasDebugConsole) { OVRLipSyncDebugConsole.Clear(); OVRLipSyncDebugConsole.ClearTimeout(1.5f); if (audioLoopback) OVRLipSyncDebugConsole.Log("LOOPBACK MODE: ENABLED"); else OVRLipSyncDebugConsole.Log("LOOPBACK MODE: DISABLED"); } } // LocalTouchEventCallback void LocalTouchEventCallback(OVRTouchpad.TouchEvent touchEvent) { string g = "LINEAR GAIN: "; switch (touchEvent) { case (OVRTouchpad.TouchEvent.SingleTap): ToggleAudioLoopback(); break; case (OVRTouchpad.TouchEvent.Up): gain += 1.0f; if (gain > 15.0f) gain = 15.0f; g += gain; if (hasDebugConsole) { OVRLipSyncDebugConsole.Clear(); OVRLipSyncDebugConsole.Log(g); OVRLipSyncDebugConsole.ClearTimeout(1.5f); } break; case (OVRTouchpad.TouchEvent.Down): gain -= 1.0f; if (gain < 1.0f) gain = 1.0f; g += gain; if (hasDebugConsole) { OVRLipSyncDebugConsole.Clear(); OVRLipSyncDebugConsole.Log(g); OVRLipSyncDebugConsole.ClearTimeout(1.5f); } break; } } }
{ "content_hash": "ee726ec89791ab76b373a01257787982", "timestamp": "", "source": "github", "line_count": 370, "max_line_length": 104, "avg_line_length": 29.475675675675674, "alnum_prop": 0.5058683293599854, "repo_name": "davidezordan/MixedRealitySamples", "id": "9499e3349dd91888ce67cbd83eb021cff306f988", "size": "12013", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Oculus Demo/Assets/Oculus/LipSync/Scripts/OVRLipSyncContext.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "17515940" }, { "name": "GLSL", "bytes": "37630" }, { "name": "HLSL", "bytes": "102589" }, { "name": "JavaScript", "bytes": "43789" }, { "name": "Mathematica", "bytes": "46437" }, { "name": "ShaderLab", "bytes": "586118" }, { "name": "Smalltalk", "bytes": "6" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Tyler Chen Design</title> <meta name="description" content="I'm Tyler Chen, UW PhD student, and this is a portfolio of my art."> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width user-scalable=no"> <link href="tc.ico" rel="shortcut icon" > <link href="css/pages.css" rel="stylesheet" type="text/css" media="screen" /> </head> <body> <div id="cover"></div> <a href="./"><div id="header"><page>Art as a Process</page><span id="tyler">tyler</span><span id="chen">chen</span></div></a> <div id="contentContainer"> <p><i>"Art as a process [...] focuses on experimentation and the creative process rather than a pre-imagined or calculated end product"</i></p> <img src="projects/aap/Full/self.png" class=""> <p>The task for this image was to draw a representation of how you see yourself.</p> <img src="projects/aap/large.jpg"> <img id="name" src="projects/aap/Full/name.png"> <p>"Fill the page with your name."</p> <img src="projects/aap/IMG_20141008_214810.jpg"> <div style="height: 20px;"></div> </div> </body> <script type="text/javascript" src="scripts/pages.js"></script> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-50592837-3', 'auto'); ga('send', 'pageview'); </script> </html>
{ "content_hash": "979845a348f8ad67fed862dd041965cd", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 147, "avg_line_length": 34.916666666666664, "alnum_prop": 0.6676610978520287, "repo_name": "tchen01/design", "id": "8f0cb7b47f45437444e50a4441222c1d4321495d", "size": "1676", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "AAP.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "36806" }, { "name": "HTML", "bytes": "415351" }, { "name": "JavaScript", "bytes": "18028" } ], "symlink_target": "" }
var view = require('../../view/view'); exports.main = function (tokens, pipes, exit, environment) { var out = new view.bridge(pipes.viewOut); out.print('Unknown command "' + tokens[0] + '"'); return exit(false); }
{ "content_hash": "9f20fe137f41744354f69fdfd7de2a07", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 60, "avg_line_length": 31.571428571428573, "alnum_prop": 0.6425339366515838, "repo_name": "ChineseDron/TermKit", "id": "0e60f64956653805584e2c897d189c29f4f83bcf", "size": "221", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Node/shell/builtin/null.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "14444" }, { "name": "HTML", "bytes": "7808" }, { "name": "JavaScript", "bytes": "200078" }, { "name": "Python", "bytes": "1099" } ], "symlink_target": "" }
#import "EC2Filter.h" #ifdef AWS_MULTI_FRAMEWORK #import <AWSRuntime/AmazonServiceRequestConfig.h> #else #import "../AmazonServiceRequestConfig.h" #endif /** * Describe Spot Price History Request */ @interface EC2DescribeSpotPriceHistoryRequest:AmazonServiceRequestConfig { NSDate *startTime; NSDate *endTime; NSMutableArray *instanceTypes; NSMutableArray *productDescriptions; NSMutableArray *filters; NSString *availabilityZone; NSNumber *maxResults; NSString *nextToken; } /** * Default constructor for a new object. Callers should use the * property methods to initialize this object after creating it. */ -(id)init; /** * The start date and time of the Spot Instance price history data. */ @property (nonatomic, retain) NSDate *startTime; /** * The end date and time of the Spot Instance price history data. */ @property (nonatomic, retain) NSDate *endTime; /** * Specifies the instance type to return. */ @property (nonatomic, retain) NSMutableArray *instanceTypes; /** * The description of the AMI. */ @property (nonatomic, retain) NSMutableArray *productDescriptions; /** * A list of filters used to match properties for SpotPriceHistory. For a * complete reference to the available filter keys for this operation, * see the <a * "http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/">Amazon * EC2 API reference</a>. */ @property (nonatomic, retain) NSMutableArray *filters; /** * Filters the results by availability zone (ex: 'us-east-1a'). */ @property (nonatomic, retain) NSString *availabilityZone; /** * Specifies the number of rows to return. */ @property (nonatomic, retain) NSNumber *maxResults; /** * Specifies the next set of rows to return. */ @property (nonatomic, retain) NSString *nextToken; /** * Adds a single object to instanceTypes. * This function will alloc and init instanceTypes if not already done. */ -(void)addInstanceType:(NSString *)instanceTypeObject; /** * Adds a single object to productDescriptions. * This function will alloc and init productDescriptions if not already done. */ -(void)addProductDescription:(NSString *)productDescriptionObject; /** * Adds a single object to filters. * This function will alloc and init filters if not already done. */ -(void)addFilter:(EC2Filter *)filterObject; /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. */ -(NSString *)description; @end
{ "content_hash": "96d6d004cee3e68e40c9f90a4e515b6a", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 77, "avg_line_length": 23.227272727272727, "alnum_prop": 0.7221135029354208, "repo_name": "jetthoughts/motion-recorder", "id": "2b3ba2a6c38730d4e53610d652c1021660ed806b", "size": "3139", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "vendor/Pods/AWSiOSSDK/src/include/EC2/EC2DescribeSpotPriceHistoryRequest.h", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "16899" } ], "symlink_target": "" }
import dispenser import datetime import time import threading #for retrieving update #import jhttp #for posting containers #import pcontainers #for dispensing, canning of containers import Dispensing #for button import PinManager as PM #for all constant variables for dispensing import CONSTANTS as const #for retrieving #import SQLiteDBQueries as SQLite #import logs """ def ConnectionCheckandUpdate(): Devices = Dispensing.scanForAll() postData = {} for addr in Devices: containers =[] containers.append({"Container":addr, "Available":True }) postData.update({"Dispenser ID": D.DISPENSER_ID, "Containers": containers}) #check to see if we are connected to server connected = pcontainers.pContainers(json.dumps(postData)) if (connected == 200): time.sleep(120) #if connected is successful call http request to pull updates data = jhttp.jRequest(D.DISPENSER_ID) #this will update the SQLite jhttp.SQLUpdate(data) sTime = datetime.datetime.strptime(data['Operation Start Time'], '%I:%M %p').time() eTime = datetime.datetime.strptime(data['Operation End Time'], '%I:%M %p').time() D.infoUpdate(sTime,eTime) for container in data['Containers']: addr = int(container['Container ID']) numberPills = int(container['Pill Count']) dosage = int(med['Dose']) frequency = datetime.datetime.timedelta(hours = int(med['Frequency'])) start_time = datetime.datetime.strptime(med['Daily Time'], '%I:%M %p').time() inital_time = datetime.datetime.strptime(med['Scheduled Time'], ' %m/%d/%Y %I:%M %p ') newContainer = dispenser.Container(addr, dosage, frequency, initial_time, start_time, numberPills, dispenser.DISPENSE_HEAP, dispenser.EACH_CONTAINER,Devices) # UPDATE SQL LITE update = 1 else: #parse local database to see previous entries contain = SQLite.fetchContainers() if (Contain == None): update = -1 else: D.infoUpdate(contain.OstartTime, contain.OendTime) for each in contain: x = dis.Container( contain.containerID ,contain.dose ,contain.frequency ,contain.scheduledTime ,contain.dailyTime ,contain.pillCount ,dispenser.DISPENSE_HEAP ,dispenser.EACH_CONTAINER ,dispenser.DEVICES ) update = 0 """ D = dispenser.Dispenser() print "\n" print "\n" print "\n" print "MERA Start Program Time: " , datetime.datetime.now().strftime('%m/%d/%Y %I:%M:%p') #update = ConnectionCheckandUpdate() print "\n" print "\n" print "\n" print "Retrieving data for update" update = 0 if (update ==-1): tries = 0 while (update == -1 and tries < 5): tries += 1 #update = ConnectionCheckandUpdate() print "Trying to connect..." ,tries Devices = {8: "a", 40: "c" } #creating dummy dispensers x = dispenser.Container( 8 ,2 ,datetime.timedelta(hours=5) ,datetime.datetime.now()+datetime.timedelta(minutes = 1) ,datetime.time(9,0,0) ,30 ,D.DISPENSE_HEAP ,D.EACH_CONTAINER ,Devices ) print x.timestamp x = dispenser.Container( 40 ,5 ,datetime.timedelta(hours=20) ,datetime.datetime.now()+datetime.timedelta(minutes = 5) ,datetime.time(9,0,0) ,30 ,D.DISPENSE_HEAP ,D.EACH_CONTAINER ,Devices ) print x.timestamp #put what we have just created into a gigantic while loop start = datetime.time (9,0,0) end = datetime.time(21,0,0) D.infoUpdate(start,end) while (True): while ((datetime.datetime.now().time()>D.OPERATION_START_TIME) and (datetime.datetime.now().time() < D.OPERATION_END_TIME)): nextDispense = (D.DISPENSE_HEAP.getStart() - datetime.datetime.now()).total_seconds() nextCheck = 600 if (nextDispense < nextCheck): #time.sleep(nextDispense) PM.setLEDState("READY") print "Setting LED" while(True): isNotPressed = True while(datetime.datetime.now()>=D.DISPENSE_HEAP.getStart() and datetime.datetime.now()<=D.DISPENSE_HEAP.getEnd() and isNotPressed): #ConnectionCheckandUpdate() if(update == 1): print "there was an upadte from the server" isNotPressed = PM.getButton() #isNotPressed = False #Button is pressed if (not isNotPressed): window = D.DISPENSE_HEAP.dispenseWindow(D.EACH_CONTAINER) print "Items in the window" , window devices = Dispensing.startDispensing(window) print "Dispenseing" for addr in devices: if (devices[addr] in const.ERROR.keys()): print "Device", addr, ": ", const.ERROR[devices[addr]] elif(devices[addr] == 0): print "Device", addr, ": Dispense succesfull" elif(devices[addr] == None): print "Device", addr, ": Invalid number of dosage" else: print "Device", addr, ": Failed to dispense ", devices[addr], " pills" devices[addr] = None #after getting the results send the log to server else: D.DISPENSE_HEAP.checkExpired(D.EACH_CONTAINER) #update all expired elements (loop)? from in the heap #log all expired elements #check if next non-expired element has entered window. Break if not within window if (datetime.datetime.now()< D.DISPENSE_HEAP.getStart() or datetime.datetime.now()> D.DISPENSE_HEAP.getEnd()): break; #break out if next element is not within window PM.setLEDState("UNAVAILABLE") print "Set LED to UNAIVALABLE" else: print "Outside of Window of Dispensing Check Connection to server" print "Until the next window opens" time.sleep(nextCheck) #ConnectionCheckandUpdate() #146.95.190.36
{ "content_hash": "07d53092d28bcbeb656dd6d8895d2de2", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 160, "avg_line_length": 31.377142857142857, "alnum_prop": 0.6822072482243672, "repo_name": "hishehim/MERA-Dispenser-Unit", "id": "c964312525a39773b06316b781ec9118cca70d4e", "size": "5491", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MainProgramCode/flow.py", "mode": "33188", "license": "mit", "language": [ { "name": "Arduino", "bytes": "4869" }, { "name": "Python", "bytes": "36781" }, { "name": "Shell", "bytes": "174" } ], "symlink_target": "" }
<?php declare(strict_types=1); namespace Limoncello\Tests\Application\Commands; use Limoncello\Application\Commands\ApplicationCommand; use Limoncello\Application\Exceptions\ConfigurationException; use Limoncello\Container\Container; use Limoncello\Contracts\Application\ApplicationConfigurationInterface; use Limoncello\Contracts\Application\CacheSettingsProviderInterface; use Limoncello\Contracts\Commands\IoInterface; use Limoncello\Contracts\FileSystem\FileSystemInterface; use Limoncello\Contracts\Settings\SettingsProviderInterface; use Limoncello\Tests\Application\TestCase; use Mockery; use Mockery\Mock; use ReflectionException; use ReflectionMethod; /** * @package Limoncello\Tests\Application */ class ApplicationCommandTest extends TestCase { /** * Test command descriptions. */ public function testCommandDescriptions(): void { $this->assertNotEmpty(ApplicationCommand::getName()); $this->assertNotEmpty(ApplicationCommand::getHelp()); $this->assertNotEmpty(ApplicationCommand::getDescription()); $this->assertNotEmpty(ApplicationCommand::getArguments()); $this->assertEmpty(ApplicationCommand::getOptions()); } /** * Test command called with invalid action parameter. */ public function testInvalidAction(): void { $container = new Container(); $inOut = $this->createInOutMock( ApplicationCommand::ARG_ACTION, 'non_existing_action', true ); ApplicationCommand::execute($container, $inOut); // Mockery will do checks when the test finishes $this->assertTrue(true); } /** * Test action. * * @throws ReflectionException */ public function testCache(): void { $container = new Container(); /** @var Mock $providerMock */ $providerMock = Mockery::mock(CacheSettingsProviderInterface::class); $container[SettingsProviderInterface::class] = $providerMock; $container[CacheSettingsProviderInterface::class] = $providerMock; $providerMock->shouldReceive('getApplicationConfiguration')->once()->withNoArgs() ->andReturn([ ApplicationConfigurationInterface::KEY_CACHE_FOLDER => '/some/path', ApplicationConfigurationInterface::KEY_CACHE_CALLABLE => 'Namespace\\ClassName::methodName', ]); $providerMock->shouldReceive('serialize')->once()->withNoArgs()->andReturn(['some' => 'cache']); /** @var Mock $fsMock */ $container[FileSystemInterface::class] = $fsMock = Mockery::mock(FileSystemInterface::class); $fsMock->shouldReceive('write')->once()->withAnyArgs()->andReturnUndefined(); $inOut = $this->createInOutMock(ApplicationCommand::ARG_ACTION, ApplicationCommand::ACTION_CREATE_CACHE); $method = new ReflectionMethod(ApplicationCommand::class, 'run'); $method->setAccessible(true); $command = new ApplicationCommand(); $method->invoke($command, $container, $inOut); // Mockery will do checks when the test finishes $this->assertTrue(true); } /** * Test action. * * @throws ReflectionException */ public function testCacheInvalidCallable(): void { $this->expectException(ConfigurationException::class); $container = new Container(); /** @var Mock $providerMock */ $providerMock = Mockery::mock(CacheSettingsProviderInterface::class); $container[SettingsProviderInterface::class] = $providerMock; $container[CacheSettingsProviderInterface::class] = $providerMock; $providerMock->shouldReceive('getApplicationConfiguration')->once()->withNoArgs() ->andReturn([ ApplicationConfigurationInterface::KEY_CACHE_FOLDER => '/some/path', ApplicationConfigurationInterface::KEY_CACHE_CALLABLE => '', // <-- invalid value ]); $inOut = $this->createInOutMock(ApplicationCommand::ARG_ACTION, ApplicationCommand::ACTION_CREATE_CACHE); $method = new ReflectionMethod(ApplicationCommand::class, 'run'); $method->setAccessible(true); $command = new ApplicationCommand(); $method->invoke($command, $container, $inOut); // Mockery will do checks when the test finishes $this->assertTrue(true); } /** * Test action. * * @throws ReflectionException */ public function testClear(): void { $container = new Container(); /** @var Mock $providerMock */ $providerMock = Mockery::mock(CacheSettingsProviderInterface::class); $container[SettingsProviderInterface::class] = $providerMock; $container[CacheSettingsProviderInterface::class] = $providerMock; $providerMock->shouldReceive('getApplicationConfiguration')->once()->withNoArgs() ->andReturn([ // the code requires real existing method ApplicationConfigurationInterface::KEY_CACHE_CALLABLE => __METHOD__, ]); /** @var Mock $fsMock */ $container[FileSystemInterface::class] = $fsMock = Mockery::mock(FileSystemInterface::class); $fsMock->shouldReceive('exists')->once()->withAnyArgs()->andReturn(true); $fsMock->shouldReceive('delete')->once()->withAnyArgs()->andReturnUndefined(); $inOut = $this->createInOutMock(ApplicationCommand::ARG_ACTION, ApplicationCommand::ACTION_CLEAR_CACHE); $method = new ReflectionMethod(ApplicationCommand::class, 'run'); $method->setAccessible(true); $command = new ApplicationCommand(); $method->invoke($command, $container, $inOut); // Mockery will do checks when the test finishes $this->assertTrue(true); } /** * Test action. * * @throws ReflectionException */ public function testClearNonExistingCache(): void { $container = new Container(); /** @var Mock $providerMock */ $providerMock = Mockery::mock(CacheSettingsProviderInterface::class); $container[SettingsProviderInterface::class] = $providerMock; $container[CacheSettingsProviderInterface::class] = $providerMock; $providerMock->shouldReceive('getApplicationConfiguration')->once()->withNoArgs() ->andReturn([ ApplicationConfigurationInterface::KEY_CACHE_CALLABLE => 'Namespace\\ClassName::methodName', ]); /** @var Mock $fsMock */ $inOut = $this->createInOutMock(ApplicationCommand::ARG_ACTION, ApplicationCommand::ACTION_CLEAR_CACHE); $method = new ReflectionMethod(ApplicationCommand::class, 'run'); $method->setAccessible(true); $command = new ApplicationCommand(); $method->invoke($command, $container, $inOut); // Mockery will do checks when the test finishes $this->assertTrue(true); } /** * Test action. * * @throws ReflectionException */ public function testParseCacheCallable1(): void { $mightBeCallable = ''; $method = new ReflectionMethod(ApplicationCommand::class, 'parseCacheCallable'); $method->setAccessible(true); $command = new ApplicationCommand(); $result = $method->invoke($command, $mightBeCallable); $this->assertEquals([null, null, null], $result); } /** * Test action. * * @throws ReflectionException */ public function testParseCacheCallable2(): void { $mightBeCallable = ['NamespaceName\\ClassName', 'methodName']; $method = new ReflectionMethod(ApplicationCommand::class, 'parseCacheCallable'); $method->setAccessible(true); $command = new ApplicationCommand(); $result = $method->invoke($command, $mightBeCallable); $this->assertEquals(['NamespaceName', 'ClassName', 'methodName'], $result); } /** * Test action. * * @throws ReflectionException */ public function testParseCacheCallable3(): void { $mightBeCallable = ['NamespaceName\\123ClassName', 'methodName']; // <- numbers not allowed $method = new ReflectionMethod(ApplicationCommand::class, 'parseCacheCallable'); $method->setAccessible(true); $command = new ApplicationCommand(); $result = $method->invoke($command, $mightBeCallable); $this->assertEquals([null, null, null], $result); } /** * @param string $arName * @param string $argValue * @param bool $expectErrors * * @return IoInterface */ private function createInOutMock(string $arName, string $argValue, bool $expectErrors = false): IoInterface { /** @var Mock $mock */ $mock = Mockery::mock(IoInterface::class); $mock->shouldReceive('getArgument')->zeroOrMoreTimes()->with($arName)->andReturn($argValue); if ($expectErrors === true) { $mock->shouldReceive('writeError')->zeroOrMoreTimes()->withAnyArgs()->andReturnSelf(); } $mock->shouldReceive('writeInfo')->zeroOrMoreTimes()->withAnyArgs()->andReturnSelf(); /** @var IoInterface $mock */ return $mock; } }
{ "content_hash": "6cb9f77f4e139cd7050f52258a4e7c0f", "timestamp": "", "source": "github", "line_count": 259, "max_line_length": 113, "avg_line_length": 36.48262548262548, "alnum_prop": 0.6347761667901365, "repo_name": "limoncello-php/framework", "id": "592f02ae437d6ab91667aa6aa19062a2592e5b60", "size": "10050", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/Application/tests/Commands/ApplicationCommandTest.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "572" }, { "name": "HTML", "bytes": "15" }, { "name": "Lua", "bytes": "1951" }, { "name": "PHP", "bytes": "3356439" }, { "name": "Shell", "bytes": "2624" }, { "name": "TypeScript", "bytes": "59450" } ], "symlink_target": "" }
package org.jbpm.workbench.common.client.util; import com.google.gwt.user.client.ui.Composite; public abstract class UTCDateBoxImplShared extends Composite implements UTCDateBoxImpl { /** * Sets the visible length of the date input. The HTML5 * implementation will ignore this. */ @Override public void setVisibleLength(int length) {} /** * Sets the date value (as milliseconds at midnight UTC since 1/1/1970) */ @Override public final void setValue(Long value) { setValue(value, true); } }
{ "content_hash": "0082a0c00e3b80de6605b5eb253e1edb", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 88, "avg_line_length": 24.391304347826086, "alnum_prop": 0.679144385026738, "repo_name": "pefernan/jbpm-console-ng", "id": "a8435c3d8080617666c44c1afcb8804e002f5822", "size": "1182", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jbpm-wb-common/jbpm-wb-common-client/src/main/java/org/jbpm/workbench/common/client/util/UTCDateBoxImplShared.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "28454" }, { "name": "FreeMarker", "bytes": "2262" }, { "name": "HTML", "bytes": "61877" }, { "name": "Java", "bytes": "2298838" }, { "name": "Visual Basic", "bytes": "18019" } ], "symlink_target": "" }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/compositor/test/test_compositor_host.h" #include <memory> #include "base/compiler_specific.h" #include "base/macros.h" #include "base/threading/thread_task_runner_handle.h" #include "base/time/time.h" #include "components/viz/common/surfaces/local_surface_id.h" #include "ui/compositor/compositor.h" #include "ui/gfx/native_widget_types.h" namespace ui { class TestCompositorHostAndroid : public TestCompositorHost { public: TestCompositorHostAndroid(const gfx::Rect& bounds, ui::ContextFactory* context_factory) { compositor_ = std::make_unique<ui::Compositor>( context_factory->AllocateFrameSinkId(), context_factory, base::ThreadTaskRunnerHandle::Get(), false /* enable_pixel_canvas */); // TODO(sievers): Support onscreen here. compositor_->SetAcceleratedWidget(gfx::kNullAcceleratedWidget); compositor_->SetScaleAndSize(1.0f, gfx::Size(bounds.width(), bounds.height()), viz::LocalSurfaceIdAllocation()); } // Overridden from TestCompositorHost: void Show() override { compositor_->SetVisible(true); } ui::Compositor* GetCompositor() override { return compositor_.get(); } private: std::unique_ptr<ui::Compositor> compositor_; DISALLOW_COPY_AND_ASSIGN(TestCompositorHostAndroid); }; TestCompositorHost* TestCompositorHost::Create( const gfx::Rect& bounds, ui::ContextFactory* context_factory) { return new TestCompositorHostAndroid(bounds, context_factory); } } // namespace ui
{ "content_hash": "542c9883b97d0860006a8885de594e4b", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 78, "avg_line_length": 35.16326530612245, "alnum_prop": 0.7028438769587928, "repo_name": "endlessm/chromium-browser", "id": "4c9342e1898dcfb1e951700f3ffebc220465db97", "size": "1723", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ui/compositor/test/test_compositor_host_android.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package algebra package lattice import scala.{specialized => sp} import algebra.ring.CommutativeRig /** * A bounded distributive lattice is a lattice that both bounded and distributive */ trait BoundedDistributiveLattice[@sp(Int, Long, Float, Double) A] extends Any with BoundedLattice[A] with DistributiveLattice[A] { self => /** * Return a CommutativeRig using join and meet. Note this must obey the commutative rig laws since * meet(a, one) = a, and meet and join are associative, commutative and distributive. */ def asCommutativeRig: CommutativeRig[A] = new CommutativeRig[A] { def zero: A = self.zero def one: A = self.one def plus(x: A, y: A): A = self.join(x, y) def times(x: A, y: A): A = self.meet(x, y) } override def dual: BoundedDistributiveLattice[A] = new BoundedDistributiveLattice[A] { def meet(a: A, b: A) = self.join(a, b) def join(a: A, b: A) = self.meet(a, b) def one = self.zero def zero = self.one override def dual = self } } object BoundedDistributiveLattice extends BoundedMeetSemilatticeFunctions[BoundedDistributiveLattice] with BoundedJoinSemilatticeFunctions[BoundedDistributiveLattice] { /** * Access an implicit `BoundedDistributiveLattice[A]`. */ @inline final def apply[@sp(Int, Long, Float, Double) A](implicit ev: BoundedDistributiveLattice[A]): BoundedDistributiveLattice[A] = ev def minMax[@sp(Int, Long, Float, Double)A](min: A, max: A)(implicit ord: Order[A]): BoundedDistributiveLattice[A] = new MinMaxBoundedDistributiveLattice(min, max) } class MinMaxBoundedDistributiveLattice[A](min: A, max: A)(implicit o: Order[A]) extends MinMaxLattice[A] with BoundedDistributiveLattice[A] { def zero = min def one = max }
{ "content_hash": "6c87e30e2304669aaa6b1b6fcde3939e", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 138, "avg_line_length": 35.89795918367347, "alnum_prop": 0.7106310403638431, "repo_name": "tixxit/algebra", "id": "9e22a1d779313eda5c313a224ec4118c2d37a611", "size": "1759", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/main/scala/algebra/lattice/BoundedDistributiveLattice.scala", "mode": "33188", "license": "mit", "language": [ { "name": "Scala", "bytes": "116412" }, { "name": "Shell", "bytes": "19258" } ], "symlink_target": "" }
require 'rails/generators/base' module MongoModel module Generators class ModelGenerator < Rails::Generators::NamedBase source_root File.expand_path('../templates', __FILE__) argument :attributes, :type => :array, :default => [], :banner => "field:type field:type" class_option :timestamps, :type => :boolean, :aliases => "-T", :default => true, :desc => "Add timestamp fields (created_at, updated_at)" class_option :embedded, :type => :boolean, :aliases => "-E", :default => false, :desc => "Inherit from EmbeddedDocument" check_class_collision def create_model_file template 'model.rb', File.join('app/models', class_path, "#{file_name}.rb") end hook_for :test_framework end end end
{ "content_hash": "f65780e1da9843ccbcf897735e0c736f", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 144, "avg_line_length": 34.63636363636363, "alnum_prop": 0.6404199475065617, "repo_name": "spohlenz/mongomodel", "id": "8de1fa50530b01b1a904c3cd716200d38cb1a268", "size": "762", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/rails/generators/mongo_model/model/model_generator.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "364337" } ], "symlink_target": "" }
package com.google.gwt.query.client; import static com.google.gwt.query.client.plugins.QueuePlugin.Queue; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArrayMixed; import com.google.gwt.core.client.JsArrayString; import com.google.gwt.core.client.ScriptInjector; import com.google.gwt.dom.client.BodyElement; import com.google.gwt.dom.client.ButtonElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.InputElement; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.dom.client.Node; import com.google.gwt.dom.client.NodeList; import com.google.gwt.dom.client.OptionElement; import com.google.gwt.dom.client.SelectElement; import com.google.gwt.dom.client.Style.Display; import com.google.gwt.dom.client.TextAreaElement; import com.google.gwt.query.client.builders.JsonBuilder; import com.google.gwt.query.client.css.HasCssValue; import com.google.gwt.query.client.css.TakesCssValue; import com.google.gwt.query.client.css.TakesCssValue.CssSetter; import com.google.gwt.query.client.impl.AttributeImpl; import com.google.gwt.query.client.impl.DocumentStyleImpl; import com.google.gwt.query.client.impl.SelectorEngine; import com.google.gwt.query.client.js.JsCache; import com.google.gwt.query.client.js.JsMap; import com.google.gwt.query.client.js.JsNamedArray; import com.google.gwt.query.client.js.JsNodeArray; import com.google.gwt.query.client.js.JsObjectArray; import com.google.gwt.query.client.js.JsUtils; import com.google.gwt.query.client.plugins.Effects; import com.google.gwt.query.client.plugins.Events; import com.google.gwt.query.client.plugins.Plugin; import com.google.gwt.query.client.plugins.Widgets; import com.google.gwt.query.client.plugins.ajax.Ajax; import com.google.gwt.query.client.plugins.ajax.Ajax.Settings; import com.google.gwt.query.client.plugins.deferred.Deferred; import com.google.gwt.query.client.plugins.deferred.PromiseFunction; import com.google.gwt.query.client.plugins.effects.PropertiesAnimation.Easing; import com.google.gwt.query.client.plugins.events.EventsListener; import com.google.gwt.query.client.plugins.widgets.WidgetsUtils; import com.google.gwt.regexp.shared.MatchResult; import com.google.gwt.regexp.shared.RegExp; import com.google.gwt.safehtml.shared.SafeHtml; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Event; import com.google.gwt.user.client.EventListener; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * GwtQuery is a GWT clone of the popular jQuery library. */ public class GQuery implements Lazy<GQuery, LazyGQuery> { private enum DomMan { AFTER, APPEND, BEFORE, PREPEND; } /** * A POJO used to store the top/left CSS positioning values of an element. */ public static class Offset { public int left; public int top; public Offset(int left, int top) { this.left = left; this.top = top; } public Offset add(int left, int top) { return new Offset(this.left + left, this.top + top); } public String toString() { return top + "+" + left; } } /** * Class used internally to create DOM element from html snippet. */ private static class TagWrapper { public static final TagWrapper DEFAULT = new TagWrapper(0, "", ""); private String postWrap; private String preWrap; private int wrapDepth; public TagWrapper(int wrapDepth, String preWrap, String postWrap) { this.wrapDepth = wrapDepth; this.postWrap = postWrap; this.preWrap = preWrap; } } /** * Implementation class to modify attributes. */ protected static AttributeImpl attributeImpl; /** * The body element in the current page. */ public static final BodyElement body = GWT.isClient() ? Document.get().getBody() : null; /** * A Browser object with a set of browser-specific flags. */ public static final Browser browser = GWT.isClient() ? GWT.<Browser>create(Browser.class) : null; /** * An object with the same methods than window.console. */ public static final Console console = GWT.isClient() ? GWT.<Console>create(Console.class) : null; /** * Object to store element data (public so as we can access to it from tests). */ public static JsCache dataCache = null; /** * The document element in the current page. */ public static final Document document = GWT.isClient() ? Document.get() : null; /** * Static reference Effects plugin. */ public static Class<Effects> Effects = com.google.gwt.query.client.plugins.Effects.Effects; /** * Implementation engine used for CSS selectors. */ protected static SelectorEngine engine; /** * Static reference Events plugin. */ public static Class<Events> Events = com.google.gwt.query.client.plugins.Events.Events; /** * A static reference to the GQuery class. */ public static Class<GQuery> GQUERY = GQuery.class; private static final String OLD_DATA_PREFIX = "old-"; private static final String OLD_DISPLAY = OLD_DATA_PREFIX + "display"; private static JsMap<Class<? extends GQuery>, Plugin<? extends GQuery>> plugins; // Sizzle POS regex : usefull in some methods // TODO: Share this static with SelectorEngineSizzle private static RegExp posRegex = RegExp .compile("^:(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\))?(?=[^\\-]|$)$"); /** * Implementation class used for style manipulations. */ private static DocumentStyleImpl styleImpl; private static RegExp tagNameRegex = RegExp.compile("<([\\w:-]+)"); /** * Static reference to the Widgets plugin. */ public static Class<Widgets> Widgets = com.google.gwt.query.client.plugins.Widgets.Widgets; /** * The window object. */ public static final Element window = GWT.isClient() ? ScriptInjector.TOP_WINDOW.<Element> cast() : null; private static Element windowData = null; private static JsNamedArray<TagWrapper> wrapperMap; /** * Create an empty GQuery object. */ public static GQuery $() { return new GQuery(JsNodeArray.create()); } /** * Wrap a GQuery around any object, supported objects are: * String, GQuery, Function, Widget, JavaScriptObject. * * In the case of string, we accept a CSS selector which is then used to match a set of * elements, or a raw HTML to create a GQuery element containing those elements. Xpath * selector is supported in browsers with native xpath engine. * * In the case of a JavaScriptObject we handle: * Element, Event, Node, Nodelist, Function, and native functions or arrays. * * If the case of a native function, we execute it and return empty. */ public static GQuery $(Object o) { if (o != null) { if (o instanceof String) { return $((String) o); } if (o instanceof SafeHtml) { return $(((SafeHtml) o).asString()); } if (o instanceof GQuery) { return (GQuery) o; } if (o instanceof Function) { return new GQuery(((Function) o).getElement()); } if (JsUtils.isElement(o)) { return new GQuery(JsUtils.<Element> cast(o)); } if (o instanceof JsonBuilder) { return new GQuery(((JsonBuilder) o).<Element>getDataImpl()); } if (o instanceof IsWidget) { return $(Arrays.asList(o)); } if (o instanceof JavaScriptObject) { JavaScriptObject jso = (JavaScriptObject) o; // Execute a native javascript function like jquery does if (JsUtils.isFunction(jso)) { new JsUtils.JsFunction(jso).fe(); return $(); } // Wraps a native array like jquery does if (!JsUtils.isWindow(jso) && !JsUtils.isElement(jso) && JsUtils.isArray(jso)) { JsArrayMixed c = jso.cast(); JsNodeArray elms = JsNodeArray.create(); for (int i = 0; i < c.length(); i++) { Object obj = c.getObject(i); if (obj instanceof Node) { elms.addNode((Node) obj); } } return new GQuery(elms); } // Wraps a native NodeList if (JsUtils.isNodeList(jso)) { return new GQuery(jso.<NodeList<Element>> cast()); } // Wraps an event if (JsUtils.isEvent(jso)) { jso = jso.<Event>cast().getCurrentEventTarget(); } // Otherwise we wrap it as an element return new GQuery(jso.<Element> cast()); } throw new RuntimeException("Error: GQuery.$(Object o) could not wrap the type : " + o.getClass().getName() + " " + o); } return $(); } /** * Create a new GQuery given a list of {@link com.google.gwt.dom.client.Node} or * {@link com.google.gwt.user.client.ui.IsWidget}. */ public static GQuery $(List<?> nodesOrWidgets) { JsNodeArray elms = JsNodeArray.create(); if (nodesOrWidgets != null) { for (Object o : nodesOrWidgets) { if (o instanceof Node) { elms.addNode((Node) o); } else if (o instanceof IsWidget) { elms.addNode(((IsWidget) o).asWidget().getElement()); } } } return new GQuery(elms); } /** * This function accepts a string containing a CSS selector which is then used to match a set of * elements, or it accepts raw HTML creating a GQuery element containing those elements. Xpath * selector is supported in browsers with native xpath engine. */ public static GQuery $(String selectorOrHtml) { return $(selectorOrHtml, document); } /** * This function accepts a string containing a CSS selector which is then used to match a set of * elements, or it accepts raw HTML creating a GQuery element containing those elements. The * second parameter is is a class reference to a plugin to be used. * * Xpath selector is supported in browsers with native xpath engine. */ public static <T extends GQuery> T $(String selector, Class<T> plugin) { return $(selector, document, plugin); } /** * This function accepts a string containing a CSS selector which is then used to match a set of * elements, or it accepts raw HTML creating a GQuery element containing those elements. The * second parameter is the context to use for the selector, or the document where the new elements * will be created. * * Xpath selector is supported in browsers with native xpath engine. */ public static GQuery $(String selectorOrHtml, Node ctx) { String selector = null; if (selectorOrHtml == null || (selector = selectorOrHtml.trim()).length() == 0) { return $(); } if (selector.startsWith("<")) { return innerHtml(selectorOrHtml, JsUtils.getOwnerDocument(ctx)); } return new GQuery().select(selectorOrHtml, ctx); } /** * This function accepts a string containing a CSS selector which is then used to match a set of * elements, or it accepts raw HTML creating a GQuery element containing those elements. The * second parameter is the context to use for the selector. The third parameter is the class * plugin to use. * * Xpath selector is supported in browsers with native xpath engine. */ @SuppressWarnings("unchecked") public static <T extends GQuery> T $(String selector, Node context, Class<T> plugin) { try { if (plugins != null) { T gquery = (T) plugins.get(plugin).init(new GQuery().select(selector, context)); return gquery; } throw new RuntimeException("No plugin for class " + plugin); } catch (Exception e) { throw new RuntimeException(e); } } /** * This function accepts a string containing a CSS selector which is then used to match a set of * elements, or it accepts raw HTML creating a GQuery element containing those elements. The * second parameter is the context to use for the selector, or the document where the new elements * will be created. * * Xpath selector is supported in browsers with native xpath engine. */ public static GQuery $(String selectorOrHtml, Widget context) { return $(selectorOrHtml, context.getElement()); } /** * This function accepts a string containing a CSS selector which is then used to match a set of * elements, or it accepts raw HTML creating a GQuery element containing those elements. The * second parameter is the context to use for the selector. The third parameter is the class * plugin to use. * * Xpath selector is supported in browsers with native xpath engine. */ public static <T extends GQuery> T $(String selector, Widget context, Class<T> plugin) { return $(selector, context.getElement(), plugin); } /** * Wrap a GQuery around one widget or an array of existing ones. */ public static GQuery $(Widget... widgets) { return $(Arrays.asList(widgets)); } /** * Wrap a GQuery around one node or an array of existing ones. */ public static GQuery $(Node... nodes) { return $(Arrays.asList(nodes)); } /** * Create an empty JSON object. */ public static Properties $$() { return $$(null); } /** * Wrap a JSON object. */ public static Properties $$(String properties) { return Properties.create(properties); } /** * Perform an ajax request to the server. */ public static Promise ajax(Properties p) { return Ajax.ajax(p); } /** * Perform an ajax request to the server. */ public static Promise ajax(Settings settings) { return Ajax.ajax(settings); } /** * Perform an ajax request to the server. */ public static Promise ajax(String url, Settings settings) { return Ajax.ajax(url, settings); } protected static GQuery cleanHtmlString(String elem, Document doc) { MatchResult mResult = tagNameRegex.exec(elem); if (mResult == null) { return $(doc.createTextNode(elem)); } String tag = mResult.getGroup(1); if (wrapperMap == null) { initWrapperMap(); } TagWrapper wrapper = wrapperMap.get(tag.toLowerCase()); if (wrapper == null) { wrapper = TagWrapper.DEFAULT; } // TODO: fix IE link tag serialization // TODO: fix IE <script> tag // TODO: add fixes for IE TBODY issue // We use a temporary element to wrap the elements Element div = doc.createDivElement(); div.setInnerHTML(wrapper.preWrap + elem.trim() + wrapper.postWrap); Node n = div; int depth = wrapper.wrapDepth; while (depth-- != 0) { n = n.getLastChild(); } return // return all nodes added to the wrapper $(n.getChildNodes()) // detach nodes from their temporary parent .remove(null, false); } /** * Return true if the element b is contained in a. */ public static boolean contains(Element a, Element b) { return getSelectorEngine().contains(a, b); } /** * Get the element data matching the key. */ public static <T> T data(Element e, String key) { return data(e, key, null); } /** * Store arbitrary data associated with the specified element. * * We store this data in a global js object having the structure: * datacache [element.hashCode()] [key] = value * * @return the value stored in the element with the given name */ public static <T> T data(Element element, String key, T value) { return data(element, key, value, null); } private static <T> T data(Element element, String key, T value, Class<? extends T> clz) { if (dataCache == null) { windowData = JavaScriptObject.createObject().cast(); dataCache = JavaScriptObject.createObject().cast(); } element = element == window || element.getNodeName() == null ? windowData : element; if (element != null && key != null) { int id = element.hashCode(); if (value == null) { return dataCache.exists(id) ? dataCache.getCache(id).get(key, clz) : null; } if (!dataCache.exists(id)) { dataCache.put(id, JsCache.createObject().cast()); } dataCache.getCache(id).put(key, value); } return value; } /** * Execute a function around each object. */ public static void each(JsArrayMixed objects, Function f) { for (int i = 0, l = objects.length(); i < l; i++) { f.f(i, objects.getObject(i)); } } /** * Execute a function around each object. */ public static <T> void each(List<T> objects, Function f) { for (int i = 0, l = objects.size(); i < l; i++) { f.f(i, objects.get(i)); } } /** * Execute a function around each object. */ public static <T> void each(T[] objects, Function f) { for (int i = 0, l = objects.length; i < l; i++) { f.f(i, objects[i]); } } /** * Perform an ajax request to the server using GET. */ public static Promise get(String url, Properties data, final Function onSuccess) { return Ajax.get(url, data, onSuccess); } /** * We will use the fact as GWT use the widget itself as EventListener ! If no Widget associated * with the element, this method returns null. */ protected static Widget getAssociatedWidget(Element e) { try { EventListener listener = DOM.getEventListener((com.google.gwt.user.client.Element) e); // No listener attached to the element, so no widget exist for this element if (listener == null) { return null; } if (listener instanceof Widget) { // GWT uses the widget as event listener return (Widget) listener; } else if (listener instanceof EventsListener) { // GQuery replaces the gwt event listener and save it EventsListener gQueryListener = (EventsListener) listener; if (gQueryListener.getOriginalEventListener() != null && gQueryListener.getOriginalEventListener() instanceof Widget) { return (Widget) gQueryListener.getOriginalEventListener(); } } } catch (Exception e2) { // Some times this code could raise an exception. // We do not want GQuery to fail, but in dev-mode we log the error. e2.printStackTrace(); } return null; } private static AttributeImpl getAttributeImpl() { if (attributeImpl == null) { attributeImpl = GWT.create(AttributeImpl.class); } return attributeImpl; } /** * Perform an ajax request to the server using POST and parsing the json response. */ public static Promise getJSON(String url, Properties data, final Function onSuccess) { return Ajax.getJSON(url, data, onSuccess); } /** * Perform an ajax request to the server using scripts tags and parsing the json response. The * request is not subject to the same origin policy restrictions. * * Server side should accept a parameter to specify the callback funcion name, and it must return * a valid json object wrapped this callback function. * * Example: * * <pre> Client code: getJSONP("http://server.exampe.com/getData.php",$$("myCallback:'?', otherParameter='whatever'"), new Function(){ public void f() { Properties p = getDataProperties(); alert(p.getStr("k1"); }}); Server response: myCallback({"k1":"v1", "k2":"v2"}); </pre> * */ public static Promise getJSONP(String url, Properties data, final Function onSuccess) { return Ajax.getJSONP(url, data, onSuccess); } protected static DocumentStyleImpl getStyleImpl() { if (styleImpl == null) { styleImpl = getSelectorEngine().getDocumentStyleImpl(); } return styleImpl; } /** * Return only the set of objects with match the predicate. */ @SuppressWarnings("unchecked") public static <T> T[] grep(T[] objects, Predicate f) { ArrayList<Object> ret = new ArrayList<>(); for (int i = 0, l = objects.length; i < l; i++) { if (f.f(objects[i], i)) { ret.add(objects[i]); } } return (T[]) ret.toArray(new Object[0]); } private static boolean hasClass(Element e, String clz) { return e.getClassName().matches("(^|.*\\s)" + clz + "(\\s.*|$)"); } private static void initWrapperMap() { TagWrapper tableWrapper = new TagWrapper(1, "<table>", "</table>"); TagWrapper selectWrapper = new TagWrapper(1, "<select multiple=\"multiple\">", "</select>"); TagWrapper trWrapper = new TagWrapper(3, "<table><tbody><tr>", "</tr></tbody></table>"); wrapperMap = JsNamedArray.create(); wrapperMap.put("option", selectWrapper); wrapperMap.put("optgroup", selectWrapper); wrapperMap.put("legend", new TagWrapper(1, "<fieldset>", "</fieldset>")); wrapperMap.put("thead", tableWrapper); wrapperMap.put("tbody", tableWrapper); wrapperMap.put("tfoot", tableWrapper); wrapperMap.put("colgroup", tableWrapper); wrapperMap.put("caption", tableWrapper); wrapperMap.put("tr", new TagWrapper(2, "<table><tbody>", "</tbody></table>")); wrapperMap.put("td", trWrapper); wrapperMap.put("th", trWrapper); wrapperMap.put("col", new TagWrapper(2, "<table><tbody></tbody><colgroup>", "</colgroup></table>")); wrapperMap.put("area", new TagWrapper(1, "<map>", "</map>")); } private static GQuery innerHtml(String html, Document doc) { return cleanHtmlString(html, doc); } protected static String[] jsArrayToString(JsArrayString array) { if (GWT.isScript()) { return JsUtils.castArrayString(array); } else { String result[] = new String[array.length()]; for (int i = 0, l = result.length; i < l; i++) { result[i] = array.get(i); } return result; } } /** * Return a lazy version of the GQuery interface. Lazy function calls are simply queued up and not * executed immediately. */ public static LazyGQuery<?> lazy() { return $().createLazy(); } /** * Perform an ajax request to the server using POST. */ public static Promise post(String url, Properties data, final Function onSuccess) { return Ajax.post(url, data, onSuccess); } public static <T extends GQuery> Class<T> registerPlugin(Class<T> plugin, Plugin<T> pluginFactory) { // TODO: decide whether change plugins type to java.util.list // Right now we only test static methods in gquery, so this is only needed when initializing // plugins shortcuts in gquery. if (GWT.isClient()) { if (plugins == null) { plugins = JsMap.createObject().cast(); } plugins.put(plugin, pluginFactory); } return plugin; } /** * Provides a way to execute callback Functions based on one or more objects * that represent asynchronous events. * * Arguments can be of any Object, but normally you would pass Promises. * In the case you provide a GQuery object it will call the promise() method to return * a Promise which will be executed when the queue is resolved. * In the case you provide a normal Object, it will return a promise which will be immediately * resolved with the object as argument. * In the case you provide a Function it will executed and if the f(Object...) method returns * a new promise it will be used, otherwise we will use the returned object like in the last case. * * It Returns a new promise which will be finalized when all of its subordinates finish. * In the case of all subordinates are resolved correctly the promise will be resolved * otherwise it will be rejected. */ public static Promise when(Object... subordinates) { return Deferred.when(subordinates); } /** * A constructor function that returns a chainable utility object with methods to register * multiple callbacks into callback queues, invoke callback queues, and relay the success * or failure state of any synchronous or asynchronous function. */ public static Promise.Deferred Deferred() { return new Deferred(); } public static SelectorEngine getSelectorEngine() { if (engine == null) { engine = GWT.create(SelectorEngine.class); } return engine; } private static native void scrollIntoViewImpl(Node n) /*-{ if (n) n.scrollIntoView() }-*/; private static native void setElementValue(Element e, String value) /*-{ e.value = value; }-*/; protected Node currentContext; protected String currentSelector; /** * Immutable array of matched elements, modify this using setArray. */ private Element[] elements = new Element[0]; /** * The nodeList of matched elements, modify this using setArray. */ // TODO: remove this and use elements, change return type of get() private NodeList<Element> nodeList = JavaScriptObject.createArray().cast(); private GQuery previousObject; private GQuery() { } private GQuery(Element element) { this(JsNodeArray.create(element)); } protected GQuery(GQuery gq) { if (gq != null) { elements = gq.elements; nodeList = gq.nodeList; currentSelector = gq.currentSelector; currentContext = gq.currentContext; } } private GQuery(JsNodeArray nodes) { this(nodes.<NodeList<Element>> cast()); } private GQuery(NodeList<Element> list) { setArray(list); } /** * Add elements to the set of matched elements if they are not included yet. * * It construct a new GQuery object and does not modify the original ones. * * It also update the selector appending the new one. */ public GQuery add(GQuery elementsToAdd) { return pushStack(JsUtils.copyNodeList(nodeList, elementsToAdd.nodeList, true) .<JsNodeArray> cast(), "add", join(",", getSelector(), elementsToAdd.getSelector())); } /** * Add elements to the set of matched elements if they are not included yet. */ public GQuery add(String selector) { return add($(selector)); } /** * Add the previous selection to the current selection. Useful for traversing elements, and then * adding something that was matched before the last traversal. */ public GQuery addBack() { return previousObject != null ? add(previousObject) : this; } /** * Adds the specified classes to each matched element. */ public GQuery addClass(String... classes) { for (Element e : elements) { // issue 81 : ensure that the element is an Element node. if (Element.is(e)) { for (String clz : classes) { e.addClassName(clz); } } } return this; } /** * Insert content after each of the matched elements. The elements must already be inserted into * the document (you can't insert an element after another if it's not in the page). */ public GQuery after(GQuery query) { return domManip(query, DomMan.AFTER); } /** * Insert content after each of the matched elements. The elements must already be inserted into * the document (you can't insert an element after another if it's not in the page). */ public GQuery after(Node n) { return domManip($(n), DomMan.AFTER); } /** * Insert content after each of the matched elements. The elements must already be inserted into * the document (you can't insert an element after another if it's not in the page). */ public GQuery after(String html) { return domManip(html, DomMan.AFTER); } /** * Insert content after each of the matched elements. The elements must already be inserted into * the document (you can't insert an element after another if it's not in the page). */ public GQuery after(SafeHtml safeHtml) { return after(safeHtml.asString()); } private void allNextSiblingElements(Element firstChildElement, JsNodeArray result, Element elem, GQuery until, String filterSelector) { while (firstChildElement != null) { if (until != null && until.index(firstChildElement) != -1) { return; } if (firstChildElement != elem && (filterSelector == null || $(firstChildElement).is(filterSelector))) { result.addNode(firstChildElement); } firstChildElement = firstChildElement.getNextSiblingElement(); } } private void allPreviousSiblingElements(Element firstChildElement, JsNodeArray result, GQuery until, String filterSelector) { while (firstChildElement != null) { if (until != null && until.index(firstChildElement) != -1) { return; } if (filterSelector == null || $(firstChildElement).is(filterSelector)) { result.addNode(firstChildElement); } firstChildElement = getPreviousSiblingElement(firstChildElement); } } /** * Add the previous selection to the current selection. Useful for traversing elements, and then * adding something that was matched before the last traversal. * @deprecated use addBack() instead */ @Deprecated public GQuery andSelf() { return addBack(); } /** * * The animate() method allows you to create animation effects on any numeric HTML Attribute, * CSS property, or color CSS property. * * Concerning to numeric properties, values are treated as a number of pixels unless otherwise * specified. The units em and % can be specified where applicable. * * By default animate considers css properties, if you wanted to animate element attributes you * should to prepend the symbol dollar to the attribute name. It's useful to animate svg elements. * * NOTE: The ability of animating attribute values is only available in gquery but not jquery * * Example: * * <pre class="code"> * // move the element from its original position to left:500px * $("#foo").animate("left:'500'"); * * // Change the width html attribute of a table, note the symbol '$' to * // tell gquery which it is an html-attribute instead of a css-property. * $("table").animate("$width:'500'"); * </pre> * * In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'. * These shortcuts allow for custom hiding and showing animations that take into account the * display type of the element. Animated properties can also be relative. If a value is supplied * with a leading += or -= sequence of characters, then the target value is computed by adding or * subtracting the given number from the current value of the property. * * Example: * * <pre class="code"> * // move the element from its original position to 500px to the left for 500ms and * // change the background color of the element at the end of the animation * * $("#foo").animate("left:'+=500'", new Function(){ * public void f(Element e){ * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED); * } * }); * </pre> * * The default duration of the animation is 500ms. * * For color css properties, values can be specified via hexadecimal or rgb or literal values. * * Example: * * <pre class="code"> * $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)'"); * </pre> * * @param stringOrProperties the property to animate : "cssName:'value'" * @param funcs an array of {@link Function} called once the animation is complete */ public GQuery animate(Object stringOrProperties, Function... funcs) { return as(Effects).animate(stringOrProperties, funcs); } /** * * The animate() method allows you to create animation effects on any numeric HTML Attribute, * CSS property, or color CSS property. * * Concerning to numeric properties, values are treated as a number of pixels unless otherwise * specified. The units em and % can be specified where applicable. * * By default animate considers css properties, if you wanted to animate element attributes you * should to prepend the symbol dollar to the attribute name. It's useful to animate svg elements. * * NOTE: The ability of animating attribute values is only available in gquery but not jquery * * Example: * * <pre class="code"> * // move the element from its original position to left:500px for 500ms using a swing easing * $("#foo").animate("left:'500'", 500, Easing.SWING); * * // Change the width html attribute of a table, note the symbol '$' to * // tell gquery which it is an html-attribute instead of a css-property. * // the animation will last 400ms, and we use the LINEAR easing algorithm * $("table").animate(Properties.create("{$width: '500', $border: '10'}"), 400, Easing.LINEAR); * </pre> * * In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'. * These shortcuts allow for custom hiding and showing animations that take into account the * display type of the element. Animated properties can also be relative. If a value is supplied * with a leading += or -= sequence of characters, then the target value is computed by adding or * subtracting the given number from the current value of the property. * * Example: * * <pre class="code"> * // move the element from its original position to 500px to the left and 5OOpx down for 400ms. * // use a swing easing function for the transition * $("#foo").animate(Properties.create("{top:'+=500px',left:'+=500px'}"), 400, Easing.SWING); * </pre> * * For color css properties, values can be specified via hexadecimal or rgb or literal values. * * Example: * * <pre class="code"> * $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)'"), 400, Easing.SWING); * </pre> * * @param stringOrProperties a String or a {@link Properties} object containing css properties to * animate. * @param funcs an array of {@link Function} called once the animation is complete * @param duration the duration in milliseconds of the animation * @param easing the easing function to use for the transition */ public GQuery animate(Object stringOrProperties, int duration, Easing easing, Function... funcs) { return as(Effects).animate(stringOrProperties, duration, easing, funcs); } /** * The animate() method allows you to create animation effects on any numeric HTML Attribute, * CSS property, or color CSS property. * * Concerning to numeric properties, values are treated as a number of pixels unless otherwise * specified. The units em and % can be specified where applicable. * * By default animate considers css properties, if you wanted to animate element attributes you * should to prepend the symbol dollar to the attribute name. It's useful to animate svg elements. * * NOTE: The ability of animating attribute values is only available in gquery but not jquery * * Example: * * <pre class="code"> * // move the element from its original position to left:500px for 500ms * $("#foo").animate("left:'500'", 500); * * // Change the width html attribute of a table, note the symbol '$' to * // tell gquery which it is an html-attribute instead of a css-property. * // the animation will last 400ms * $("table").animate("$width:'500'"), 400); * </pre> * * In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'. * These shortcuts allow for custom hiding and showing animations that take into account the * display type of the element. Animated properties can also be relative. If a value is supplied * with a leading += or -= sequence of characters, then the target value is computed by adding or * subtracting the given number from the current value of the property. * * Example: * * <pre class="code"> * // move the element from its original position to 500px to the left for 1000ms and * // change the background color of the element at the end of the animation * $("#foo").animate("left:'+=500'", 1000, new Function(){ * public void f(Element e){ * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED); * } * }); * </pre> * * For color css properties, values can be specified via hexadecimal or rgb or literal values. * * Example: * * <pre class="code"> * $("#foo").animate("backgroundColor:'red', color:'#ffffff', borderColor:'rgb(129, 0, 70)', 1000"); * </pre> * * @param stringOrProperties the set of properties to animate : "cssName:'value'" * @param funcs an array of {@link Function} called once the animation is complete. */ public GQuery animate(Object stringOrProperties, int duration, Function... funcs) { return as(Effects).animate(stringOrProperties, duration, funcs); } /** * Append content to the inside of every matched element. This operation is similar to doing an * appendChild to all the specified elements, adding them into the document. */ public GQuery append(GQuery query) { return domManip(query, DomMan.APPEND); } /** * Append content to the inside of every matched element. This operation is similar to doing an * appendChild to all the specified elements, adding them into the document. */ public GQuery append(Node n) { return domManip($(n), DomMan.APPEND); } /** * Append content to the inside of every matched element. This operation is similar to doing an * appendChild to all the specified elements, adding them into the document. */ public GQuery append(String html) { return domManip(html, DomMan.APPEND); } /** * Append content to the inside of every matched element. This operation is similar to doing an * appendChild to all the specified elements, adding them into the document. */ public GQuery append(SafeHtml safeHtml) { return append(safeHtml.asString()); } /** * All of the matched set of elements will be inserted at the end of the element(s) specified by * the parameter other. * * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B), * instead of appending B to A, you're appending A to B. */ public GQuery appendTo(GQuery other) { other.append(this); return this; } /** * All of the matched set of elements will be inserted at the end of the element(s) specified by * the parameter other. * * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B), * instead of appending B to A, you're appending A to B. */ public GQuery appendTo(Node n) { GQuery a = $(n); GQuery b = this; a.append(b); return this; } /** * All of the matched set of elements will be inserted at the end of the element(s) specified by * the parameter other. * * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B), * instead of appending B to A, you're appending A to B. */ public GQuery appendTo(String html) { $(html).append(this); return this; } /** * All of the matched set of elements will be inserted at the end of the element(s) specified by * the parameter other. * * The operation $(A).appendTo(B) is, essentially, the reverse of doing a regular $(A).append(B), * instead of appending B to A, you're appending A to B. */ public GQuery appendTo(SafeHtml safeHtml) { return appendTo(safeHtml.asString()); } /** * Convert to Plugin interface provided by Class literal. */ @SuppressWarnings("unchecked") public <T extends GQuery> T as(Class<T> plugin) { // GQuery is not a plugin for itself if (plugin == GQUERY) { return (T) this; } else if (plugins != null) { Plugin<?> p = plugins.get(plugin); if (p != null) { return (T) p.init(this); } } throw new RuntimeException("No plugin registered for class " + plugin.getName()); } /** * Set a key/value object as properties to all matched elements. * * Example: $("img").attr(new Properties("src: 'test.jpg', alt: 'Test Image'")) */ public GQuery attr(Properties properties) { for (String name : properties.keys()) { attr(name, properties.getStr(name)); } return this; } /** * Access a property on the first matched element. This method makes it easy to retrieve a * property value from the first matched element. If the element does not have an attribute with * such a name, empty string is returned. Attributes include title, alt, src, href, width, style, * etc. */ public String attr(String name) { return isEmpty() ? "" : get(0).getAttribute(name); } /** * Set a single property to a computed value, on all matched elements. */ public GQuery attr(String key, Function closure) { int i = 0; for (Element e : elements) { Object val = closure.f(e.<com.google.gwt.dom.client.Element> cast(), i++); $(e).attr(key, val); } return this; } /** * Set a single property to a value, on all matched elements. */ public GQuery attr(String key, Object value) { assert key != null : "key cannot be null"; assert !"$H".equalsIgnoreCase(key) : "$H is a GWT reserved attribute. Changing its value will break your application."; getAttributeImpl().setAttribute(this, key, value); return this; } /** * Insert content before each of the matched elements. The elements must already be inserted into * the document (you can't insert an element before another if it's not in the page). */ public GQuery before(GQuery query) { return domManip(query, DomMan.BEFORE); } /** * Insert content before each of the matched elements. The elements must already be inserted into * the document (you can't insert an element before another if it's not in the page). */ public GQuery before(Node n) { return domManip($(n), DomMan.BEFORE); } /** * Insert content before each of the matched elements. The elements must already be inserted into * the document (you can't insert an element before another if it's not in the page). */ public GQuery before(String html) { return domManip(html, DomMan.BEFORE); } /** * Binds a set of handlers to a particular Event for each matched element. * * The event handlers are passed as Functions that you can use to prevent default behavior. To * stop both default action and event bubbling, the function event handler has to return false. * * You can pass an additional Object data to your Function as the second parameter * */ public GQuery bind(int eventbits, final Object data, final Function... funcs) { return as(Events).bind(eventbits, data, funcs); } /** * Binds a set of handlers to a particular Event for each matched element. * * The event handlers are passed as Functions that you can use to prevent default behavior. To * stop both default action and event bubbling, the function event handler has to return false. * */ public GQuery bind(int eventbits, final Function... funcs) { return as(Events).bind(eventbits, null, funcs); } /** * Binds a set of handlers to a particular Event for each matched element. * * The event handlers are passed as Functions that you can use to prevent default behavior. To * stop both default action and event bubbling, the function event handler has to return false. * * You can pass an additional Object data to your Function as the second parameter * */ public GQuery bind(String eventType, final Object data, final Function... funcs) { return as(Events).bind(eventType, data, funcs); } /** * Binds a set of handlers to a particular Event for each matched element. * * The event handlers are passed as Functions that you can use to prevent default behavior. To * stop both default action and event bubbling, the function event handler has to return false. * */ public GQuery bind(String eventType, final Function... funcs) { return as(Events).bind(eventType, null, funcs); } /** * Bind Handlers or fire Events for each matched element. */ private GQuery bindOrFire(int eventbits, final Object data, final Function... funcs) { if (funcs.length == 0) { return trigger(eventbits); } else { return bind(eventbits, data, funcs); } } /** * Bind Handlers or fire Events for each matched element. */ private GQuery bindOrFire(String eventname, final Object data, final Function... funcs) { if (funcs.length == 0) { return as(Events).triggerHtmlEvent(eventname); } else { return bind(eventname, data, funcs); } } /** * Bind a set of functions to the blur event of each matched element. Or trigger the blur event if * no functions are provided. */ public GQuery blur(Function... f) { bindOrFire(Event.ONBLUR, null, f); if (!isEmpty() && f.length == 0) { get(0).blur(); } return this; } /** * Bind a set of functions to the change event of each matched element. Or trigger the event if no * functions are provided. */ public GQuery change(Function... f) { return bindOrFire(Event.ONCHANGE, null, f); } /** * Get a set of elements containing all of the unique immediate children of each of the matched * set of elements. Also note: while parents() will look at all ancestors, children() will only * consider immediate child elements. */ public GQuery children() { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { allNextSiblingElements(e.getFirstChildElement(), result, null, null, null); } return new GQuery(unique(result)); } /** * Get a set of elements containing all of the unique children of each of the matched set of * elements. This set is filtered with the expressions that will cause only elements matching any * of the selectors to be collected. */ public GQuery children(String... filters) { return children().filter(filters); } private void cleanGQData(Element... elements) { for (Element el : elements) { try { EventsListener.clean(el); removeData(el, null); } catch (Exception e) { // If for some reason event/data removal fails, do not break the app, // just log the error in dev-mode // e.g.: this happens when removing iframes which are no fully loaded. e.printStackTrace(); } } } /** * Remove from the Effects queue all {@link Function} that have not yet been run. */ public GQuery clearQueue() { return as(Queue).clearQueue(); } /** * Remove from the queue all {@link Function} that have not yet been run. */ public GQuery clearQueue(String queueName) { return as(Queue).clearQueue(queueName); } /** * Bind a set of functions to the click event of each matched element. Or trigger the event if no * functions are provided. */ public GQuery click(Function... f) { return bindOrFire(Event.ONCLICK, null, f); } /** * Clone matched DOM Elements and select the clones. This is useful for moving copies of the * elements to another location in the DOM. */ public GQuery clone() { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { result.addNode(e.cloneNode(true)); } GQuery ret = new GQuery(result); ret.currentContext = currentContext; ret.currentSelector = currentSelector; return ret; } /** * Get the first ancestor element that matches the selector (for each matched element), beginning * at the current element and progressing up through the DOM tree. * * @param selector * @return */ public GQuery closest(String selector) { return closest(selector, null); } /** * Get the first ancestor element that matches the selector (for each matched element), beginning * at the current element and progressing up through the DOM tree until reach the * <code>context</code> node. * * If no context is passed in then the context of the gQuery object will be used instead. * */ public GQuery closest(String selector, Node context) { assert selector != null; if (context == null) { context = currentContext; } GQuery pos = posRegex.test(selector) ? $(selector, context) : null; JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { Element current = e; while (current != null && current.getOwnerDocument() != null && current != context) { boolean match = pos != null ? pos.index(current) > -1 : $(current).is(selector); if (match) { result.addNode(current); break; } else { current = current.getParentElement(); } } } return $(unique(result)); } /** * Returns a {@link Map} object as key a selector and as value the list of ancestor elements * matching this selectors, beginning at the first matched element and progressing up through the * DOM. This method allows retrieving the list of ancestors matching many selectors by traversing * the DOM only one time. * * @return */ public JsNamedArray<NodeList<Element>> closest(String[] selectors) { return closest(selectors, null); } /** * Returns a {@link Map} object as key a selector and as value the list of ancestor elements * matching this selectors, beginning at the first matched element and progressing up through the * DOM until reach the <code>context</code> node.. This method allows retrieving the list of * ancestors matching many selectors by traversing the DOM only one time. * * @return */ public JsNamedArray<NodeList<Element>> closest(String[] selectors, Node context) { JsNamedArray<NodeList<Element>> results = JsNamedArray.create(); if (context == null) { context = currentContext; } Element first = get(0); if (first != null && selectors != null && selectors.length > 0) { JsNamedArray<GQuery> matches = JsNamedArray.create(); for (String selector : selectors) { if (!matches.exists(selector)) { matches.put(selector, posRegex.test(selector) ? $(selector, context) : null); } } Element current = first; while (current != null && current.getOwnerDocument() != null && current != context) { // for each selector, check if the current element match it. for (String selector : matches.keys()) { GQuery pos = matches.get(selector); boolean match = pos != null ? pos.index(current) > -1 : $(current).is(selector); if (match) { JsNodeArray elementsMatchingSelector = results.get(selector).cast(); if (elementsMatchingSelector == null) { elementsMatchingSelector = JsNodeArray.create(); results.put(selector, elementsMatchingSelector); } elementsMatchingSelector.addNode(current); } } current = current.getParentElement(); } } return results; } /** * Filter the set of elements to those that contain the specified text. */ public GQuery contains(String text) { JsNodeArray array = JsNodeArray.create(); for (Element e : elements) { if ($(e).text().contains(text)) { array.addNode(e); } } return $(array); } /** * Find all the child nodes inside the matched elements (including text nodes), or the content * document, if the element is an iframe. */ public GQuery contents() { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { if (JsUtils.isWindow(e) || "iframe".equalsIgnoreCase(e.getTagName())) { result.addNode(getStyleImpl().getContentDocument(e)); } else { NodeList<Node> children = e.getChildNodes(); for (int i = 0, l = children.getLength(); i < l; i++) { result.addNode(children.getItem(i)); } } } return new GQuery(unique(result)); } public LazyGQuery<?> createLazy() { return GWT.create(GQuery.class); } /** * Set CSS a single style property on every matched element using type-safe enumerations. * * The best way to use this method (i.e. to generate a CssSetter) is to take the desired css * property defined in {@link CSS} class and call the {@link TakesCssValue#with(HasCssName)} * method on it. * * ex : * * <pre class="code"> * $("#myDiv").css(CSS.TOP.with(Length.cm(15))); * $("#myDiv").css(CSS.BACKGROUND.with(RGBColor.SILVER, ImageValue.url(""), * BackgroundRepeat.NO_REPEAT, BackgroundAttachment.FIXED, * BackgroundPosition.CENTER)); * $("#myDiv").css(CSS.BACKGROUND_ATTACHMENT.with(BackgroundAttachment.FIXED)); * * </pre> * */ public GQuery css(CssSetter... cssSetter) { for (Element e : elements) { for (CssSetter s : cssSetter) { s.applyCss(e); } } return this; } /** * Return a style property on the first matched element using type-safe enumerations. * * Ex : $("#myId").css(CSS.BACKGROUND_COLOR); */ public String css(HasCssValue property) { return css(property, true); } /** * Return a style property on the first matched element using type-safe enumerations. * * The parameter force has a special meaning here: - When force is false, returns the value of the * css property defined in the style attribute of the element. - Otherwise it returns the real * computed value. * * For instance if you define 'display=none' not in the element style but in the css stylesheet, * it returns an empty string unless you pass the parameter force=true. * * Ex : $("#myId").css(CSS.WIDTH, true); */ public String css(HasCssValue property, boolean force) { return css(property.getCssName(), force); } /** * Set a key/value object as style properties to all matched elements. This serves as the best way * to set a large number of style properties on all matched elements. You can use either js maps * or pure css syntax. * * Example: * * <pre class="code"> * $(".item").css(Properties.create("color: 'red', background:'blue'")) * $(".item").css(Properties.create("color: red; background: blue;")) * </pre> */ public GQuery css(Properties properties) { for (String property : properties.keys()) { css(property, properties.getStr(property)); } return this; } /** * Return a style property on the first matched element. */ public String css(String name) { return css(name, true); } /** * Return a style property on the first matched element. * * The parameter force has a special meaning here: * <ul> * <li>When force is false, returns the value of the css property defined in the style attribute * of the element. * <li>Otherwise it returns the real computed value. * </ul> * * For instance if you don't define 'display=none'in the element style but in the css stylesheet, * it returns an empty string unless you pass the parameter force=true. */ public String css(String name, boolean force) { return isEmpty() ? "" : getStyleImpl().curCSS(get(0), name, force); } /** * Set a single style property to a value, on all matched elements. * */ public GQuery css(String prop, String val) { for (Element e : elements) { getStyleImpl().setStyleProperty(e, prop, val); } return this; } /** * Set CSS a single style property on every matched element using type-safe enumerations. This * method allows you to set manually the value or set <i>inherit</i> value * * ex : * * <pre class="code"> * $(#myId).css(CSS.TEXT_DECORATION, CSS.INHERIT); * </pre> */ public GQuery css(TakesCssValue<?> cssProperty, String value) { return css(cssProperty.getCssName(), value); } /** * Returns the numeric value of a css property. */ public double cur(String prop) { return cur(prop, false); } /** * Returns the numeric value of a css property. * * The parameter force has a special meaning: - When force is false, returns the value of the css * property defined in the set of style attributes. - When true returns the real computed value. */ public double cur(String prop, boolean force) { return isEmpty() ? 0 : getStyleImpl().cur(get(0), prop, force); } /** * Return the value at the named data store for the first element in the set of matched * elements. */ @SuppressWarnings("unchecked") public <T> T data(String name) { return isEmpty() ? null : (T) data(get(0), name, null); } /** * Return the value at the named data store for the first element in the set of matched * elements, as set by data(name, value), with desired return type. * * @param clz return type class literal */ public <T> T data(String name, Class<? extends T> clz) { return isEmpty() ? null : data(get(0), name, null, clz); } /** * Store arbitrary data associated with the matched elements in the named data store. */ public GQuery data(String name, Object value) { for (Element e : elements()) { data(e, name, value); } return this; } /** * Bind a set of functions to the dblclick event of each matched element. Or trigger the event if * no functions are provided. */ public GQuery dblclick(Function... f) { return bindOrFire(Event.ONDBLCLICK, null, f); } /** * Insert a delay (in ms) in the GQuery queue, and optionally execute one o more functions if * provided when the delay finishes. It uses the effects queue namespace, so you can stack any of * the methods in the effects plugin. * * Example: * * <pre class="code"> * $("#foo").slideUp(300) * .delay(800) * .fadeIn(400); * </pre> * * When this statement is executed, the element slides up for 300 milliseconds and then pauses for * 800 milliseconds before fading in for 400 milliseconds. Aditionally after those 800 * milliseconds the element color is set to red. * * NOTE that this methods affects only methods which uses the queue like effects. So the following * example is wrong: * * <pre> * $("#foo").css(CSS.COLOR.with(RGBColor.RED)).delay(800).css(CSS.COLOR.with(RGBColor.BLACK)); * </pre> * * The code above will not insert a delay of 800 ms between the css() calls ! For this kind of * behavior, you should execute these methods puting them in inline functions passed as argument * to the delay() method, or adding them to the queue. * * <pre> * $("#foo").css(CSS.COLOR.with(RGBColor.RED)).delay(800, lazy().css(CSS.COLOR.with(RGBColor.BLACK)).done()); * $("#foo").css(CSS.COLOR.with(RGBColor.RED)).delay(800).queue(lazy().css(CSS.COLOR.with(RGBColor.BLACK)).dequeue().done()); * </pre> */ public GQuery delay(int milliseconds, Function... f) { return as(Queue).delay(milliseconds, f); } /** * Insert a delay (in ms) in the queue identified by the <code>queueName</code> parameter, and * optionally execute one o more functions if provided when the delay finishes. * * If <code>queueName</code> is null or equats to 'fx', the delay will be inserted to the Effects * queue. * * Example : * * <pre class="code"> * $("#foo").queue("colorQueue", lazy().css(CSS.COLOR.with(RGBColor.RED)).dequeue("colorQueue").done()) * .delay(800, "colorQueue") * .queue("colorQueue", lazy().css(CSS.COLOR.with(RGBColor.BLACK)).dequeue("colorQueue").done()); * </pre> * * When this statement is executed, the text color of the element changes to red and then wait for * 800 milliseconds before changes the text color to black. * */ public GQuery delay(int milliseconds, String queueName, Function... f) { return as(Queue).delay(milliseconds, queueName, f); } /** * Attach <code>handlers</code> to one or more events for all elements that match the * <code>selector</code>, now or in the future, based on a specific set of root elements. * * Example: * * <pre> * $("table").delegate("td", Event.ONCLICK, new Function(){ * public void f(Element e){ * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED)); * } * }); * </pre> * * This code above add an handler on click event on all cell (the existing oneand the future cell) * of all table. This code is equivalent to : * * <pre> * $("table").each(new Function(){ * public void f(Element table){ * $("td", table).live(Event.ONCLICK, new Function(){ * public void f(Element e){ * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED)); * } * } * }); * * </pre> * * You can attach the handlers to many events by using the '|' operator ex: * * <pre> * $("div.main").delegate(".subMain", Event.ONCLICK | Event.ONDBLCLICK, new Function(){...}); * </pre> * @deprecated use {@link #on(String, String, Function...)} */ public GQuery delegate(String selector, int eventbits, Function... handlers) { return delegate(selector, eventbits, null, handlers); } /** * Attach <code>handlers</code> to one or more events for all elements that match the * <code>selector</code>, now or in the future, based on a specific set of root elements. The * <code>data</code> parameter allows us to pass data to the handler. * * Example: * * <pre> * $("table").delegate("td", "click", new Function(){ * public void f(Element e){ * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED)); * } * }); * </pre> * * This code above add an handler on click event on all cell (the existing oneand the future cell) * of all table. This code is equivalent to : * * <pre> * $("table").each(new Function(){ * public void f(Element table){ * $("td", table).live("click", new Function(){ * public void f(Element e){ * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED)); * } * } * }); * * </pre> * * You can pass attach the handlers to many events by using the '|' operator ex: * * <pre> * $("div.main").delegate(".subMain", Event.ONCLICK | Event.ONDBLCLICK, new Function(){...}); * </pre> * @deprecated use {@link #on(String, String, Object, Function...)} */ public GQuery delegate(String selector, int eventbits, Object data, Function... handlers) { for (Element e : elements) { $(selector, e).live(eventbits, data, handlers); } return this; } /** * Attach <code>handlers</code> to one or more events for all elements that match the * <code>selector</code>, now or in the future, based on a specific set of root elements. * * Example: * * <pre> * $("table").delegate("td", "click", new Function(){ * public void f(Element e){ * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED)); * } * }); * </pre> * * This code above add an handler on click event on all cell (the existing oneand the future cell) * of all table. This code is equivalent to : * * <pre> * $("table").each(new Function(){ * public void f(Element table){ * $("td", table).live("click", new Function(){ * public void f(Element e){ * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED)); * } * } * }); * * </pre> * * You can pass attach the handlers to many events by specifying a String with espaced event type. * ex: * * <pre> * $("div.main").delegate(".subMain", "click dblclick", new Function(){...}); * </pre> * * </pre> * @deprecated use {@link #on(String, String, Function...)} */ public GQuery delegate(String selector, String eventType, Function... handlers) { return delegate(selector, eventType, null, handlers); } /** * Attach <code>handlers</code> to one or more events for all elements that match the * <code>selector</code>, now or in the future, based on a specific set of root elements. * * Example: * * <pre> * $("table").delegate("td", "click", new Function(){ * public void f(Element e){ * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED)); * } * }); * </pre> * * This code above add an handler on click event on all cell (the existing oneand the future cell) * of all table. This code is equivalent to : * * <pre> * $("table").each(new Function(){ * public void f(Element table){ * $("td", table).live("click", new Function(){ * public void f(Element e){ * $(e).css(CSS.BACKGROUND_COLOR.with(RGBColor.RED)); * } * } * }); * * You can pass attach the handlers to many events by specifying a String with espaced event type. * ex: * * <pre> * $("div.main").delegate(".subMain", "click dblclick", new Function(){...}); * </pre> * * </pre> * @deprecated use {@link #on(String, String, Object, Function...)} */ public GQuery delegate(String selector, String eventType, Object data, Function... handlers) { for (Element e : elements) { $(selector, e).live(eventType, data, handlers); } return this; } /** * Execute the next function on the Effects queue for the matched elements. This method is usefull * to tell when a function you add in the Effects queue is ended and so the next function in the * queue can start. * * Note: you should be sure to call dequeue() in all functions of a queue chain, otherwise the * queue execution will be stopped. */ public GQuery dequeue() { return as(Queue).dequeue(); } /** * Execute the next function on the queue named as queueName for the matched elements. This method * is usefull to tell when a function you add in the Effects queue is ended and so the next * function in the queue can start. */ public GQuery dequeue(String queueName) { return as(Queue).dequeue(queueName); } /** * Detach all matched elements from the DOM. This method is the same than {@link #remove()} method * except all data and event handlers are not remove from the element. This method is useful when * removed elements are to be reinserted into the DOM at a later time. */ public GQuery detach() { return remove(null, false); } /** * Detach from the DOM all matched elements filtered by the <code>filter</code>.. This method is * the same than {@link #remove(String)} method except all data and event handlers are not remove * from the element. This method is useful when removed elements are to be reinserted into the DOM * at a later time. */ public GQuery detach(String filter) { return remove(filter, false); } /** * Remove all event handlers previously attached using {@link #live(String, Function)}. In order * for this method to function correctly, the selector used with it must match exactly the * selector initially used with {@link #live(String, Function)}. * * @deprecated use {@link #off(String, String)} instead */ public GQuery die() { return die(0); } /** * Remove an event handlers previously attached using {@link #live(int, Function)} In order for * this method to function correctly, the selector used with it must match exactly the selector * initially used with {@link #live(int, Function)}. * @deprecated use {@link #off(String)} */ public GQuery die(int eventbits) { return as(Events).die(eventbits); } /** * Remove an event handlers previously attached using {@link #live(String, Function)} In order for * this method to function correctly, the selector used with it must match exactly the selector * initially used with {@link #live(String, Function)}. */ public GQuery die(String eventName) { return as(Events).die(eventName); } private GQuery domManip(GQuery g, DomMan type, Element... elms) { JsNodeArray newNodes = JsNodeArray.create(); if (elms.length == 0) { elms = elements; } for (int i = 0, l = elms.length; i < l; i++) { Element e = elms[i]; if (e.getNodeType() == Node.DOCUMENT_NODE) { e = e.<Document> cast().getBody(); } for (int j = 0, size = g.size(); j < size; j++) { // Widget w = getAssociatedWidget(g.get(j)); // GqUi.detachWidget(w); Node n = g.get(j); // If an element selected is inserted elsewhere, it will be moved into the target (not // cloned). // If there is more than one target element, however, cloned copies of the inserted element // will be created for each target after the first if (i > 0) { n = n.cloneNode(true); } switch (type) { case PREPEND: newNodes.addNode(e.insertBefore(n, e.getFirstChild())); break; case APPEND: newNodes.addNode(e.appendChild(n)); break; case AFTER: newNodes.addNode(e.getParentNode().insertBefore(n, e.getNextSibling())); break; case BEFORE: newNodes.addNode(e.getParentNode().insertBefore(n, e)); break; } EventsListener.rebind(n.<Element> cast()); // GqUi.attachWidget(w); } } // TODO: newNodes.size() > g.size() makes testRebind fail if (newNodes.size() >= g.size()) { g.setArray(newNodes); } return this; } // TODO: this should be handled by the other domManip method private GQuery domManip(String htmlString, DomMan type) { JsMap<Document, GQuery> cache = JsMap.createObject().cast(); for (Element e : elements) { Document d = JsUtils.getOwnerDocument(e); GQuery g = cache.get(d); if (g == null) { g = cleanHtmlString(htmlString, d); cache.put(d, g); } domManip(g.clone(), type, e); } return this; } /** * Run one or more Functions over each element of the GQuery. You have to override one of these * funcions: public void f(Element e) public String f(Element e, int i) */ public GQuery each(Function... f) { if (f != null) { for (Function f1 : f) { if (f1 != null) { int i = 0; for (Element e : elements) { f1.f(e.<com.google.gwt.dom.client.Element> cast(), i++); } } } } return this; } /** * Returns the working set of nodes as a Java array. <b>Do NOT</b> attempt to modify this array, * e.g. assign to its elements, or call Arrays.sort() */ public Element[] elements() { return elements; } /** * Remove all child nodes from the set of matched elements. In the case of a document element, it * removes all the content You should call this method whenever you create a new iframe and you * want to add dynamic content to it. */ public GQuery empty() { for (Element e : elements) { if (e.getNodeType() == Element.DOCUMENT_NODE) { getStyleImpl().emptyDocument(e.<Document> cast()); } else { Node c = e.getFirstChild(); while (c != null) { removeData(c.<Element> cast(), null); WidgetsUtils.detachWidget(getAssociatedWidget(e)); EventsListener.clean(c.<Element> cast()); e.removeChild(c); c = e.getFirstChild(); } } } return this; } /** * Revert the most recent 'destructive' operation, changing the set of matched elements to its * previous state (right before the destructive operation). */ public GQuery end() { return previousObject != null ? previousObject : new GQuery(); } /** * Reduce GQuery to element in the specified position. This method accept negative index. A * negative index is counted from the end of the matched set: * * Example: * * <pre> * $("div").eq(0) will reduce the matched set to the first matched div * $("div").eq(1) will reduce the matched set to the second matched div * * $("div").eq(-1) will reduce the matched set to the last matched div * $("div").eq(-2) will reduce the matched set to the second-to-last matched div * ... * </pre> */ public GQuery eq(int pos) { return $(get(pos)); } /** * Bind a set of functions to the error event of each matched element. Or trigger the event if no * functions are provided. */ public GQuery error(Function... f) { return bindOrFire(Event.ONERROR, null, f); } /** * Fade in all matched elements by adjusting their opacity. The effect will take 1000 milliseconds * to complete */ public GQuery fadeIn(Function... f) { return as(Effects).fadeIn(f); } /** * Fade in all matched elements by adjusting their opacity. */ public GQuery fadeIn(int millisecs, Function... f) { return as(Effects).fadeIn(millisecs, f); } /** * Fade the opacity of all matched elements to a specified opacity and firing * an optional callback after completion. Only the opacity is adjusted for * this animation, meaning that all of the matched elements should already * have some form of height and width associated with them. */ public GQuery fadeTo(int millisecs, double opacity, Function... f) { return as(Effects).fadeTo(millisecs, opacity, f); } /** * Fade the opacity of all matched elements to a specified opacity and firing * an optional callback after completion. Only the opacity is adjusted for * this animation, meaning that all of the matched elements should already * have some form of height and width associated with them. */ public GQuery fadeTo(double opacity, Function... f) { return as(Effects).fadeTo(opacity, f); } /** * Fade out all matched elements by adjusting their opacity. The effect will take 1000 * milliseconds to complete */ public GQuery fadeOut(Function... f) { return as(Effects).fadeOut(f); } /** * Fade out all matched elements by adjusting their opacity. */ public GQuery fadeOut(int millisecs, Function... f) { return as(Effects).fadeOut(millisecs, f); } /** * Toggle the visibility of all matched elements by adjusting their opacity and firing an optional * callback after completion. Only the opacity is adjusted for this animation, meaning that all of * the matched elements should already have some form of height and width associated with them. */ public Effects fadeToggle(int millisecs, Function... f) { return as(Effects).fadeToggle(millisecs, f); } /** * Removes all elements from the set of matched elements that do not match the specified function. * The function is called with a context equal to the current element. If the function returns * false, then the element is removed - anything else and the element is kept. */ public GQuery filter(Predicate filterFn) { JsNodeArray result = getSelectorEngine().filter(nodeList, filterFn).cast(); return pushStack(result, "filter", currentSelector); } /** * Removes all elements from the set of matched elements that do not pass the specified css * expression. This method is used to narrow down the results of a search. * By default it works for either detached and attached elements unless * {@link SelectorEngine#filterDetached} is set to false. */ public GQuery filter(String... filters) { String selector = join(", ", filters); JsNodeArray result = getSelectorEngine().filter(nodeList, selector).cast(); return pushStack(result, "filter", selector); } /** * Removes all elements from the set of matched elements that do not pass the specified css * expression. This method is used to narrow down the results of a search. * Setting filterDetached parameter to true, means that we should consider detached elements * as well which implies some performance penalty. */ public GQuery filter(boolean filterDetached, String... filters) { String selector = join(", ", filters); JsNodeArray result = getSelectorEngine().filter(nodeList, selector, filterDetached).cast(); return pushStack(result, "filter", selector); } /** * Removes all elements from the set of matched elements that do not pass the specified css * expression. This method is used to narrow down the results of a search. * Setting considerDetached parameter to true, means that we should consider detached elements * as well which implies some performance penalties. */ public GQuery filter(boolean filterDetached, String selector) { if (selector.isEmpty()) { return this; } JsNodeArray result = getSelectorEngine().filter(nodeList, selector, filterDetached).cast(); return pushStack(result, "filter", selector); } /** * Searches for all elements that match the specified css expression. This method is a good way to * find additional descendant elements with which to process. * * Provide a comma-separated list of expressions to apply multiple filters at once. */ public GQuery find(String... filters) { JsNodeArray array = JsNodeArray.create(); for (String selector : filters) { for (Element e : elements) { for (Element c : $(selector, e).elements) { array.addNode(c); } } } return pushStack(unique(array), "find", filters[0]); } /** * Reduce the set of matched elements to the first in the set. */ public GQuery first() { return eq(0); } /** * Bind a set of functions to the focus event of each matched element. Or trigger the event and * move the input focus to the first element if no functions are provided. */ public GQuery focus(Function... f) { bindOrFire(Event.ONFOCUS, null, f); if (!isEmpty() && f.length == 0) { get(0).focus(); } return this; } /** * Return all elements matched in the GQuery as a NodeList. @see #elements() for a method which * returns them as an immutable Java array. */ public NodeList<Element> get() { return nodeList; } /** * Return the ith element matched. This method accept negative index. A negative index is counted * from the end of the matched set. * * Example: * * <pre> * $("div").get(0) will return the first matched div * $("div").get(1) will return the second matched div * * $("div").get(-1) will return the last matched div * $("div").get(-2) will return the secont-to-last matched div * ... * </pre> */ public Element get(int i) { int l = elements.length; if (i >= 0 && i < l) { return elements[i]; } if (i < 0 && l + i >= 0) { return elements[l + i]; } return null; } public Node getContext() { return currentContext; } /** * Return the previous set of matched elements prior to the last destructive operation (e.g. * query) */ public GQuery getPreviousObject() { return end(); } private native Element getPreviousSiblingElement(Element elem) /*-{ var sib = elem.previousSibling; while (sib && sib.nodeType != 1) sib = sib.previousSibling; return sib; }-*/; /** * Return the selector representing the current set of matched elements. */ public String getSelector() { return currentSelector; } /** * Returns true any of the specified classes are present on any of the matched Reduce the set of * matched elements to all elements after a given position. The position of the element in the set * of matched elements starts at 0 and goes to length - 1. */ public GQuery gt(int pos) { return slice(pos + 1, -1); } /** * Reduce the set of matched elements to those that have a descendant that matches the Element. */ public GQuery has(final Element elem) { return filter(new Predicate() { public boolean f(Element e, int index) { return contains(e, elem); } }); } /** * Reduce the set of matched elements to those that have a descendant that matches the selector. */ public GQuery has(final String selector) { return filter(new Predicate() { public boolean f(Element e, int index) { return !$(selector, e).isEmpty(); } }); } /** * Returns true any of the specified classes are present on any of the matched elements. */ public boolean hasClass(String... classes) { for (Element e : elements) { for (String clz : classes) { if (hasClass(e, clz)) { return true; } } } return false; } /** * Get the current computed, pixel, height of the first matched element. It does not include * margin, padding nor border. */ public int height() { return (int) cur("height", true); } /** * Set the height of every element in the matched set. */ public GQuery height(int height) { for (Element e : elements) { e.getStyle().setPropertyPx("height", height); } return this; } /** * Set the height style property of every matched element. It's useful for using 'percent' or 'em' * units Example: $(".a").height("100%") */ public GQuery height(String height) { return css("height", height); } /** * Make invisible all matched elements. */ public GQuery hide() { for (Element e : elements) { String currentDisplay = getStyleImpl().curCSS(e, "display", false); Object old = data(e, OLD_DISPLAY, null); if (old == null && currentDisplay.length() != 0 && !"none".equals(currentDisplay)) { data(e, OLD_DISPLAY, currentDisplay); } } // Set the display value in a separate for loop to avoid constant reflow // Reflows is very bad in performance point of view for (Element e : elements) { e.getStyle().setDisplay(Display.NONE); } return this; } /** * Bind a function to the mouseover event of each matched element. A method for simulating * hovering (moving the mouse on, and off, an object). This is a custom method which provides an * 'in' to a frequent task. Whenever the mouse cursor is moved over a matched element, the first * specified function is fired. Whenever the mouse moves off of the element, the second specified * function fires. * * Since GQuery 1.4.0, this method binds handlers for both mouseenter and mouseleave events. */ public GQuery hover(Function fover, Function fout) { return bind("mouseenter", fover).bind("mouseleave", fout); } /** * Get the innerHTML of the first matched element. */ public String html() { return isEmpty() ? "" : get(0).getInnerHTML(); } /** * Set the innerHTML of every matched element. */ public GQuery html(String html) { for (Element e : elements) { if (e.getNodeType() == Node.DOCUMENT_NODE) { e = e.<Document> cast().getBody(); } e.setInnerHTML(html); } return this; } /** * Set the innerHTML of every matched element. */ public GQuery html(SafeHtml safeHtml) { return html(safeHtml.asString()); } /** * Get the id of the first matched element. */ public String id() { return attr("id"); } /** * Set the id of the first matched element. */ public GQuery id(String id) { return eq(0).attr("id", id); } /** * Find the index of the specified Element. */ public int index(Element element) { int i = 0; for (Element e : elements) { if (e == element) { return i; } i++; } return -1; } /** * Return the position of the first matched element in relation with its sibblings. */ public int index() { return prevAll().size(); } /** * Returns the inner height of the first matched element, including padding but not the vertical * scrollbar height, border, or margin. */ public int innerHeight() { return (int) cur("clientHeight", true); } /** * Returns the inner width of the first matched element, including padding but not the vertical * scrollbar width, border, or margin. */ public int innerWidth() { return (int) cur("clientWidth", true); } /** * Insert all of the matched elements after another, specified, set of elements. */ public GQuery insertAfter(Element elem) { return insertAfter($(elem)); } /** * Insert all of the matched elements after another, specified, set of elements. */ public GQuery insertAfter(GQuery query) { for (Element e : elements) { query.after(e); } return this; } /** * Insert all of the matched elements after another, specified, set of elements. */ public GQuery insertAfter(String selector) { return insertAfter($(selector)); } /** * Insert all of the matched elements before another, specified, set of elements. * * The elements must already be inserted into the document (you can't insert an element after * another if it's not in the page). */ public GQuery insertBefore(Element item) { return insertBefore($(item)); } /** * Insert all of the matched elements before another, specified, set of elements. * * The elements must already be inserted into the document (you can't insert an element after * another if it's not in the page). */ public GQuery insertBefore(GQuery query) { for (Element e : elements) { query.before(e); } return this; } /** * Insert all of the matched elements before another, specified, set of elements. * * The elements must already be inserted into the document (you can't insert an element after * another if it's not in the page). */ public GQuery insertBefore(String selector) { return insertBefore($(selector)); } /** * Checks the current selection against an expression and returns true, if at least one element of * the selection fits the given expression. Does return false, if no element fits or the * expression is not valid. */ public boolean is(String... filters) { return !filter(filters).isEmpty(); } /** * Returns true if the number of matched elements is 0. */ public boolean isEmpty() { return size() == 0; } /** * Return true if the first element is visible.isVisible. */ public boolean isVisible() { return isEmpty() ? false : getStyleImpl().isVisible(get(0)); } /** * Bind a set of functions to the keydown event of each matched element. Or trigger the event if * no functions are provided. */ public GQuery keydown(Function... f) { return bindOrFire(Event.ONKEYDOWN, null, f); } /** * Trigger a keydown event passing the key pushed. */ public GQuery keydown(int key) { return trigger(Event.ONKEYDOWN, key); } /** * Bind a set of functions to the keypress event of each matched element. Or trigger the event if * no functions are provided. */ public GQuery keypress(Function... f) { return bindOrFire(Event.ONKEYPRESS, null, f); } /** * Trigger a keypress event passing the key pushed. */ public GQuery keypress(int key) { return trigger(Event.ONKEYPRESS, key); } /** * Bind a set of functions to the keyup event of each matched element. Or trigger the event if no * functions are provided. */ public GQuery keyup(Function... f) { return bindOrFire(Event.ONKEYUP, null, f); } /** * Trigger a keyup event passing the key pushed. */ public GQuery keyup(int key) { return trigger(Event.ONKEYUP, key); } /** * Reduce the set of matched elements to the final one in the set. */ public GQuery last() { return eq(size() - 1); } /** * Returns the computed left position of the first element matched. */ public int left() { return (int) cur("left", true); } /** * Returns the number of elements currently matched. The size function will return the same value. */ public int length() { return size(); } /** * Attach a handler for this event to all elements which match the current selector, now and in * the future. * @deprecated use {@link #on(String, Function...)} */ public GQuery live(int eventbits, Function... funcs) { return as(Events).live(eventbits, null, funcs); } /** * Attach a handler for this event to all elements which match the current selector, now and in * the future. * @deprecated use {@link #on(String, Object, Function...)} */ public GQuery live(int eventbits, Object data, Function... funcs) { return as(Events).live(eventbits, data, funcs); } /** * <p> * Attach a handler for this event to all elements which match the current selector, now and in * the future. * <p> * Ex : * * <pre> * $(".clickable").live("click", new Function(){ * public void f(Element e){ * $(e).css(CSS.COLOR.with(RGBColor.RED)); * } * }); * </pre> * * With this code, all elements with class "clickable" present in the DOM or added to the DOM in * the future will be clickable. The text color will be changed to red when they will be clicked. * So if after in the code, you add another element : * * <pre> * $("body").append("<div class='clickable'>Click me and I will be red</div>"); * </pre> * * The click on this new element will also trigger the handler. * </p> * <p> * In the same way, if you add "clickable" class on some existing element, these elements will be * clickable also. * </p> * <p> * <h3>important remarks</h3> * <ul> * <li> * The live method should be always called after a selector</li> * <li> * Live events are bound to the context of the {@link GQuery} object : * * <pre> * $(".clickable", myElement).live("click", new Function(){ * public void f(Element e){ * $(e).css(CSS.COLOR.with(RGBColor.RED)); * } * }); * </pre> * The {@link Function} will be called only on elements having the class "clickable" and being * descendant of myElement.</li> * </ul> * </p> * @deprecated use {@link #on(String, Function...)} */ public GQuery live(String eventName, Function... funcs) { return as(Events).live(eventName, null, funcs); } /** * <p> * Attach a handler for this event to all elements which match the current selector, now and in * the future. The <code>data</code> parameter allows us to pass data to the handler. * <p> * Ex : * * <pre> * $(".clickable").live("click", new Function(){ * public void f(Element e){ * $(e).css(CSS.COLOR.with(RGBColor.RED)); * } * }); * </pre> * * With this code, all elements with class "clickable" present in the DOM or added to the DOM in * the future will be clickable. The text color will be changed to red when they will be clicked. * So if after in the code, you add another element : * * <pre> * $("body").append("<div class='clickable'>Click me and I will be red</div>"); * </pre> * * The click on this new element will also trigger the handler. * </p> * <p> * In the same way, if you add "clickable" class on some existing element, these elements will be * clickable also. * </p> * <p> * <h3>important remarks</h3> * <ul> * <li> * The live method should be always called after a selector</li> * <li> * Live events are bound to the context of the {@link GQuery} object : * * <pre> * $(".clickable", myElement).live("click", new Function(){ * public void f(Element e){ * $(e).css(CSS.COLOR.with(RGBColor.RED)); * } * }); * </pre> * The {@link Function} will be called only on elements having the class "clickable" and being * descendant of myElement.</li> * </ul> * </p> * @deprecated use {@link #on(String, Object, Function...)} */ public GQuery live(String eventName, Object data, Function... funcs) { return as(Events).live(eventName, data, funcs); } /** * Bind a function to the load event of each matched element. */ @Deprecated public GQuery load(Function f) { return bind(Event.ONLOAD, f); } /** * Load data from the server and place the returned HTML into the matched element. * * The url allows us to specify a portion of the remote document to be inserted. This is achieved * with a special syntax for the url parameter. If one or more space characters are included in * the string, the portion of the string following the first space is assumed to be a GQuery * selector that determines the content to be loaded. * */ public GQuery load(String url) { return load(url, null, null); } /** * Load data from the server and place the returned HTML into the matched element. * * The url allows us to specify a portion of the remote document to be inserted. This is achieved * with a special syntax for the url parameter. If one or more space characters are included in * the string, the portion of the string following the first space is assumed to be a GQuery * selector that determines the content to be loaded. * */ public GQuery load(String url, IsProperties data, final Function onSuccess) { return as(Ajax.Ajax).load(url, data, onSuccess); } /** * Reduce the set of matched elements to all elements before a given position. The position of the * element in the set of matched elements starts at 0 and goes to length - 1. */ public GQuery lt(int pos) { return slice(0, pos); } /** * Pass each element in the current matched set through a function, producing a new array * containing the return values. When the call to the function returns a null it is not added to * the array. */ public <W> List<W> map(Function f) { ArrayList<W> ret = new ArrayList<>(); int i = 0; for (Element e : elements) { @SuppressWarnings("unchecked") W o = (W) f.f(e.<com.google.gwt.dom.client.Element> cast(), i++); if (o != null) { ret.add(o); } } return ret; } /** * Bind a set of functions to the mousedown event of each matched element. Or trigger the event if * no functions are provided. */ public GQuery mousedown(Function... f) { return bindOrFire(Event.ONMOUSEDOWN, null, f); } /** * Bind an event handler to be fired when the mouse enter an element, or trigger that handler on * an element if no functions are provided. * * The mouseenter event differs from mouseover in the way it handles event bubbling. When * mouseover is used on an element having inner element(s), then when the mouse pointer moves hover * of the Inner element, the handler would be triggered. This is usually undesirable behavior. The * mouseenter event, on the other hand, only triggers its handler when the mouse enters the * element it is bound to, not a descendant. */ public GQuery mouseenter(Function... f) { return as(Events).mouseenter(f); } /** * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on * an element if no functions are provided. * * The mouseleave event differs from mouseout in the way it handles event bubbling. When * mouseout is used on an element having inner element(s), then when the mouse pointer moves out * of the Inner element, the handler would be triggered. This is usually undesirable behavior. The * mouseleave event, on the other hand, only triggers its handler when the mouse leaves the * element it is bound to, not a descendant. */ public GQuery mouseleave(Function... f) { return as(Events).mouseleave(f); } /** * Bind a set of functions to the mousemove event of each matched element. Or trigger the event if * no functions are provided. */ public GQuery mousemove(Function... f) { return bindOrFire(Event.ONMOUSEMOVE, null, f); } /** * Bind a set of functions to the mouseout event of each matched element. Or trigger the event if * no functions are provided. */ public GQuery mouseout(Function... f) { return bindOrFire(Event.ONMOUSEOUT, null, f); } /** * Bind a set of functions to the mouseover event of each matched element. Or trigger the event if * no functions are provided. */ public GQuery mouseover(Function... f) { return bindOrFire(Event.ONMOUSEOVER, null, f); } /** * Bind a set of functions to the mouseup event of each matched element. Or trigger the event if * no functions are provided. */ public GQuery mouseup(Function... f) { return bindOrFire(Event.ONMOUSEUP, null, f); } /** * Get a set of elements containing the unique next siblings of each of the given set of elements. * next only returns the very next sibling for each element, not all next siblings see {#nextAll}. */ public GQuery next() { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { Element next = e.getNextSiblingElement(); if (next != null) { result.addNode(next); } } return pushStack(unique(result), "next", getSelector()); } /** * Get a set of elements containing the unique next siblings of each of the given set of elements * filtered by 1 or more selectors. next only returns the very next sibling for each element, not * all next siblings see {#nextAll}. */ public GQuery next(String... selectors) { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { Element next = e.getNextSiblingElement(); if (next != null) { result.addNode(next); } } return pushStack(result, "next", selectors[0]).filter(selectors); } /** * Get all following siblings of each element in the set of matched elements. */ public GQuery nextAll() { return nextAll(null); } /** * Get all following siblings of each element in the set of matched elements, filtered by a * selector. */ public GQuery nextAll(String filter) { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { allNextSiblingElements(e.getNextSiblingElement(), result, null, null, filter); } return pushStack(unique(result), "nextAll", getSelector()); } /** * Get all following siblings of each element up to but not including the element matched by the * selector. * * @param selector * @return */ public GQuery nextUntil(String selector) { return nextUntil($(selector), null); } /** * Get all following siblings of each element up to but not including the element matched by the * selector, filtered by a selector. * * @param selector * @return */ public GQuery nextUntil(String selector, String filter) { return nextUntil($(selector), filter); } /** * Get all following siblings of each element up to but not including the element matched by the * DOM node. * * @param selector * @return */ public GQuery nextUntil(Element until) { return nextUntil($(until), null); } /** * Get all following siblings of each element up to but not including the element matched by the * DOM node, filtered by a selector. * * @return */ public GQuery nextUntil(Element until, String filter) { return nextUntil($(until), filter); } /** * Get all following siblings of each element up to but not including the element matched by the * GQuery object. * * @return */ public GQuery nextUntil(GQuery until) { return nextUntil(until, null); } /** * Get all following siblings of each element up to but not including the element matched by the * GQuery object, filtered by a selector. * * @return */ public GQuery nextUntil(GQuery until, String filter) { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { allNextSiblingElements(e.getNextSiblingElement(), result, null, until, filter); } return pushStack(unique(result), "nextUntil", getSelector()); } /** * Removes the specified Element from the set of matched elements. This method is used to remove a * single Element from a jQuery object. */ public GQuery not(Element elem) { JsNodeArray array = JsNodeArray.create(); for (Element e : elements) { if (e != elem) { array.addNode(e); } } return $(array); } /** * Removes any elements inside the passed set of elements from the set of matched elements. */ public GQuery not(GQuery gq) { GQuery ret = this; for (Element e : gq.elements) { ret = ret.not(e); } return ret; } /** * Removes elements matching the specified expression from the set of matched elements. */ public GQuery not(String... filters) { GQuery ret = this; for (String f : filters) { ret = ret.not($(f)); } return ret; } /** * Get the current offset of the first matched element, in pixels, relative to the document. The * returned object contains two integer properties, top and left. The method works only with * visible elements. */ public Offset offset() { Element e = get(0); return e == null ? new Offset(0, 0) : new Offset(e.getAbsoluteLeft(), e.getAbsoluteTop()); } /** * Set the current coordinates of every element in the set of matched elements, relative to the document. */ public GQuery offset(Offset offset) { assert offset() != null : "offset cannot be null"; return offset(offset.top, offset.left); } /** * Set the current coordinates of every element in the set of matched elements, relative to the document. */ public GQuery offset(int top, int left) { for (Element element : elements()) { GQuery g = $(element); String position = g.css("position", true); if ("static".equals(position)) { css("position", "relative"); } Offset curOffset = g.offset(); String curCSSTop = g.css("top", true); String curCSSLeft = g.css("left", true); long curTop = 0; long curLeft = 0; if (("absolute".equals(position) || "fixed".equals(position)) && ("auto".equals(curCSSTop) || "auto".equals(curCSSLeft))) { Offset curPosition = g.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { try { curTop = Long.parseLong(curCSSTop); } catch (NumberFormatException e) { curTop = 0; } try { curLeft = Long.parseLong(curCSSLeft); } catch (NumberFormatException e) { curLeft = 0; } } long newTop = top - curOffset.top + curTop; long newLeft = left - curOffset.left + curLeft; g.css("top", "" + newTop).css("left", "" + newLeft); } return this; } /** * Returns a GQuery collection with the positioned parent of the first matched element. This is * the first parent of the element that has position (as in relative or absolute). This method * only works with visible elements. */ public GQuery offsetParent() { if (isEmpty()) { return $(); } Element offParent = JsUtils.or(get(0).getOffsetParent(), body); while (offParent != null && !"body".equalsIgnoreCase(offParent.getTagName()) && !"html".equalsIgnoreCase(offParent.getTagName()) && "static".equals(getStyleImpl().curCSS(offParent, "position", true))) { offParent = offParent.getOffsetParent(); } return new GQuery(offParent); } /** * Attach an event handler function for one or more events to the selected elements. */ public GQuery on(String eventName, Function... funcs) { return bind(eventName, funcs); } /** * Attach an event handler function for one or more events to the selected elements. */ public GQuery on(String eventName, Object data, Function... funcs) { return bind(eventName, data, funcs); } /** * Attach an event handler function for one or more events to the selected elements. */ public GQuery on(String eventName, String selector, Function... funcs) { if (selector == null || selector.isEmpty()) { return on(eventName, funcs); } return delegate(selector, eventName, funcs); } /** * Attach an event handler function for one or more events to the selected elements. */ public GQuery on(String eventName, String selector, Object data, Function... funcs) { if (selector == null || selector.isEmpty()) { return on(eventName, data, funcs); } return delegate(selector, eventName, data, funcs); } /** * Remove all event handlers. */ public GQuery off() { return as(Events).off(); } /** * Remove an event handler. */ public GQuery off(String eventName) { return unbind(eventName, null); } /** * Remove an event handler. */ public GQuery off(String eventName, Function f) { return unbind(eventName, f); } /** * Remove an event handler. */ public GQuery off(String eventName, String selector) { if (selector == null || selector.isEmpty()) { return off(eventName); } return undelegate(selector, eventName); } /** * Binds a handler to a particular Event (like Event.ONCLICK) for each matched element. The * handler is executed only once for each element. * * The event handler is passed as a Function that you can use to prevent default behavior. To stop * both default action and event bubbling, the function event handler has to return false. * * You can pass an additional Object data to your Function as the second parameter */ public GQuery one(int eventbits, final Object data, final Function f) { return as(Events).one(eventbits, data, f); } /** * Get the current computed height for the first element in the set of matched elements, including * padding, border, but not the margin. */ public int outerHeight() { return outerHeight(false); } /** * Get the current computed height for the first element in the set of matched elements, including * padding, border, and optionally margin. */ public int outerHeight(boolean includeMargin) { if (isEmpty()) { return 0; } // height including padding and border int outerHeight = (int) cur("offsetHeight", true); if (includeMargin) { outerHeight += cur("marginTop", true) + cur("marginBottom", true); } return outerHeight; } /** * Get the current computed width for the first element in the set of matched elements, including * padding, border, but not the margin. */ public int outerWidth() { return outerWidth(false); } /** * Get the current computed width for the first element in the set of matched elements, including * padding and border and optionally margin. */ public int outerWidth(boolean includeMargin) { if (isEmpty()) { return 0; } // width including padding and border int outerWidth = (int) cur("offsetWidth", true); if (includeMargin) { outerWidth += cur("marginRight", true) + cur("marginLeft", true); } return outerWidth; } /** * Get a set of elements containing the unique parents of the matched set of elements. */ public GQuery parent() { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { Element p = e.getParentElement(); if (p != null) { result.addNode(p); } } return new GQuery(unique(result)); } /** * Get a set of elements containing the unique parents of the matched set of elements. You may use * an optional expressions to filter the set of parent elements that will match one of them. */ public GQuery parent(String... filters) { return parent().filter(filters); } /** * Get a set of elements containing the unique ancestors of the matched set of elements (except * for the root element). */ public GQuery parents() { return parentsUntil((String) null); } /** * Get a set of elements containing the unique ancestors of the matched set of elements (except * for the root element). The matched elements are filtered, returning those that match any of the * filters. */ public GQuery parents(String... filters) { return parents().filter(filters); } /** * Get the ancestors of each element in the current set of matched elements, up to but not * including the element matched by the selector. */ public GQuery parentsUntil(final String selector) { return parentsUntil(new Predicate() { @Override public <T> boolean f(T e, int index) { return selector != null && $(e).is(selector); } }); } /** * Get the ancestors of each element in the current set of matched elements, up to but not * including the node. */ public GQuery parentsUntil(final Node node) { return parentsUntil(new Predicate() { @Override public <T> boolean f(T e, int index) { return node != null && e == node; } }); } private GQuery parentsUntil(Predicate predicate) { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { int i = 0; Node par = e.getParentNode(); while (par != null && par != document) { if (predicate.f(par, i)) { break; } result.addNode(par); par = par.getParentNode(); i++; } } return new GQuery(unique(result)).setPreviousObject(this); } /** * Gets the top and left position of an element relative to its offset parent. The returned object * contains two Integer properties, top and left. For accurate calculations make sure to use pixel * values for margins, borders and padding. This method only works with visible elements. */ public Offset position() { if (isEmpty()) { return new Offset(0, 0); } Element element = get(0); // Get *real* offsetParent Element offsetParent = get(0).getOffsetParent(); // Get correct offsets Offset offset = offset(); Offset parentOffset = null; if (offsetParent == body || offsetParent == (Node) document) { parentOffset = new Offset(0, 0); } else { parentOffset = $(offsetParent).offset(); } // Subtract element margins int topMargin = (int) getStyleImpl().cur(element, "marginTop", true); // TODO: move this check to getStyleImpl() // When margin-left = auto, Safari and chrome return a value while IE and // Firefox return 0 // force the margin-left to 0 if margin-left = auto. int leftMargin = 0; if (!"auto".equals(element.getStyle().getMarginLeft())) { leftMargin = (int) getStyleImpl().cur(element, "marginLeft", true); } offset = offset.add(-leftMargin, -topMargin); // Add offsetParent borders int parentOffsetBorderTop = (int) getStyleImpl().cur(offsetParent, "borderTopWidth", true); int parentOffsetBorderLeft = (int) getStyleImpl().cur(offsetParent, "borderLeftWidth", true); parentOffset = parentOffset.add(parentOffsetBorderLeft, parentOffsetBorderTop); // Subtract the two offsets return offset.add(-parentOffset.left, -parentOffset.top); } /** * Prepend content to the inside of every matched element. This operation is the best way to * insert elements inside, at the beginning, of all matched elements. */ public GQuery prepend(GQuery query) { return domManip(query, DomMan.PREPEND); } /** * Prepend content to the inside of every matched element. This operation is the best way to * insert elements inside, at the beginning, of all matched elements. */ public GQuery prepend(Node n) { return domManip($(n), DomMan.PREPEND); } /** * Prepend content to the inside of every matched element. This operation is the best way to * insert elements inside, at the beginning, of all matched elements. */ public GQuery prepend(String html) { return domManip(html, DomMan.PREPEND); } /** * All of the matched set of elements will be inserted at the beginning of the element(s) * specified by the parameter other. * * The operation $(A).prependTo(B) is, essentially, the reverse of doing a regular * $(A).prepend(B), instead of prepending B to A, you're prepending A to B. */ public GQuery prependTo(GQuery other) { other.prepend(this); return this; } /** * All of the matched set of elements will be inserted at the beginning of the element(s) * specified by the parameter other. * * The operation $(A).prependTo(B) is, essentially, the reverse of doing a regular * $(A).prepend(B), instead of prepending B to A, you're prepending A to B. */ public GQuery prependTo(Node n) { $(n).prepend(this); return this; } /** * All of the matched set of elements will be inserted at the beginning of the element(s) * specified by the parameter other. * * The operation $(A).prependTo(B) is, essentially, the reverse of doing a regular * $(A).prepend(B), instead of prepending B to A, you're prepending A to B. */ public GQuery prependTo(String html) { $(html).prepend(this); return this; } /** * Get a set of elements containing the unique previous siblings of each of the matched set of * elements. Only the immediately previous sibling is returned, not all previous siblings. */ public GQuery prev() { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { Element next = getPreviousSiblingElement(e); if (next != null) { result.addNode(next); } } return new GQuery(unique(result)); } /** * Get a set of elements containing the unique previous siblings of each of the matched set of * elements filtered by selector. Only the immediately previous sibling is returned, not all * previous siblings. */ public GQuery prev(String... selectors) { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { Element next = getPreviousSiblingElement(e); if (next != null) { result.addNode(next); } } return new GQuery(unique(result)).filter(selectors); } /** * Get all preceding siblings of each element in the set of matched elements. */ public GQuery prevAll() { return prevAll(null); } /** * Get all preceding siblings of each element in the set of matched elements filtered by a * selector. */ public GQuery prevAll(String selector) { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { allPreviousSiblingElements(getPreviousSiblingElement(e), result, null, selector); } return pushStack(unique(result), "prevAll", getSelector()); } /** * Get all preceding siblings of each element up to but not including the element matched by the * <code>selector</code>. * * The elements are returned in order from the closest sibling to the farthest. */ public GQuery prevUntil(String selector) { return prevUntil($(selector), null); } /** * Get all preceding siblings of each element up to but not including the <code>until</code> * element. * * The elements are returned in order from the closest sibling to the farthest. */ public GQuery prevUntil(Element until) { return prevUntil($(until), null); } /** * Get all preceding siblings of each element up to but not including the <code>until</code> * element. * * The elements are returned in order from the closest sibling to the farthest. */ public GQuery prevUntil(GQuery until) { return prevUntil(until, null); } /** * Get all preceding siblings of each element matching the <code>filter</code> up to but not * including the element matched by the <code>selector</code>. * * The elements are returned in order from the closest sibling to the farthest. */ public GQuery prevUntil(String selector, String filter) { return prevUntil($(selector), filter); } /** * Get all preceding siblings of each element matching the <code>filter</code> up to but not * including the <code>until</code> element. * */ public GQuery prevUntil(Element until, String filter) { return prevUntil($(until), filter); } /** * Get all preceding siblings of each element matching the <code>filter</code> up to but not * including the element matched by the <code>until</code> element. * */ public GQuery prevUntil(GQuery until, String filter) { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { allPreviousSiblingElements(getPreviousSiblingElement(e), result, until, filter); } return pushStack(unique(result), "prevUntil", getSelector()); } /** * Returns a dynamically generated Promise that is resolved once all actions * in the queue have ended. */ public Promise promise() { return as(Queue).promise(); } /** * Returns a dynamically generated Promise that is resolved once all actions * in the named queue have ended. */ public Promise promise(String name) { return as(Queue).promise(name); } /** * Get the value of a property for the first element in the set of matched elements. * * @param key the name of the property to be accessed * @return the value of the property, in the case the property is a 'boolean' it * returns a Boolean object, and a Double if is a 'number', so be prepared * if you cast to other numeric objects. In the case of the property is undefined * it returns null. */ public <T> T prop(String key) { assert key != null : "Key is null"; return isEmpty() ? null : JsUtils.<T> prop(get(0), key); } /** * Get the value of a property for the first element in the set of matched elements. * * @param key the name of the property to be accessed * @param clz the class of the type to return * * @return the value of the property, it safely check the type passed as parameter * and preform the aproproate transformations for numbers and booleans. * In the case of the property is undefined it returns null. */ public <T> T prop(String key, Class<? extends T> clz) { assert key != null : "Key is null"; return isEmpty() ? null : JsUtils.<T> prop(get(0), key, clz); } /** * Sets a property to a value on all matched elements. * * @param key the name of the boolean property to be set * @param value the value specified. In the case the value is a Number, it is set * as a 'number' in the javascript object and the same with Boolean. * * @return this <code>GQuery</code> object * */ public GQuery prop(String key, Object value) { assert key != null : "Key is null"; for (Element e : elements) { JsUtils.prop(e, key, value); } return this; } /** * Sets a boolean property to a computed value on all matched elements. * * @param key the name of the boolean property to be set * @param closure the closure to be used to compute the value the specified boolean property * should be set to; the <code>closure</code> is * {@linkplain Function#f(com.google.gwt.dom.client.Element, int) passed} the target * element and its index as arguments and is expected to return either a * <code>Boolean</code> value or an object whose textual representation is converted to a * <code>Boolean</code> value; <code>null</code> return values are ignored * * @return this <code>GQuery</code> object * */ public GQuery prop(String key, Function closure) { assert key != null : "Key is null"; assert closure != null : "Closure is null"; int i = 0; for (Element e : elements) { Object value = closure.f(e, i++); JsUtils.prop(e, key, value); } return this; } protected GQuery pushStack(JsNodeArray elts, String name, String selector) { GQuery g = new GQuery(elts); g.setPreviousObject(this); g.setSelector(selector); g.currentContext = currentContext; return g; } /** * Show the number of functions in the efects queue to be executed on the first matched element. */ public int queue() { return as(Queue).queue(); } /** * Put a set of {@link Function} at the end of the Effects queue. * * Example: * * <pre class="code"> * $("#foo").animate("left:'+=500'", 400) * .queue(new Function(){ * public void f(Element e){ * $(e).css(CSS.BACKGROUNG_COLOR.with(RGBColor.RED)); * $(e).dequeue(); * } * }) * .animate("left:'-=500'", 400) * .queue(lazy().css("color", "yellow"); * * </pre> * * When this statement is executed, the element move to 500 px to left for 400 ms, then its * background color is changed to red and then move to 500px to right for 400ms, and finally its * color is set to yellow. * * Please note that {@link #dequeue()} function is needed at the end of your function to start the * next function in the queue. In lazy() methods you should call dequeue() just before the done() * call. {@see #dequeue()} */ public GQuery queue(Function... f) { return as(Queue).queue(f); } /** * Show the number of functions in the queued named as queueName to be executed on the first * matched element. */ public int queue(String queueName) { return as(Queue).queue(queueName); } /** * Put a set of {@link Function} at the end of a queue. * * Example: * * <pre class="code"> * $("#foo").queue("myQueue", new Function(){ * public void f(Element e){ * $(e).css(CSS.BACKGROUNG_COLOR.with(RGBColor.RED)); * dequeue("myQueue"); * } * }) * .delay(500, "myQueue") * .queue("myQueue", lazy().css(CSS.COLOR.with(RGBColor.YELLOW)).dequeue("myQueue").done()); * </pre> * * When this statement is executed, the background color of the element is set to red, then wait * 500ms before to set the text color of the element to yellow. right for 400ms. * * Please note that {@link #dequeue()} function is needed at the end of your function to start the * next function in the queue. In lazy() methods you should call dequeue() just before the done() * call. {@see #dequeue()} */ public GQuery queue(String queueName, Function... f) { return as(Queue).queue(queueName, f); } /** * Specify a function to execute when the DOM is fully loaded. * * While JavaScript provides the load event for executing code when a page is rendered, this event * is not seen if we attach an event listener after the document has been loaded. * This guarantees that our gwt code will be executed either it's executed synchronously before the * DOM has been rendered (ie: single script linker in header) or asynchronously. */ public Promise ready(Function... fncs) { return new PromiseFunction() { public void f(final com.google.gwt.query.client.Promise.Deferred dfd) { if ("complete" == $(document).prop("readyState")) { dfd.resolve(); } else { $(document).on("load", new Function() { public void f() { dfd.resolve(); } }); } } }.done(fncs); } /** * Removes all matched elements from the DOM. */ public GQuery remove() { return remove(null, true); } /** * Removes from the DOM all matched elements filtered by the <code>filter</code>. */ public GQuery remove(String filter) { return remove(filter, true); } /** * Removes all matched elements from the DOM and cleans their data and bound events if the value * of <code>clean</code> parameter is set to true. The <code> filter</code> parameter allows to * filter the matched set to remove. */ protected GQuery remove(String filter, boolean clean) { for (Element e : elements) { if (filter == null || $(e).filter(filter).length() == 1) { if (clean) { // clean data linked to the children // TODO: "*" fails in queryselectorall (webkit mobile) cleanGQData($("*", e).elements()); // clean data linked to the element itself cleanGQData(e); } Widget w = getAssociatedWidget(e); if (w != null) { w.removeFromParent(); } else { e.removeFromParent(); } } } return this; } /** * Remove the named attribute from every element in the matched set. */ public GQuery removeAttr(String key) { getAttributeImpl().removeAttribute(this, key); return this; } /** * Removes the specified classes to each matched element. * * If no arguments are provided, it removes all classes like jquery does. */ public GQuery removeClass(String... classes) { for (Element e : elements) { if (Element.is(e)) { if (classes.length == 0) { e.setClassName(null); } else { for (String clz : classes) { e.removeClassName(clz); } } } } return this; } protected void removeData(Element item, String name) { if (dataCache == null) { windowData = JavaScriptObject.createObject().cast(); dataCache = JavaScriptObject.createObject().cast(); } item = item == window || item.getNodeName() == null ? windowData : item; int id = item.hashCode(); if (name != null) { if (dataCache.exists(id)) { dataCache.getCache(id).delete(name); if (dataCache.getCache(id).isEmpty()) { // Save memory removeData(item, null); } } } else { // when the element cache is empty we remove its entry to save memory (issue 132) dataCache.delete(id); } } /** * Removes named data store from an element. */ public GQuery removeData(String name) { for (Element e : elements) { removeData(e, name); } return this; } /** * Remove a property for the set of matched elements. */ public GQuery removeProp(String name) { for (Element e : elements) { e.<JsCache> cast().delete(name); } return this; } /** * Replaces the element <code>elem</code> by the specified selector with the matched elements. * This function is the complement to replaceWith() which does the same task with the parameters * reversed. * * @return a {@link GQuery} object containing the new elements. */ public GQuery replaceAll(Element elem) { return replaceAll($(elem)); } /** * Replaces the elements matched by the target with the selected elements. This function is the * complement to replaceWith() which does the same task with the parameters reversed. * * @return a {@link GQuery} object containing the new elements. */ public GQuery replaceAll(GQuery target) { // if there is only one element and it is not attached to the dom, we have // to clone it to be reused on each element of target (if target contains // more than one element) boolean mustBeCloned = length() == 1 && parents().filter("body").length() == 0; List<Element> newElements = new ArrayList<>(); for (int i = 0, l = target.size(); i < l; i++) { GQuery that = (i > 0 && mustBeCloned) ? this.clone() : this; $(target.get(i)).replaceWith(that); newElements.addAll(Arrays.asList(that.elements)); } return $(newElements); } /** * Replaces the elements matched by the specified selector with the matched elements. This * function is the complement to replaceWith() which does the same task with the parameters * reversed. * * @return a {@link GQuery} object containing the new elements. */ public GQuery replaceAll(String selector) { return replaceAll($(selector)); } /** * Replaces all matched elements with the specified element. * * @return the GQuery element that was just replaced, which has been removed from the DOM and not * the new element that has replaced it. */ public GQuery replaceWith(Element elem) { return replaceWith($(elem)); } /** * Replaces all matched elements with elements selected by <code>target</code> . * * @return the GQuery element that was just replaced, which has been removed from the DOM and not * the new element that has replaced it. */ public GQuery replaceWith(GQuery target) { for (Element el : elements) { Element nextSibling = el.getNextSiblingElement(); if (nextSibling != null) { $(nextSibling).before(target); } else { Element parent = el.getParentElement(); $(parent).append(target); } $(el).remove(); } return this; } /** * Replaces all matched elements with the specified HTML. * * @return the GQuery element that was just replaced, which has been removed from the DOM and not * the new element that has replaced it. */ public GQuery replaceWith(String html) { for (Element el : elements) { Element nextSibling = el.getNextSiblingElement(); if (nextSibling != null) { $(nextSibling).before(html); } else { Element parent = el.getParentElement(); $(parent).append(html); } $(el).remove(); } return this; } /** * Bind a set of functions to the resize event of each matched element, or tigger the resize event * if no functions are provided. * * Note that although all elements can be configured to handle resize events, by default only * window will trigger it when it is resized, for an arbitrary element you have to trigger the * event after resizing the object. * */ public GQuery resize(Function... f) { return bindOrFire("resize", null, f); } /** * Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. */ public GQuery resize(final Function f) { return bindOrFire("resize", null, f); } /** * Save a set of Css properties of every matched element. */ public void restoreCssAttrs(String... cssProps) { for (Element e : elements) { for (String a : cssProps) { String datakey = OLD_DATA_PREFIX + a; getStyleImpl().setStyleProperty(e, a, (String) data(e, datakey, null)); removeData(e, datakey); } } } /** * Restore a set of previously saved Css properties in every matched element. */ public void saveCssAttrs(String... cssProps) { for (Element e : elements) { for (String a : cssProps) { data(OLD_DATA_PREFIX + a, getStyleImpl().curCSS(e, a, false)); } } } /** * Bind a set of functions to the scroll event of each matched element. Or trigger the event if no * functions are provided. */ public GQuery scroll(Function... f) { return bindOrFire(Event.ONSCROLL, null, f); } /** * Scrolls the first matched element into view. */ public GQuery scrollIntoView() { if (!isEmpty()) { scrollIntoViewImpl(get(0)); } return this; } /** * Scrolls the first matched element into view. * * If ensure == true, it crawls up the DOM hierarchy, adjusting the scrollLeft and scrollTop * properties of each scroll-able element to ensure that the specified element is completely in * view. It adjusts each scroll position by the minimum amount necessary. */ public GQuery scrollIntoView(boolean ensure) { if (!isEmpty() && ensure) { DOM.scrollIntoView((com.google.gwt.user.client.Element) get(0)); } else { scrollIntoView(); } return this; } /** * Gets the scroll left offset of the first matched element. This method works for both visible * and hidden elements. */ public int scrollLeft() { Element e = get(0); if (e == null) { return 0; } if (e == window || e.getNodeName() == null) { return Window.getScrollLeft(); } else if (e == (Node) document) { return document.getScrollLeft(); } else { return e.getScrollLeft(); } } /** * The scroll left offset is set to the passed value on all matched elements. This method works * for both visible and hidden elements. */ public GQuery scrollLeft(int left) { for (Element e : elements) { if (e == window || e.getNodeName() == null || e == (Node) document) { Window.scrollTo(left, $(e).scrollTop()); } else { e.setPropertyInt("scrollLeft", left); } } return this; } /** * * Scrolls the contents of all matched elements to the specified co-ordinate becoming the top left * corner of the viewable area. * * This method is only useful where there are areas of the document not viewable within the * current viewable area of the window and the visible property of the window's scrollbar must be * set to true. * */ public GQuery scrollTo(int left, int top) { scrollLeft(left).scrollTop(top); return this; } /** * Gets the scroll top offset of the first matched element. This method works for both visible and * hidden elements. */ public int scrollTop() { Element e = get(0); if (e == null) { return 0; } if (e == window || e.getNodeName() == null) { return Window.getScrollTop(); } else if (e == (Node) document) { return document.getScrollTop(); } else { return e.getScrollTop(); } } /** * The scroll top offset is set to the passed value on all matched elements. This method works for * both visible and hidden elements. */ public GQuery scrollTop(int top) { for (Element e : elements) { if (e == window || e.getNodeName() == null || e == (Node) document) { Window.scrollTo($(e).scrollLeft(), top); } else { e.setPropertyInt("scrollTop", top); } } return this; } public GQuery select() { return as(Events).triggerHtmlEvent("select"); } private GQuery select(String selector, Node context) { NodeList<Element> n = getSelectorEngine().select(selector, context == null ? document : context); currentSelector = selector; currentContext = context != null ? context : document; return setArray(n); } /** * Force the current matched set of elements to become the specified array of elements. */ public GQuery setArray(NodeList<Element> list) { if (list != null) { nodeList.<JsCache> cast().clear(); int l = list.getLength(); elements = new Element[l]; for (int i = 0; i < l; i++) { elements[i] = list.getItem(i); nodeList.<JsObjectArray<Element>> cast().add(list.getItem(i)); } } return this; } public GQuery setPreviousObject(GQuery previousObject) { this.previousObject = previousObject; return this; } public GQuery setSelector(String selector) { this.currentSelector = selector; return this; } /** * Make all matched elements visible. */ public GQuery show() { for (Element e : elements) { String currentDisplay = e.getStyle().getDisplay(); String oldDisplay = (String) data(e, OLD_DISPLAY, null); // reset the display if (oldDisplay == null && "none".equals(currentDisplay)) { getStyleImpl().setStyleProperty(e, "display", ""); currentDisplay = ""; } // check if the stylesheet impose display: none. If it is the case, determine // the default display for the tag and store it at the element level if ("".equals(currentDisplay) && !getStyleImpl().isVisible(e)) { data(e, OLD_DISPLAY, getStyleImpl().defaultDisplay(e.getNodeName())); } } // set the display value in a separate for loop to avoid constant reflow // because broswer reflow is triggered each time we gonna set and after get (in // isVisibleProperty() method) // the diplay property. Reflows is very bad in performance point of view for (Element e : elements) { String currentDisplay = e.getStyle().getDisplay(); if ("".equals(currentDisplay) || "none".equals(currentDisplay)) { getStyleImpl().setStyleProperty(e, "display", JsUtils.or((String) data(e, OLD_DISPLAY, null), "")); } } removeData(OLD_DISPLAY); return this; } /** * Get a set of elements containing all of the unique siblings of each of the matched set of * elements. */ public GQuery siblings() { JsNodeArray result = JsNodeArray.create(); for (Element e : elements) { allNextSiblingElements(e.getParentElement().getFirstChildElement(), result, e, null, null); } return new GQuery(unique(result)); } /** * Get a set of elements containing all of the unique siblings of each of the matched set of * elements filtered by the provided set of selectors. */ public GQuery siblings(String... selectors) { return siblings().filter(selectors); } /** * Return the number of elements in the matched set. */ public int size() { return elements.length; } /** * Selects a subset of the matched elements. */ public GQuery slice(int start, int end) { JsNodeArray slice = JsNodeArray.create(); int l = size(); if (end == -1 || end > l) { end = l; } for (int i = start; i < end; i++) { slice.addNode(get(i)); } return new GQuery(slice); } /** * Reveal all matched elements by adjusting their height and firing an optional callback after * completion. */ public Effects slideDown(Function... f) { return as(Effects).slideDown(f); } /** * Reveal all matched elements by adjusting their height and firing an optional callback after * completion. */ public Effects slideDown(int millisecs, Function... f) { return as(Effects).slideDown(millisecs, f); } /** * Toggle the visibility of all matched elements by adjusting their height and firing an optional * callback after completion. Only the height is adjusted for this animation, causing all matched * elements to be hidden or shown in a "sliding" manner */ public Effects slideToggle(Function... f) { return as(Effects).slideToggle(f); } /** * Toggle the visibility of all matched elements by adjusting their height and firing an optional * callback after completion. Only the height is adjusted for this animation, causing all matched * elements to be hidden or shown in a "sliding" manner */ public Effects slideToggle(int millisecs, Function... f) { return as(Effects).slideToggle(millisecs, f); } /** * Hide all matched elements by adjusting their height and firing an optional callback after * completion. */ public Effects slideUp(Function... f) { return as(Effects).slideUp(f); } /** * Hide all matched elements by adjusting their height and firing an optional callback after * completion. */ public Effects slideUp(int millisecs, Function... f) { return as(Effects).slideUp(millisecs, f); } /** * When .stop() is called on an element, the currently-running animation (if any) is immediately * stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called, * the element will now still be displayed, but will be a fraction of its previous height. * Callback functions are not called but the next animation in the queue begins immediately. */ public GQuery stop() { return stop(false); } /** * When .stop() is called on an element, the currently-running animation (if any) is immediately * stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called, * the element will now still be displayed, but will be a fraction of its previous height. * Callback functions are not called but the next animation in the queue begins immediately. * * If the clearQueue parameter is provided with a value of true, then the rest of the animations * in the queue are removed and never run. */ public GQuery stop(boolean clearQueue) { return stop(clearQueue, false); } /** * When .stop() is called on an element, the currently-running animation (if any) is immediately * stopped. If, for instance, an element is being hidden with .slideUp() when .stop() is called, * the element will now still be displayed, but will be a fraction of its previous height. * Callback functions are not called but the next animation in the queue begins immediately. * * If the clearQueue parameter is provided with a value of true, then the rest of the animations * in the queue are removed and never run. * * If the jumpToEnd property is provided with a value of true, the current animation stops, but * the element is immediately given its target values for each CSS property. The callback * functions are then immediately called, if provided. */ public GQuery stop(boolean clearQueue, boolean jumpToEnd) { return as(Queue).stop(clearQueue, jumpToEnd); } /** * Bind a set of functions to the submit event of each matched element. Or submit a form if no * functions are provided. */ public GQuery submit(Function... funcs) { return bindOrFire("submit", null, funcs); } /** * Return the concatened text contained in the matched elements. */ public String text() { String result = ""; for (Element e : elements) { result += JsUtils.text(e); } return result; } /** * Set the innerText of every matched element. */ public GQuery text(String txt) { for (Element e : elements) { e.setInnerText(txt); } return this; } /** * Toggle visibility of elements. */ public GQuery toggle() { for (Element e : elements) { if (getStyleImpl().isVisible(e)) { $(e).hide(); } else { $(e).show(); e.getStyle().setDisplay(Display.BLOCK); } } return this; } /** * Toggle among two or more function calls every other click. */ public GQuery toggle(final Function... fn) { for (Element e : elements) { $(e).click(new Function() { int click = 0; public boolean f(Event e) { int n = fn.length == 1 ? 0 : (click++ % fn.length); return fn[n].f(e); } }); } return this; } /** * Adds or removes the specified classes to each matched element depending on the class's * presence. */ public GQuery toggleClass(String... classes) { for (Element e : elements) { for (String clz : classes) { if (hasClass(e, clz)) { e.removeClassName(clz); } else { e.addClassName(clz); } } } return this; } /** * Adds or removes the specified classes to each matched element depending on the value of the * switch argument. * * if addOrRemove is true, the class is added and in the case of false it is removed. */ public GQuery toggleClass(String clz, boolean addOrRemove) { if (addOrRemove) { addClass(clz); } else { removeClass(clz); } return this; } /** * Returns the computed top position of the first element matched. */ public int top() { return (int) cur("top", true); } /** * Produces a string representation of the matched elements. */ public String toString() { return toString(false); } /** * Produces a string representation of the matched elements. */ public String toString(boolean pretty) { String r = ""; for (Element e : elements) { if (window.equals(e)) { continue; } String elStr; try { elStr = JsUtils.isXML(e) ? JsUtils.XML2String(e) : e.getString(); } catch (Exception e2) { elStr = "< " + (e == null ? "null" : e.getNodeName()) + "(gquery, error getting the element string representation: " + e2.getMessage() + ")/>"; } r += (pretty && r.length() > 0 ? "\n " : "") + elStr; } return r; } /** * Trigger a browser native event on each matched element. */ public GQuery trigger(NativeEvent event) { return as(Events).trigger(event, new Function[] {}); } /** * Trigger a set of events on each matched element. * * For keyboard events you can pass a second parameter which represents the key-code of the pushed * key. * * Example: fire(Event.ONCLICK | Event.ONFOCUS) Example: fire(Event.ONKEYDOWN. 'a'); */ public GQuery trigger(int eventbits, int... keys) { return as(Events).trigger(eventbits, keys); } /** * Trigger a event in all matched elements. * * @param eventName An string representing the type of the event desired * @param datas Additional parameters to pass along to the event handlers. */ public GQuery trigger(String eventName, Object... datas) { return as(Events).triggerHtmlEvent(eventName, datas); } /** * Removes all events that match the eventbits. */ public GQuery unbind(int eventbits) { return as(Events).unbind(eventbits); } /** * Removes the function passed from the set of events which match the eventbits. */ public GQuery unbind(int eventbits, Function f) { return as(Events).unbind(eventbits, null, f); } /** * Removes all events that match the eventList. */ public GQuery unbind(String eventList) { return unbind(eventList, null); } /** * Removes all events that match the eventList. */ public GQuery unbind(String eventList, Function f) { return as(Events).unbind(eventList, f); } /** * Remove all event delegation that have been bound using * {@link #delegate(String, int, Function...)} {@link #live(int, Function...)} methods. * * @deprecated use {@link #off()} */ public GQuery undelegate() { return as(Events).undelegate(); } /** * Undelegate is a way of removing event handlers that have been bound using * {@link #delegate(String, int, Function...)} method. * * @deprecated use {@link #off(String)} */ public GQuery undelegate(String selector) { for (Element e : elements) { $(selector, e).die(); } return this; } /** * Undelegate is a way of removing event handlers that have been bound using * {@link #delegate(String, int, Function...)} method. * * @deprecated use {@link #off(String)} */ public GQuery undelegate(String selector, int eventBit) { for (Element e : elements) { $(selector, e).die(eventBit); } return this; } /** * Undelegate is a way of removing event handlers that have been bound using * {@link #delegate(String, int, Function...)} method. * * @deprecated use {@link #off(String, String)} */ public GQuery undelegate(String selector, String eventName) { for (Element e : elements) { $(selector, e).die(eventName); } return this; } /** * Remove all duplicate elements from an array of elements. Note that this only works on arrays of * DOM elements, not strings or numbers. */ public JsNodeArray unique(NodeList<Element> result) { return JsUtils.unique(result.<JsArray<Element>> cast()).cast(); } /** * This method removes the element's parent. The matched elements replaces their parents within * the DOM structure. It is the inverse of {@link GQuery#wrap(GQuery)} method. * * @return */ public GQuery unwrap() { for (Element parent : parent().elements) { if (!"body".equalsIgnoreCase(parent.getTagName())) { GQuery g = $(parent); g.replaceWith(g.children()); } } return this; } /** * Gets the content of the value attribute of the first matched element, returns only the first * value even if it is a multivalued element. To get an array of all values in multivalues * elements use vals(). * * When the first element is a radio-button and is not checked, then it looks for the first * checked radio-button that has the same name in the list of matched elements. * * When there are not matched elements it returns null. */ public String val() { if (isEmpty()) { return null; } String[] v = vals(); return v == null ? null : v.length > 0 ? v[0] : ""; } /** * Sets the value attribute of every matched element based in the return value of the function * evaluated for this element. * * NOTE: in jquery the function receives the arguments in different way, first index and them the * actual value, but we use the normal way in gquery Function, first the element and second the * index. */ public GQuery val(Function f) { for (int i = 0; i < size(); i++) { eq(i).val(f.f(get(i), i).toString()); } return this; } /** * Sets the 'value' attribute of every matched element, but does not set the checked flag to * checkboxes or radiobuttons. * * If you wanted to set values in collections of checkboxes o radiobuttons use val(String[]) * instead */ public GQuery val(String value) { for (Element e : elements) { setElementValue(e, value); } return this; } /** * Sets the value of every matched element. * * There is a different behaviour depending on the element type: * <ul> * <li>select multiple: options whose value match any of the passed values will be set. * <li>select single: the last option whose value matches any of the passed values will be set. * <li>input radio: the last input whose value matches any of the passed values will be set. * <li>input checkbox: inputs whose value match any of the passed values will be set. * <li>textarea, button, and other input: value will set to a string result of joining with coma, * all passed values * </ul> * * NOTE: if you wanted call this function with just one parameter, you have to pass an array * signature to avoid call the overloaded val(String) method: * * $(...).val(new String[]{"value"}); */ public GQuery val(String... values) { String value = join(",", values); for (Element e : elements) { String name = e.getNodeName(); if ("select".equalsIgnoreCase(name)) { SelectElement s = SelectElement.as(e); s.setSelectedIndex(-1); for (String v : values) { if (s.isMultiple()) { for (int i = 0, l = s.getOptions().getLength(); i < l; i++) { if (v.equals(s.getOptions().getItem(i).getValue())) { s.getOptions().getItem(i).setSelected(true); } } } else { s.setValue(v); } } } else if ("input".equalsIgnoreCase(name)) { InputElement ie = InputElement.as(e); String type = ie.getType(); if ("radio".equalsIgnoreCase(type) || "checkbox".equalsIgnoreCase(type)) { ie.setChecked(false); for (String v : values) { if (ie.getValue().equals(v)) { ie.setChecked(true); break; } } } else { ie.setValue(value); } } else { setElementValue(e, value); } } return this; } /** * Gets the content of the value attribute of the first matched element, returns more than one * value if it is a multiple select. * * When the first element is a radio-button and is not checked, then it looks for a the first * checked radio-button that has the same name in the list of matched elements. * * This method always returns an array. If no valid value can be determined the array will be * empty, otherwise it will contain one or more values. */ public String[] vals() { if (!isEmpty()) { Element e = get(0); if (e.getNodeName().equalsIgnoreCase("select")) { SelectElement se = SelectElement.as(e); if (se.isMultiple()) { JsArrayString result = JsArrayString.createArray().cast(); for (int i = 0, l = se.getOptions().getLength(); i < l; i++) { OptionElement oe = se.getOptions().getItem(i); if (oe.isSelected()) { result.set(result.length(), oe.getValue()); } } return result.length() > 0 ? jsArrayToString(result) : null; } else if (se.getSelectedIndex() >= 0) { return new String[] {se.getOptions().getItem(se.getSelectedIndex()).getValue()}; } } else if (e.getNodeName().equalsIgnoreCase("input")) { InputElement ie = InputElement.as(e); return new String[] {ie.getValue()}; } else if (e.getNodeName().equalsIgnoreCase("textarea")) { return new String[] {TextAreaElement.as(e).getValue()}; } else if (e.getNodeName().equalsIgnoreCase("button")) { return new String[] {ButtonElement.as(e).getValue()}; } } return new String[0]; } @Deprecated public boolean visible() { return isVisible(); } /** * Return the first non null attached widget from the matched elements or null if there isn't any. */ @SuppressWarnings("unchecked") public <W extends Widget> W widget() { return (W) widget(0); } /** * Return the nth non null attached widget from the matched elements or null if there isn't any. */ public <W extends Widget> W widget(int n) { for (Element e : elements) { @SuppressWarnings("unchecked") W w = (W) getAssociatedWidget(e); if (w != null) { if (n == 0) { return w; } n--; } } return null; } /** * return the list of attached widgets matching the query. */ public List<Widget> widgets() { List<Widget> widgets = new ArrayList<>(); for (Element e : elements) { Widget w = getAssociatedWidget(e); if (w != null) { widgets.add(w); } } return widgets; } /** * Return the list of attached widgets instance of the provided class matching the query. * * This method is very useful for decoupled views, so as we can access widgets from other views * without maintaining methods which export them. * */ @SuppressWarnings("unchecked") public <W extends Widget> List<W> widgets(Class<W> clazz) { List<W> ret = new ArrayList<>(); for (Widget w : widgets()) { // isAssignableFrom does not work in gwt. Class<?> c = w.getClass(); do { if (c.equals(clazz)) { ret.add((W) w); break; } c = c.getSuperclass(); } while (c != null); } return ret; } /** * Get the current computed, pixel, width of the first matched element. It does not include * margin, padding nor border. */ public int width() { return (int) cur("width", true); } /** * Set the width of every matched element. */ public GQuery width(int width) { for (Element e : elements) { e.getStyle().setPropertyPx("width", width); } return this; } /** * Set the width style property of every matched element. It's useful for using 'percent' or 'em' * units Example: $(".a").width("100%") */ public GQuery width(String width) { return css("width", width); } /** * Wrap each matched element with the specified HTML content. This wrapping process is most useful * for injecting additional structure into a document, without ruining the original semantic * qualities of a document. This works by going through the first element provided (which is * generated, on the fly, from the provided HTML) and finds the deepest descendant element within * its structure -- it is that element that will enwrap everything else. */ public GQuery wrap(Element elem) { return wrap($(elem)); } /** * Wrap each matched element with the specified HTML content. This wrapping process is most useful * for injecting additional structure into a document, without ruining the original semantic * qualities of a document. This works by going through the first element provided (which is * generated, on the fly, from the provided HTML) and finds the deepest descendant element within * its structure -- it is that element that will enwrap everything else. */ public GQuery wrap(GQuery query) { for (Element e : elements) { $(e).wrapAll(query); } return this; } /** * Wrap each matched element with the specified HTML content. This wrapping process is most useful * for injecting additional structure into a document, without ruining the original semantic * qualities of a document. This works by going through the first element provided (which is * generated, on the fly, from the provided HTML) and finds the deepest descendant element within * its structure -- it is that element that will enwrap everything else. */ public GQuery wrap(String html) { return wrap($(html)); } /** * Wrap each matched element with the specified SafeHtml content. This wrapping process is most useful * for injecting additional structure into a document, without ruining the original semantic * qualities of a document. This works by going through the first element provided (which is * generated, on the fly, from the provided SafeHtml) and finds the deepest descendant element within * its structure -- it is that element that will enwrap everything else. */ public GQuery wrap(SafeHtml safeHtml) { return wrap($(safeHtml)); } /** * Wrap all the elements in the matched set into a single wrapper element. This is different from * .wrap() where each element in the matched set would get wrapped with an element. This wrapping * process is most useful for injecting additional structure into a document, without ruining the * original semantic qualities of a document. * * This works by going through the first element provided (which is generated, on the fly, from * the provided HTML) and finds the deepest descendant element within its structure -- it is that * element that will enwrap everything else. */ public GQuery wrapAll(Element elem) { return wrapAll($(elem)); } /** * Wrap all the elements in the matched set into a single wrapper element. This is different from * .wrap() where each element in the matched set would get wrapped with an element. This wrapping * process is most useful for injecting additional structure into a document, without ruining the * original semantic qualities of a document. * * This works by going through the first element provided (which is generated, on the fly, from * the provided HTML) and finds the deepest descendant element within its structure -- it is that * element that will enwrap everything else. */ public GQuery wrapAll(GQuery query) { if (!isEmpty()) { GQuery wrap = query.clone(); if (get(0).getParentNode() != null) { wrap.insertBefore(get(0)); } for (Element e : wrap.elements) { Node n = e; while (n.getFirstChild() != null && n.getFirstChild().getNodeType() == Node.ELEMENT_NODE) { n = n.getFirstChild(); } $((Element) n).append(this); } } return this; } /** * Wrap all the elements in the matched set into a single wrapper element. This is different from * .wrap() where each element in the matched set would get wrapped with an element. This wrapping * process is most useful for injecting additional structure into a document, without ruining the * original semantic qualities of a document. * * This works by going through the first element provided (which is generated, on the fly, from * the provided HTML) and finds the deepest descendant element within its structure -- it is that * element that will enwrap everything else. */ public GQuery wrapAll(String html) { return wrapAll($(html)); } /** * Wrap all the elements in the matched set into a single wrapper element. This is different from * .wrap() where each element in the matched set would get wrapped with an element. This wrapping * process is most useful for injecting additional structure into a document, without ruining the * original semantic qualities of a document. * * This works by going through the first element provided (which is generated, on the fly, from * the provided SafeHtml) and finds the deepest descendant element within its structure -- it is that * element that will enwrap everything else. */ public GQuery wrapAll(SafeHtml safeHtml) { return wrapAll(safeHtml.asString()); } /** * Wrap the inner child contents of each matched element (including text nodes) with an HTML * structure. This wrapping process is most useful for injecting additional structure into a * document, without ruining the original semantic qualities of a document. This works by going * through the first element provided (which is generated, on the fly, from the provided HTML) and * finds the deepest ancestor element within its structure -- it is that element that will enwrap * everything else. */ public GQuery wrapInner(Element elem) { return wrapInner($(elem)); } /** * Wrap the inner child contents of each matched element (including text nodes) with an HTML * structure. This wrapping process is most useful for injecting additional structure into a * document, without ruining the original semantic qualities of a document. This works by going * through the first element provided (which is generated, on the fly, from the provided HTML) and * finds the deepest ancestor element within its structure -- it is that element that will enwrap * everything else. */ public GQuery wrapInner(GQuery query) { for (Element e : elements) { $(e).contents().wrapAll(query); } return this; } /** * Wrap the inner child contents of each matched element (including text nodes) with an HTML * structure. This wrapping process is most useful for injecting additional structure into a * document, without ruining the original semantic qualities of a document. This works by going * through the first element provided (which is generated, on the fly, from the provided HTML) and * finds the deepest ancestor element within its structure -- it is that element that will enwrap * everything else. */ public GQuery wrapInner(String html) { return wrapInner($(html)); } /** * Wrap the inner child contents of each matched element (including text nodes) with an SafeHtml * structure. This wrapping process is most useful for injecting additional structure into a * document, without ruining the original semantic qualities of a document. This works by going * through the first element provided (which is generated, on the fly, from the provided SafeHtml) and * finds the deepest ancestor element within its structure -- it is that element that will enwrap * everything else. */ public GQuery wrapInner(SafeHtml safeHtml) { return wrapInner(safeHtml.asString()); } private String join(String chr, String... values) { String value = ""; for (int i = 0; i < values.length; i++) { value += i > 0 ? chr + values[i] : values[i]; } return value; } }
{ "content_hash": "03b935f4c0103a061f613d1a0c227348", "timestamp": "", "source": "github", "line_count": 5060, "max_line_length": 127, "avg_line_length": 32.42628458498024, "alnum_prop": 0.6487137136832097, "repo_name": "gwtquery/gwtquery", "id": "4d680690d8e7fa88b36c79267602da73ba574c1b", "size": "164669", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "gwtquery-core/src/main/java/com/google/gwt/query/client/GQuery.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6584" }, { "name": "HTML", "bytes": "17375" }, { "name": "Java", "bytes": "1696396" }, { "name": "Perl", "bytes": "2474" }, { "name": "Shell", "bytes": "3179" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="JSHintConfiguration" version="2.5.1" use-config-file="false"> <option asi="false" /> <option bitwise="true" /> <option boss="false" /> <option browser="true" /> <option browserify="false" /> <option camelcase="true" /> <option couch="false" /> <option curly="true" /> <option debug="false" /> <option devel="true" /> <option dojo="false" /> <option elision="false" /> <option enforceall="false" /> <option eqeqeq="true" /> <option eqnull="false" /> <option es3="false" /> <option es5="false" /> <option esnext="false" /> <option evil="false" /> <option expr="false" /> <option forin="true" /> <option freeze="true" /> <option funcscope="false" /> <option futurehostile="false" /> <option gcl="false" /> <option globalstrict="false" /> <option immed="false" /> <option iterator="false" /> <option jasmine="false" /> <option jquery="true" /> <option lastsemic="false" /> <option latedef="true" /> <option laxbreak="false" /> <option laxcomma="false" /> <option loopfunc="false" /> <option maxcomplexity="10" /> <option maxdepth="4" /> <option maxerr="50" /> <option maxlen="150" /> <option maxparams="8" /> <option maxstatements="30" /> <option mocha="false" /> <option module="false" /> <option mootools="false" /> <option moz="false" /> <option multistr="false" /> <option newcap="true" /> <option noarg="true" /> <option nocomma="false" /> <option node="false" /> <option noempty="true" /> <option nomen="false" /> <option nonbsp="true" /> <option nonew="true" /> <option nonstandard="false" /> <option notypeof="false" /> <option noyield="false" /> <option onevar="false" /> <option passfail="false" /> <option phantom="false" /> <option plusplus="false" /> <option predef="require,define,requirejs" /> <option proto="false" /> <option prototypejs="false" /> <option qunit="false" /> <option quotmark="false" /> <option rhino="false" /> <option scripturl="false" /> <option shadow="false" /> <option shelljs="false" /> <option singleGroups="false" /> <option smarttabs="false" /> <option strict="true" /> <option sub="false" /> <option supernew="false" /> <option trailing="true" /> <option typed="false" /> <option undef="true" /> <option unused="true" /> <option validthis="false" /> <option varstmt="false" /> <option white="false" /> <option withstmt="false" /> <option worker="false" /> <option wsh="false" /> <option yui="false" /> </component> </project>
{ "content_hash": "5bc32b4aabe997a9638e48a333a6202b", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 80, "avg_line_length": 30.64835164835165, "alnum_prop": 0.5797776980996773, "repo_name": "franksrevenge/elements-of-visual-style", "id": "7e585980dc6ad1e8868a8f0ada41298c5f1eb0f4", "size": "2789", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/jsLinters/jshint.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "JavaScript", "bytes": "188851" } ], "symlink_target": "" }
import React from 'react' import { Segment } from 'shengnian-ui-react' const SegmentExampleVeryPadded = () => ( <Segment padded='very'> Very padded content. </Segment> ) export default SegmentExampleVeryPadded
{ "content_hash": "d6d9f160022cf96764f00d80245d778c", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 44, "avg_line_length": 22, "alnum_prop": 0.7272727272727273, "repo_name": "shengnian/shengnian-ui-react", "id": "0f3234a04f379fa21410a49c8d9d453eb46d2544", "size": "220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/app/Examples/elements/Segment/Variations/SegmentExampleVeryPadded.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1233" }, { "name": "JavaScript", "bytes": "1168671" }, { "name": "TypeScript", "bytes": "116" } ], "symlink_target": "" }
var notify = require("gulp-notify"); module.exports = function() { var args = Array.prototype.slice.call(arguments); // Send error to notification center with gulp-notify notify.onError({ title: "Compile Error", message: "<%= error %>" }).apply(this, args); // Keep gulp from hanging on this task this.emit('end'); };
{ "content_hash": "0f0a8a8bb99bd0da476a3580dd7b0db0", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 57, "avg_line_length": 24.066666666666666, "alnum_prop": 0.6204986149584487, "repo_name": "jobready/skyfire", "id": "0f1185246b7512440d8b017ffe7e08937e8c0b03", "size": "361", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "gulp/util/handleErrors.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "6895" }, { "name": "Ruby", "bytes": "3988" }, { "name": "Shell", "bytes": "115" } ], "symlink_target": "" }
package org.wso2.siddhi.core.query.pattern; import org.apache.log4j.Logger; import org.testng.AssertJUnit; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import org.wso2.siddhi.core.SiddhiAppRuntime; import org.wso2.siddhi.core.SiddhiManager; import org.wso2.siddhi.core.event.Event; import org.wso2.siddhi.core.query.output.callback.QueryCallback; import org.wso2.siddhi.core.stream.input.InputHandler; import org.wso2.siddhi.core.util.EventPrinter; import java.util.concurrent.atomic.AtomicInteger; public class ComplexPatternTestCase { private static final Logger log = Logger.getLogger(ComplexPatternTestCase.class); private int inEventCount; private AtomicInteger count; private int removeEventCount; private boolean eventArrived; @BeforeMethod public void init() { inEventCount = 0; removeEventCount = 0; eventArrived = false; count = new AtomicInteger(); } @Test public void testQuery1() throws InterruptedException { log.info("testPatternComplex1 - OUT 2"); SiddhiManager siddhiManager = new SiddhiManager(); String streams = "" + "define stream Stream1 (symbol string, price float, volume int); " + "define stream Stream2 (symbol string, price float, volume int); "; String query = "" + "@info(name = 'query1') " + "from every ( e1=Stream1[price > 20] -> e2=Stream2[price > e1.price] or e3=Stream2['IBM' == symbol]) " + " -> e4=Stream2[price > e1.price] " + "select e1.price as price1, e2.price as price2, e3.price as price3, e4.price as price4 " + "insert into OutputStream ;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timestamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timestamp, inEvents, removeEvents); if (inEvents != null) { for (Event event : inEvents) { inEventCount++; switch (inEventCount) { case 1: AssertJUnit.assertArrayEquals(new Object[]{55.6f, 55.7f, null, 57.7f}, event.getData()); break; case 2: AssertJUnit.assertArrayEquals(new Object[]{54.0f, 57.7f, null, 59.7f}, event.getData()); break; default: AssertJUnit.assertSame(1, inEventCount); } } } if (removeEvents != null) { removeEventCount = removeEventCount + removeEvents.length; } eventArrived = true; } }); InputHandler stream1 = siddhiAppRuntime.getInputHandler("Stream1"); InputHandler stream2 = siddhiAppRuntime.getInputHandler("Stream2"); siddhiAppRuntime.start(); stream1.send(new Object[]{"WSO2", 55.6f, 100}); Thread.sleep(100); stream2.send(new Object[]{"WSO2", 55.7f, 100}); Thread.sleep(100); stream2.send(new Object[]{"GOOG", 55f, 100}); Thread.sleep(100); stream1.send(new Object[]{"GOOG", 54f, 100}); Thread.sleep(100); stream2.send(new Object[]{"IBM", 57.7f, 100}); Thread.sleep(100); stream2.send(new Object[]{"IBM", 59.7f, 100}); Thread.sleep(100); AssertJUnit.assertEquals("Number of success events", 2, inEventCount); AssertJUnit.assertEquals("Number of remove events", 0, removeEventCount); AssertJUnit.assertEquals("Event arrived", true, eventArrived); siddhiAppRuntime.shutdown(); } @Test public void testQuery2() throws InterruptedException { log.info("testPatternComplex2 - OUT 1"); SiddhiManager siddhiManager = new SiddhiManager(); String streams = "" + "define stream Stream1 (symbol string, price float, volume int); " + "define stream Stream2 (symbol string, price float, volume int); "; String query = "" + "@info(name = 'query1') " + "from every ( e1=Stream1[price > 20] -> e2=Stream1[price > 20]<1:2>) -> e3=Stream1[price > e1.price] " + "select e1.price as price1, e2[0].price as price2_0, e2[1].price as price2_1, e3.price as price3 " + "insert into OutputStream ;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timestamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timestamp, inEvents, removeEvents); if (inEvents != null) { for (Event event : inEvents) { inEventCount++; switch (inEventCount) { case 1: AssertJUnit.assertArrayEquals(new Object[]{55.6f, 54.0f, 53.6f, 57.0f}, event.getData()); break; default: AssertJUnit.assertSame(1, inEventCount); } } } if (removeEvents != null) { removeEventCount = removeEventCount + removeEvents.length; } eventArrived = true; } }); InputHandler stream1 = siddhiAppRuntime.getInputHandler("Stream1"); InputHandler stream2 = siddhiAppRuntime.getInputHandler("Stream2"); siddhiAppRuntime.start(); stream1.send(new Object[]{"WSO2", 55.6f, 100}); Thread.sleep(100); stream1.send(new Object[]{"GOOG", 54f, 100}); Thread.sleep(100); stream1.send(new Object[]{"WSO2", 53.6f, 100}); Thread.sleep(100); stream1.send(new Object[]{"GOOG", 57f, 100}); Thread.sleep(100); AssertJUnit.assertEquals("Number of success events", 1, inEventCount); AssertJUnit.assertEquals("Number of remove events", 0, removeEventCount); AssertJUnit.assertEquals("Event arrived", true, eventArrived); siddhiAppRuntime.shutdown(); } @Test public void testQuery3() throws InterruptedException { log.info("testPatternComplex3 - OUT 3"); SiddhiManager siddhiManager = new SiddhiManager(); String streams = "" + "define stream Stream1 (symbol string, price float, volume int); "; String query = "" + "@info(name = 'query1') " + "from every e1 = Stream1 [ price >= 50 and volume > 100 ] -> e2 = Stream1 [price <= 40 ] <2:> -> e3 =" + " Stream1 [volume <= 70 ] " + "select e1.symbol as symbol1, e2[last].symbol as symbol2, e3.symbol as symbol3 " + "insert into StockQuote;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timestamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timestamp, inEvents, removeEvents); if (inEvents != null) { for (Event event : inEvents) { inEventCount++; switch (inEventCount) { case 1: AssertJUnit.assertArrayEquals(new Object[]{"IBM", "FB", "WSO2"}, event.getData()); break; case 2: AssertJUnit.assertArrayEquals(new Object[]{"ADP", "WSO2", "AMZN"}, event.getData()); break; case 3: AssertJUnit.assertArrayEquals(new Object[]{"WSO2", "QQQ", "CSCO"}, event.getData()); break; default: AssertJUnit.assertSame(3, inEventCount); } } } if (removeEvents != null) { removeEventCount = removeEventCount + removeEvents.length; } eventArrived = true; } }); InputHandler stream1 = siddhiAppRuntime.getInputHandler("Stream1"); siddhiAppRuntime.start(); stream1.send(new Object[]{"IBM", 75.6f, 105}); Thread.sleep(100); stream1.send(new Object[]{"GOOG", 39.8f, 91}); stream1.send(new Object[]{"FB", 35f, 81}); stream1.send(new Object[]{"WSO2", 21f, 61}); stream1.send(new Object[]{"ADP", 50f, 101}); stream1.send(new Object[]{"GOOG", 41.2f, 90}); stream1.send(new Object[]{"FB", 40f, 100}); stream1.send(new Object[]{"WSO2", 33.6f, 85}); stream1.send(new Object[]{"AMZN", 23.5f, 55}); stream1.send(new Object[]{"WSO2", 51.7f, 180}); stream1.send(new Object[]{"TXN", 34f, 61}); stream1.send(new Object[]{"QQQ", 24.6f, 45}); stream1.send(new Object[]{"CSCO", 181.6f, 40}); stream1.send(new Object[]{"WSO2", 53.7f, 200}); Thread.sleep(100); AssertJUnit.assertEquals("Number of success events", 3, inEventCount); AssertJUnit.assertEquals("Number of remove events", 0, removeEventCount); AssertJUnit.assertEquals("Event arrived", true, eventArrived); siddhiAppRuntime.shutdown(); } @Test public void testQuery4() throws InterruptedException { log.info("testPatternComplex4 - OUT 2"); SiddhiManager siddhiManager = new SiddhiManager(); String streams = "" + "define stream Stream1 (symbol string, price float, volume int); " + "define stream Stream2 (symbol string, price float, volume int); "; String query = "" + "@info(name = 'query1') " + "from every e1 = Stream1 [ price >= 50 and volume > 100 ] " + " -> e2 = Stream2 [price <= 40 ] <1:> -> e3 = Stream2 [volume <= 70 ] " + "select e3.symbol as symbol1, e2[0].symbol as symbol2, e3.volume as symbol3 " + "insert into StockQuote;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timestamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timestamp, inEvents, removeEvents); if (inEvents != null) { for (Event event : inEvents) { inEventCount++; switch (inEventCount) { case 1: AssertJUnit.assertArrayEquals(new Object[]{"WSO2", "GOOG", 65}, event.getData()); break; case 2: AssertJUnit.assertArrayEquals(new Object[]{"WSO2", "DDD", 60}, event.getData()); break; default: AssertJUnit.assertSame(2, inEventCount); } } } if (removeEvents != null) { removeEventCount = removeEventCount + removeEvents.length; } eventArrived = true; } }); InputHandler stream1 = siddhiAppRuntime.getInputHandler("Stream1"); InputHandler stream2 = siddhiAppRuntime.getInputHandler("Stream2"); siddhiAppRuntime.start(); stream1.send(new Object[]{"IBM", 75.6f, 105}); Thread.sleep(100); stream2.send(new Object[]{"GOOG", 21f, 81}); stream2.send(new Object[]{"WSO2", 176.6f, 65}); stream1.send(new Object[]{"BIRT", 21f, 81}); stream1.send(new Object[]{"AMBA", 126.6f, 165}); stream2.send(new Object[]{"DDD", 23f, 181}); stream2.send(new Object[]{"BIRT", 21f, 86}); stream2.send(new Object[]{"BIRT", 21f, 82}); stream2.send(new Object[]{"WSO2", 176.6f, 60}); stream1.send(new Object[]{"AMBA", 126.6f, 165}); stream2.send(new Object[]{"DOX", 16.2f, 25}); Thread.sleep(100); AssertJUnit.assertEquals("Number of success events", 2, inEventCount); AssertJUnit.assertEquals("Number of remove events", 0, removeEventCount); AssertJUnit.assertEquals("Event arrived", true, eventArrived); siddhiAppRuntime.shutdown(); } @Test public void testQuery5() throws InterruptedException { log.info("testPatternComplex5 - OUT 1"); SiddhiManager siddhiManager = new SiddhiManager(); String streams = "" + "define stream Stream1 (symbol string, price float, volume int); " + "define stream Stream2 (symbol string, price float, volume int); "; String query = "" + "@info(name = 'query1') " + "from e1 = Stream1 [ price >= 50 and volume > 100 ] -> e2 = Stream2 [e1.symbol != 'AMBA' ] " + " -> e3 = Stream2 [volume <= 70 ] " + "select e3.symbol as symbol1, e2[0].symbol as symbol2, e3.volume as volume3 " + "insert into StockQuote;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timestamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timestamp, inEvents, removeEvents); if (inEvents != null) { for (Event event : inEvents) { inEventCount++; switch (inEventCount) { case 1: AssertJUnit.assertArrayEquals(new Object[]{"WSO2", "GOOG", 65}, event.getData()); break; default: AssertJUnit.assertSame(1, inEventCount); } } } if (removeEvents != null) { removeEventCount = removeEventCount + removeEvents.length; } eventArrived = true; } }); InputHandler stream1 = siddhiAppRuntime.getInputHandler("Stream1"); InputHandler stream2 = siddhiAppRuntime.getInputHandler("Stream2"); siddhiAppRuntime.start(); stream1.send(new Object[]{"IBM", 75.6f, 105}); Thread.sleep(100); stream2.send(new Object[]{"GOOG", 21f, 81}); stream2.send(new Object[]{"WSO2", 176.6f, 65}); stream1.send(new Object[]{"BIRT", 21f, 81}); stream1.send(new Object[]{"AMBA", 126.6f, 165}); stream2.send(new Object[]{"DDD", 23f, 181}); stream2.send(new Object[]{"BIRT", 21f, 86}); stream2.send(new Object[]{"BIRT", 21f, 82}); stream2.send(new Object[]{"WSO2", 176.6f, 60}); stream1.send(new Object[]{"AMBA", 126.6f, 165}); stream2.send(new Object[]{"DOX", 16.2f, 25}); Thread.sleep(100); AssertJUnit.assertEquals("Number of success events", 1, inEventCount); AssertJUnit.assertEquals("Number of remove events", 0, removeEventCount); AssertJUnit.assertEquals("Event arrived", true, eventArrived); siddhiAppRuntime.shutdown(); } @Test public void testQuery6() throws InterruptedException { log.info("testPatternComplex6 - OUT 1"); SiddhiManager siddhiManager = new SiddhiManager(); String streams = "" + "define stream Stream1 (symbol string, price float, volume int); " + "define stream Stream2 (symbol string, price float, volume int); "; String query = "" + "@info(name = 'query1') " + "from every e1 = Stream1 -> e2 = Stream2 [e1.symbol != 'AMBA' ] <2:> -> e3 = Stream2 [volume <= 70 ] " + "select e3.symbol as symbol1, e2[0].symbol as symbol2, e3.volume as volume3 " + "insert into StockQuote;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(streams + query); siddhiAppRuntime.addCallback("query1", new QueryCallback() { @Override public void receive(long timestamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timestamp, inEvents, removeEvents); if (inEvents != null) { for (Event event : inEvents) { inEventCount++; switch (inEventCount) { case 1: AssertJUnit.assertArrayEquals(new Object[]{"WSO2", "GOOG", 65}, event.getData()); break; case 2: AssertJUnit.assertArrayEquals(new Object[]{"IBN", "DDD", 70}, event.getData()); break; default: AssertJUnit.assertSame(2, inEventCount); } } } if (removeEvents != null) { removeEventCount = removeEventCount + removeEvents.length; } eventArrived = true; } }); InputHandler stream1 = siddhiAppRuntime.getInputHandler("Stream1"); InputHandler stream2 = siddhiAppRuntime.getInputHandler("Stream2"); siddhiAppRuntime.start(); stream1.send(new Object[]{"IBM", 75.6f, 105}); Thread.sleep(100); stream2.send(new Object[]{"GOOG", 21f, 51}); stream2.send(new Object[]{"FBX", 21f, 81}); stream2.send(new Object[]{"WSO2", 176.6f, 65}); stream1.send(new Object[]{"BIRT", 21f, 81}); stream1.send(new Object[]{"AMBA", 126.6f, 165}); stream2.send(new Object[]{"DDD", 23f, 181}); stream2.send(new Object[]{"BIRT", 21f, 86}); stream2.send(new Object[]{"IBN", 21f, 70}); stream2.send(new Object[]{"WSO2", 176.6f, 90}); stream1.send(new Object[]{"AMBA", 126.6f, 165}); stream2.send(new Object[]{"DOX", 16.2f, 25}); Thread.sleep(100); AssertJUnit.assertEquals("Number of success events", 2, inEventCount); AssertJUnit.assertEquals("Number of remove events", 0, removeEventCount); AssertJUnit.assertEquals("Event arrived", true, eventArrived); siddhiAppRuntime.shutdown(); } }
{ "content_hash": "26a2504274c2de76be42309dfe3ab6e7", "timestamp": "", "source": "github", "line_count": 453, "max_line_length": 120, "avg_line_length": 42.77704194260485, "alnum_prop": 0.5379812158117453, "repo_name": "codemogroup/siddhi", "id": "ea7440361d3c99b2d2651012be3219d66525c5c9", "size": "20051", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "modules/siddhi-core/src/test/java/org/wso2/siddhi/core/query/pattern/ComplexPatternTestCase.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "19715" }, { "name": "FreeMarker", "bytes": "12043" }, { "name": "Java", "bytes": "6406731" }, { "name": "Shell", "bytes": "524" } ], "symlink_target": "" }
package br.com.smom.smommobile.to; public class ResponseResourceTO { private int code; private String description; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
{ "content_hash": "e8d722601f1398fa49bd62f0b2ffa99e", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 52, "avg_line_length": 18.391304347826086, "alnum_prop": 0.6312056737588653, "repo_name": "feliperodriguesprado/android", "id": "4f32669141d192eeb986d237a938bf5502df3f82", "size": "423", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SmomMobile/app/src/main/java/br/com/smom/smommobile/to/ResponseResourceTO.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "48061" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in J. gen. appl. Microbiol. , Tokyo 33(2): 171 (1987) #### Original name Sporobolomyces sasicola Nakase & M. Suzuki, 1987 ### Remarks null
{ "content_hash": "2e835b45c47af029745332a1a5e69eda", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 50, "avg_line_length": 17.23076923076923, "alnum_prop": 0.6964285714285714, "repo_name": "mdoering/backbone", "id": "31ecbeb788de325d803d1d8f5e320f43e4166097", "size": "296", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Microbotryomycetes/Sporidiobolales/Sporidiobolaceae/Sporobolomyces/Sporobolomyces sasicola/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
AT.prototype.initConverter = function ()  { var self = this, converterCacheCanvas = { x: {}, y: {} }; var convertTo = self.convertTo = { pcX: function (arg, targetID) { if (!targetID) { targetID = 0; } return (arg / self.scale - self.gap[targetID].left - self.transX) / convertTo.canvasX(self.targetList[targetID].diameter) * 100; }, pcY: function (arg, targetID) { if (!targetID) { targetID = 0; } // Attention: converting the target diameter using the x-axe; // otherwise an error will occur return (arg / self.scale - self.gap[targetID].top - self.transY) / convertTo.canvasX(self.targetList[targetID].diameter) * 100; }, pxX: function (arg, targetID) { if (!targetID) { targetID = 0; } return ((convertTo.canvasX(self.targetList[targetID].diameter) / 100) * arg + self.gap[targetID].left + self.transX) * self.scale; }, pxY: function (arg, targetID) { if (!targetID) { targetID = 0; } // Attention: converting the target diameter using the x-axe; // otherwise an error will occur return ((convertTo.canvasX(self.targetList[targetID].diameter) / 100) * arg + self.gap[targetID].top + self.transY) * self.scale; }, canvasX: function (arg, targetDiameter) { if (!targetDiameter) { targetDiameter = 100; } if (!converterCacheCanvas.x[targetDiameter]) { converterCacheCanvas.x[targetDiameter] = {}; } var tmpCache = converterCacheCanvas.x[targetDiameter]; if (!tmpCache[arg]) { tmpCache[arg] = self.width / 100 * targetDiameter / 100 * arg; } return tmpCache[arg]; }, canvasY: function (arg, targetDiameter) { if (!targetDiameter) { targetDiameter = 100; } if (!converterCacheCanvas.y[targetDiameter]) { converterCacheCanvas.y[targetDiameter] = {}; } var tmpCache = converterCacheCanvas.y[targetDiameter]; if (!tmpCache[arg]) { tmpCache[arg] = self.height / 100 * targetDiameter / 100 * arg; } return tmpCache[arg]; } }; };
{ "content_hash": "e55eb9d0f1ae82304d279991072b6f94", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 74, "avg_line_length": 21.372340425531913, "alnum_prop": 0.6445993031358885, "repo_name": "archer96/archerTarget.js", "id": "2a10f1b692784933bc647cce9da73a5580973573", "size": "2010", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/lib/initConverter.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2642" }, { "name": "JavaScript", "bytes": "459068" }, { "name": "PHP", "bytes": "936" } ], "symlink_target": "" }
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class admin_transaction extends CI_Controller { var $member_id; var $user; function __construct() { # code... parent::__construct(); if($this->nativesession->get( 'is_gan_admin_logged_in' ) == FALSE) { redirect(base_url('admin/login' )); } // $this->nativesession->set( 'gan_admin_login_map', $this->uri->segment( 1 ) ); $this->load->model(array('admin_transaction_model', 'profile_model')); $this->load->helper('string'); $this->load->helper(array('form', 'url')); $this->load->library('form_validation'); $this->member_id = $this->nativesession->get('member_id'); $this->user = $this->profile_model->get_profile_details($this->nativesession->get('member_code')); } function index() { $breadcrums = array( 'Transaction Requests' => '' ); $data = array( 'breadcrums' => $breadcrums, 'title' => 'Transaction Requests', 'subtitle' => 'manage Request', 'user' => $this->user ); $this->template ->set_partial('more_css', 'admin/ewallet_css') ->set_partial('more_js', 'admin/ewallet_js') ->set_layout('template_admin') ->build('admin/transaction_request', $data); } function listings() { $this->load->model('help_model'); $search = (isset($_GET['sSearch']) ? $_GET['sSearch']: null); // $iTotalRecords = $this->help_model->get_max_pages($search); $iTotalRecords = 5; $iDisplayLength = intval($_GET['iDisplayLength']); $iDisplayLength = $iDisplayLength < 0 ? $iTotalRecords : $iDisplayLength; $iDisplayStart = intval($_GET['iDisplayStart']); $sEcho = intval($_GET['sEcho']); $recs = array(); // $recs = $this->help_model->show_help($iDisplayStart, $iDisplayLength, $search); $records = array(); $records["aaData"] = array(); $end = $iDisplayStart + $iDisplayLength; /* foreach($recs as $rows){ $items = array(); $items[] = $rows['title']; $items[] = $rows['title']; $items[] = $rows['title']; $items[] = $rows['category_name']; $items[] = $action; $records["aaData"][] = $items; } */ for($i = 0; $i <= $end; $i++){ $action = ""; $action .= ' <a href="#" data-id="0" class="btn btn-xs blue btn-editable"><i class="fa fa-pencil"></i> Process</a>'; $items = array(); $items[] = '01/'.$i.'/2014'; $items[] = '123456789'; $items[] = 'Wallet Transfer'; $items[] = $i . '.00'; $items[] = $action; $records["aaData"][] = $items; } $records["sEcho"] = $sEcho; $records["iTotalRecords"] = $iTotalRecords; $records["iTotalDisplayRecords"] = $iTotalRecords; echo json_encode($records); } } ?>
{ "content_hash": "b0706d828a942c45efbae38744ea4376", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 119, "avg_line_length": 23.376068376068375, "alnum_prop": 0.5765996343692871, "repo_name": "kobe8bird/gan", "id": "fef76e5abab99c482a927f5feb6ac6f18907a800", "size": "2735", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/controllers/admin/admin_transaction.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "460" }, { "name": "HTML", "bytes": "309813" }, { "name": "JavaScript", "bytes": "31633" }, { "name": "PHP", "bytes": "2261888" } ], "symlink_target": "" }
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); ?> <section class="content-header"> <h1> <?= wpn_lang('module_title') ?> <small><?= wpn_lang('module_description') ?></small> </h1> <ol class="breadcrumb"> <li><a href="<?= site_url('admin/dashboard'); ?>"><i class="fa fa-dashboard"></i> <?= wpn_lang('wpn_menu_dashboard') ?></a></li> <li><i class="fa fa-cog"></i> <?= anchor('admin/developers', wpn_lang('module_title')); ?></li> <li><i class="fa fa-cog"></i> <?= wpn_lang('module_backup_list') ?></li> </ol> </section> <section class="content"> <div class="box"> <div class="box-header with-border"> <h3 class="box-title"><?= wpn_lang('module_backup_list') ?></h3> <div class="box-tools pull-right"> <?php if($compatible) echo anchor('admin/developers/backups/1', glyphicon('plus-sign') . wpn_lang('wpn_bot_new'), array('class' => 'btn btn-sm btn-primary')); else echo '<span class="text-danger">'.wpn_lang('msg_compatibility').'</span>'; ?> </div> </div> <div class="box-body"> <div class="table-responsive"> <div class="container-fluid"> <?= $listagem; ?> </div> </div> </div> </div> </section>
{ "content_hash": "a50bf072f0cf05f7761458a29b4fdd8e", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 157, "avg_line_length": 40.30555555555556, "alnum_prop": 0.4879393521709166, "repo_name": "elieldepaula/wpanel", "id": "1496fd96d52647b136324eb9b980e8e827358c62", "size": "1451", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "app/modules/admin/views/developers/backups.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1059" }, { "name": "CSS", "bytes": "664811" }, { "name": "HTML", "bytes": "1719392" }, { "name": "JavaScript", "bytes": "2191679" }, { "name": "PHP", "bytes": "2856544" } ], "symlink_target": "" }
import { RawDataWrapper } from "System/Base/Wrapper"; import { kcsapi_mst_stype } from "System/Interfaces/Master/kcsapi_mst_ship"; import { IIdentifiable } from "System/Base/Interfaces/IIdentifiable"; export class ShipTypeInfo extends RawDataWrapper<kcsapi_mst_stype> implements IIdentifiable { public get Id(): number { return this.raw.api_id } public get SortId(): number { return this.raw.api_sortno } public get Name(): string { return this.raw.api_name } public get RepairMultiply(): number { return this.raw.api_scnt } constructor(api_data: kcsapi_mst_stype) { super(api_data); } }
{ "content_hash": "1e52f8492b51eb0e8831317a74b9b8dc", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 93, "avg_line_length": 39.86666666666667, "alnum_prop": 0.7474916387959866, "repo_name": "WolfgangKurz/BeerViewer", "id": "938965b60b5bcbd99ae10c391c4e4795d0f009ad", "size": "598", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "WindowFrame/source/System/Master/Wrappers/ShipTypeInfo.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "214733" }, { "name": "CSS", "bytes": "34822" }, { "name": "HTML", "bytes": "29833" }, { "name": "JavaScript", "bytes": "2429" }, { "name": "PowerShell", "bytes": "2019" }, { "name": "TypeScript", "bytes": "196318" } ], "symlink_target": "" }
package org.bridj.util; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.junit.Test; /** * * @author ochafik */ public class BytecodeAnalyzerTest { public static class MyStruct { int a, b, c; public static class SubStruct { int sa, sb, sc; public native void subNative(); } public static class SubStructDeriv extends SubStruct { int sa2, sb2, sc2; public native void subSubNative(); } } @Test public void testFields() throws IOException { assertEquals(Arrays.asList("a", "b", "c"), BytecodeAnalyzer.getFieldNames(MyStruct.class, Object.class)); assertEquals(Arrays.asList("sa", "sb", "sc"), BytecodeAnalyzer.getFieldNames(MyStruct.SubStruct.class, Object.class)); assertEquals(Arrays.asList("sa2", "sb2", "sc2"), BytecodeAnalyzer.getFieldNames(MyStruct.SubStructDeriv.class, MyStruct.SubStructDeriv.class)); assertEquals(Arrays.asList("sa", "sb", "sc", "sa2", "sb2", "sc2"), BytecodeAnalyzer.getFieldNames(MyStruct.SubStructDeriv.class, Object.class)); List<String[]> sigs = BytecodeAnalyzer.getNativeMethodSignatures(MyStruct.SubStructDeriv.class); assertEquals(2, sigs.size()); assertEquals("subNative", sigs.get(0)[1]); assertEquals("subSubNative", sigs.get(1)[1]); } @Test public void testMethods() throws IOException { assertEquals(Arrays.asList("<init>"), BytecodeAnalyzer.getMethodNames(MyStruct.class, Object.class)); } }
{ "content_hash": "199d6089b1e4d8d50bdd4194c5cc008d", "timestamp": "", "source": "github", "line_count": 48, "max_line_length": 152, "avg_line_length": 34.375, "alnum_prop": 0.6563636363636364, "repo_name": "twitwi/BridJ", "id": "828f42c1dd667963fda13fd70f8dc5fd49dd470e", "size": "3356", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/test/java/org/bridj/util/BytecodeAnalyzerTest.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "7749" }, { "name": "Batchfile", "bytes": "5356" }, { "name": "C", "bytes": "156971" }, { "name": "C++", "bytes": "61083" }, { "name": "Java", "bytes": "1584908" }, { "name": "Makefile", "bytes": "7030" }, { "name": "Objective-C", "bytes": "9798" }, { "name": "Shell", "bytes": "30305" } ], "symlink_target": "" }
namespace Packets { namespace Baal { DECLARE_PACKET_BAAL_BEGIN(BaalAuthReply, 0x02) uint result; DECLARE_PACKET_BAAL_END() } } #endif // _BAALAUTHREPLY_H_
{ "content_hash": "b8d7c1a95e4eacf5f0f07cea5848b2f2", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 48, "avg_line_length": 15.090909090909092, "alnum_prop": 0.7048192771084337, "repo_name": "soarqin/blitzd", "id": "a1be228a71be41bd89a8dd486276e5ee986f8130", "size": "244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "blitzd/packets/baal/BaalAuthReply.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "6110496" }, { "name": "C++", "bytes": "347978" }, { "name": "Lua", "bytes": "4611" }, { "name": "Objective-C", "bytes": "30562" } ], "symlink_target": "" }
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-example98-jquery</title> <script src="../../components/jquery-1.10.2/jquery.js"></script> <script src="../../../angular.js"></script> <script src="script.js"></script> </head> <body ng-app="formExample"> <div ng-controller="Controller"> <form name="form" class="css-form" novalidate> Name: <input type="text" ng-model="user.name" name="uName" required /><br /> E-mail: <input type="email" ng-model="user.email" name="uEmail" required/><br /> <div ng-show="form.uEmail.$dirty && form.uEmail.$invalid">Invalid: <span ng-show="form.uEmail.$error.required">Tell us your email.</span> <span ng-show="form.uEmail.$error.email">This is not a valid email.</span> </div> Gender: <input type="radio" ng-model="user.gender" value="male" />male <input type="radio" ng-model="user.gender" value="female" />female<br /> <input type="checkbox" ng-model="user.agree" name="userAgree" required /> I agree: <input ng-show="user.agree" type="text" ng-model="user.agreeSign" required /><br /> <div ng-show="!user.agree || !user.agreeSign">Please agree and sign.</div> <button ng-click="reset()" ng-disabled="isUnchanged(user)">RESET</button> <button ng-click="update(user)" ng-disabled="form.$invalid || isUnchanged(user)">SAVE</button> </form> </div> </body> </html>
{ "content_hash": "fbe871cec9f5e3ded697254945cdadc3", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 82, "avg_line_length": 36.609756097560975, "alnum_prop": 0.6149233844103931, "repo_name": "maelalan/planch", "id": "78bb99a52ec8805b20a673e57cc2ea1de23434b8", "size": "1501", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "vendor/assets/javascripts/docs/examples/example-example98/index-jquery.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3377" }, { "name": "CoffeeScript", "bytes": "1849" }, { "name": "JavaScript", "bytes": "715" }, { "name": "Ruby", "bytes": "56950" }, { "name": "Shell", "bytes": "1749" } ], "symlink_target": "" }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping> <!-- Created by the Middlegen Hibernate plugin 2.1 http://boss.bekk.no/boss/middlegen/ http://www.hibernate.org/ --> <class name="com.sjc.cc.entity.TccIpConfigInfo" table="T_CC_IP_CONFIG_INFO"> <id name="ipConfigId" type="java.lang.Long" column="IP_CONFIG_ID"> <generator class="identity" /> </id> <property name="ipType" type="java.lang.String" column="IP_TYPE" length="100" /> <property name="usedFlag" type="java.lang.String" column="USED_FLAG" length="2" /> <property name="ipAddress" type="java.lang.String" column="IP_ADDRESS" length="100" /> <property name="remark" type="java.lang.String" column="REMARK" length="3000" /> <property name="name" type="java.lang.String" column="NAME" length="100" /> <property name="memo" type="java.lang.String" column="MEMO" length="3000" /> <property name="crtUserId" type="java.lang.Long" column="CRT_USER_ID" length="10" /> <property name="crtDttm" type="java.util.Date" column="CRT_DTTM" length="7" /> <property name="lastuptDttm" type="java.util.Date" column="LASTUPT_DTTM" length="7" /> <property name="lastuptUserId" type="java.lang.Long" column="LASTUPT_USER_ID" length="10" /> <property name="enableFlg" type="java.lang.String" column="ENABLE_FLG" length="1" /> <!-- Associations --> <!-- bi-directional one-to-many association to TccPhysiscResourceInfo --> <set name="tccPhysiscResourceInfos" lazy="true" inverse="true" cascade="none"> <key> <column name="IP_CONFIG_ID" /> </key> <one-to-many class="com.sjc.cc.entity.TccPhysiscResourceInfo" /> </set> <!-- bi-directional one-to-many association to TccConfigAssApplycase --> <set name="tccConfigAssApplycases" lazy="true" inverse="true" cascade="none"> <key> <column name="IP_CONFIG_ID" /> </key> <one-to-many class="com.sjc.cc.entity.TccConfigAssApplycase" /> </set> <!-- bi-directional one-to-many association to TccApplyedHostinfo --> <set name="tccApplyedHostinfos" lazy="true" inverse="true" cascade="none"> <key> <column name="IP_CONFIG_ID" /> </key> <one-to-many class="com.sjc.cc.entity.TccApplyedHostinfo" /> </set> </class> </hibernate-mapping>
{ "content_hash": "b05fa650642e0e45bbff991dbbd74dbb", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 75, "avg_line_length": 33.17333333333333, "alnum_prop": 0.6463022508038585, "repo_name": "AfricaRegex/SjcProduct", "id": "0aabd175cb9341ce9af5ef09165f0dd660529df7", "size": "2488", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SjcProject/src/com/sjc/cc/entity/hbm/TccIpConfigInfo.hbm.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1927361" }, { "name": "HTML", "bytes": "1917494" }, { "name": "Java", "bytes": "5927481" }, { "name": "JavaScript", "bytes": "5379574" } ], "symlink_target": "" }
require 'rspec/core/rake_task' RSpec::Core::RakeTask.new :default do |spec| spec.pattern = './spec/**/*_spec.rb' end # Shortcut to skip the adapter specs, and run only with the basic PG # connection. I use this occasionally to make sure ActiveRecord isn't loaded, # so any accidental Rails-isms are caught. RSpec::Core::RakeTask.new :pg do |spec| spec.pattern = './spec/unit/*_spec.rb' end
{ "content_hash": "1e35977c15f192725dffdcf1e22a8408", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 77, "avg_line_length": 33, "alnum_prop": 0.7196969696969697, "repo_name": "brandur/que", "id": "d8f9b479c4642dd5019fcba76c39ade1b6a6f127", "size": "396", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "tasks/rspec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "98998" } ], "symlink_target": "" }
using System; using System.Linq; namespace AcademyPopcorn { public class IndestructibleBlock : Block { public const char Symbol = '|'; public IndestructibleBlock(MatrixCoords upperLeft) : base(upperLeft) { this.body[0, 0] = IndestructibleBlock.Symbol; } public override void RespondToCollision(CollisionData collisionData) { //base.RespondToCollision(collisionData); } } }
{ "content_hash": "3b7e0a77a72926104296b9b0f8c72756", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 76, "avg_line_length": 22.857142857142858, "alnum_prop": 0.6166666666666667, "repo_name": "TelerikAcademy/flextry-Telerik-Academy", "id": "be8775a31d51a6b12a3db66a913bfe397fd8495f", "size": "482", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "Programming with C#/3. C# Object-Oriented Programming/08. OOP Practical Workshop - Academy Popcorn/AcademyPopcorn/AcademyPopcorn/IndestructibleBlock.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "102569" }, { "name": "Batchfile", "bytes": "99" }, { "name": "C#", "bytes": "7915135" }, { "name": "C++", "bytes": "71174" }, { "name": "CSS", "bytes": "428966" }, { "name": "CoffeeScript", "bytes": "290" }, { "name": "HTML", "bytes": "499757" }, { "name": "JavaScript", "bytes": "2446339" }, { "name": "PHP", "bytes": "85835" }, { "name": "SQLPL", "bytes": "941" }, { "name": "Shell", "bytes": "37" }, { "name": "Smalltalk", "bytes": "1146" }, { "name": "TypeScript", "bytes": "11347" }, { "name": "XSLT", "bytes": "1129" } ], "symlink_target": "" }