text
stringlengths
2
1.04M
meta
dict
<?php namespace PDepend\Source\AST; use PDepend\Source\ASTVisitor\ASTVisitor; use PDepend\Util\Cache\CacheDriver; /** * This class provides an interface to a single source file. * * @copyright 2008-2017 Manuel Pichler. All rights reserved. * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ class ASTCompilationUnit extends AbstractASTArtifact { /** * The internal used cache instance. * * @var \PDepend\Util\Cache\CacheDriver * @since 0.10.0 */ protected $cache = null; /** * The unique identifier for this function. * * @var string */ protected $id = null; /** * The source file name/path. * * @var string */ protected $fileName = null; /** * The comment for this type. * * @var string */ protected $comment = null; /** * The files start line. This property must always have the value <em>1</em>. * * @var integer * @since 0.10.0 */ protected $startLine = 0; /** * The files end line. * * @var integer * @since 0.10.0 */ protected $endLine = 0; /** * List of classes, interfaces and functions that parsed from this file. * * @var \PDepend\Source\AST\AbstractASTArtifact[] * @since 0.10.0 */ protected $childNodes = array(); /** * Was this file instance restored from the cache? * * @var boolean * @since 0.10.0 */ protected $cached = false; /** * Normalized code in this file. * * @var string */ private $source = null; /** * Constructs a new source file instance. * * @param string $fileName The source file name/path. */ public function __construct($fileName) { if (strpos($fileName, 'php://') === 0) { $this->fileName = $fileName; } elseif ($fileName !== null) { $this->fileName = realpath($fileName); } } /** * Returns the physical file name for this object. * * @return string */ public function getName() { return $this->fileName; } /** * Returns the physical file name for this object. * * @return string */ public function getFileName() { return $this->fileName; } /** * Returns a id for this code node. * * @return string */ public function getId() { return $this->id; } /** * Sets the unique identifier for this file instance. * * @param string $id Identifier for this file. * @return void * @since 0.9.12 */ public function setId($id) { $this->id = $id; } /** * Setter method for the used parser and token cache. * * @param \PDepend\Util\Cache\CacheDriver $cache * @return \PDepend\Source\AST\ASTCompilationUnit * @since 0.10.0 */ public function setCache(CacheDriver $cache) { $this->cache = $cache; return $this; } /** * Returns normalized source code with stripped whitespaces. * * @return array(integer=>string) */ public function getSource() { $this->readSource(); return $this->source; } /** * Returns an <b>array</b> with all tokens within this file. * * @return array(array) */ public function getTokens() { return (array) $this->cache ->type('tokens') ->restore($this->getId()); } /** * Sets the tokens for this file. * * @param array(array) $tokens The generated tokens. * * @return void */ public function setTokens(array $tokens) { $this->cache ->type('tokens') ->store($this->getId(), $tokens); } /** * Adds a source item that was parsed from this source file. * * @param \PDepend\Source\AST\AbstractASTArtifact $artifact * @return void * @since 0.10.0 */ public function addChild(AbstractASTArtifact $artifact) { $this->childNodes[$artifact->getId()] = $artifact; } /** * Returns the start line number for this source file. For an existing file * this value must always be <em>1</em>, while it can be <em>0</em> for a * not existing dummy file. * * @return integer * @since 0.10.0 */ public function getStartLine() { if ($this->startLine === 0) { $this->readSource(); } return $this->startLine; } /** * Returns the start line number for this source file. For an existing file * this value must always be greater <em>0</em>, while it can be <em>0</em> * for a not existing dummy file. * * @return integer * @since 0.10.0 */ public function getEndLine() { if ($this->endLine === 0) { $this->readSource(); } return $this->endLine; } /** * This method will return <b>true</b> when this file instance was restored * from the cache and not currently parsed. Otherwise this method will return * <b>false</b>. * * @return boolean * @since 0.10.0 */ public function isCached() { return $this->cached; } /** * ASTVisitor method for node tree traversal. * * @param \PDepend\Source\ASTVisitor\ASTVisitor $visitor * @return void */ public function accept(ASTVisitor $visitor) { $visitor->visitCompilationUnit($this); } /** * The magic sleep method will be called by PHP's runtime environment right * before it serializes an instance of this class. This method returns an * array with those property names that should be serialized. * * @return array(string) * @since 0.10.0 */ public function __sleep() { return array( 'cache', 'childNodes', 'comment', 'endLine', 'fileName', 'startLine', 'id' ); } /** * The magic wakeup method will is called by PHP's runtime environment when * a serialized instance of this class was unserialized. This implementation * of the wakeup method restores the references between all parsed entities * in this source file and this file instance. * * @return void * @since 0.10.0 * @see \PDepend\Source\AST\ASTCompilationUnit::$childNodes */ public function __wakeup() { $this->cached = true; foreach ($this->childNodes as $childNode) { $childNode->setCompilationUnit($this); } } /** * Returns the string representation of this class. * * @return string */ public function __toString() { return ($this->fileName === null ? '' : $this->fileName); } /** * Reads the source file if required. * * @return void */ protected function readSource() { if ($this->source === null && (file_exists($this->fileName) || strpos($this->fileName, 'php://') === 0)) { $source = file_get_contents($this->fileName); $this->source = str_replace(array("\r\n", "\r"), "\n", $source); $this->startLine = 1; $this->endLine = substr_count($this->source, "\n") + 1; } } // Deprecated methods // @codeCoverageIgnoreStart /** * This method can be called by the PDepend runtime environment or a * utilizing component to free up memory. This methods are required for * PHP version < 5.3 where cyclic references can not be resolved * automatically by PHP's garbage collector. * * @return void * @since 0.9.12 * @deprecated Since 0.10.0 */ public function free() { fwrite(STDERR, __METHOD__ . ' is deprecated since version 0.10.0' . PHP_EOL); } // @codeCoverageIgnoreEnd }
{ "content_hash": "8b46ffb1e0cf6ee72ed1796bff93719a", "timestamp": "", "source": "github", "line_count": 345, "max_line_length": 114, "avg_line_length": 23.481159420289856, "alnum_prop": 0.5495617824959882, "repo_name": "AnttiKurittu/kirjuri", "id": "81aa641cfe6a5fb978d5134301d2b016551ada46", "size": "9920", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "vendor/pdepend/pdepend/src/main/php/PDepend/Source/AST/ASTCompilationUnit.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "577381" }, { "name": "HTML", "bytes": "1387360" }, { "name": "JavaScript", "bytes": "2179013" }, { "name": "PHP", "bytes": "208507" } ], "symlink_target": "" }
<div id="fixed_header" class="fixedHeaderContainer{% if include.alwayson %} visible{% endif %}"> <div class="headerWrapper wrapper"> <header> <a href="{{ '/' | absolute_url }}"> <img src="{{ '/static/logo.svg' | relative_url }}"> <h2>{{ site.title }}</h2> </a> <div class="navigationWrapper navigationFull" id="flat_nav"> <nav class="navigation"> <ul> {% for item in site.data.nav %} <li class="navItem{% if page.collection == item.category or page.category == item.category %} navItemActive{% endif %}"> {% if item.category == "external" %} <a href="{{ item.href }}">{{ item.title }}</a> {% else %} <a href="{{ item.href | relative_url }}">{{ item.title }}</a> {% endif %} </li> {% endfor %} {% if site.searchconfig %} {% include nav_search.html inputselector="search_input" %} {% endif %} </ul> </nav> </div> <div class="navigationWrapper navigationSlider" id="navigation_wrap"> {% include nav/header_nav.html %} </div> </header> </div> </div>
{ "content_hash": "34c226bd852a794eebfabaf158358b79", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 134, "avg_line_length": 38.40625, "alnum_prop": 0.49145646867371845, "repo_name": "facebook/hack-codegen", "id": "fd7d21ea85fbb717a34ca008d6734c77bec0bdd8", "size": "1229", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/_includes/nav.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Hack", "bytes": "178382" } ], "symlink_target": "" }
from django.db.models import Q, Sum from django.db.models.deletion import ProtectedError from django.db.utils import IntegrityError from django.forms.models import modelform_factory from django.test import TestCase, skipIfDBFeature from .models import ( A, Address, B, Board, C, CharLink, Company, Contact, Content, D, Developer, Guild, HasLinkThing, Link, Node, Note, OddRelation1, OddRelation2, Organization, Person, Place, Related, Restaurant, Tag, Team, TextLink, ) class GenericRelationTests(TestCase): def test_inherited_models_content_type(self): """ GenericRelations on inherited classes use the correct content type. """ p = Place.objects.create(name="South Park") r = Restaurant.objects.create(name="Chubby's") l1 = Link.objects.create(content_object=p) l2 = Link.objects.create(content_object=r) self.assertEqual(list(p.links.all()), [l1]) self.assertEqual(list(r.links.all()), [l2]) def test_reverse_relation_pk(self): """ The correct column name is used for the primary key on the originating model of a query. See #12664. """ p = Person.objects.create(account=23, name='Chef') Address.objects.create(street='123 Anywhere Place', city='Conifer', state='CO', zipcode='80433', content_object=p) qs = Person.objects.filter(addresses__zipcode='80433') self.assertEqual(1, qs.count()) self.assertEqual('Chef', qs[0].name) def test_charlink_delete(self): oddrel = OddRelation1.objects.create(name='clink') CharLink.objects.create(content_object=oddrel) oddrel.delete() def test_textlink_delete(self): oddrel = OddRelation2.objects.create(name='tlink') TextLink.objects.create(content_object=oddrel) oddrel.delete() def test_q_object_or(self): """ SQL query parameters for generic relations are properly grouped when OR is used (#11535). In this bug the first query (below) works while the second, with the query parameters the same but in reverse order, does not. The issue is that the generic relation conditions do not get properly grouped in parentheses. """ note_contact = Contact.objects.create() org_contact = Contact.objects.create() Note.objects.create(note='note', content_object=note_contact) org = Organization.objects.create(name='org name') org.contacts.add(org_contact) # search with a non-matching note and a matching org name qs = Contact.objects.filter(Q(notes__note__icontains=r'other note') | Q(organizations__name__icontains=r'org name')) self.assertIn(org_contact, qs) # search again, with the same query parameters, in reverse order qs = Contact.objects.filter( Q(organizations__name__icontains=r'org name') | Q(notes__note__icontains=r'other note')) self.assertIn(org_contact, qs) def test_join_reuse(self): qs = Person.objects.filter( addresses__street='foo' ).filter( addresses__street='bar' ) self.assertEqual(str(qs.query).count('JOIN'), 2) def test_generic_relation_ordering(self): """ Ordering over a generic relation does not include extraneous duplicate results, nor excludes rows not participating in the relation. """ p1 = Place.objects.create(name="South Park") p2 = Place.objects.create(name="The City") c = Company.objects.create(name="Chubby's Intl.") Link.objects.create(content_object=p1) Link.objects.create(content_object=c) places = list(Place.objects.order_by('links__id')) def count_places(place): return len([p for p in places if p.id == place.id]) self.assertEqual(len(places), 2) self.assertEqual(count_places(p1), 1) self.assertEqual(count_places(p2), 1) def test_target_model_is_unsaved(self): """Test related to #13085""" # Fails with another, ORM-level error dev1 = Developer(name='Joe') note = Note(note='Deserves promotion', content_object=dev1) with self.assertRaises(IntegrityError): note.save() def test_target_model_len_zero(self): """ Saving a model with a GenericForeignKey to a model instance whose __len__ method returns 0 (Team.__len__() here) shouldn't fail (#13085). """ team1 = Team.objects.create(name='Backend devs') note = Note(note='Deserve a bonus', content_object=team1) note.save() def test_target_model_bool_false(self): """ Saving a model with a GenericForeignKey to a model instance whose __bool__ method returns False (Guild.__bool__() here) shouldn't fail (#13085). """ g1 = Guild.objects.create(name='First guild') note = Note(note='Note for guild', content_object=g1) note.save() @skipIfDBFeature('interprets_empty_strings_as_nulls') def test_gfk_to_model_with_empty_pk(self): """Test related to #13085""" # Saving model with GenericForeignKey to model instance with an # empty CharField PK b1 = Board.objects.create(name='') tag = Tag(label='VP', content_object=b1) tag.save() def test_ticket_20378(self): # Create a couple of extra HasLinkThing so that the autopk value # isn't the same for Link and HasLinkThing. hs1 = HasLinkThing.objects.create() hs2 = HasLinkThing.objects.create() hs3 = HasLinkThing.objects.create() hs4 = HasLinkThing.objects.create() l1 = Link.objects.create(content_object=hs3) l2 = Link.objects.create(content_object=hs4) self.assertSequenceEqual(HasLinkThing.objects.filter(links=l1), [hs3]) self.assertSequenceEqual(HasLinkThing.objects.filter(links=l2), [hs4]) self.assertSequenceEqual(HasLinkThing.objects.exclude(links=l2), [hs1, hs2, hs3]) self.assertSequenceEqual(HasLinkThing.objects.exclude(links=l1), [hs1, hs2, hs4]) def test_ticket_20564(self): b1 = B.objects.create() b2 = B.objects.create() b3 = B.objects.create() c1 = C.objects.create(b=b1) c2 = C.objects.create(b=b2) c3 = C.objects.create(b=b3) A.objects.create(flag=None, content_object=b1) A.objects.create(flag=True, content_object=b2) self.assertSequenceEqual(C.objects.filter(b__a__flag=None), [c1, c3]) self.assertSequenceEqual(C.objects.exclude(b__a__flag=None), [c2]) def test_ticket_20564_nullable_fk(self): b1 = B.objects.create() b2 = B.objects.create() b3 = B.objects.create() d1 = D.objects.create(b=b1) d2 = D.objects.create(b=b2) d3 = D.objects.create(b=b3) d4 = D.objects.create() A.objects.create(flag=None, content_object=b1) A.objects.create(flag=True, content_object=b1) A.objects.create(flag=True, content_object=b2) self.assertSequenceEqual(D.objects.exclude(b__a__flag=None), [d2]) self.assertSequenceEqual(D.objects.filter(b__a__flag=None), [d1, d3, d4]) self.assertSequenceEqual(B.objects.filter(a__flag=None), [b1, b3]) self.assertSequenceEqual(B.objects.exclude(a__flag=None), [b2]) def test_extra_join_condition(self): # A crude check that content_type_id is taken in account in the # join/subquery condition. self.assertIn("content_type_id", str(B.objects.exclude(a__flag=None).query).lower()) # No need for any joins - the join from inner query can be trimmed in # this case (but not in the above case as no a objects at all for given # B would then fail). self.assertNotIn(" join ", str(B.objects.exclude(a__flag=True).query).lower()) self.assertIn("content_type_id", str(B.objects.exclude(a__flag=True).query).lower()) def test_annotate(self): hs1 = HasLinkThing.objects.create() hs2 = HasLinkThing.objects.create() HasLinkThing.objects.create() b = Board.objects.create(name=str(hs1.pk)) Link.objects.create(content_object=hs2) link = Link.objects.create(content_object=hs1) Link.objects.create(content_object=b) qs = HasLinkThing.objects.annotate(Sum('links')).filter(pk=hs1.pk) # If content_type restriction isn't in the query's join condition, # then wrong results are produced here as the link to b will also match # (b and hs1 have equal pks). self.assertEqual(qs.count(), 1) self.assertEqual(qs[0].links__sum, link.id) link.delete() # Now if we don't have proper left join, we will not produce any # results at all here. # clear cached results qs = qs.all() self.assertEqual(qs.count(), 1) # Note - 0 here would be a nicer result... self.assertIs(qs[0].links__sum, None) # Finally test that filtering works. self.assertEqual(qs.filter(links__sum__isnull=True).count(), 1) self.assertEqual(qs.filter(links__sum__isnull=False).count(), 0) def test_filter_targets_related_pk(self): HasLinkThing.objects.create() hs2 = HasLinkThing.objects.create() link = Link.objects.create(content_object=hs2) self.assertNotEqual(link.object_id, link.pk) self.assertSequenceEqual(HasLinkThing.objects.filter(links=link.pk), [hs2]) def test_editable_generic_rel(self): GenericRelationForm = modelform_factory(HasLinkThing, fields='__all__') form = GenericRelationForm() self.assertIn('links', form.fields) form = GenericRelationForm({'links': None}) self.assertTrue(form.is_valid()) form.save() links = HasLinkThing._meta.get_field('links') self.assertEqual(links.save_form_data_calls, 1) def test_ticket_22998(self): related = Related.objects.create() content = Content.objects.create(related_obj=related) Node.objects.create(content=content) # deleting the Related cascades to the Content cascades to the Node, # where the pre_delete signal should fire and prevent deletion. with self.assertRaises(ProtectedError): related.delete() def test_ticket_22982(self): place = Place.objects.create(name='My Place') self.assertIn('GenericRelatedObjectManager', str(place.links)) def test_filter_on_related_proxy_model(self): place = Place.objects.create() Link.objects.create(content_object=place) self.assertEqual(Place.objects.get(link_proxy__object_id=place.id), place)
{ "content_hash": "f6fec9859e88ee88252f9309a0aed015", "timestamp": "", "source": "github", "line_count": 253, "max_line_length": 92, "avg_line_length": 43.13833992094862, "alnum_prop": 0.6367051493494594, "repo_name": "tomchristie/django", "id": "9add025a46a2a926b1039394fedac62d64f40021", "size": "10914", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "tests/generic_relations_regress/tests.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "55975" }, { "name": "HTML", "bytes": "219349" }, { "name": "JavaScript", "bytes": "252940" }, { "name": "Makefile", "bytes": "125" }, { "name": "Python", "bytes": "12092827" }, { "name": "Shell", "bytes": "809" }, { "name": "Smarty", "bytes": "130" } ], "symlink_target": "" }
#ifndef WCL_SERIAL_H #define WCL_SERIAL_H #include <sys/types.h> #include <termios.h> #include <string> #include <wcl/api.h> #include "IODevice.h" namespace wcl { /** * This class implements RS232 processing under unix using POSIX standards, * with support for a few non compliant posix features. If you need strict POSIX * compliance, define _POSIX_SOURCE_ * * Note: http://www.easysw.com/~mike/serial/serial.html is a great reference for * RS232 information. http://digilander.libero.it/robang/rubrica/serial.htm has * details about the meanings of the different termio options * * At the time of writing there was 3 different ways to do serial these are: * o Termios * o Termio * o pre termio (really adhoc) * * This class implements RS232 support via termios * * RS232 Has the following Signals/Lines * o GND - Logic Ground * Needed for operation ( A referance voltage for other signals) * o TXD - Transmitted data * Transmit data from PC->Device, either 1 (mark) or 0 (space) * o RXD - Received data * Received data from Device->PC, 1(mark), 0 (space) * o DCD - Data Carrier Detect * Indicates the device connected is online, not always used * o DTR - Data Terminal Ready * Indicates the computer is ready to send to the device, optional * o CTS - Clear To Send * Received from the device, indicates the device is ready to receive * data from the PC. (optional) * o RTS - Request To Send * Signal line indicating if the device is allowed to send to the pc. * (optional) * o RING - Incomming Call * Singal line indicating there is an incomming connection (used by * modems) * * CTS/RTS are used for hardware flow control and can be ignored. Most things * however make use of them. So the minium a cable needs is GND,TXD,RXD. However * the normal to include flow control: GND, TXD, RXD, CTS, RTS. Modems normally * also include the RING Signal line. * */ class WCL_API Serial : public IODevice { public: enum StopBits { ONE=0, TWO=CSTOPB }; enum Parity { NONE = 0, //Enabling Parity (E,O,S) will enable the parity ODD = 1, //checking & parity bit stripping EVEN = 2, //use extra params to setParity to SPACE= 3 }; //disable checking/stripping enum DataBits { DB_FIVE = CS5, DB_SIX = CS6, DB_SEVEN = CS7, DB_EIGHT = CS8 }; // 8 is the norm enum BaudRate { BAUD_0 = B0, // Drops DTR line BAUD_300 = B300, BAUD_1200 = B1200, BAUD_2400 = B2400, BAUD_4800 = B4800, BAUD_9600 = B9600, #ifdef B14400 BAUD_14400 = B14400, // Not all O/S support 14400, so only use it if supported #endif BAUD_19200 = B19200, BAUD_38400 = B38400, BAUD_57600 = B57600, #ifndef _POSIX_SOURCE_ // Note these speeds are not POSIX compliant // Speeds above 115200 are not supported by standard PC // hardware BAUD_115200 = B115200, BAUD_230400 = B230400, #ifdef B460800 BAUD_460800 = B460800, #endif #ifdef B921600 BAUD_921600 = B921600 #endif #endif }; enum FlowControl { DISABLED = 0, RTSCTS = 1, // Hardware (RTS/CTS lines) XONXOFF = 2, // Software RTSCTS_XONXOFF= 3 // HW & Software }; enum InputMode { RAW, // Character mode LINE }; // Line mode // The lines/Signal listed below can be used with the // setLine and getSignal methods to individually get // the state of a signal. The enum numbers relate to the pin of a 9 pin DSub // serial connector. The comments below indicate the equivilant 25 pin DSUB enum Line { TXD = 3, // OUT Signal (Transmit data) D25 pin 2 DTR = 4, // OUT Signal (Data Terminal Ready) D25 pin 20 //GND = 5 // Ground, Not Usable D25 pin 7 RTS = 7, // OUT Signal (Request To Send) D25 pin 4 }; enum Signal { DCD = 1, // IN Signal (Data Carrier Detect) D25 pin 8 //RXD = 2, // IN Signal (Received data) D25 pin 3 // This pin logic state can't be detected by most pc // hardware as the uart doesn't provide gpio // access to the line. DSR = 4, // IN Signal (Data Send Ready) D25 pin 6 CTS = 8, // IN Signal (Clear To Send) D25 pin 5 RI = 16, // IN Signal (Ring Indicator) D25 pin 22 }; }; Serial(); virtual ~Serial(); bool open( const char *device, const BaudRate, const DataBits = DB_EIGHT , const Parity = NONE, const StopBits = ONE, const InputMode = RAW, const FlowControl = DISABLED, const BlockingMode = BLOCKING, const Flush = INPUT, const Signal= (const Signal)0 ); // Set this to DCD to NOT ignore the DCD signal virtual bool flush( const Flush = BOTH ); // Clear fifos, don't write it bool drain(); // Wait for data to be written bool close(bool = true); // close & optionall restores preopen state virtual ssize_t read ( void *buffer, size_t size ); virtual ssize_t write( const void *buffer, size_t size ); virtual ssize_t write( const std::string & ); virtual void writeUntil( void *buffer, const size_t size); virtual void readUntil(void *buffer, size_t size); virtual ssize_t getAvailableCount(); virtual bool isValid() const; BaudRate getBaudRate() const; BlockingMode getBlockingMode() const; StopBits getStopBits() const; Parity getParity() const; DataBits getDataBits() const; FlowControl getFlowControl() const; InputMode getInputMode() const; // When calling theses, check the return values. If // a call is not valid on the given port it will fail and return // false. virtual bool setBlockingMode( const BlockingMode ); bool setStopBits( const StopBits ); bool setParity( const Parity, const bool strip=true, const bool check=true, const bool mark=false ); bool setDataBits( const DataBits ); bool setBaudRate( const BaudRate ); bool setFlowControl( const FlowControl ); bool setInputMode( const InputMode ); // See Parity enum above for details about these bool getParityCheck() const; bool getParityMark() const; bool getParityStrip() const; // Set / Get the state of a particular signal bool setLine ( const Line, bool ); bool getSignal ( const Signal ); Signal getSignals(); // Attempt to determine the baud rate automatically bool scanBaudRate(); // Current baud rate scanner has fixed character/baudrate set bool scanBaudRate( const char = '\n', const BaudRate = (const BaudRate)( BAUD_1200 | BAUD_2400 | BAUD_4800 | BAUD_9600 #ifdef B14400 | BAUD_14400 #endif | BAUD_19200 | BAUD_38400 | BAUD_57600 #ifndef _POSIX_SOURCE_ | BAUD_115200 #endif ) ); // Get the actual file descriptor int operator *() const; private: int fd; Parity parity; InputMode input; BlockingMode blocking; FlowControl flow; bool applyImmediately; // original state of the port struct termios origstate; /* * Maintains the current state of the port * Consists of: * c_cflag - control options * c_lflag - line options * c_iflag - input options * c_oflag - ouput options * c_cc - control character * c_ispeed - input baudrate * c_ospeed - output baudrate */ struct termios currstate; bool apply(); bool applyParams( const struct termios &); // For now we prevent copying of the object // This is due to requiring locking on the port so // we don't get unknown states. - benjsc 20070118 Serial(const Serial &); Serial operator = (const Serial &); }; }; //namespace wcl #endif
{ "content_hash": "ae91091b4e6e099b612848e3369ed9e7", "timestamp": "", "source": "github", "line_count": 253, "max_line_length": 104, "avg_line_length": 31.675889328063242, "alnum_prop": 0.6275268280509109, "repo_name": "WearableComputerLab/LibWCL", "id": "47c97b34509a1063fc99d9909c0015f8f6690445", "size": "9401", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/wcl/rawports/Serial.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "3018630" }, { "name": "C++", "bytes": "3925718" }, { "name": "LLVM", "bytes": "3482" }, { "name": "Makefile", "bytes": "4555" }, { "name": "Python", "bytes": "186150" }, { "name": "QMake", "bytes": "386" }, { "name": "Shell", "bytes": "352991" } ], "symlink_target": "" }
package com.app.tvrecyclerview; import android.graphics.Color; import java.io.IOException; import java.io.InputStream; import java.util.Random; public class Utils { public static String inputStreamToString(InputStream inputStream) { try { byte[] bytes = new byte[inputStream.available()]; inputStream.read(bytes, 0, bytes.length); String json = new String(bytes); return json; } catch (IOException e) { return null; } } public static int getRandColor() { Random random = new Random(); return Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256)); } }
{ "content_hash": "5e224bb21a29819dac7c65bab3fd790c", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 94, "avg_line_length": 26.807692307692307, "alnum_prop": 0.6312769010043041, "repo_name": "henryblue/TvRecyclerView", "id": "b7081614ccd81ad139e2fabaa03a6d484c3456e5", "size": "697", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/app/tvrecyclerview/Utils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "151598" } ], "symlink_target": "" }
package nc.vo.lxt.pub.test; import junit.framework.TestCase; import nc.bs.lxt.pub.WSTool; import nc.vo.pub.BusinessException; public class WSToolTest extends TestCase { public WSToolTest(String name) { super(name); } public void testWSAuth() throws BusinessException { WSTool.callByHttpBasicAuth( "http://erpdev.crmsc.com.cn:8000/sap/bc/srt/rfc/sap/zws_fkdjk/206/zws_fkdjk/zws_fkdjk", getSoapMsg(), "zhoujs", "zhouman"); } private String getSoapMsg() { StringBuffer soap = new StringBuffer(); soap.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:urn=\"urn:sap-com:document:sap:soap:functions:mc-style\">"); soap.append(" <soapenv:Header/>"); soap.append(" <soapenv:Body>"); soap.append(" <urn:ZfiFkdjk>"); soap.append(" <!--Optional:-->"); soap.append(" <IAedat>"); soap.append(" <!--Zero or more repetitions:-->"); soap.append(" <item>"); soap.append(" <Sign>I</Sign>"); soap.append(" <Option>BT</Option>"); soap.append(" <Low>20130101</Low>"); soap.append(" <High>20131231</High>"); soap.append(" </item>"); soap.append(" </IAedat>"); soap.append(" <!--Optional:-->"); soap.append(" <IBukrs>"); soap.append(" <!--Zero or more repetitions:-->"); soap.append(" <item>"); soap.append(" <Sign>I</Sign>"); soap.append(" <Option>BT</Option>"); soap.append(" <Low>0001</Low>"); soap.append(" <High>2300</High>"); soap.append(" </item>"); soap.append(" </IBukrs>"); soap.append(" <OTab>"); soap.append(" </OTab>"); soap.append(" </urn:ZfiFkdjk>"); soap.append(" </soapenv:Body>"); soap.append("</soapenv:Envelope>"); return soap.toString(); } }
{ "content_hash": "bd3e0f94d7ba46fbf50576d6eb004a9e", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 159, "avg_line_length": 37.283018867924525, "alnum_prop": 0.5435222672064778, "repo_name": "isurgeli/nclxt", "id": "b0ef6e9a177dc64fc9a73eaa8e6b25efc102a62b", "size": "1976", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lxtpub63/Code/src/test/nc/vo/lxt/pub/test/WSToolTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "76599" }, { "name": "Visual Basic", "bytes": "2199" } ], "symlink_target": "" }
{% include thingmonk-header.html %} <div class="content"> <main id="mainContent" role="main" class="primary small-12 columns"> <div data-sticky-container> <div class="sticky" id="sticky-magellan" data-sticky data-margin-top="0" data-top-anchor="sections" data-sticky-on="large"> <div class="c-nav"> <nav data-magellan class="c-nav__nav"> <ul class="horizontal menu expanded"> <!-- <li class="c-nav__highlight"> <a href="/index.html#thingmonk"><span>Thingmonk</span> September 2016</a> </li> --> <li><a href="/index.html#about">About</a></li> <li><a href="/index.html#news">News</a></li> <li><a href="/index.html#speakers">Speakers</a></li> <li><a href="/index.html#sponsors">Sponsors</a></li> <li><a href="/index.html#agenda">Agenda</a></li> <li><a href="/index.html#buy">Buy tickets</a></li> <li><a href="/index.html#coc">Code of Conduct</a></li> </ul> </nav> </div> </div> </div> {{ content }} </main> </div> {% include thingmonk-footer.html %}
{ "content_hash": "8b17e107b9f775e1553541cbb4b4e85c", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 131, "avg_line_length": 37.935483870967744, "alnum_prop": 0.5340136054421769, "repo_name": "thingmonk/thingmonk.github.io", "id": "f588a5b9440da15f0c1bcccba4a5ae2e826b8066", "size": "1176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_layouts/thingmonk.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "156123" }, { "name": "HTML", "bytes": "72095" }, { "name": "JavaScript", "bytes": "3191" } ], "symlink_target": "" }
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute 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. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =head1 NAME Bio::EnsEMBL::Compara::RunnableDB::PairAligner::UcscChainFactory =head1 DESCRIPTION Effectively splits a UCSC chain file into smaller bits by using a seek position and the number of lines to be read, to allow for parallel processing =cut package Bio::EnsEMBL::Compara::RunnableDB::PairAligner::UcscChainFactory; use strict; use Bio::EnsEMBL::Utils::Exception qw(throw); use base ('Bio::EnsEMBL::Compara::RunnableDB::BaseRunnable'); ############################################################ =head2 fetch_input Title : fetch_input Usage : $self->fetch_input Returns : nothing Args : none =cut sub fetch_input { my( $self) = @_; #Read at least this many lines to the next chain my $step = $self->param('step'); #Open Ucsc chain file open(FILE, $self->param('chain_file')) or die ("Unable to open " . $self->param('chain_file')); my $seek_positions; my $prev_pos = 0; my $line_num = 1; my $first_chain = 1; # #Read through UCSC chain file. Store the position of the first chain tag #(prev_pos) and read $step lines and store the number of lines until you #reach the next chain tag ($line_num-1) # while (<FILE>) { my $curr_pos = tell(FILE); #current position in file if (/chain /) { if ($first_chain || $line_num >= $step) { my $pos_line; %$pos_line = ('pos' => $prev_pos, 'line' => $line_num-1); push @$seek_positions, $pos_line; $line_num = 1; $first_chain = 0; } } $prev_pos = $curr_pos; $line_num++; } #Store last position my $pos_line; %$pos_line = ('pos' => $prev_pos, 'line' => $line_num-1); push @$seek_positions, $pos_line; close FILE; for (my $index = 0; $index < (@$seek_positions-1); $index++) { my $seek_pos = $seek_positions->[$index]->{pos}; my $num_lines = $seek_positions->[$index+1]->{line}; my $output_id = "{seek_offset=>" . $seek_pos . ",num_lines=>" . $num_lines . "}"; $self->dataflow_output_id($output_id, 2); } } 1;
{ "content_hash": "94e57b39f456a5b8f133f47f0d5f2fa7", "timestamp": "", "source": "github", "line_count": 110, "max_line_length": 149, "avg_line_length": 26.927272727272726, "alnum_prop": 0.6448345712356516, "repo_name": "ckongEbi/ensembl-compara", "id": "4fddab395b058aaa7f42d8ed6c52ff02b3153498", "size": "2962", "binary": false, "copies": "1", "ref": "refs/heads/release/80", "path": "modules/Bio/EnsEMBL/Compara/RunnableDB/PairAligner/UcscChainFactory.pm", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "461" }, { "name": "Java", "bytes": "42153" }, { "name": "Perl", "bytes": "5553583" }, { "name": "Shell", "bytes": "6731" }, { "name": "Tcl", "bytes": "2577" } ], "symlink_target": "" }
<?php /** * DO NOT EDIT THIS FILE! * * This file was automatically generated from external sources. * * Any manual change here will be lost the next time the SDK * is updated. You've been warned! */ namespace DTS\eBaySDK\Test\ReturnManagement\Types; use DTS\eBaySDK\ReturnManagement\Types\EnumerationDetailType; class EnumerationDetailTypeTest extends \PHPUnit_Framework_TestCase { private $obj; protected function setUp() { $this->obj = new EnumerationDetailType(); } public function testCanBeCreated() { $this->assertInstanceOf('\DTS\eBaySDK\ReturnManagement\Types\EnumerationDetailType', $this->obj); } public function testExtendsBaseType() { $this->assertInstanceOf('\DTS\eBaySDK\Types\BaseType', $this->obj); } }
{ "content_hash": "95bfa664c59445e434f8ef6dd40d8332", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 105, "avg_line_length": 24.09090909090909, "alnum_prop": 0.70062893081761, "repo_name": "davidtsadler/ebay-sdk-php", "id": "dbf8194a466d39a6f8429d24e2d14cb4c093040e", "size": "795", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/ReturnManagement/Types/EnumerationDetailTypeTest.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "10944" }, { "name": "PHP", "bytes": "9958599" } ], "symlink_target": "" }
import Gaffer import GafferScene GafferScene.TweakPlug = Gaffer.TweakPlug GafferScene.TweaksPlug = Gaffer.TweaksPlug
{ "content_hash": "2ba4c619af4d14731ed6e6c1d0664f23", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 42, "avg_line_length": 23.6, "alnum_prop": 0.8559322033898306, "repo_name": "johnhaddon/gaffer", "id": "34b66ad5e213727152d8a4f6160ef3aa129ca433", "size": "1914", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "startup/GafferScene/tweakPlugCompatibility.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "5790" }, { "name": "C", "bytes": "61993" }, { "name": "C++", "bytes": "9571062" }, { "name": "CMake", "bytes": "85201" }, { "name": "GLSL", "bytes": "6208" }, { "name": "Python", "bytes": "10271481" }, { "name": "Ruby", "bytes": "419" }, { "name": "Shell", "bytes": "14389" } ], "symlink_target": "" }
const { readFileSync, writeFileSync, emptyDirSync } = require('fs-extra'); const glob = require('glob'); const { kebabCase } = require('lodash'); const DEST_DIR = 'docs'; const read = (file) => readFileSync(file, 'utf8'); const write = (file, contents) => writeFileSync(`${DEST_DIR}/${file}.md`, contents); const getTitle = (contents) => contents.match(/^#\s*(.*?)$/m) || []; const getSidebarTitle = (contents) => contents.match(/^<!--\s*(.*?)(?:\s*#([\w-]+))?\s*-->/) || []; const stripTitle = (contents) => contents.replace(/^#.*?$/m, ''); const markdownToDocusaurus = (contents) => contents.replace( /^>\s*\*\*(\w+):\*\*\s*(.*?)$/gm, (_, $1, $2) => `:::${$1.toLowerCase()}\n${$2}\n:::` ); const htmlToXml = (contents) => contents.replace(/<br>/g, '<br />'); const getEditUrl = (relativePath) => `https://github.com/styleguidist/react-styleguidist/edit/master/${relativePath.replace( '../docs', 'docs' )}`; const template = ({ id, title, sidebarLabel, editUrl, contents }) => `--- id: ${id} title: ${title} sidebar_label: ${sidebarLabel} custom_edit_url: ${getEditUrl(editUrl)} --- ${stripTitle(htmlToXml(markdownToDocusaurus(contents)))}`; emptyDirSync(DEST_DIR); console.log('Syncing docs...'); const docs = glob.sync('../docs/*.md'); docs.forEach((filepath) => { console.log(`👉 ${filepath}`); const contents = read(filepath); const [, title] = getTitle(contents); const [, sidebarLabel = title, customId] = getSidebarTitle(contents); const id = customId || kebabCase(sidebarLabel); write( id, template({ id, title, sidebarLabel, editUrl: filepath, contents, }) ); });
{ "content_hash": "3b8c986384953c405662dcea2925067f", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 99, "avg_line_length": 26.672131147540984, "alnum_prop": 0.6183159188690842, "repo_name": "styleguidist/react-styleguidist", "id": "6257826efdf6f3d3a1c2b6cd1acf0cd309a08db6", "size": "1689", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "site/scripts/sync.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9282" }, { "name": "JavaScript", "bytes": "48177" }, { "name": "Shell", "bytes": "521" }, { "name": "TypeScript", "bytes": "466566" } ], "symlink_target": "" }
package akka.actor import scala.collection.mutable.ListBuffer /** * Requirements are as follows: * The first thing the actor needs to do, is to subscribe to a channel of events, * Then it must replay (process) all "old" events * Then it has to wait for a GoAhead signal to begin processing the new events * It mustn't "miss" events that happen between catching up with the old events and getting the GoAhead signal */ class UnnestedReceives extends Actor { //If you need to store sender/senderFuture you can change it to ListBuffer[(Any, Channel)] val queue = new ListBuffer[Any]() //This message processes a message/event def process(msg: Any): Unit = println("processing: " + msg) //This method subscribes the actor to the event bus def subscribe() {} //Your external stuff //This method retrieves all prior messages/events def allOldMessages() = List() override def preStart { //We override preStart to be sure that the first message the actor gets is //'Replay, that message will start to be processed _after_ the actor is started self ! 'Replay //Then we subscribe to the stream of messages/events subscribe() } def receive = { case 'Replay => //Our first message should be a 'Replay message, all others are invalid allOldMessages() foreach process //Process all old messages/events become { //Switch behavior to look for the GoAhead signal case 'GoAhead => //When we get the GoAhead signal we process all our buffered messages/events queue foreach process queue.clear become { //Then we change behaviour to process incoming messages/events as they arrive case msg => process(msg) } case msg => //While we haven't gotten the GoAhead signal, buffer all incoming messages queue += msg //Here you have full control, you can handle overflow etc } } }
{ "content_hash": "ad83ea3956dce46f092d6fac834b8940", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 110, "avg_line_length": 41.47826086956522, "alnum_prop": 0.7017819706498952, "repo_name": "ktoso/asciidoctor-sbt-plugin", "id": "a291f34af7d678e99afafe08eabd2ce2fe73511d", "size": "1982", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/sbt-test/sbt-asciidoctor/simple-doc/src/test/scala/akka/actor/UnnestedReceives.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "92667" }, { "name": "HTML", "bytes": "134596" }, { "name": "Java", "bytes": "4386" }, { "name": "JavaScript", "bytes": "29358" }, { "name": "Scala", "bytes": "54781" } ], "symlink_target": "" }
maintainer "Opscode, Inc." maintainer_email "[email protected]" license "Apache 2.0" description "Installs memcached and provides a define to set up an instance of memcache via runit" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "1.0.2" depends "runit" recipe "memcached", "Installs and configures memcached" %w{ ubuntu debian redhat fedora centos }.each do |os| supports os end attribute "memcached/memory", :display_name => "Memcached Memory", :description => "Memory allocated for memcached instance", :default => "64" attribute "memcached/port", :display_name => "Memcached Port", :description => "Port to use for memcached instance", :default => "11211" attribute "memcached/user", :display_name => "Memcached User", :description => "User to run memcached instance as", :default => "nobody" attribute "memcached/listen", :display_name => "Memcached IP Address", :description => "IP address to use for memcached instance", :default => "0.0.0.0"
{ "content_hash": "66985bdea652ff1a1da2495e9ac85125", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 104, "avg_line_length": 32.303030303030305, "alnum_prop": 0.6857410881801126, "repo_name": "glennpratt/memcached", "id": "acc21b85c3801e4cfc7dfcdfe160a1f7ccc8ec30", "size": "1066", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "metadata.rb", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package com.mongodb.internal.operation; import com.mongodb.MongoNamespace; import com.mongodb.client.model.Collation; import com.mongodb.connection.ConnectionDescription; import com.mongodb.connection.ServerDescription; import com.mongodb.internal.async.AsyncBatchCursor; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.binding.AsyncConnectionSource; import com.mongodb.internal.binding.AsyncReadBinding; import com.mongodb.internal.binding.ConnectionSource; import com.mongodb.internal.binding.ReadBinding; import com.mongodb.internal.connection.AsyncConnection; import com.mongodb.internal.connection.Connection; import com.mongodb.internal.connection.QueryResult; import com.mongodb.internal.operation.CommandOperationHelper.CommandReadTransformer; import com.mongodb.internal.operation.CommandOperationHelper.CommandReadTransformerAsync; import com.mongodb.internal.session.SessionContext; import org.bson.BsonDocument; import org.bson.BsonString; import org.bson.BsonValue; import org.bson.codecs.Codec; import org.bson.codecs.Decoder; import java.util.concurrent.TimeUnit; import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback; import static com.mongodb.internal.operation.CommandOperationHelper.CommandCreator; import static com.mongodb.internal.operation.CommandOperationHelper.executeRetryableRead; import static com.mongodb.internal.operation.CommandOperationHelper.executeRetryableReadAsync; import static com.mongodb.internal.operation.DocumentHelper.putIfNotNull; import static com.mongodb.internal.operation.DocumentHelper.putIfNotZero; import static com.mongodb.internal.operation.OperationHelper.LOGGER; import static com.mongodb.internal.operation.OperationReadConcernHelper.appendReadConcernToCommand; /** * Finds the distinct values for a specified field across a single collection. * * <p>This class is not part of the public API and may be removed or changed at any time</p> */ public class DistinctOperation<T> implements AsyncReadOperation<AsyncBatchCursor<T>>, ReadOperation<BatchCursor<T>> { private static final String VALUES = "values"; private final MongoNamespace namespace; private final String fieldName; private final Decoder<T> decoder; private boolean retryReads; private BsonDocument filter; private long maxTimeMS; private Collation collation; private BsonValue comment; public DistinctOperation(final MongoNamespace namespace, final String fieldName, final Decoder<T> decoder) { this.namespace = notNull("namespace", namespace); this.fieldName = notNull("fieldName", fieldName); this.decoder = notNull("decoder", decoder); } public BsonDocument getFilter() { return filter; } public DistinctOperation<T> filter(final BsonDocument filter) { this.filter = filter; return this; } public DistinctOperation<T> retryReads(final boolean retryReads) { this.retryReads = retryReads; return this; } public boolean getRetryReads() { return retryReads; } public long getMaxTime(final TimeUnit timeUnit) { notNull("timeUnit", timeUnit); return timeUnit.convert(maxTimeMS, TimeUnit.MILLISECONDS); } public DistinctOperation<T> maxTime(final long maxTime, final TimeUnit timeUnit) { notNull("timeUnit", timeUnit); this.maxTimeMS = TimeUnit.MILLISECONDS.convert(maxTime, timeUnit); return this; } public Collation getCollation() { return collation; } public DistinctOperation<T> collation(final Collation collation) { this.collation = collation; return this; } public BsonValue getComment() { return comment; } public DistinctOperation<T> comment(final BsonValue comment) { this.comment = comment; return this; } @Override public BatchCursor<T> execute(final ReadBinding binding) { return executeRetryableRead(binding, namespace.getDatabaseName(), getCommandCreator(binding.getSessionContext()), createCommandDecoder(), transformer(), retryReads); } @Override public void executeAsync(final AsyncReadBinding binding, final SingleResultCallback<AsyncBatchCursor<T>> callback) { executeRetryableReadAsync(binding, namespace.getDatabaseName(), getCommandCreator(binding.getSessionContext()), createCommandDecoder(), asyncTransformer(), retryReads, errorHandlingCallback(callback, LOGGER)); } private Codec<BsonDocument> createCommandDecoder() { return CommandResultDocumentCodec.create(decoder, VALUES); } private QueryResult<T> createQueryResult(final BsonDocument result, final ConnectionDescription description) { return new QueryResult<T>(namespace, BsonDocumentWrapperHelper.<T>toList(result, VALUES), 0L, description.getServerAddress()); } private CommandReadTransformer<BsonDocument, BatchCursor<T>> transformer() { return new CommandReadTransformer<BsonDocument, BatchCursor<T>>() { @Override public BatchCursor<T> apply(final BsonDocument result, final ConnectionSource source, final Connection connection) { QueryResult<T> queryResult = createQueryResult(result, connection.getDescription()); return new QueryBatchCursor<T>(queryResult, 0, 0, decoder, comment, source); } }; } private CommandReadTransformerAsync<BsonDocument, AsyncBatchCursor<T>> asyncTransformer() { return new CommandReadTransformerAsync<BsonDocument, AsyncBatchCursor<T>>() { @Override public AsyncBatchCursor<T> apply(final BsonDocument result, final AsyncConnectionSource source, final AsyncConnection connection) { QueryResult<T> queryResult = createQueryResult(result, connection.getDescription()); return new AsyncSingleBatchQueryCursor<T>(queryResult); } }; } private CommandCreator getCommandCreator(final SessionContext sessionContext) { return new CommandCreator() { @Override public BsonDocument create(final ServerDescription serverDescription, final ConnectionDescription connectionDescription) { return getCommand(sessionContext, connectionDescription); } }; } private BsonDocument getCommand(final SessionContext sessionContext, final ConnectionDescription connectionDescription) { BsonDocument commandDocument = new BsonDocument("distinct", new BsonString(namespace.getCollectionName())); appendReadConcernToCommand(sessionContext, connectionDescription.getMaxWireVersion(), commandDocument); commandDocument.put("key", new BsonString(fieldName)); putIfNotNull(commandDocument, "query", filter); putIfNotZero(commandDocument, "maxTimeMS", maxTimeMS); if (collation != null) { commandDocument.put("collation", collation.asDocument()); } putIfNotNull(commandDocument, "comment", comment); return commandDocument; } }
{ "content_hash": "9bb590988e372749c8e2b9dd221da7fa", "timestamp": "", "source": "github", "line_count": 173, "max_line_length": 134, "avg_line_length": 42.14450867052023, "alnum_prop": 0.7370731038266356, "repo_name": "rozza/mongo-java-driver", "id": "584225cbe9363f14fd6e9624472d150f4aacdbcf", "size": "7893", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "driver-core/src/main/com/mongodb/internal/operation/DistinctOperation.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "2678541" }, { "name": "Java", "bytes": "9782409" }, { "name": "Scala", "bytes": "1253739" }, { "name": "Shell", "bytes": "37374" } ], "symlink_target": "" }
/***************************************************************************** sc_object.h -- Abstract base class of all SystemC `simulation' objects. Original Author: Stan Y. Liao, Synopsys, Inc. CHANGE LOG AT THE END OF THE FILE *****************************************************************************/ #ifndef SC_OBJECT_H #define SC_OBJECT_H #include "sysc/utils/sc_iostream.h" #include "sysc/kernel/sc_attribute.h" namespace sc_core { class sc_event; class sc_module; class sc_runnable; class sc_simcontext; class sc_trace_file; #define SC_KERNEL_MODULE_PREFIX "$$$$kernel_module$$$$_" // ---------------------------------------------------------------------------- // CLASS : sc_object // // Abstract base class of all SystemC `simulation' objects. // ---------------------------------------------------------------------------- class sc_object { friend class sc_event; friend class sc_module; friend class sc_module_dynalloc_list; friend class sc_object_manager; friend class sc_process_b; friend class sc_runnable; public: const char* name() const { return m_name.c_str(); } const char* basename() const; virtual void print(::std::ostream& os=::std::cout ) const; // dump() is more detailed than print() virtual void dump(::std::ostream& os=::std::cout ) const; virtual void trace( sc_trace_file* tf ) const; virtual const char* kind() const { return "sc_object"; } sc_simcontext* simcontext() const { return m_simc; } // add attribute bool add_attribute( sc_attr_base& ); // get attribute by name sc_attr_base* get_attribute( const std::string& name_ ); const sc_attr_base* get_attribute( const std::string& name_ ) const; // remove attribute by name sc_attr_base* remove_attribute( const std::string& name_ ); // remove all attributes void remove_all_attributes(); // get the number of attributes int num_attributes() const; // get the attribute collection sc_attr_cltn& attr_cltn(); const sc_attr_cltn& attr_cltn() const; virtual const std::vector<sc_event*>& get_child_events() const { return m_child_events; } virtual const std::vector<sc_object*>& get_child_objects() const { return m_child_objects; } sc_object* get_parent() const { return m_parent; } sc_object* get_parent_object() const { return m_parent; } protected: sc_object(); sc_object(const char* nm); sc_object( const sc_object& ); sc_object& operator=( const sc_object& ); virtual ~sc_object(); virtual void add_child_event( sc_event* event_p ); virtual void add_child_object( sc_object* object_p ); virtual bool remove_child_event( sc_event* event_p ); virtual bool remove_child_object( sc_object* object_p ); private: void detach(); virtual void orphan_child_events(); virtual void orphan_child_objects(); void sc_object_init(const char* nm); private: /* Each simulation object is associated with a simulation context */ mutable sc_attr_cltn* m_attr_cltn_p; // attributes for this object. std::vector<sc_event*> m_child_events; // list of child events. std::vector<sc_object*> m_child_objects; // list of child objects. std::string m_name; // name of this object. sc_object* m_parent; // parent for this object. sc_simcontext* m_simc; // simcontext ptr / empty indicator }; inline sc_object& sc_object::operator=( sc_object const & ) { // deliberately do nothing return *this; } // ---------------------------------------------------------------------------- extern const char SC_HIERARCHY_CHAR; extern bool sc_enable_name_checking; inline sc_object* sc_get_parent( const sc_object* obj_p ) { return obj_p->get_parent_object(); } } // namespace sc_core /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Andy Goodrich, Forte Design Systems 5 September 2003 Description of Modification: - Made creation of attributes structure conditional on its being used. This eliminates 100 bytes of storage for each normal sc_object. *****************************************************************************/ // $Log: sc_object.h,v $ // Revision 1.13 2011/08/29 18:04:32 acg // Philipp A. Hartmann: miscellaneous clean ups. // // Revision 1.12 2011/08/26 20:46:10 acg // Andy Goodrich: moved the modification log to the end of the file to // eliminate source line number skew when check-ins are done. // // Revision 1.11 2011/03/06 15:55:11 acg // Andy Goodrich: Changes for named events. // // Revision 1.10 2011/03/05 19:44:20 acg // Andy Goodrich: changes for object and event naming and structures. // // Revision 1.9 2011/03/05 01:39:21 acg // Andy Goodrich: changes for named events. // // Revision 1.8 2011/02/18 20:27:14 acg // Andy Goodrich: Updated Copyrights. // // Revision 1.7 2011/02/13 21:47:37 acg // Andy Goodrich: update copyright notice. // // Revision 1.6 2011/01/25 20:50:37 acg // Andy Goodrich: changes for IEEE 1666 2011. // // Revision 1.5 2011/01/18 20:10:44 acg // Andy Goodrich: changes for IEEE1666_2011 semantics. // // Revision 1.4 2010/07/22 20:02:33 acg // Andy Goodrich: bug fixes. // // Revision 1.3 2009/02/28 00:26:58 acg // Andy Goodrich: changed boost name space to sc_boost to allow use with // full boost library applications. // // Revision 1.2 2008/05/22 17:06:26 acg // Andy Goodrich: updated copyright notice to include 2008. // // Revision 1.1.1.1 2006/12/15 20:20:05 acg // SystemC 2.3 // // Revision 1.5 2006/04/20 17:08:17 acg // Andy Goodrich: 3.0 style process changes. // // Revision 1.4 2006/04/11 23:13:21 acg // Andy Goodrich: Changes for reduced reset support that only includes // sc_cthread, but has preliminary hooks for expanding to method and thread // processes also. // // Revision 1.3 2006/01/13 18:44:30 acg // Added $Log to record CVS changes into the source. #endif // SC_OBJECT_H
{ "content_hash": "8ff7b23f494b0c60e46e21bd2c7567cc", "timestamp": "", "source": "github", "line_count": 215, "max_line_length": 80, "avg_line_length": 30.451162790697673, "alnum_prop": 0.5776691614479914, "repo_name": "pombredanne/metamorphosys-desktop", "id": "ca80be0c35d2681622e3d99b9a95d68f521e9083", "size": "7468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "metamorphosys/tonka/models/SystemC/systemc-2.3.0/src/sysc/kernel/sc_object.h", "mode": "33261", "license": "mit", "language": [ { "name": "Arduino", "bytes": "10683" }, { "name": "Assembly", "bytes": "117345" }, { "name": "Awk", "bytes": "3591" }, { "name": "Batchfile", "bytes": "228118" }, { "name": "BitBake", "bytes": "4526" }, { "name": "C", "bytes": "3613212" }, { "name": "C#", "bytes": "11617773" }, { "name": "C++", "bytes": "51448188" }, { "name": "CMake", "bytes": "3055" }, { "name": "CSS", "bytes": "109563" }, { "name": "Clojure", "bytes": "37831" }, { "name": "Eagle", "bytes": "3782687" }, { "name": "Emacs Lisp", "bytes": "8514" }, { "name": "GAP", "bytes": "49124" }, { "name": "Groff", "bytes": "2178" }, { "name": "Groovy", "bytes": "7686" }, { "name": "HTML", "bytes": "4025250" }, { "name": "Inno Setup", "bytes": "35715" }, { "name": "Java", "bytes": "489537" }, { "name": "JavaScript", "bytes": "167454" }, { "name": "Lua", "bytes": "1660" }, { "name": "Makefile", "bytes": "97209" }, { "name": "Mathematica", "bytes": "26" }, { "name": "Matlab", "bytes": "80874" }, { "name": "Max", "bytes": "78198" }, { "name": "Modelica", "bytes": "44541139" }, { "name": "Objective-C", "bytes": "34004" }, { "name": "Perl", "bytes": "19285" }, { "name": "PostScript", "bytes": "400254" }, { "name": "PowerShell", "bytes": "19749" }, { "name": "Processing", "bytes": "1477" }, { "name": "Prolog", "bytes": "3121" }, { "name": "Protocol Buffer", "bytes": "58995" }, { "name": "Python", "bytes": "5517835" }, { "name": "Ruby", "bytes": "4483" }, { "name": "Shell", "bytes": "956773" }, { "name": "Smarty", "bytes": "37892" }, { "name": "TeX", "bytes": "4183594" }, { "name": "Visual Basic", "bytes": "22546" }, { "name": "XSLT", "bytes": "332312" } ], "symlink_target": "" }
class AddColumsToOrders < ActiveRecord::Migration def change add_column :orders, :stripe_charge_id, :string add_column :orders, :stripe_customer_id, :string add_column :orders, :card_last_4_digit, :integer add_column :orders, :card_brand, :string add_column :orders, :card_exp_month, :integer add_column :orders, :card_exp_year, :integer add_column :orders, :is_refunded, :boolean add_column :orders, :refund_amount, :float end end
{ "content_hash": "b83de47253c6d52ae968d0a82400cc5a", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 52, "avg_line_length": 39, "alnum_prop": 0.6987179487179487, "repo_name": "salayhin/crowdfunding", "id": "23c304326c0dc07fd4d0bd015bfc7136b923d1ef", "size": "468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/migrate/20140630022859_add_colums_to_orders.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "249983" }, { "name": "CoffeeScript", "bytes": "2978" }, { "name": "JavaScript", "bytes": "98155" }, { "name": "Ruby", "bytes": "80410" } ], "symlink_target": "" }
package org.apache.camel.component.braintree; import java.util.List; import java.util.UUID; import com.braintreegateway.BraintreeGateway; import com.braintreegateway.Customer; import com.braintreegateway.CustomerRequest; import com.braintreegateway.PaymentMethod; import com.braintreegateway.PaymentMethodRequest; import com.braintreegateway.Result; import com.google.common.collect.Lists; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.braintree.internal.PaymentMethodGatewayApiMethod; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PaymentMethodGatewayIntegrationTest extends AbstractBraintreeTestSupport { private static final Logger LOG = LoggerFactory.getLogger(PaymentMethodGatewayIntegrationTest.class); private static final String PATH_PREFIX = getApiNameAsString(PaymentMethodGatewayApiMethod.class); private BraintreeGateway gateway; private Customer customer; private final List<String> paymentMethodsTokens; // ************************************************************************* // // ************************************************************************* public PaymentMethodGatewayIntegrationTest() { this.customer = null; this.gateway = null; this.paymentMethodsTokens = Lists.newLinkedList(); } @Override protected void doPostSetup() throws Exception { this.gateway = getGateway(); this.customer = gateway.customer().create( new CustomerRequest() .firstName("user") .lastName(UUID.randomUUID().toString()) ).getTarget(); if (customer != null) { LOG.info("Customer created - id={}", this.customer.getId()); } } @Override public void tearDown() throws Exception { if (this.gateway != null) { for (String token : this.paymentMethodsTokens) { if (this.gateway.paymentMethod().delete(token).isSuccess()) { LOG.info("PaymentMethod deleted - token={}", token); } else { LOG.warn("Unable to delete PaymentMethod - token={}", token); } } this.paymentMethodsTokens.clear(); if (this.gateway.customer().delete(this.customer.getId()).isSuccess()) { LOG.info("Customer deleted - id={}", this.customer.getId()); } else { LOG.warn("Unable to delete customer - id={}", this.customer.getId()); } } } private PaymentMethod createPaymentMethod() { Result<? extends PaymentMethod> result = this.gateway.paymentMethod().create( new PaymentMethodRequest() .customerId(this.customer.getId()) .paymentMethodNonce("fake-valid-payroll-nonce")); assertNotNull("create result", result); assertTrue(result.isSuccess()); LOG.info("PaymentMethod created - token={}", result.getTarget().getToken()); return result.getTarget(); } // ************************************************************************* // // ************************************************************************* @Test public void testCreate() throws Exception { assertNotNull("BraintreeGateway can't be null", this.gateway); assertNotNull("Customer can't be null", this.customer); final Result<PaymentMethod> result = requestBody("direct://CREATE", new PaymentMethodRequest() .customerId(this.customer.getId()) .paymentMethodNonce("fake-valid-payroll-nonce"), Result.class); assertNotNull("create result", result); assertTrue(result.isSuccess()); LOG.info("PaymentMethod created - token={}", result.getTarget().getToken()); this.paymentMethodsTokens.add(result.getTarget().getToken()); } @Test public void testDelete() throws Exception { assertNotNull("BraintreeGateway can't be null", this.gateway); assertNotNull("Customer can't be null", this.customer); final PaymentMethod paymentMethod = createPaymentMethod(); final Result<PaymentMethod> deleteResult = requestBody( "direct://DELETE", paymentMethod.getToken(), Result.class); assertNotNull("create result", deleteResult); assertTrue(deleteResult.isSuccess()); LOG.info("PaymentMethod deleted - token={}", paymentMethod.getToken()); } @Test public void testFind() throws Exception { assertNotNull("BraintreeGateway can't be null", this.gateway); assertNotNull("Customer can't be null", this.customer); final PaymentMethod paymentMethod = createPaymentMethod(); this.paymentMethodsTokens.add(paymentMethod.getToken()); final PaymentMethod method = requestBody( "direct://FIND", paymentMethod.getToken(), PaymentMethod.class ); assertNotNull("find result", method); LOG.info("PaymentMethod found - token={}", method.getToken()); } @Test public void testUpdate() throws Exception { assertNotNull("BraintreeGateway can't be null", this.gateway); assertNotNull("Customer can't be null", this.customer); final PaymentMethod paymentMethod = createPaymentMethod(); this.paymentMethodsTokens.add(paymentMethod.getToken()); final Result<PaymentMethod> result = requestBodyAndHeaders( "direct://UPDATE", null, new BraintreeHeaderBuilder() .add("token", paymentMethod.getToken()) .add("request", new PaymentMethodRequest() .billingAddress() .company("Apache") .streetAddress("100 Maple Lane") .done()) .build(), Result.class); assertNotNull("update result", result); assertTrue(result.isSuccess()); LOG.info("PaymentMethod updated - token={}", result.getTarget().getToken()); } // ************************************************************************* // ROUTES // ************************************************************************* @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { public void configure() { // test route for create from("direct://CREATE") .to("braintree://" + PATH_PREFIX + "/create?inBody=request"); // test route for delete from("direct://DELETE") .to("braintree://" + PATH_PREFIX + "/delete?inBody=token"); // test route for find from("direct://FIND") .to("braintree://" + PATH_PREFIX + "/find?inBody=token"); // test route for update from("direct://UPDATE") .to("braintree://" + PATH_PREFIX + "/update"); } }; } }
{ "content_hash": "6a3f08b4cba410e3c3431d4f885e4aa6", "timestamp": "", "source": "github", "line_count": 190, "max_line_length": 105, "avg_line_length": 37.51052631578948, "alnum_prop": 0.5756980496702679, "repo_name": "edigrid/camel", "id": "fec897d4312c28e4c2a666408cac4bf6e947547e", "size": "7930", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "components/camel-braintree/src/test/java/org/apache/camel/component/braintree/PaymentMethodGatewayIntegrationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "106" }, { "name": "CSS", "bytes": "30373" }, { "name": "Eagle", "bytes": "2898" }, { "name": "Elm", "bytes": "5970" }, { "name": "FreeMarker", "bytes": "11410" }, { "name": "Groovy", "bytes": "53008" }, { "name": "HTML", "bytes": "176896" }, { "name": "Java", "bytes": "50965044" }, { "name": "JavaScript", "bytes": "90232" }, { "name": "Protocol Buffer", "bytes": "578" }, { "name": "Python", "bytes": "36" }, { "name": "Ruby", "bytes": "4802" }, { "name": "Scala", "bytes": "322615" }, { "name": "Shell", "bytes": "17527" }, { "name": "Tcl", "bytes": "4974" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "284394" } ], "symlink_target": "" }
package json import ( "gopkg.in/check.v1" "testing" ) type Suite struct{} var _ = check.Suite(new(Suite)) func Test(t *testing.T) { check.TestingT(t) } func (s *Suite) TestParse(c *check.C) { var currentTokens []Token given := func(tokens ...Token) { currentTokens = tokens } expect := func(expected Value) { actual, error := Parse(currentTokens) if c.Check(error, check.IsNil) { c.Check(actual, check.DeepEquals, expected) } } tstring := func(s string) Token { return Token{TokenType: TSTRING, String: s} } tnumber := func(n float64) Token { return Token{TokenType: TNUMBER, Number: n} } tobjectopen := Token{TokenType: TOBJECTOPEN} tobjectclose := Token{TokenType: TOBJECTCLOSE} tarrayopen := Token{TokenType: TARRAYOPEN} tarrayclose := Token{TokenType: TARRAYCLOSE} tcolon := Token{TokenType: TCOLON} tcomma := Token{TokenType: TCOMMA} ttrue := Token{TokenType: TTRUE} tfalse := Token{TokenType: TFALSE} tnull := Token{TokenType: TNULL} type keyvalue struct { key string value Value } jobject := func(keyvalues ...keyvalue) Value { value := Value{Type: VOBJECT, Properties: make(map[string]Value)} for _, keyvalue := range keyvalues { value.Properties[keyvalue.key] = keyvalue.value } return value } jkeyvalue := func(key string, value Value) keyvalue { return keyvalue{key, value} } jarray := func(elements ...Value) Value { return Value{Type: VARRAY, Elements: elements} } jnumber := func(n float64) Value { return Value{Type: VNUMBER, Number: n} } jstring := func(s string) Value { return Value{Type: VSTRING, String: s} } jtrue := Value{Type: VTRUE} jfalse := Value{Type: VFALSE} jnull := Value{Type: VNULL} given(tnull) expect(jnull) given(tfalse) expect(jfalse) given(ttrue) expect(jtrue) given(tnumber(1.2)) expect(jnumber(1.2)) given(tstring("str")) expect(jstring("str")) given(tobjectopen, tobjectclose) expect(jobject()) given(tarrayopen, tarrayclose) expect(jarray()) given(tobjectopen, tstring("key"), tcolon, tstring("value"), tobjectclose) expect(jobject(jkeyvalue("key", jstring("value")))) given(tobjectopen, tstring("key1"), tcolon, tstring("value1"), tcomma, tstring("key2"), tcolon, tstring("value2"), tobjectclose) expect(jobject( jkeyvalue("key1", jstring("value1")), jkeyvalue("key2", jstring("value2")))) given(tarrayopen, tstring("element"), tarrayclose) expect(jarray(jstring("element"))) given(tarrayopen, tstring("element0"), tcomma, tnumber(1.0), tcomma, ttrue, tcomma, tfalse, tcomma, tnull, tarrayclose) expect(jarray( jstring("element0"), jnumber(1.0), jtrue, jfalse, jnull)) }
{ "content_hash": "bdde9f98c10936ad56e90e6282f46b56", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 67, "avg_line_length": 21.69918699186992, "alnum_prop": 0.6875234170101161, "repo_name": "rillig/go-yacc-examples", "id": "240ff62e2d8ddb9a8e5a9cc1860d8162335bd163", "size": "2669", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "json/json_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "6933" }, { "name": "Yacc", "bytes": "2362" } ], "symlink_target": "" }
package com.google.firebase.firestore.local; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.annotation.Config; @RunWith(RobolectricTestRunner.class) @Config(manifest = Config.NONE) public class MemoryBundleCacheTest extends BundleCacheTestCase { @Override Persistence getPersistence() { return PersistenceTestHelpers.createEagerGCMemoryPersistence(); } }
{ "content_hash": "d28bef343ac8f2fd32964c092eb87822", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 67, "avg_line_length": 28.2, "alnum_prop": 0.8226950354609929, "repo_name": "firebase/firebase-android-sdk", "id": "b015e7856c5ec05431c46f0712b7d39a4f0640c4", "size": "1012", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "firebase-firestore/src/test/java/com/google/firebase/firestore/local/MemoryBundleCacheTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AIDL", "bytes": "1486" }, { "name": "C", "bytes": "6703" }, { "name": "C++", "bytes": "86300" }, { "name": "Java", "bytes": "12705758" }, { "name": "JavaScript", "bytes": "5242" }, { "name": "Kotlin", "bytes": "360846" }, { "name": "Makefile", "bytes": "21550" }, { "name": "Mustache", "bytes": "4739" }, { "name": "PureBasic", "bytes": "10781995" }, { "name": "Python", "bytes": "79496" }, { "name": "Ruby", "bytes": "2545" }, { "name": "Shell", "bytes": "4240" } ], "symlink_target": "" }
<?php namespace erdiko\core; use Erdiko; /** Response Class */ class Response { /** Theme object */ protected $_theme; /** Theme name */ protected $_themeName; /** Theme template */ protected $_themeTemplate = 'default'; /** Content */ protected $_content = null; /** Data */ protected $_data = array(); /** * Constructor * * @param Theme $theme - Theme Object (Container) */ public function __construct($theme = null) { $this->_theme = $theme; } /** * Set data value * * @param mixed $key * @param mixed $value */ public function setDataValue($key, $value) { $this->_data[$key] = $value; } /** * Get data value * * @param mixed $key * @return mixed */ public function getDataValue($key) { return $this->_data[$key]; } /** * Set theme * * @param Theme object $theme - Theme Object (Container) */ public function setTheme($theme) { $this->_theme = $theme; } /** * Get theme * * @return Theme */ public function getTheme() { return $this->_theme; } /** * Set Theme Name * * @param string $themeName */ public function setThemeName($themeName) { $this->_themeName = $themeName; } /** * Get the theme name * * @return string $name */ public function getThemeName() { $name = (empty($this->_themeName)) ? $this->_theme->getName() : $this->_themeName; return $name; } /** * Set Theme Template * * @param string $tamplate */ public function setThemeTemplate($template) { $this->_themeTemplate = $template; if ($this->getTheme() != null) { $this->getTheme()->setTemplate($this->_themeTemplate); } } /** * Get the theme template * * @return string $_themeTemplate */ public function getThemeTemplate() { return $this->_themeTemplate; } /** * Set content * * @param Container $content - e.g. View or Layout Object */ public function setContent($content) { $this->_content = $content; } /** * Get content * * @return string */ public function getContent() { return $this->_content; } /** * Append some html content to the existing content * * @param string $content * @todo check to see if content is a container, if so treat accordingly */ public function appendContent($content) { $this->_content .= $content; } /** * Render * * @return string */ public function render() { // error_log("themeName: {$this->_themeName}"); $content = (is_subclass_of($this->_content, '\erdiko\core\Container')) ? $this->_content->toHtml() : $this->_content; if ($this->_theme !== null) { $this->_theme->setContent($content); // rendered html (body content) $this->_theme->setData($this->_data); // data injected from Response/Controller $html = $this->_theme->toHtml(); } elseif (!empty($this->_themeName)) { // error_log("themeName: {$this->_themeName}"); $this->_theme = new \erdiko\core\Theme($this->_themeName, null, $this->_themeTemplate); $this->_theme->setContent($content); // rendered html (body content) $this->_theme->setData($this->_data); // data injected from Response/Controller $html = $this->_theme->toHtml(); } else { $html = $content; } return $html; } /** * Render and send data to browser then end request * * @notice USE WITH CAUTION */ public function send() { echo $this->render(); die(); } }
{ "content_hash": "c23a2595cb9a146f5b80cec244060a1c", "timestamp": "", "source": "github", "line_count": 187, "max_line_length": 99, "avg_line_length": 21.37433155080214, "alnum_prop": 0.511883912934701, "repo_name": "direction123/erdiko-core", "id": "9e71320702d9e7fd7de37fa7f43b72abf6f600fc", "size": "4226", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/erdiko/core/Response.php", "mode": "33261", "license": "mit", "language": [ { "name": "PHP", "bytes": "112140" } ], "symlink_target": "" }
#include <linux/init.h> #include <linux/pci.h> #include <linux/range.h> #include "bus_numa.h" LIST_HEAD(pci_root_infos); static struct pci_root_info *x86_find_pci_root_info(int bus) { struct pci_root_info *info; if (list_empty(&pci_root_infos)) return NULL; list_for_each_entry(info, &pci_root_infos, list) if (info->busn.start == bus) return info; return NULL; } void x86_pci_root_bus_resources(int bus, struct list_head *resources) { struct pci_root_info *info = x86_find_pci_root_info(bus); struct pci_root_res *root_res; struct pci_host_bridge_window *window; bool found = false; if (!info) goto default_resources; printk(KERN_DEBUG "PCI: root bus %02x: hardware-probed resources\n", bus); /* already added by acpi ? */ list_for_each_entry(window, resources, list) if (window->res->flags & IORESOURCE_BUS) { found = true; break; } if (!found) pci_add_resource(resources, &info->busn); list_for_each_entry(root_res, &info->resources, list) { struct resource *res; struct resource *root; res = &root_res->res; pci_add_resource(resources, res); if (res->flags & IORESOURCE_IO) root = &ioport_resource; else root = &iomem_resource; insert_resource(root, res); } return; default_resources: /* * We don't have any host bridge aperture information from the * "native host bridge drivers," e.g., amd_bus or broadcom_bus, * so fall back to the defaults historically used by pci_create_bus(). */ printk(KERN_DEBUG "PCI: root bus %02x: using default resources\n", bus); pci_add_resource(resources, &ioport_resource); pci_add_resource(resources, &iomem_resource); } struct pci_root_info __init *alloc_pci_root_info(int bus_min, int bus_max, int node, int link) { struct pci_root_info *info; info = kzalloc(sizeof(*info), GFP_KERNEL); if (!info) return info; sprintf(info->name, "PCI Bus #%02x", bus_min); INIT_LIST_HEAD(&info->resources); info->busn.name = info->name; info->busn.start = bus_min; info->busn.end = bus_max; info->busn.flags = IORESOURCE_BUS; info->node = node; info->link = link; list_add_tail(&info->list, &pci_root_infos); return info; } void update_res(struct pci_root_info *info, resource_size_t start, resource_size_t end, unsigned long flags, int merge) { struct resource *res; struct pci_root_res *root_res; if (start > end) return; if (start == MAX_RESOURCE) return; if (!merge) goto addit; /* try to merge it with old one */ list_for_each_entry(root_res, &info->resources, list) { resource_size_t final_start, final_end; resource_size_t common_start, common_end; res = &root_res->res; if (res->flags != flags) continue; common_start = max(res->start, start); common_end = min(res->end, end); if (common_start > common_end + 1) continue; final_start = min(res->start, start); final_end = max(res->end, end); res->start = final_start; res->end = final_end; return; } addit: /* need to add that */ root_res = kzalloc(sizeof(*root_res), GFP_KERNEL); if (!root_res) return; res = &root_res->res; res->name = info->name; res->flags = flags; res->start = start; res->end = end; list_add_tail(&root_res->list, &info->resources); }
{ "content_hash": "3777c3717495beef3594136a78b8b988", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 74, "avg_line_length": 21.993197278911566, "alnum_prop": 0.6650170120630993, "repo_name": "zhengdejin/X1_Code", "id": "c2735feb2508148ec16efab887ec1aab2dcc0aec", "size": "3233", "binary": false, "copies": "2646", "ref": "refs/heads/master", "path": "kernel-3.10/arch/x86/pci/bus_numa.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "4528" }, { "name": "Assembly", "bytes": "10107915" }, { "name": "Awk", "bytes": "18681" }, { "name": "Batchfile", "bytes": "144" }, { "name": "C", "bytes": "519266172" }, { "name": "C++", "bytes": "11700846" }, { "name": "GDB", "bytes": "18113" }, { "name": "Lex", "bytes": "47705" }, { "name": "M4", "bytes": "3388" }, { "name": "Makefile", "bytes": "1619668" }, { "name": "Objective-C", "bytes": "2963724" }, { "name": "Perl", "bytes": "570279" }, { "name": "Perl 6", "bytes": "3727" }, { "name": "Python", "bytes": "92743" }, { "name": "Roff", "bytes": "55837" }, { "name": "Scilab", "bytes": "21433" }, { "name": "Shell", "bytes": "185922" }, { "name": "SourcePawn", "bytes": "2711" }, { "name": "UnrealScript", "bytes": "6113" }, { "name": "XS", "bytes": "1240" }, { "name": "Yacc", "bytes": "92226" } ], "symlink_target": "" }
const DrawCard = require('../../drawcard.js'); class PutToTheTorch extends DrawCard { setupCardAbilities(ability) { this.reaction({ max: ability.limit.perChallenge(1), when: { afterChallenge: event => event.challenge.challengeType === 'military' && event.challenge.winner === this.controller && event.challenge.attackingPlayer === this.controller && event.challenge.strengthDifference >= 5 }, target: { activePromptTitle: 'Select a location', cardCondition: card => card.location === 'play area' && card.controller !== this.controller && card.getType() === 'location', gameAction: 'discard' }, handler: (context) => { context.target.controller.discardCard(context.target); this.game.addMessage('{0} plays {1} to discard {2}', context.player, this, context.target); } }); } } PutToTheTorch.code = '01042'; module.exports = PutToTheTorch;
{ "content_hash": "ada491c3b079325374233aca0790e6af", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 141, "avg_line_length": 41.73076923076923, "alnum_prop": 0.5612903225806452, "repo_name": "Antaiseito/throneteki_for_doomtown", "id": "7c12ac4022910396b93c0056975f43cc54e2b3e9", "size": "1085", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/game/cards/01-Core/PutToTheTorch.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "32295" }, { "name": "HTML", "bytes": "1200" }, { "name": "JavaScript", "bytes": "2338367" } ], "symlink_target": "" }
using System; using System.Threading; using System.Runtime.Serialization; namespace System.Globalization { [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class CultureNotFoundException : ArgumentException, ISerializable { private string m_invalidCultureName; // unrecognized culture name public CultureNotFoundException() : base(DefaultMessage) { } public CultureNotFoundException(String message) : base(message) { } public CultureNotFoundException(String paramName, String message) : base(message, paramName) { } public CultureNotFoundException(String message, Exception innerException) : base(message, innerException) { } public CultureNotFoundException(String paramName, string invalidCultureName, String message) : base(message, paramName) { m_invalidCultureName = invalidCultureName; } public CultureNotFoundException(String message, string invalidCultureName, Exception innerException) : base(message, innerException) { m_invalidCultureName = invalidCultureName; } protected CultureNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { m_invalidCultureName = (string)info.GetValue("InvalidCultureName", typeof(string)); } [System.Security.SecurityCritical] // auto-generated_required public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } base.GetObjectData(info, context); info.AddValue("InvalidCultureName", m_invalidCultureName, typeof(string)); } public virtual string InvalidCultureName { get { return m_invalidCultureName; } } private static String DefaultMessage { get { return SR.Argument_CultureNotSupported; } } private String FormatedInvalidCultureId { get { return InvalidCultureName; } } public override String Message { get { String s = base.Message; if ( m_invalidCultureName != null) { String valueMessage = SR.Format(SR.Argument_CultureInvalidIdentifier, FormatedInvalidCultureId); if (s == null) return valueMessage; return s + Environment.NewLine + valueMessage; } return s; } } } }
{ "content_hash": "188d754f95ba9c59c1998177a72d9116", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 116, "avg_line_length": 29.25, "alnum_prop": 0.5705982905982906, "repo_name": "naamunds/coreclr", "id": "bd59efb6ea99527951f19519ac8eaade1335013a", "size": "3139", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/mscorlib/corefx/System/Globalization/CultureNotFoundException.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "946471" }, { "name": "Awk", "bytes": "5865" }, { "name": "Batchfile", "bytes": "63370" }, { "name": "C", "bytes": "5705703" }, { "name": "C#", "bytes": "133870864" }, { "name": "C++", "bytes": "68579711" }, { "name": "CMake", "bytes": "549517" }, { "name": "Groff", "bytes": "529523" }, { "name": "Groovy", "bytes": "48976" }, { "name": "HTML", "bytes": "16196" }, { "name": "Makefile", "bytes": "2527" }, { "name": "Objective-C", "bytes": "223940" }, { "name": "Perl", "bytes": "24550" }, { "name": "PowerShell", "bytes": "9231" }, { "name": "Python", "bytes": "69403" }, { "name": "Shell", "bytes": "67033" }, { "name": "Smalltalk", "bytes": "1359502" }, { "name": "SuperCollider", "bytes": "1621" }, { "name": "Yacc", "bytes": "157348" } ], "symlink_target": "" }
'use strict'; describe('Pieces E2E Tests:', function () { describe('Test Pieces page', function () { it('Should report missing credentials', function () { browser.get('http://localhost:3001/pieces'); expect(element.all(by.repeater('piece in pieces')).count()).toEqual(0); }); }); });
{ "content_hash": "5d46ffb901abd0578d84b6dbb21b8669", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 77, "avg_line_length": 30.9, "alnum_prop": 0.627831715210356, "repo_name": "dpxxdp/segue4", "id": "57d7cc00c62fa3b3b2400ce77cb5f68c0f547b46", "size": "309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/pieces/tests/e2e/pieces.e2e.tests.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2467" }, { "name": "HTML", "bytes": "65824" }, { "name": "JavaScript", "bytes": "443024" }, { "name": "Shell", "bytes": "685" } ], "symlink_target": "" }
export default function makeChange ({price, amountGiven}) { if (!Number.isInteger(price) || !Number.isInteger(amountGiven)) { throw new Error('Please input integer amounts inside of an object, e.g. {price: 100, amountGiven: 169} to get $0.69 in change') } let change = amountGiven - price let result = { quarters: 0, dimes: 0, nickels: 0, pennies: 0 } let values = { quarters: 25, dimes: 10, nickels: 5, pennies: 1 } for (let denomination in values) { if (change === 0) { return result } result[denomination] = Math.floor(change / values[denomination]) change = change % values[denomination] } return result }
{ "content_hash": "f5c2d412f0a39dbbc8cfef5a6d84becc", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 131, "avg_line_length": 28.25, "alnum_prop": 0.6430678466076696, "repo_name": "leikkisa/core-algorithms", "id": "356380c6b71309e1892aabe305b04ba9fa61c4b2", "size": "863", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/makeChange.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "10636" } ], "symlink_target": "" }
from .sub_resource import SubResource class BackendAddressPool(SubResource): """Pool of backend IP addresses. Variables are only populated by the server, and will be ignored when sending a request. :param id: Resource ID. :type id: str :ivar backend_ip_configurations: Gets collection of references to IP addresses defined in network interfaces. :vartype backend_ip_configurations: list[~azure.mgmt.network.v2017_03_01.models.NetworkInterfaceIPConfiguration] :ivar load_balancing_rules: Gets load balancing rules that use this backend address pool. :vartype load_balancing_rules: list[~azure.mgmt.network.v2017_03_01.models.SubResource] :ivar outbound_nat_rule: Gets outbound rules that use this backend address pool. :vartype outbound_nat_rule: ~azure.mgmt.network.v2017_03_01.models.SubResource :param provisioning_state: Get provisioning state of the public IP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'. :type provisioning_state: str :param name: Gets name of the resource that is unique within a resource group. This name can be used to access the resource. :type name: str :param etag: A unique read-only string that changes whenever the resource is updated. :type etag: str """ _validation = { 'backend_ip_configurations': {'readonly': True}, 'load_balancing_rules': {'readonly': True}, 'outbound_nat_rule': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'backend_ip_configurations': {'key': 'properties.backendIPConfigurations', 'type': '[NetworkInterfaceIPConfiguration]'}, 'load_balancing_rules': {'key': 'properties.loadBalancingRules', 'type': '[SubResource]'}, 'outbound_nat_rule': {'key': 'properties.outboundNatRule', 'type': 'SubResource'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, } def __init__(self, id=None, provisioning_state=None, name=None, etag=None): super(BackendAddressPool, self).__init__(id=id) self.backend_ip_configurations = None self.load_balancing_rules = None self.outbound_nat_rule = None self.provisioning_state = provisioning_state self.name = name self.etag = etag
{ "content_hash": "4c1313e4772773f2545d3e38aea2f71a", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 128, "avg_line_length": 42.3448275862069, "alnum_prop": 0.6640879478827362, "repo_name": "AutorestCI/azure-sdk-for-python", "id": "67f2ddd8888c2d687d2959e8b07fc5100e0c62eb", "size": "2930", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "azure-mgmt-network/azure/mgmt/network/v2017_03_01/models/backend_address_pool.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "34619070" } ], "symlink_target": "" }
package com.marco.marplex.schoolbook; import android.animation.Animator; import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.app.Dialog; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.content.ContextCompat; import android.support.v4.widget.NestedScrollView; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.CardView; import android.support.v7.widget.Toolbar; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.akexorcist.roundcornerprogressbar.RoundCornerProgressBar; import com.github.clans.fab.FloatingActionButton; import com.github.clans.fab.FloatingActionMenu; import com.marco.marplex.schoolbook.models.Obiettivo; import com.marco.marplex.schoolbook.models.Voto; import com.marco.marplex.schoolbook.utilities.ObjectiveUtil; import com.marco.marplex.schoolbook.utilities.SharedPreferences; import com.marco.marplex.schoolbook.utilities.Votes; import com.mikhaellopez.circularprogressbar.CircularProgressBar; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import lecho.lib.hellocharts.gesture.ContainerScrollType; import lecho.lib.hellocharts.model.Line; import lecho.lib.hellocharts.model.LineChartData; import lecho.lib.hellocharts.model.PointValue; import lecho.lib.hellocharts.util.ChartUtils; import lecho.lib.hellocharts.view.LineChartView; public class Materia extends AppCompatActivity{ @Bind(R.id.votoOrale) TextView orale; @Bind(R.id.mediaVoti) TextView media; @Bind(R.id.votoScritto) TextView scritto; @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.card_view) CardView mCardView; @Bind(R.id.card_objective) CardView mObjectiveCard; @Bind(R.id.ipoteticCard) CardView mIpoteticCard; @Bind(R.id.txt_votoIpotetico) TextView mIpoteticVote; @Bind(R.id.txt_mediaFinale) TextView mFinalAverage; @Bind(R.id.txt_currentAverage) TextView mCurrentAverageText; @Bind(R.id.txt_objective) TextView mObjecivetiveText; @Bind(R.id.txt_objectiveTitle) TextView mObjectiveTitleText; @Bind(R.id.pbar_objective) RoundCornerProgressBar mObjectiveProgressBar; @Bind(R.id.pbar_materiaPrimo) CircularProgressBar progress; @Bind(R.id.fab_addObjective) FloatingActionButton mAddObjective; @Bind(R.id.fab_menu) FloatingActionMenu fabMenu; @Bind(R.id.chart) LineChartView chart; @Bind(R.id.nested) NestedScrollView scrollView; private double totalAverage; private int nOfVotes; private double sum; private String[] mObjecivesArray; private int periodo; private String title; private boolean isNormal = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_materia); ButterKnife.bind(this); setSupportActionBar(toolbar); Bundle b = getIntent().getExtras(); scrollView.setSmoothScrollingEnabled(true); chart.setContainerScrollEnabled(false, ContainerScrollType.HORIZONTAL); chart.setContainerScrollEnabled(false, ContainerScrollType.VERTICAL); chart.setZoomEnabled(false); scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() { @Override public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { if(oldScrollY-scrollY > 0 && !isNormal){ fabMenu.animate() .alpha(1f) .setDuration(400) .start(); isNormal = true; }else if(oldScrollY-scrollY < 0 && isNormal){ fabMenu.animate() .alpha(0f) .setDuration(400) .start(); isNormal = false; } } }); mIpoteticCard.setVisibility(View.GONE); mAddObjective.setAlpha(0f); mAddObjective.setScaleX(0f); mAddObjective.setScaleY(0f); mAddObjective.animate() .alpha(1f) .scaleX(1f) .scaleY(1f) .setDuration(500) .start(); title = b.getString("materia"); periodo = b.getInt("periodo"); if(b.getInt("obiettivo", -1) != -1){ int obiettivo = b.getInt("obiettivo"); showAndConfigureObjective(obiettivo); ObjectiveUtil.setObiettivo(Materia.this, title, periodo, new Obiettivo(obiettivo)); } String materia = title.toUpperCase().substring(0,1)+title.toLowerCase().substring(1, title.length()); getSupportActionBar().setTitle(materia); getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); List<Voto> materiaVoti = Votes.getNumericalVotesByMateria(this, title, periodo); nOfVotes = materiaVoti.size(); //Chart List<Line> lines = new ArrayList<Line>(); for (int i = 0; i < nOfVotes-1; ++i) { List<PointValue> values = new ArrayList<PointValue>(); for (int j = 0; j < nOfVotes; ++j) { values.add(new PointValue(j, (float)Votes.getNumericalVoteByString(materiaVoti.get(j).voto)).setLabel(materiaVoti.get(j).voto)); } Line line = new Line(values); line.setColor(ContextCompat.getColor(this, R.color.colorPrimaryGreen)); line.setCubic(true); line.setFilled(true); line.setHasLabels(true); line.setHasLabelsOnlyForSelected(false); line.setHasLines(true); line.setHasPoints(true); line.setPointColor(ChartUtils.COLORS[(i + 1) % ChartUtils.COLORS.length]); lines.add(line); } LineChartData data = new LineChartData(lines); data.setAxisXBottom(null); data.setAxisYLeft(null); data.setBaseValue(1); chart.setLineChartData(data); double sumScritto = 0; int scrittoTimes = 0; double sumOrale = 0; int oraleTimes = 0; for(int i=0; i<materiaVoti.size(); i++){ if(materiaVoti.get(i).tipo.equals("Scritto") || materiaVoti.get(i).tipo.equals("Pratico")){ sumScritto += Votes.getNumericalVoteByString(materiaVoti.get(i).voto); System.out.println(Votes.getNumericalVoteByString(materiaVoti.get(i).voto)); scrittoTimes++; }else{ sumOrale += Votes.getNumericalVoteByString(materiaVoti.get(i).voto); System.out.println(Votes.getNumericalVoteByString(materiaVoti.get(i).voto)); oraleTimes++; } sum += Votes.getNumericalVoteByString(materiaVoti.get(i).voto); System.out.println(Votes.getNumericalVoteByString(materiaVoti.get(i).voto)); } totalAverage = sum/nOfVotes; if(Double.isNaN(totalAverage)) chart.setVisibility(View.GONE); double scrittoAverage = sumScritto/scrittoTimes; double oraleAverage = sumOrale/oraleTimes; int decimalDigits = Integer.parseInt(SharedPreferences.loadString(this, "pref", "setting_digits")); String scrittoText = Double.isNaN(arrotondaRint(scrittoAverage, decimalDigits)) ? "-" : arrotondaRint(scrittoAverage, decimalDigits)+""; String oraleText = Double.isNaN(arrotondaRint(oraleAverage, decimalDigits)) ? "-" : arrotondaRint(oraleAverage, decimalDigits)+""; String mediaText = Double.isNaN(arrotondaRint(totalAverage, decimalDigits)) ? "-" : arrotondaRint(totalAverage, decimalDigits)+""; scritto.setText(scrittoText); orale.setText(oraleText); media.setText(mediaText); ObjectAnimator animator = new ObjectAnimator().ofFloat(progress, "progress", (float) totalAverage * 10); animator.setInterpolator(new AccelerateDecelerateInterpolator()); animator.setDuration(1500).start(); mCardView.setAlpha(0f); PropertyValuesHolder holderAlpha = PropertyValuesHolder.ofFloat("alpha", 1f); new ObjectAnimator().ofPropertyValuesHolder(mCardView, holderAlpha) .setDuration(300) .start(); if(ObjectiveUtil.isObiettivoSaved(this, materia, periodo)){ Obiettivo obiettivo = ObjectiveUtil.getObiettivoByMateria(this, title, periodo); showAndConfigureObjective(obiettivo.getObiettivo()); } } @OnClick(R.id.img_removeObjective) public void removeObjective(View view){ ObjectiveUtil.removeObiettivo(this, title, periodo); mObjectiveCard.animate() .alpha(0f) .setDuration(300) .setListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) {} @Override public void onAnimationEnd(Animator animation) { mObjectiveCard.setVisibility(View.GONE); } @Override public void onAnimationCancel(Animator animation) {} @Override public void onAnimationRepeat(Animator animation) {} }) .start(); Snackbar.make(view, "Obiettivo eliminato", Snackbar.LENGTH_SHORT).show(); isNormal = true; } @OnClick(R.id.fab_ipoteticAverage) public void selectIpoteticVotes(View view){ View thisView = LayoutInflater.from(this).inflate(R.layout.ordina, null, false); final Dialog mBottomSheetDialog = new Dialog (this, R.style.MaterialDialogSheet); setLayoutForDialog(mBottomSheetDialog, thisView, "Quale voto pensi di aver preso?"); ListView numberList = (ListView)view.findViewById( R.id.materie); final String[] choices = new String[10]; for(int index = 1; index <= 10; index++) choices[index-1] = index+""; ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, choices); ListView numberLis = (ListView)thisView.findViewById( R.id.materie); numberLis.setAdapter(arrayAdapter); numberLis.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { mBottomSheetDialog.cancel(); mIpoteticVote.setText(choices[i]); int ipoteticVote = Integer.parseInt(choices[i]); int decimalDigits = Integer.parseInt(SharedPreferences.loadString(Materia.this, "pref", "setting_digits")); double finalAverage = arrotondaRint((sum+ipoteticVote)/(nOfVotes+1), decimalDigits); mFinalAverage.setText(finalAverage+""); mIpoteticCard.setVisibility(View.VISIBLE); mIpoteticCard.setAlpha(0f); mIpoteticCard.animate().alpha(1f).setDuration(300).start(); fabMenu.close(true); } }); } @OnClick(R.id.fab_addObjective) public void showObjectives(View myView){ View view = LayoutInflater.from(this).inflate(R.layout.ordina, null, false); final Dialog mBottomSheetDialog = new Dialog (this, R.style.MaterialDialogSheet); setLayoutForDialog(mBottomSheetDialog, view, "A quale voto desideri arrivare?"); ListView numberList = (ListView)view.findViewById( R.id.materie); mObjecivesArray = new String[10-(int)totalAverage]; for(int i = (int) totalAverage; i<10; i++){ mObjecivesArray[10-i-1] = (i + 1) + ""; } ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mObjecivesArray); numberList.setAdapter(arrayAdapter); numberList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { mBottomSheetDialog.cancel(); showAndConfigureObjective(Integer.parseInt(mObjecivesArray[i])); ObjectiveUtil.setObiettivo(Materia.this, title, periodo, new Obiettivo(Integer.parseInt(mObjecivesArray[i]))); fabMenu.close(true); } }); } private void showAndConfigureObjective(int obiettivo){ if(mObjectiveCard.getVisibility() == View.GONE){ mObjectiveCard.setAlpha(0f); mObjectiveCard.animate() .alpha(1f) .setDuration(300) .start(); } mObjectiveCard.setAlpha(1f); mObjectiveCard.setVisibility(View.VISIBLE); int objective = obiettivo; mCurrentAverageText.setText(String.valueOf(arrotondaRint(totalAverage, 2))); mObjecivetiveText.setText(obiettivo+""); mObjectiveProgressBar.setMax(100); mObjectiveProgressBar.setProgress(0); float percentFromDelta = ( (float) totalAverage - (int) totalAverage ) / ( objective - (int) totalAverage ) * 100; ObjectAnimator objectAnimator = new ObjectAnimator().ofFloat(mObjectiveProgressBar, "progress", percentFromDelta); objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); objectAnimator .setDuration(1000) .start(); double voteToGet = arrotondaRint( ( objective * ( nOfVotes + 1 ) ) - sum, 2); ArrayList<Double> votesToGet = new ArrayList<>(); int index = 1; double savedVote = voteToGet; double tmpSum = sum; if(voteToGet > 10) { while (voteToGet > 10) { votesToGet.add(10.0); if(index > 8){ Snackbar.make(mAddObjective, "Impossibile raggiungere questo obbiettivo.", Snackbar.LENGTH_SHORT).show(); break; } tmpSum += votesToGet.get(votesToGet.size()-1); voteToGet = arrotondaRint( ( objective * ( nOfVotes + index + 1) ) - tmpSum, 1); index++; } votesToGet.add(Math.abs(voteToGet)); if(index < 8) { String text = new String(); for (int i = 0; i < votesToGet.size(); i++) { if (i == votesToGet.size() - 1) text += votesToGet.get(i); else text += votesToGet.get(i) + ", "; } mObjectiveTitleText.setText("Devi prendere questi voti: " + text); }else{ mObjectiveTitleText.setText("Devi prendere almeno un " + savedVote); } }else { mObjectiveTitleText.setText("Devi prendere almeno un " + savedVote); } } private void setLayoutForDialog(Dialog dialog, View view, String customText){ view.findViewById(R.id.dialog_title).setVisibility(View.VISIBLE); ((TextView)view.findViewById(R.id.dialog_title)).setText(customText); dialog.setContentView(view); dialog.setCancelable(true); dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); dialog.getWindow().setGravity(Gravity.BOTTOM); dialog.show(); } @Override public boolean onOptionsItemSelected(MenuItem menuItem) { switch (menuItem.getItemId()) { case android.R.id.home: onBackPressed(); default: return super.onOptionsItemSelected(menuItem); } } public static double arrotondaRint(double value, int numCifreDecimali) { double temp = Math.pow(10, numCifreDecimali); return Math.rint(value * temp) / temp; } }
{ "content_hash": "30d4f756d1b5469bdcf332ff83b3243d", "timestamp": "", "source": "github", "line_count": 392, "max_line_length": 144, "avg_line_length": 41.60459183673469, "alnum_prop": 0.6459010362376602, "repo_name": "Marplex/Schoolbook", "id": "0c12d4105dc8a898d828fa29340a264a2b40ab04", "size": "16309", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/marco/marplex/schoolbook/Materia.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "263551" } ], "symlink_target": "" }
var Api = require('./Api') var async = require('async') class List { constructor(opts, config, logger) { this.opts = opts this.logger = logger this.api = new Api(config) if (opts.json == null) { opts.json = false } this.jsonOut = opts.json } run(cb) { this.api.getDumps((err, dumps) => { if (err) return cb(err) let shouldShowCompletedMesssage = true if (!this.jsonOut) { dumps.map((dump) => { this.logger.info(`- Dump ID: [ ${dump.dumpId} ] Sequence: [ ${dump.sequence} ] Account ID: [ ${dump.accountId} ] Number of Files: [ ${dump.numFiles} ] Finished: [ ${dump.finished} ] Expires At: [ ${dump.expires} ] Created At: [ ${dump.createdAt} ]`) }) } else { this.logger.info(JSON.stringify(dumps)) shouldShowCompletedMesssage = false } cb(null, shouldShowCompletedMesssage) }) } } module.exports = List
{ "content_hash": "160353a8f0edc77b9d6ec025d39262fa", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 57, "avg_line_length": 25.72222222222222, "alnum_prop": 0.5885529157667386, "repo_name": "instructure/canvas-data-cli", "id": "fd8b7ac1f5bf6770b8938bbf1be175b675be2ed0", "size": "926", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/List.js", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "231" }, { "name": "JavaScript", "bytes": "74204" }, { "name": "Makefile", "bytes": "157" }, { "name": "Shell", "bytes": "172" } ], "symlink_target": "" }
function cacheRestoreNavigationOrder(prefix) { return [ prefix + "onBeforeNavigate", prefix + "onCommitted", prefix + "onCompleted" ]; } onload = async function() { let tab = await promise(chrome.tabs.create, {"url": "about:blank"}); let config = await promise(chrome.test.getConfig); let port = config.testServer.port; var URL_A = "http://a.com:" + port + "/extensions/api_test/webnavigation/backForwardCache/a.html"; var URL_B = "http://b.com:" + port + "/extensions/api_test/webnavigation/backForwardCache/b.html"; chrome.test.runTests([ // First navigates to a.html which redirects to to b.html which uses // history.back() to navigate back to a.html function forwardBack() { expect([ { label: "a-onBeforeNavigate", event: "onBeforeNavigate", details: { frameId: 0, parentFrameId: -1, processId: -1, tabId: 0, timeStamp: 0, url: URL_A }}, { label: "a-onCommitted", event: "onCommitted", details: { frameId: 0, parentFrameId: -1, processId: 0, tabId: 0, timeStamp: 0, transitionQualifiers: [], transitionType: "link", url: URL_A }}, { label: "a-onDOMContentLoaded", event: "onDOMContentLoaded", details: { frameId: 0, parentFrameId: -1, processId: 0, tabId: 0, timeStamp: 0, url: URL_A }}, { label: "a-onCompleted", event: "onCompleted", details: { frameId: 0, parentFrameId: -1, processId: 0, tabId: 0, timeStamp: 0, url: URL_A }}, { label: "b-onBeforeNavigate", event: "onBeforeNavigate", details: { frameId: 0, parentFrameId: -1, processId: -1, tabId: 0, timeStamp: 0, url: URL_B }}, { label: "b-onCommitted", event: "onCommitted", details: { frameId: 0, parentFrameId: -1, processId: 1, tabId: 0, timeStamp: 0, transitionQualifiers: [], transitionType: "link", url: URL_B }}, { label: "b-onDOMContentLoaded", event: "onDOMContentLoaded", details: { frameId: 0, parentFrameId: -1, processId: 1, tabId: 0, timeStamp: 0, url: URL_B }}, { label: "b-onCompleted", event: "onCompleted", details: { frameId: 0, parentFrameId: -1, processId: 1, tabId: 0, timeStamp: 0, url: URL_B }}, { label: "c-onBeforeNavigate", event: "onBeforeNavigate", details: { frameId: 0, parentFrameId: -1, processId: -1, tabId: 0, timeStamp: 0, url: URL_A }}, { label: "c-onCommitted", event: "onCommitted", details: { frameId: 0, parentFrameId: -1, processId: 0, tabId: 0, timeStamp: 0, transitionQualifiers: ["forward_back"], transitionType: "link", url: URL_A }}, { label: "c-onCompleted", event: "onCompleted", details: { frameId: 0, parentFrameId: -1, processId: 0, tabId: 0, timeStamp: 0, url: URL_A }}], [ navigationOrder("a-"), navigationOrder("b-"), cacheRestoreNavigationOrder("c-"), isLoadedBy("b-", "a-"), isLoadedBy("c-", "b-")]); chrome.tabs.update(tab.id, { url: URL_A }); }, ]); };
{ "content_hash": "22e5ac40885c8d39f02da0b5b6e03e51", "timestamp": "", "source": "github", "line_count": 122, "max_line_length": 72, "avg_line_length": 36, "alnum_prop": 0.4198542805100182, "repo_name": "ric2b/Vivaldi-browser", "id": "86aeca0c4eda02ad8e80605b85c2c7c6deb4f265", "size": "4625", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chromium/chrome/test/data/extensions/api_test/webnavigation/backForwardCache/test_forwardBack.js", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
pushd "$SRC/zlib" ./configure --static --prefix="$WORK" make -j$(nproc) CFLAGS="$CFLAGS -fPIC" make install popd #build hdf5 pushd "$SRC" tar -xvf hdf5-1.12.1.tar.gz cd hdf5-1.12.1 ./configure --disable-shared --disable-deprecated-symbols --disable-hl --disable-parallel --disable-trace --disable-internal-debug --disable-asserts --disable-tests --disable-tools --with-pic --with-zlib="$WORK" --prefix="$WORK" make -j$(nproc) make install popd # build matio ./autogen.sh ./configure --prefix="$WORK" --disable-shared --with-hdf5="$WORK" --with-zlib="$WORK" make -j$(nproc) make install MATIO_INCLUDE="$WORK/include" MATIO_LIBS_NO_FUZZ="$WORK/lib/libmatio.a $WORK/lib/libhdf5.a $WORK/lib/libz.a" MATIO_LIBS="$LIB_FUZZING_ENGINE $MATIO_LIBS_NO_FUZZ" # build fuzzers cd ./ossfuzz for fuzzers in $(find . -name '*_fuzzer.cpp'); do base=$(basename -s .cpp $fuzzers) $CXX $CXXFLAGS -std=c++11 -I$MATIO_INCLUDE $fuzzers -o $OUT/$base $MATIO_LIBS zip -q -r ${base}_seed_corpus.zip ../share done find . -name '*_fuzzer.dict' -exec cp -v '{}' $OUT ';' find . -name '*_fuzzer_seed_corpus.zip' -exec cp -v '{}' $OUT ';'
{ "content_hash": "2522a79fb6a7c771a6beb34587e8bc3f", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 228, "avg_line_length": 31.97142857142857, "alnum_prop": 0.6791778373547811, "repo_name": "tbeu/matio", "id": "30a32c34778da0ba8ea4c5ab688fe636c22e6256", "size": "1808", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ossfuzz/build.sh", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "1005192" }, { "name": "C++", "bytes": "4537" }, { "name": "CMake", "bytes": "71674" }, { "name": "Fortran", "bytes": "151426" }, { "name": "M4", "bytes": "80524" }, { "name": "MATLAB", "bytes": "3343" }, { "name": "Makefile", "bytes": "37173" }, { "name": "Objective-C", "bytes": "6831" }, { "name": "Shell", "bytes": "32944" } ], "symlink_target": "" }
package it.polito.ai.polibox.web.controllers.result; import it.polito.ai.polibox.persistency.model.Resource; public class SharingItemWrapper { private int id; private String name; private boolean directory; private Integer pending; public SharingItemWrapper(int id, String name,boolean directory,Integer pending) { this.id=id; this.name=name; this.directory=directory; this.pending=pending; } public SharingItemWrapper(Resource res,Integer pending) { this.id=res.getId(); this.name=res.getName(); this.directory=res.isDirectory(); this.pending=pending; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isDirectory() { return directory; } public void setDirectory(boolean directory) { this.directory = directory; } public Integer getPending() { return pending; } public void setPending(Integer pending) { this.pending = pending; } }
{ "content_hash": "26fe2ba441b7b0b550463d7a45c30931", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 83, "avg_line_length": 18, "alnum_prop": 0.7212643678160919, "repo_name": "IDepla/polibox", "id": "b6380cd9e6f0d562536bdb5d9cee32fd6cb58158", "size": "2344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/it/polito/ai/polibox/web/controllers/result/SharingItemWrapper.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6094" }, { "name": "HTML", "bytes": "21607" }, { "name": "Java", "bytes": "593168" }, { "name": "JavaScript", "bytes": "80664" }, { "name": "PLpgSQL", "bytes": "23602" } ], "symlink_target": "" }
package com.bitdubai.fermat_api.layer.dmp_middleware.wallet_skin.exceptions; import com.bitdubai.fermat_api.FermatException; /** * The Exception <code>com.bitdubai.fermat_api.layer.middleware.wallet_language.CantAddLanguageStringException</code> * is thrown when a we cannot add a language string. * <p/> * * Created by Leon Acosta - ([email protected]) on 29/07/15. * * @version 1.0 * @since Java JDK 1.7 */ public class CantCloseWalletSkinException extends FermatException { /** * This is the constructor that every inherited FermatException must implement * * @param message the short description of the why this exception happened, there is a public static constant called DEFAULT_MESSAGE that can be used here * @param cause the exception that triggered the throwing of the current exception, if there are no other exceptions to be declared here, the cause should be null * @param context a String that provides the values of the variables that could have affected the exception * @param possibleReason an explicative reason of why we believe this exception was most likely thrown */ public CantCloseWalletSkinException(String message, Exception cause, String context, String possibleReason) { super(message, cause, context, possibleReason); } }
{ "content_hash": "3c03636e7cf31081115cc1afe2b8a023", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 175, "avg_line_length": 49.74074074074074, "alnum_prop": 0.742367833209233, "repo_name": "fvasquezjatar/fermat-unused", "id": "9c3c2c1a25fc6e16d94b4def7945f28d94cdcd01", "size": "1343", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fermat-api/src/main/java/com/bitdubai/fermat_api/layer/dmp_middleware/wallet_skin/exceptions/CantCloseWalletSkinException.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1204" }, { "name": "Groovy", "bytes": "76309" }, { "name": "HTML", "bytes": "322840" }, { "name": "Java", "bytes": "14027288" }, { "name": "Scala", "bytes": "1353" } ], "symlink_target": "" }
<?php // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import Joomla controllerform library jimport('joomla.application.component.controllerform'); /** * HelloWorld Controller */ class WebLabControllerWebLab extends JControllerForm { public function save($key=null, $urlVar=null){ $db =& JFactory::getDBO(); $exp_array = array(); $data = JRequest::getVar('jform', array(), 'post', 'array'); $usergroup = 0; if($_GET["id"] == 0) { $usergroup = $data['usergroup']; } else { $usergroup = $_GET['id']; } foreach($data['experimentselect'] as $experiment) { $experiment_array = explode(',', $experiment); array_push($exp_array, $experiment_array[0]); $query = "SELECT gid FROM #__weblab WHERE gid = " . $usergroup . " AND exp_name='" . $experiment_array[0] . "' AND cat_name='" . $experiment_array[1] . "'"; $db->setQuery($query); $column = $db->loadResultArray(); if (empty($column)) { $query = "INSERT INTO #__weblab (gid, exp_name, cat_name) VALUES (" . $usergroup . ", '" . $experiment_array[0] . "','" . $experiment_array[1] . "')"; $db->setQuery($query); $db->query(); } } $query = "SELECT exp_name FROM #__weblab WHERE gid = " . $usergroup; $db->setQuery($query); $column = $db->loadResultArray(); foreach($column as $exp_name) { if(!in_array($exp_name, $exp_array)) { $query = "DELETE FROM #__weblab WHERE exp_name='" . $exp_name . "' AND gid=" . $usergroup; $db->setQuery($query); $db->query(); } } //print_r(parent::save($key, $urlVar)); parent::cancel(); } }
{ "content_hash": "ca69343df1468d89829a1b7b3ac52857", "timestamp": "", "source": "github", "line_count": 62, "max_line_length": 162, "avg_line_length": 28.79032258064516, "alnum_prop": 0.5411764705882353, "repo_name": "porduna/weblabdeusto", "id": "aef158bdbcaff1a67baa9973a1a2a2b4819ff286", "size": "1785", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "server/consumers/joomla/admin/controllers/weblab.php", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "4785" }, { "name": "ActionScript", "bytes": "8508" }, { "name": "Batchfile", "bytes": "7753" }, { "name": "C", "bytes": "19456" }, { "name": "C#", "bytes": "315160" }, { "name": "C++", "bytes": "9547" }, { "name": "CSS", "bytes": "203478" }, { "name": "CoffeeScript", "bytes": "39146" }, { "name": "Go", "bytes": "7076" }, { "name": "HTML", "bytes": "610251" }, { "name": "Java", "bytes": "856300" }, { "name": "JavaScript", "bytes": "1538963" }, { "name": "Makefile", "bytes": "24995" }, { "name": "Mako", "bytes": "1236" }, { "name": "PHP", "bytes": "159985" }, { "name": "Python", "bytes": "3780070" }, { "name": "Shell", "bytes": "7880" }, { "name": "Smarty", "bytes": "40320" }, { "name": "TSQL", "bytes": "717" }, { "name": "VHDL", "bytes": "5874" } ], "symlink_target": "" }
namespace { constexpr char kCharset[] = ";charset="; constexpr char kDefaultCharset[] = "US-ASCII"; constexpr char kEncodingUTF8Charset[] = "UTF-8"; } // namespace namespace exo { std::string GetCharset(const std::string& mime_type) { // We special case UTF-8 to provide minimal handling of X11 apps. if (mime_type == ui::kMimeTypeLinuxUtf8String) return std::string(kEncodingUTF8Charset); auto pos = mime_type.find(kCharset); if (pos == std::string::npos) return std::string(kDefaultCharset); return mime_type.substr(pos + sizeof(kCharset) - 1); } } // namespace exo
{ "content_hash": "19dfd5b08cfb6c03a1af292b135ce9e6", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 67, "avg_line_length": 27, "alnum_prop": 0.702020202020202, "repo_name": "scheib/chromium", "id": "dd8ebef4659aa83b795bb62321dcc6b284b29483", "size": "852", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "components/exo/mime_utils.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import girder_client GIRDER_URL = 'http://127.0.0.1/api/v1' GIRDER_LOGIN = 'user' GIRDER_API_KEY = 'API_KEY' gc = girder_client.GirderClient(apiUrl=GIRDER_URL) gc.authenticate(username=GIRDER_LOGIN, apiKey=GIRDER_API_KEY) def handle_item(item, bc): bc = bc + (item['name'],) print '/'.join(bc) def handle_folder(folder, bc): bc = bc + (folder['name'],) folders = gc.listFolder(folder['_id'], 'folder', limit=0) items = gc.listItem(folder['_id'], limit=0) for child in folders: handle_folder(child, bc) for item in items: handle_item(item, bc) def handle_collection(collection): bc = ('collection', collection['name']) folders = gc.listFolder(collection['_id'], 'collection', limit=0) for folder in folders: handle_folder(folder, bc) def handle_user(user): bc = ('user', user['email']) folders = gc.listFolder(user['_id'], 'user', limit=0) for folder in folders: handle_folder(folder, bc) def main(): users = gc.listUser(limit=0) for user in users: handle_user(user) collections = gc.listCollection(limit=0) for collection in collections: handle_collection(collection) if __name__ == '__main__': main()
{ "content_hash": "463a638190538a19a47e3c8978e25968", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 69, "avg_line_length": 27.954545454545453, "alnum_prop": 0.6341463414634146, "repo_name": "data-exp-lab/girder", "id": "56df5dcc218c25241120bd74b369bf09f2a97809", "size": "1230", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "scripts/midas/walk_girder.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CMake", "bytes": "42365" }, { "name": "CSS", "bytes": "61237" }, { "name": "Dockerfile", "bytes": "2416" }, { "name": "HCL", "bytes": "1424" }, { "name": "HTML", "bytes": "170299" }, { "name": "JavaScript", "bytes": "1399182" }, { "name": "Mako", "bytes": "8756" }, { "name": "Python", "bytes": "2388013" }, { "name": "Roff", "bytes": "17" }, { "name": "Ruby", "bytes": "10593" }, { "name": "Shell", "bytes": "7661" } ], "symlink_target": "" }
package org.assertj.core.error; import static org.assertj.core.util.DateUtil.formatTimeDifference; import java.util.Date; /** * Creates an error message indicating that an assertion that verifies that a {@link Date} is in minute window as * another one failed. * * @author Joel Costigliola */ public class ShouldBeInSameMinuteWindow extends BasicErrorMessageFactory { /** * Creates a new </code>{@link ShouldBeInSameMinuteWindow}</code>. * * @param actual the actual value in the failed assertion. * @param other the value used in the failed assertion to compare the actual value to. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeInSameMinuteWindow(Date actual, Date other) { return new ShouldBeInSameMinuteWindow(actual, other); } private ShouldBeInSameMinuteWindow(Date actual, Date other) { super("%nExpecting:%n <%s>%nto be close to:%n <%s>%nby less than one minute (strictly) but difference was: " + formatTimeDifference(actual, other), actual, other); } }
{ "content_hash": "bb8a3d70b734a058aa85b2ea7599c4f7", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 114, "avg_line_length": 34.645161290322584, "alnum_prop": 0.7327746741154563, "repo_name": "dorzey/assertj-core", "id": "d7cbe5bff815db6a1b917d1200992061f62bec4b", "size": "1681", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/assertj/core/error/ShouldBeInSameMinuteWindow.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "8364137" }, { "name": "Shell", "bytes": "40820" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DM.MovieApi.ApiResponse; using DM.MovieApi.MovieDb; using DM.MovieApi.MovieDb.Companies; using DM.MovieApi.MovieDb.Genres; using DM.MovieApi.MovieDb.Movies; using DM.MovieApi.MovieDb.People; using DM.MovieApi.MovieDb.TV; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DM.MovieApi.IntegrationTests { internal static class ApiResponseUtil { internal const int TestInitThrottle = 375; internal const int PagingThrottle = 225; /// <summary> /// Slows down the starting of tests to keep themoviedb.org api from denying the request /// due to too many requests. This should be placed in the [TestInitialize] method. /// </summary> public static void ThrottleTests() { System.Threading.Thread.Sleep( TestInitThrottle ); } public static void AssertErrorIsNull( ApiResponseBase response ) { Assert.IsNull( response.Error, response.Error?.ToString() ?? "Makes Complier Happy" ); } public static void AssertImagePath( string path ) { Assert.IsTrue( path.StartsWith( "/" ), $"Actual: {path}" ); Assert.IsTrue( path.EndsWith( ".jpg" ) || path.EndsWith( ".png" ), $"Actual: {path}" ); } public static async Task AssertCanPageSearchResponse<T, TSearch>( TSearch search, int minimumPageCount, int minimumTotalResultsCount, Func<TSearch, int, Task<ApiSearchResponse<T>>> apiSearch, Func<T, int> keySelector ) { if( minimumPageCount < 2 ) { Assert.Fail( "minimumPageCount must be greater than 1." ); } var allFound = new List<T>(); int pageNumber = 1; do { System.Diagnostics.Trace.WriteLine( $"search: {search} | page: {pageNumber}", "ApiResponseUti.AssertCanPageSearchResponse" ); ApiSearchResponse<T> response = await apiSearch( search, pageNumber ); AssertErrorIsNull( response ); Assert.IsNotNull( response.Results ); Assert.IsTrue( response.Results.Any() ); if( typeof( T ) == typeof( Movie ) ) { AssertMovieStructure( (IEnumerable<Movie>)response.Results ); } else if( typeof( T ) == typeof( PersonInfo ) ) { AssertPersonInfoStructure( (IEnumerable<PersonInfo>)response.Results ); } allFound.AddRange( response.Results ); Assert.AreEqual( pageNumber, response.PageNumber ); Assert.IsTrue( response.TotalPages >= minimumPageCount, $"Expected minimum of {minimumPageCount} TotalPages. Actual TotalPages: {response.TotalPages}" ); pageNumber++; // keeps the system from being throttled System.Threading.Thread.Sleep( PagingThrottle ); } while( pageNumber <= minimumPageCount ); // will be 1 greater than minimumPageCount in the last loop Assert.AreEqual( minimumPageCount + 1, pageNumber ); Assert.IsTrue( allFound.Count >= minimumTotalResultsCount, $"Actual found count: {allFound.Count} | Expected min count: {minimumTotalResultsCount}" ); if( keySelector == null ) { // people searches will usually have dups since they return movie and tv roles // in separate objects in the same result set. return; } List<IGrouping<int, T>> groupById = allFound .ToLookup( keySelector ) .ToList(); List<string> dups = groupById .Where( x => x.Skip( 1 ).Any() ) .Select( x => $"({x.Count()}) {x.First().ToString()}" ) .ToList(); const string note = "Note: Every now and then themoviedb.org API returns a duplicate; not to be alarmed, just re-run the test until it passes.\r\n\r\n"; Assert.AreEqual( 0, dups.Count, note + " Duplicates: " + Environment.NewLine + string.Join( Environment.NewLine, dups ) ); } private static void AssertPersonInfoStructure( IEnumerable<PersonInfo> people ) { // ReSharper disable PossibleMultipleEnumeration Assert.IsTrue( people.Any() ); foreach( PersonInfo person in people ) { Assert.IsTrue( person.Id > 0 ); Assert.IsFalse( string.IsNullOrWhiteSpace( person.Name ) ); foreach( PersonInfoRole role in person.KnownFor ) { // not asserting movie/tv dates as some valid dates will be null. if( role.MediaType == MediaType.Movie ) { Assert.IsFalse( string.IsNullOrWhiteSpace( role.MovieTitle ) ); Assert.IsFalse( string.IsNullOrWhiteSpace( role.MovieOriginalTitle ) ); Assert.IsNull( role.TVShowName ); Assert.IsNull( role.TVShowOriginalName ); Assert.AreEqual( DateTime.MinValue, role.TVShowFirstAirDate ); } else { Assert.IsFalse( string.IsNullOrWhiteSpace( role.TVShowName ) ); Assert.IsFalse( string.IsNullOrWhiteSpace( role.TVShowOriginalName ) ); Assert.IsNull( role.MovieTitle ); Assert.IsNull( role.MovieOriginalTitle ); Assert.AreEqual( DateTime.MinValue, role.MovieReleaseDate ); } AssertGenres( role.GenreIds, role.Genres ); } } // ReSharper restore PossibleMultipleEnumeration } public static void AssertMovieStructure( IEnumerable<Movie> movies ) { // ReSharper disable PossibleMultipleEnumeration Assert.IsTrue( movies.Any() ); foreach( Movie movie in movies ) { AssertMovieStructure( movie ); } // ReSharper restore PossibleMultipleEnumeration } public static void AssertMovieStructure( Movie movie ) { Assert.IsTrue( movie.Id > 0 ); Assert.IsFalse( string.IsNullOrWhiteSpace( movie.Title ) ); foreach( Genre genre in movie.Genres ) { Assert.IsTrue( genre.Id > 0 ); Assert.IsFalse( string.IsNullOrWhiteSpace( genre.Name ) ); } foreach( ProductionCompanyInfo info in movie.ProductionCompanies ) { Assert.IsTrue( info.Id > 0 ); Assert.IsFalse( string.IsNullOrWhiteSpace( info.Name ) ); } foreach( Country country in movie.ProductionCountries ) { Assert.IsFalse( string.IsNullOrWhiteSpace( country.Iso3166Code ) ); Assert.IsFalse( string.IsNullOrWhiteSpace( country.Name ) ); } foreach( Language language in movie.SpokenLanguages ) { Assert.IsFalse( string.IsNullOrWhiteSpace( language.Iso639Code ) ); Assert.IsFalse( string.IsNullOrWhiteSpace( language.Name ) ); } } public static void AssertMovieInformationStructure( IEnumerable<MovieInfo> movies ) { // ReSharper disable once PossibleMultipleEnumeration Assert.IsTrue( movies.Any() ); // ReSharper disable once PossibleMultipleEnumeration foreach( MovieInfo movie in movies ) { AssertMovieInformationStructure( movie ); } } public static void AssertMovieInformationStructure( MovieInfo movie ) { Assert.IsFalse( string.IsNullOrWhiteSpace( movie.Title ) ); Assert.IsTrue( movie.Id > 0 ); AssertGenres( movie.GenreIds, movie.Genres ); } public static void AssertTVShowInformationStructure( IEnumerable<TVShowInfo> tvShows ) { // ReSharper disable once PossibleMultipleEnumeration Assert.IsTrue( tvShows.Any() ); // ReSharper disable once PossibleMultipleEnumeration foreach( TVShowInfo tvShow in tvShows ) { AssertTVShowInformationStructure( tvShow ); } } public static void AssertTVShowInformationStructure( TVShowInfo tvShow ) { Assert.IsTrue( tvShow.Id > 0 ); Assert.IsFalse( string.IsNullOrEmpty( tvShow.Name ) ); AssertGenres( tvShow.GenreIds, tvShow.Genres ); } private static void AssertGenres( IReadOnlyList<int> genreIds, IReadOnlyList<Genre> genres ) { Assert.AreEqual( genreIds.Count, genres.Count ); foreach( Genre genre in genres ) { Assert.IsFalse( string.IsNullOrWhiteSpace( genre.Name ) ); Assert.IsTrue( genre.Id > 0 ); } } } }
{ "content_hash": "510b523b02898920454562456e36b8e0", "timestamp": "", "source": "github", "line_count": 242, "max_line_length": 164, "avg_line_length": 38.72727272727273, "alnum_prop": 0.5689287238583013, "repo_name": "yeah-buddy/TheMovieDbWrapper", "id": "fb9e288527a845eaa4d9c4867bd7a569ed4e4bee", "size": "9374", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DM.MovieApi.IntegrationTests/ApiResponseUtil.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "207712" } ], "symlink_target": "" }
<!-- {% comment %} 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. {% endcomment %} --> # Apache Eagle > The intelligent monitoring and alerting solution instantly analyzes big data platforms for security and performance Apache® Eagle™ is an open source analytics solution for identifying security and performance issues instantly on big data platforms e.g. Apache Hadoop, Apache Spark, NoSQL etc. It analyzes data activities, yarn applications, jmx metrics, and daemon logs etc., provides state-of-the-art alert engine to identify security breach, performance issues and shows insights. For more details, please visit [https://eagle.apache.org](https://eagle.apache.org) [![Build Status](https://builds.apache.org/buildStatus/icon?job=incubator-eagle-main)](https://builds.apache.org/job/incubator-eagle-main/) [![Coverage Status](https://coveralls.io/repos/github/apache/incubator-eagle/badge.svg)](https://coveralls.io/github/apache/incubator-eagle) ## Documentation You can find the latest Eagle documentation on [https://eagle.apache.org](https://eagle.apache.org/docs). This [README](README.md) file only contains basic setup instructions. ## Downloads * Development Version: [eagle-0.5-SNAPSHOT](https://github.com/apache/eagle/archive/master.zip) (Under development) * Latest Release * [eagle-0.4.0-incubating](http://eagle.apache.org/docs/download-latest.html) * Archived Releases * [eagle-0.3.0-incubating](http://eagle.apache.org/docs/download.html#0.3.0-incubating) * [More releases](http://eagle.apache.org/docs/download.html) ## Getting Started ### Prerequisites * [JDK 8](https://jdk8.java.net/): Java Environment `Version 1.8` * [Apache Maven](https://maven.apache.org/): Project management and comprehension tool `Version 3.x` * [NPM](https://www.npmjs.com/): Node package management tool `Version 3.x` ### Building Eagle > Since version 0.5, Eagle is only built on JDK 8. Eagle is built using [Apache Maven](https://maven.apache.org/). NPM should be installed (On MAC OS try "brew install node"). To build Eagle, run: mvn clean package -DskipTests After successfully building, you will find eagle binary tarball at: eagle-assembly/target/eagle-${VERSION}-bin.tar.gz ### Testing Eagle mvn clean test ### Developing Eagle * (Optional) Install/Start [HDP Sandbox](http://hortonworks.com/products/sandbox/) which provide an all-in-one virtual machine with most dependency services like Zookeeper, Kafka, HBase, etc and monitored hadoop components. * Import Eagle as maven project with popular IDE like [IntelliJ IDEA](https://www.jetbrains.com/idea/) * Start **Eagle Server** in `debug` mode by running (default http port: `9090`, default smtp port: `5025`) org.apache.eagle.server.ServerDebug Which will start some helpful services for convenient development: * Local Eagle Service on [`http://localhost:9090`](http://localhost:9090) * Local SMTP Service on `localhost:5025` with REST API at [`http://localhost:9090/rest/mail`](http://localhost:9090/rest/mail) * Start **Eagle Apps** with Eagle Web UI in `LOCAL MODE`. ## Getting Help * **Mail**: The fastest way to get response from eagle community is to send email to the mail list [[email protected]](mailto:[email protected]), and remember to subscribe our mail list via [[email protected]](mailto:[email protected]) * **Slack**: Join Eagle community on Slack via [https://apacheeagle.slack.com](https://apacheeagle.slack.com) * **JIRA**: Report requirements, problems or bugs through apache jira system via [https://issues.apache.org/jira/browse/EAGLE](https://issues.apache.org/jira/browse/EAGLE) ## FAQ [https://cwiki.apache.org/confluence/display/EAG/FAQ](https://cwiki.apache.org/confluence/display/EAG/FAQ) ## Contributing Please review the [Contribution to Eagle Guide](https://cwiki.apache.org/confluence/display/EAG/Contributing+to+Eagle) for information on how to get started contributing to the project. ## License Licensed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0). More details, please refer to [LICENSE](LICENSE) file.
{ "content_hash": "311831aaa51c3c24a66e64e0b0cbca37", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 366, "avg_line_length": 49.63265306122449, "alnum_prop": 0.7582236842105263, "repo_name": "qingwen220/eagle", "id": "7b541b541aa3cd69a5645b42ff4746b224a655d2", "size": "4867", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "README.md", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "2884" }, { "name": "CSS", "bytes": "22406" }, { "name": "HTML", "bytes": "187205" }, { "name": "Java", "bytes": "7050367" }, { "name": "JavaScript", "bytes": "397846" }, { "name": "Protocol Buffer", "bytes": "2231" }, { "name": "Python", "bytes": "23520" }, { "name": "Scala", "bytes": "10594" }, { "name": "Shell", "bytes": "88354" } ], "symlink_target": "" }
<?php $marketing = new WPCF_Types_Marketing_Messages(); $show_documentation_link = false; ?> <?php if ( $top = $marketing->show_top($update) ) { echo '<div class="wpcf-notif">'; echo $top; echo '</div>'; } else { $message = false; switch( $type ) { case 'post_type': if ( $update ) { $message = __( 'Congratulations! Your Post Type %s was successfully updated.', 'wpcf' ); } else { $message = __( 'congratulations! your new Post Type %s was successfully created.', 'wpcf' ); } break; case 'fields': if ( $update) { $message = __( 'Congratulations! Your custom fields group %s was successfully updated.', 'wpcf' ); } else { $message = __( 'Congratulations! Your new custom fields group %s was successfully created.', 'wpcf' ); } break; case 'taxonomy': if ( $update) { $message = __( 'Congratulations! Your Taxonomy %s was successfully updated.', 'wpcf' ); } else { $message = __( 'Congratulations! Your new Taxonomy %s was successfully created.', 'wpcf' ); } break; case 'usermeta': if ( $update) { $message = __( 'Congratulations! Your user meta group %s was successfully updated.', 'wpcf' ); } else { $message = __( 'Congratulations! Your new user meta group %s was successfully created.', 'wpcf' ); } break; } $message = sprintf($message, sprintf('<strong>%s</strong>', $title)); $marketing->update_message($message); ?> <?php if ( $show_documentation_link ) { ?> <a href="javascript:void(0);" class="wpcf-button show <?php if ( $update ) echo 'wpcf-show'; else echo 'wpcf-hide'; ?>"><?php _e( 'Show next steps and documentation', 'wpcf' ); ?><span class="wpcf-button-arrow show"></span></a> <?php } ?> <?php $class = $update ? ' wpcf-hide' : ' wpcf-show'; ?> <div class="wpcf-notif-dropdown<?php echo $class; ?>"> <span><strong><?php _e( 'Next, learn how to:', 'wpcf' ); ?></strong></span> <?php if ( $type == 'post_type' ): ?> <ul> <li><a target="_blank" href="http://wp-types.com/documentation/user-guides/using-custom-fields/?utm_source=typesplugin&utm_medium=next-steps&utm_term=adding-fields&utm_campaign=types"><?php _e( 'Enrich content using <strong>custom fields</strong>', 'wpcf' ); ?> &raquo;</a></li> <li><a target="_blank" href="http://wp-types.com/documentation/user-guides/create-custom-taxonomies/?utm_source=typesplugin&utm_medium=next-steps&utm_term=using-taxonomy&utm_campaign=types"><?php _e( 'Organize content using <strong>taxonomy</strong>', 'wpcf' ); ?> &raquo;</a></li> <li><a target="_blank" href="http://wp-types.com/documentation/user-guides/many-to-many-post-relationship/?utm_source=typesplugin&utm_medium=next-steps&utm_term=parent-child&utm_campaign=types"><?php _e( 'Connect post types as <strong>parents and children</strong>', 'wpcf' ); ?> &raquo;</a></li> <li><a target="_blank" href="http://wp-types.com/documentation/user-guides/creating-wordpress-custom-post-archives/?utm_source=typesplugin&utm_medium=next-steps&utm_term=custom-post-archives&utm_campaign=types"><?php _e('Display custom post <strong>archives</strong>', 'wpcf' ); ?> &raquo;</a></li> </ul> <?php elseif ( $type == 'taxonomy' ): ?> <ul> <li><a target="_blank" href="http://wp-types.com/documentation/user-guides/create-custom-taxonomies/?utm_source=typesplugin&utm_medium=next-steps&utm_term=using-taxonomy&utm_campaign=types"><?php _e( 'Organize content using <strong>taxonomy</strong>', 'wpcf' ); ?> &raquo;</a></li> <li><a target="_blank" href="http://wp-types.com/documentation/user-guides/creating-wordpress-custom-taxonomy-archives/?utm_source=typesplugin&utm_medium=next-steps&utm_term=custom-taxonomy-archives&utm_campaign=types"><?php _e( 'Display Taxonomy <strong>archives</strong>', 'wpcf' ); ?> &raquo;</a></li> </ul> <?php elseif ( $type == 'usermeta' ): ?> <ul> <li><a target="_blank" href="http://wp-types.com/documentation/user-guides/displaying-wordpress-user-fields/?utm_source=typesplugin&utm_medium=next-steps&utm_term=display-user-fields&utm_campaign=types"><?php _e( 'Display user fields', 'wpcf' ); ?> &raquo;</a></li> </ul> <?php else: ?> <ul> <li><a target="_blank" href="http://wp-types.com/documentation/user-guides/displaying-wordpress-custom-fields/?utm_source=typesplugin&utm_medium=next-steps&utm_term=display-custom-fields&utm_campaign=types"><?php _e( 'Display custom fields', 'wpcf' ); ?> &raquo;</a></li> <li><a target="_blank" href="http://wp-types.com/documentation/user-guides/creating-groups-of-repeating-fields-using-fields-tables/?utm_source=typesplugin&utm_medium=next-steps&utm_term=repeating-fields-group&utm_campaign=types"><?php _e( 'Create groups of repeating fields', 'wpcf' ); ?> &raquo;</a></li> </ul> <?php endif; ?> <div class="hr"></div> <span><strong><?php _e( 'Build complete sites without coding:', 'wpcf' ); ?></strong></span> <ul> <li><a href="http://wp-types.com/documentation/user-guides/view-templates/?utm_source=typesplugin&utm_medium=next-steps&utm_term=single-pages&utm_campaign=types" target="_blank"><?php _e( 'Design templates for single pages', 'wpcf' ); ?> &raquo;</a></li> <li><a href="http://wp-types.com/documentation/user-guides/views/?utm_source=typesplugin&utm_medium=next-steps&utm_term=query-and-display&utm_campaign=types" target="_blank"><?php _e( 'Load and display custom content', 'wpcf' ); ?> &raquo;</a></li> </ul> <a href="javascript:void(0);" class="wpcf-button hide" style="float:right;"><?php _e( 'Hide notifications', 'wpcf' ); ?><span class="wpcf-button-arrow hide"></span></a> </div><!-- END .wpcf-notif-dropdown --> <?php } ?>
{ "content_hash": "4d0595eddac50d037dca343c0c23bb82", "timestamp": "", "source": "github", "line_count": 118, "max_line_length": 250, "avg_line_length": 55.19491525423729, "alnum_prop": 0.573929064947029, "repo_name": "Jezfx/rocket-theme", "id": "48fda99a53dfb060b8d5dac1a36e48e24e7d8e5a", "size": "6513", "binary": false, "copies": "24", "ref": "refs/heads/master", "path": "site assets/plugins/types/library/toolset/types/marketing/congrats-post-types/index.php", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "33066" }, { "name": "CSS", "bytes": "1227239" }, { "name": "HTML", "bytes": "726572" }, { "name": "JavaScript", "bytes": "3707482" }, { "name": "LiveScript", "bytes": "6103" }, { "name": "M4", "bytes": "221" }, { "name": "Modelica", "bytes": "10338" }, { "name": "PHP", "bytes": "13144478" }, { "name": "Perl", "bytes": "2554" }, { "name": "Shell", "bytes": "5391" } ], "symlink_target": "" }
<?php namespace Zend\Http\Header; use Zend\Http\Request; /** * Allow Header * * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.7 */ class Allow implements HeaderInterface { /** * List of request methods * true states that method is allowed, false - disallowed * By default GET and POST are allowed * * @var array */ protected $methods = array( Request::METHOD_OPTIONS => false, Request::METHOD_GET => true, Request::METHOD_HEAD => false, Request::METHOD_POST => true, Request::METHOD_PUT => false, Request::METHOD_DELETE => false, Request::METHOD_TRACE => false, Request::METHOD_CONNECT => false, Request::METHOD_PATCH => false, ); /** * Create Allow header from header line * * @param string $headerLine * @return Allow * @throws Exception\InvalidArgumentException */ public static function fromString($headerLine) { $header = new static(); list($name, $value) = explode(': ', $headerLine, 2); // check to ensure proper header type for this factory if (strtolower($name) !== 'allow') { throw new Exception\InvalidArgumentException('Invalid header line for Allow string: "' . $name . '"'); } // reset list of methods $header->methods = array_fill_keys(array_keys($header->methods), false); // allow methods from header line foreach (explode(',', $value) as $method) { $method = trim(strtoupper($method)); $header->methods[$method] = true; } return $header; } /** * Get header name * * @return string */ public function getFieldName() { return 'Allow'; } /** * Get comma-separated list of allowed methods * * @return string */ public function getFieldValue() { return implode(', ', array_keys($this->methods, true, true)); } /** * Get list of all defined methods * * @return array */ public function getAllMethods() { return $this->methods; } /** * Get list of allowed methods * * @return array */ public function getAllowedMethods() { return array_keys($this->methods, true, true); } /** * Allow methods or list of methods * * @param array|string $allowedMethods * @return Allow */ public function allowMethods($allowedMethods) { foreach ((array) $allowedMethods as $method) { $method = trim(strtoupper($method)); $this->methods[$method] = true; } return $this; } /** * Disallow methods or list of methods * * @param array|string $disallowedMethods * @return Allow */ public function disallowMethods($disallowedMethods) { foreach ((array) $disallowedMethods as $method) { $method = trim(strtoupper($method)); $this->methods[$method] = false; } return $this; } /** * Convenience alias for @see disallowMethods() * * @param array|string $disallowedMethods * @return Allow */ public function denyMethods($disallowedMethods) { return $this->disallowMethods($disallowedMethods); } /** * Check whether method is allowed * * @param string $method * @return bool */ public function isAllowedMethod($method) { $method = trim(strtoupper($method)); // disallow unknown method if (! isset($this->methods[$method])) { $this->methods[$method] = false; } return $this->methods[$method]; } /** * Return header as string * * @return string */ public function toString() { return 'Allow: ' . $this->getFieldValue(); } }
{ "content_hash": "3b75bd0fceba9536fc4eccabe6a95b28", "timestamp": "", "source": "github", "line_count": 174, "max_line_length": 114, "avg_line_length": 23.977011494252874, "alnum_prop": 0.5292425695110259, "repo_name": "psrearick/zf1Codenvy", "id": "a015dce667f15150be2e26c38036524623e18837", "size": "4480", "binary": false, "copies": "27", "ref": "refs/heads/master", "path": "vendor/ZF2/library/Zend/Http/Header/Allow.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "39673" }, { "name": "Shell", "bytes": "63" } ], "symlink_target": "" }
using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Analytics.Synapse.Spark.Models { public partial class SparkSession { internal static SparkSession DeserializeSparkSession(JsonElement element) { SparkSessionState livyInfo = default; string name = default; string workspaceName = default; string sparkPoolName = default; string submitterName = default; string submitterId = default; string artifactId = default; SparkJobType? jobType = default; SparkSessionResultType? result = default; SparkScheduler schedulerInfo = default; SparkServicePlugin pluginInfo = default; IReadOnlyList<SparkServiceError> errorInfo = default; IReadOnlyDictionary<string, string> tags = default; int id = default; string appId = default; IReadOnlyDictionary<string, string> appInfo = default; string state = default; IReadOnlyList<string> log = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("livyInfo")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } livyInfo = SparkSessionState.DeserializeSparkSessionState(property.Value); continue; } if (property.NameEquals("name")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } name = property.Value.GetString(); continue; } if (property.NameEquals("workspaceName")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } workspaceName = property.Value.GetString(); continue; } if (property.NameEquals("sparkPoolName")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } sparkPoolName = property.Value.GetString(); continue; } if (property.NameEquals("submitterName")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } submitterName = property.Value.GetString(); continue; } if (property.NameEquals("submitterId")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } submitterId = property.Value.GetString(); continue; } if (property.NameEquals("artifactId")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } artifactId = property.Value.GetString(); continue; } if (property.NameEquals("jobType")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } jobType = new SparkJobType(property.Value.GetString()); continue; } if (property.NameEquals("result")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } result = new SparkSessionResultType(property.Value.GetString()); continue; } if (property.NameEquals("schedulerInfo")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } schedulerInfo = SparkScheduler.DeserializeSparkScheduler(property.Value); continue; } if (property.NameEquals("pluginInfo")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } pluginInfo = SparkServicePlugin.DeserializeSparkServicePlugin(property.Value); continue; } if (property.NameEquals("errorInfo")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } List<SparkServiceError> array = new List<SparkServiceError>(); foreach (var item in property.Value.EnumerateArray()) { if (item.ValueKind == JsonValueKind.Null) { array.Add(null); } else { array.Add(SparkServiceError.DeserializeSparkServiceError(item)); } } errorInfo = array; continue; } if (property.NameEquals("tags")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (var property0 in property.Value.EnumerateObject()) { if (property0.Value.ValueKind == JsonValueKind.Null) { dictionary.Add(property0.Name, null); } else { dictionary.Add(property0.Name, property0.Value.GetString()); } } tags = dictionary; continue; } if (property.NameEquals("id")) { id = property.Value.GetInt32(); continue; } if (property.NameEquals("appId")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } appId = property.Value.GetString(); continue; } if (property.NameEquals("appInfo")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (var property0 in property.Value.EnumerateObject()) { if (property0.Value.ValueKind == JsonValueKind.Null) { dictionary.Add(property0.Name, null); } else { dictionary.Add(property0.Name, property0.Value.GetString()); } } appInfo = dictionary; continue; } if (property.NameEquals("state")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } state = property.Value.GetString(); continue; } if (property.NameEquals("log")) { if (property.Value.ValueKind == JsonValueKind.Null) { continue; } List<string> array = new List<string>(); foreach (var item in property.Value.EnumerateArray()) { if (item.ValueKind == JsonValueKind.Null) { array.Add(null); } else { array.Add(item.GetString()); } } log = array; continue; } } return new SparkSession(livyInfo, name, workspaceName, sparkPoolName, submitterName, submitterId, artifactId, jobType, result, schedulerInfo, pluginInfo, errorInfo, tags, id, appId, appInfo, state, log); } } }
{ "content_hash": "9931d20041b59041f426687af83aab63", "timestamp": "", "source": "github", "line_count": 241, "max_line_length": 215, "avg_line_length": 39.21576763485477, "alnum_prop": 0.4046132684372024, "repo_name": "stankovski/azure-sdk-for-net", "id": "de57d517f686ee65ea3dbdc320b15f9dcf09f3cc", "size": "9589", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sdk/synapse/Azure.Analytics.Synapse.Spark/src/Generated/Models/SparkSession.Serialization.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "33972632" }, { "name": "Cucumber", "bytes": "89597" }, { "name": "Shell", "bytes": "675" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Windows.Forms; namespace TestForTimeAnalyze { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new LanchTest()); } } }
{ "content_hash": "7d7bcf5eb1da74c059baccd454609093", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 65, "avg_line_length": 22.95, "alnum_prop": 0.5620915032679739, "repo_name": "luosz/ai-algorithmplatform", "id": "7275813b95b97d4fde1a3776850166fa49f014b4", "size": "481", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "AIAlgorithmPlatform/2007/util/curvePlotTool/TestForCurvePlot/Program.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "35444" }, { "name": "Batchfile", "bytes": "380" }, { "name": "C", "bytes": "2052" }, { "name": "C#", "bytes": "5809447" }, { "name": "CSS", "bytes": "5318" }, { "name": "HTML", "bytes": "255596" }, { "name": "XSLT", "bytes": "25249" } ], "symlink_target": "" }
module RuboCop module Cop module Layout # Checks that braces used for hash literals have or don't have # surrounding space depending on configuration. # # @example EnforcedStyle: space (default) # # The `space` style enforces that hash literals have # # surrounding space. # # # bad # h = {a: 1, b: 2} # # # good # h = { a: 1, b: 2 } # # @example EnforcedStyle: no_space # # The `no_space` style enforces that hash literals have # # no surrounding space. # # # bad # h = { a: 1, b: 2 } # # # good # h = {a: 1, b: 2} # # @example EnforcedStyle: compact # # The `compact` style normally requires a space inside # # hash braces, with the exception that successive left # # braces or right braces are collapsed together in nested hashes. # # # bad # h = { a: { b: 2 } } # foo = { { a: 1 } => { b: { c: 2 } } } # # # good # h = { a: { b: 2 }} # foo = {{ a: 1 } => { b: { c: 2 }}} # # @example EnforcedStyleForEmptyBraces: no_space (default) # # The `no_space` EnforcedStyleForEmptyBraces style enforces that # # empty hash braces do not contain spaces. # # # bad # foo = { } # bar = { } # # # good # foo = {} # bar = {} # # @example EnforcedStyleForEmptyBraces: space # # The `space` EnforcedStyleForEmptyBraces style enforces that # # empty hash braces contain space. # # # bad # foo = {} # # # good # foo = { } # foo = { } # foo = { } # class SpaceInsideHashLiteralBraces < Cop include SurroundingSpace include ConfigurableEnforcedStyle include RangeHelp MSG = 'Space inside %<problem>s.' def on_hash(node) tokens = processed_source.tokens hash_literal_with_braces(node) do |begin_index, end_index| check(tokens[begin_index], tokens[begin_index + 1]) return if begin_index == end_index - 1 check(tokens[end_index - 1], tokens[end_index]) end end def autocorrect(range) lambda do |corrector| # It is possible that BracesAroundHashParameters will remove the # braces while this cop inserts spaces. This can lead to unwanted # changes to the inspected code. If we replace the brace with a # brace plus space (rather than just inserting a space), then any # removal of the same brace will give us a clobbering error. This # in turn will make RuboCop fall back on cop-by-cop # auto-correction. Problem solved. case range.source when /\s/ then corrector.remove(range) when '{' then corrector.replace(range, '{ ') else corrector.replace(range, ' }') end end end private def hash_literal_with_braces(node) tokens = processed_source.tokens begin_index = index_of_first_token(node) return unless tokens[begin_index].left_brace? end_index = index_of_last_token(node) return unless tokens[end_index].right_curly_brace? yield begin_index, end_index end def check(token1, token2) # No offense if line break inside. return if token1.line < token2.line return if token2.comment? # Also indicates there's a line break. is_empty_braces = token1.left_brace? && token2.right_curly_brace? expect_space = expect_space?(token1, token2) if offense?(token1, expect_space) incorrect_style_detected(token1, token2, expect_space, is_empty_braces) else correct_style_detected end end def expect_space?(token1, token2) is_same_braces = token1.type == token2.type is_empty_braces = token1.left_brace? && token2.right_curly_brace? if is_same_braces && style == :compact false elsif is_empty_braces cop_config['EnforcedStyleForEmptyBraces'] != 'no_space' else style != :no_space end end def incorrect_style_detected(token1, token2, expect_space, is_empty_braces) brace = (token1.text == '{' ? token1 : token2).pos range = expect_space ? brace : space_range(brace) add_offense( range, location: range, message: message(brace, is_empty_braces, expect_space) ) do style = expect_space ? :no_space : :space ambiguous_or_unexpected_style_detected(style, token1.text == token2.text) end end def ambiguous_or_unexpected_style_detected(style, is_match) if is_match ambiguous_style_detected(style, :compact) else unexpected_style_detected(style) end end def offense?(token1, expect_space) has_space = token1.space_after? expect_space ? !has_space : has_space end def message(brace, is_empty_braces, expect_space) inside_what = if is_empty_braces 'empty hash literal braces' else brace.source end problem = expect_space ? 'missing' : 'detected' format(MSG, problem: "#{inside_what} #{problem}") end def space_range(token_range) if token_range.source == '{' range_of_space_to_the_right(token_range) else range_of_space_to_the_left(token_range) end end def range_of_space_to_the_right(range) src = range.source_buffer.source end_pos = range.end_pos end_pos += 1 while src[end_pos] =~ /[ \t]/ range_between(range.begin_pos + 1, end_pos) end def range_of_space_to_the_left(range) src = range.source_buffer.source begin_pos = range.begin_pos begin_pos -= 1 while src[begin_pos - 1] =~ /[ \t]/ range_between(begin_pos, range.end_pos - 1) end end end end end
{ "content_hash": "07c72b59abb5832e484c837c7c4a721a", "timestamp": "", "source": "github", "line_count": 205, "max_line_length": 78, "avg_line_length": 32.165853658536584, "alnum_prop": 0.5225962996663633, "repo_name": "smakagon/rubocop", "id": "fe7aa64fd64f0fe9b7147a3ca9e3cb42508af010", "size": "6625", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "lib/rubocop/cop/layout/space_inside_hash_literal_braces.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "355" }, { "name": "HTML", "bytes": "7106" }, { "name": "Ruby", "bytes": "3879814" } ], "symlink_target": "" }
 #pragma once #include <aws/elasticbeanstalk/ElasticBeanstalk_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSStreamFwd.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Xml { class XmlNode; } // namespace Xml } // namespace Utils namespace ElasticBeanstalk { namespace Model { /** * <p>A regular expression representing a restriction on a string configuration * option value.</p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/elasticbeanstalk-2010-12-01/OptionRestrictionRegex">AWS * API Reference</a></p> */ class AWS_ELASTICBEANSTALK_API OptionRestrictionRegex { public: OptionRestrictionRegex(); OptionRestrictionRegex(const Aws::Utils::Xml::XmlNode& xmlNode); OptionRestrictionRegex& operator=(const Aws::Utils::Xml::XmlNode& xmlNode); void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const; void OutputToStream(Aws::OStream& oStream, const char* location) const; /** * <p>The regular expression pattern that a string configuration option value with * this restriction must match.</p> */ inline const Aws::String& GetPattern() const{ return m_pattern; } /** * <p>The regular expression pattern that a string configuration option value with * this restriction must match.</p> */ inline bool PatternHasBeenSet() const { return m_patternHasBeenSet; } /** * <p>The regular expression pattern that a string configuration option value with * this restriction must match.</p> */ inline void SetPattern(const Aws::String& value) { m_patternHasBeenSet = true; m_pattern = value; } /** * <p>The regular expression pattern that a string configuration option value with * this restriction must match.</p> */ inline void SetPattern(Aws::String&& value) { m_patternHasBeenSet = true; m_pattern = std::move(value); } /** * <p>The regular expression pattern that a string configuration option value with * this restriction must match.</p> */ inline void SetPattern(const char* value) { m_patternHasBeenSet = true; m_pattern.assign(value); } /** * <p>The regular expression pattern that a string configuration option value with * this restriction must match.</p> */ inline OptionRestrictionRegex& WithPattern(const Aws::String& value) { SetPattern(value); return *this;} /** * <p>The regular expression pattern that a string configuration option value with * this restriction must match.</p> */ inline OptionRestrictionRegex& WithPattern(Aws::String&& value) { SetPattern(std::move(value)); return *this;} /** * <p>The regular expression pattern that a string configuration option value with * this restriction must match.</p> */ inline OptionRestrictionRegex& WithPattern(const char* value) { SetPattern(value); return *this;} /** * <p>A unique name representing this regular expression.</p> */ inline const Aws::String& GetLabel() const{ return m_label; } /** * <p>A unique name representing this regular expression.</p> */ inline bool LabelHasBeenSet() const { return m_labelHasBeenSet; } /** * <p>A unique name representing this regular expression.</p> */ inline void SetLabel(const Aws::String& value) { m_labelHasBeenSet = true; m_label = value; } /** * <p>A unique name representing this regular expression.</p> */ inline void SetLabel(Aws::String&& value) { m_labelHasBeenSet = true; m_label = std::move(value); } /** * <p>A unique name representing this regular expression.</p> */ inline void SetLabel(const char* value) { m_labelHasBeenSet = true; m_label.assign(value); } /** * <p>A unique name representing this regular expression.</p> */ inline OptionRestrictionRegex& WithLabel(const Aws::String& value) { SetLabel(value); return *this;} /** * <p>A unique name representing this regular expression.</p> */ inline OptionRestrictionRegex& WithLabel(Aws::String&& value) { SetLabel(std::move(value)); return *this;} /** * <p>A unique name representing this regular expression.</p> */ inline OptionRestrictionRegex& WithLabel(const char* value) { SetLabel(value); return *this;} private: Aws::String m_pattern; bool m_patternHasBeenSet; Aws::String m_label; bool m_labelHasBeenSet; }; } // namespace Model } // namespace ElasticBeanstalk } // namespace Aws
{ "content_hash": "2f1dc621eb8ebac0a16ae5df443f4706", "timestamp": "", "source": "github", "line_count": 140, "max_line_length": 118, "avg_line_length": 33.05714285714286, "alnum_prop": 0.6791270527225584, "repo_name": "cedral/aws-sdk-cpp", "id": "72a18b6b03cd82d53ee06306caf3e8893be029f3", "size": "4747", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "aws-cpp-sdk-elasticbeanstalk/include/aws/elasticbeanstalk/model/OptionRestrictionRegex.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "294220" }, { "name": "C++", "bytes": "428637022" }, { "name": "CMake", "bytes": "862025" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "7904" }, { "name": "Java", "bytes": "352201" }, { "name": "Python", "bytes": "106761" }, { "name": "Shell", "bytes": "10891" } ], "symlink_target": "" }
#ifndef INCLUDE_SCHED_SMPCALL_H #define INCLUDE_SCHED_SMPCALL_H #include <stdbool.h> /* Calls a specific function on all other cpu's if wait is true this function will block until every cpu is finished */ void smpCallFunction(void (*func)(void* arg), void *arg, bool wait); /* Sets up the smpcall interrupt */ void smpCallInit(void); #endif
{ "content_hash": "d4144a91834619858b477b59503c3fb2", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 68, "avg_line_length": 20.235294117647058, "alnum_prop": 0.747093023255814, "repo_name": "racing19th/MiraiOS", "id": "957c449c6bd224ebb9b2f01a9225f8c6407ff138", "size": "344", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "kernel/include/sched/smpcall.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "37462" }, { "name": "C", "bytes": "33109" }, { "name": "C++", "bytes": "583" }, { "name": "Makefile", "bytes": "2779" } ], "symlink_target": "" }
""" vg_config.py: Default configuration values all here (and only here), as well as logic for reading and generating config files. """ import argparse, sys, os, os.path, errno, random, subprocess, shutil, itertools, glob, tarfile import doctest, re, json, collections, time, timeit import logging, logging.handlers, struct, socket, threading import string import getpass import pdb import textwrap import yaml from toil_vg.vg_common import require, test_docker, test_singularity # Determine what containerization to default to in the config. We use Docker # with higher priority than Singularity because Singularity is our work-around. default_container = "Docker" if test_docker() else ("Singularity" if test_singularity() else "None") default_config = textwrap.dedent(""" # Toil VG Pipeline configuration file (created by toil-vg generate-config) # This configuration file is formatted in YAML. Simply write the value (at least one space) after the colon. # Edit the values in the configuration file and then rerun the pipeline: "toil-vg run" # # URLs can take the form: "/", "s3://" # Local inputs follow the URL convention: "/full/path/to/input.txt" # S3 URLs follow the convention: "s3://bucket/directory/file.txt" # # Comments (beginning with #) do not need to be removed. # Command-line options take priority over parameters in this file. ###################################################################################################################### ########################################### ### Toil resource tuning ### # These parameters must be adjusted based on data and cluster size # when running on anything other than single-machine mode # TODO: Reduce number of parameters here. Seems fine grained, especially for disk/mem # option to spin off config files for small/medium/large datasets? # The following parameters assign resources to small helper jobs that typically don't do # do any computing outside of toil overhead. Generally do not need to be changed. misc-cores: 1 misc-mem: '1G' misc-disk: '1G' # Resources allotted for vcf preprocessing. preprocess-cores: 1 preprocess-mem: '2G' preprocess-disk: '2G' # Resources allotted for vg construction. construct-cores: 1 construct-mem: '4G' construct-disk: '2G' # Resources allotted for xg indexing. xg-index-cores: 1 xg-index-mem: '4G' xg-index-disk: '2G' # Resources allotted for xg indexing by chromosome (used for GBWT). gbwt-index-cores: 1 gbwt-index-mem: '4G' gbwt-index-disk: '2G' gbwt-index-preemptable: True # Resources allotted for gcsa pruning. Note that the vg mod commands used in # this stage generally cannot take advantage of more than one thread prune-cores: 1 prune-mem: '4G' prune-disk: '2G' # Resources allotted gcsa indexing gcsa-index-cores: 1 gcsa-index-mem: '4G' gcsa-index-disk: '8G' gcsa-index-preemptable: True # Resources allotted for snarl indexing. snarl-index-cores: 1 snarl-index-mem: '4G' snarl-index-disk: '2G' # Resources allotted for distance indexing. distance-index-cores: 8 distance-index-mem: '4G' distance-index-disk: '2G' # Resources allotted for minimizer indexing. minimizer-index-cores: 8 minimizer-index-mem: '4G' minimizer-index-disk: '2G' # Resources for BWA indexing. bwa-index-cores: 1 bwa-index-mem: '4G' bwa-index-disk: '2G' # Resources for minimap2 indexing. minimap2-index-cores: 1 minimap2-index-mem: '4G' minimap2-index-disk: '2G' # Resources for fastq splitting and gam merging # Important to assign as many cores as possible here for large fastq inputs fq-split-cores: 1 fq-split-mem: '4G' fq-split-disk: '2G' # Resources for *each* vg map job # the number of vg map jobs is controlled by reads-per-chunk (below) alignment-cores: 1 alignment-mem: '4G' alignment-disk: '2G' # Resources for chunking up a graph/gam for calling (and merging) # typically take xg for whoe grpah, and gam for a chromosome chunk-cores: 1 chunk-mem: '4G' chunk-disk: '2G' # Resources for augmenting a graph augment-cores: 1 augment-mem: '4G' augment-disk: '2G' # Resources for calling each chunk (currently includes augment/call/genotype) calling-cores: 1 calling-mem: '4G' calling-disk: '2G' # Resources for vcfeval vcfeval-cores: 1 vcfeval-mem: '4G' vcfeval-disk: '2G' # Resources for vg sim sim-cores: 2 sim-mem: '4G' sim-disk: '2G' ########################################### ### Arguments Shared Between Components ### # Use output store instead of toil for all intermediate files (use only for debugging) force-outstore: False # Toggle container support. Valid values are Docker / Singularity / None # (commenting out or Null values equivalent to None) container: """ + (default_container) + """ ############################# ### Docker Tool Arguments ### ## Docker Tool List ## ## Locations of docker images. ## If empty or commented, then the tool will be run directly from the command line instead ## of through docker. # Docker image to use for vg vg-docker: 'quay.io/vgteam/vg:v1.34.0' # Docker image to use for bcftools bcftools-docker: 'quay.io/biocontainers/bcftools:1.9--h4da6232_0' # Docker image to use for tabix tabix-docker: 'lethalfang/tabix:1.7' # Docker image to use for samtools samtools-docker: 'quay.io/ucsc_cgl/samtools:latest' # Docker image to use for bwa bwa-docker: 'quay.io/ucsc_cgl/bwa:latest' # Docker image to use for minimap2 minimap2-docker: 'evolbioinfo/minimap2:v2.14' # Docker image to use for jq jq-docker: 'celfring/jq' # Docker image to use for rtg rtg-docker: 'realtimegenomics/rtg-tools:3.8.4' # Docker image to use for pigz pigz-docker: 'quay.io/glennhickey/pigz:latest' # Docker image to use to run R scripts r-docker: 'rocker/tidyverse:3.5.1' # Docker image to use for vcflib vcflib-docker: 'quay.io/biocontainers/vcflib:1.0.0_rc1--0' # Docker image to use for Freebayes freebayes-docker: 'maxulysse/freebayes:1.2.5' # Docker image to use for Platypus platypus-docker: 'quay.io/biocontainers/platypus-variant:0.8.1.1--htslib1.7_1' # Docker image to use for hap.py happy-docker: 'donfreed12/hap.py:v0.3.9' # Docker image to use for bedtools bedtools-docker: 'quay.io/biocontainers/bedtools:2.27.0--1' # Docker image to use for bedops bedops-docker: 'quay.io/biocontainers/bedops:2.4.35--0' # Docker image to use for sveval R package sveval-docker: 'jmonlong/sveval:version-2.0.0' # Docker image to use for gatk gatk-docker: 'broadinstitute/gatk:4.1.1.0' # Docker image to use for gatk3 gatk3-docker: 'broadinstitute/gatk3:3.8-1' # Docker image to use for snpEff snpEff-docker: 'quay.io/biocontainers/snpeff:5.0--hdfd78af_1' # Docker image to use for picard picard-docker: 'broadinstitute/picard:2.21.9' # Docker image to use for whatshap whatshap-docker: 'quay.io/biocontainers/whatshap:0.18--py37h6bb024c_0' # Docker image to use for eagle eagle-docker: 'quay.io/cmarkello/eagle' # Docker image to use for vcf2shebang vcf2shebang-docker: 'quay.io/cmarkello/vcf2shebang_grch38:latest' # Docker image to use for cadd cadd-docker: 'quay.io/cmarkello/cadd_1.6:latest' # Docker image to use for cadd editor caddeditor-docker: 'quay.io/cmarkello/cadd_editor:latest' # Docker image to use for bmtb bmtb-docker: 'quay.io/cmarkello/bmtb_grch38:latest' # Docker image to use for vcftools vcftools-docker: 'biocontainers/vcftools:v0.1.16-1-deb_cv1' # Docker image to use for vt vt-docker: 'quay.io/biocontainers/vt:0.57721--heae7c10_3' # Docker image to use for deepvariant deepvariant-docker: 'google/deepvariant:1.1.0' # Docker image to use for glnexus glnexus-docker: 'quay.io/mlin/glnexus:v1.2.7' # Docker image to use for abra2 abra2-docker: 'dceoy/abra2:latest' # Docker image to use for deeptrio deeptrio-docker: 'google/deepvariant:deeptrio-1.1.0' # Docker image to use for mosaicism detection mosaicism-docker: 'quay.io/cmarkello/mosaicism_detector:latest' ############################## ### vg_construct Arguments ### # Number of times to iterate normalization when --normalized used in construction normalize-iterations: 10 ########################## ### vg_index Arguments ### # Options to pass to vg prune. # (limit to general parameters, currently -k, -e, s. # Rest decided by toil-vg via other options like prune-mode) prune-opts: [] # Options to pass to vg gcsa indexing gcsa-opts: [] # Options to pass to vg minimizer indexing minimizer-opts: [] # Randomly phase unphased variants when constructing GBWT force-phasing: True ######################## ### vg_map Arguments ### # Toggle whether reads are split into chunks single-reads-chunk: False # Number of reads per chunk to use when splitting up fastq. # (only applies if single-reads-chunk is False) # Each chunk will correspond to a vg map job reads-per-chunk: 10000000 # Core arguments for vg mapping (do not include file names or -t/--threads) # Note -i/--interleaved will be ignored. use the --interleaved option # on the toil-vg command line instead map-opts: [] # Core arguments for vg multipath mapping (do not include file names or -t/--threads) mpmap-opts: ['--output-fmt', 'GAM'] # Core arguments for vg giraffe mapping (do not include file names or -t/--threads) giraffe-opts: [] ######################## ### vg_msga Arguments ### # Core arguments for vg msgaing (do not include file names or -t/--threads) msga-opts: [] # Number of steps to conext expand target regions before aligning with msga msga-context: 50 ######################### ### vg_call Arguments ### # Options to pass to vg filter when running vg call. (do not include file names or -t/--threads) filter-opts: [] # Options to pass to vg augment. (do not include any file names or -t/--threads or -a/--augmentation-mode) augment-opts: [] # Options to pass to vg pack. (do not include any file names or -t/--threads) pack-opts: [] # Options to pass to vg call. (do not include file/contig/sample names or -t/--threads) call-opts: [] ######################### ### vcfeval Arguments ### # Options to pass to rgt vcfeval. (do not include filenaems or threads or BED) vcfeval-opts: ['--ref-overlap'] ######################### ### sim and mapeval Arguments ### # Options to pass to vg sim (should not include -x, -n, -s or -a) sim-opts: ['--read-length', '150', '--frag-len', '570', '--frag-std-dev', '165', '--sub-rate', '0.01', '--indel-rate', '0.002'] # Options to pass to bwa bwa-opts: [] # Options to pass to minimap2 minimap2-opts: ['-ax', 'sr'] """) whole_genome_config = textwrap.dedent(""" # Toil VG Pipeline configuration file (created by toil-vg generate-config) # This configuration file is formatted in YAML. Simply write the value (at least one space) after the colon. # Edit the values in the configuration file and then rerun the pipeline: "toil-vg run" # # URLs can take the form: "/", "s3://" # Local inputs follow the URL convention: "/full/path/to/input.txt" # S3 URLs follow the convention: "s3://bucket/directory/file.txt" # # Comments (beginning with #) do not need to be removed. # Command-line options take priority over parameters in this file. ###################################################################################################################### ########################################### ### Toil resource tuning ### # These parameters must be adjusted based on data and cluster size # when running on anything other than single-machine mode # TODO: Reduce number of parameters here. Seems fine grained, especially for disk/mem # option to spin off config files for small/medium/large datasets? # The following parameters assign resources to small helper jobs that typically don't do # do any computing outside of toil overhead. Generally do not need to be changed. misc-cores: 1 misc-mem: '1G' misc-disk: '1G' # Resources allotted for vcf preprocessing. preprocess-cores: 1 preprocess-mem: '8G' preprocess-disk: '64G' # Resources allotted for vg construction. construct-cores: 1 construct-mem: '64G' construct-disk: '64G' # Resources allotted for xg indexing. xg-index-cores: 16 xg-index-mem: '200G' xg-index-disk: '100G' # Resources allotted for xg indexing by chromosome (used for GBWT). gbwt-index-cores: 4 gbwt-index-mem: '50G' gbwt-index-disk: '100G' gbwt-index-preemptable: True # Resources allotted for gcsa pruning. Note that the vg mod commands used in # this stage generally cannot take advantage of more than one thread prune-cores: 2 prune-mem: '60G' prune-disk: '60G' # Resources allotted gcsa indexing gcsa-index-cores: 32 gcsa-index-mem: '220G' gcsa-index-disk: '2200G' gcsa-index-preemptable: True # Resources alloted to snarl indexing snarl-index-cores: 1 snarl-index-mem: '200G' snarl-index-disk: '100G' # Resources allotted for distance indexing. distance-index-cores: 16 distance-index-mem: '220G' distance-index-disk: '100G' # Resources allotted for minimizer indexing. minimizer-index-cores: 16 minimizer-index-mem: '110G' minimizer-index-disk: '200G' # Resources for BWA indexing. bwa-index-cores: 1 bwa-index-mem: '40G' bwa-index-disk: '40G' # Resources for minimap2 indexing. minimap2-index-cores: 1 minimap2-index-mem: '40G' minimap2-index-disk: '40G' # Resources for fastq splitting and gam merging # Important to assign as many cores as possible here for large fastq inputs fq-split-cores: 32 fq-split-mem: '4G' fq-split-disk: '200G' # Resources for *each* vg map job # the number of vg map jobs is controlled by reads-per-chunk (below) alignment-cores: 32 alignment-mem: '100G' alignment-disk: '100G' # Resources for chunking up a graph/gam for calling (and merging) # typically take xg for whoe grpah, and gam for a chromosome chunk-cores: 16 chunk-mem: '100G' chunk-disk: '100G' # Resources for augmenting a graph augment-cores: 8 augment-mem: '64G' augment-disk: '64G' # Resources for calling each chunk (currently includes augment/call/genotype) calling-cores: 8 calling-mem: '60G' calling-disk: '16G' # Resources for vcfeval vcfeval-cores: 32 vcfeval-mem: '64G' vcfeval-disk: '64G' # Resources for vg sim sim-cores: 2 sim-mem: '20G' sim-disk: '100G' ########################################### ### Arguments Shared Between Components ### # Use output store instead of toil for all intermediate files (use only for debugging) force-outstore: False # Toggle container support. Valid values are Docker / Singularity / None # (commenting out or Null values equivalent to None) container: """ + (default_container) + """ ############################# ### Docker Tool Arguments ### ## Docker Tool List ## ## Locations of docker images. ## If empty or commented, then the tool will be run directly from the command line instead ## of through docker. # Docker image to use for vg vg-docker: 'quay.io/vgteam/vg:v1.34.0' # Docker image to use for bcftools bcftools-docker: 'quay.io/biocontainers/bcftools:1.9--h4da6232_0' # Docker image to use for tabix tabix-docker: 'lethalfang/tabix:1.7' # Docker image to use for samtools samtools-docker: 'quay.io/ucsc_cgl/samtools:latest' # Docker image to use for bwa bwa-docker: 'quay.io/ucsc_cgl/bwa:latest' # Docker image to use for minimap2 minimap2-docker: 'evolbioinfo/minimap2:v2.14' # Docker image to use for jq jq-docker: 'celfring/jq' # Docker image to use for rtg rtg-docker: 'realtimegenomics/rtg-tools:3.8.4' # Docker image to use for pigz pigz-docker: 'quay.io/glennhickey/pigz:latest' # Docker image to use to run R scripts r-docker: 'rocker/tidyverse:3.5.1' # Docker image to use for vcflib vcflib-docker: 'quay.io/biocontainers/vcflib:1.0.0_rc1--0' # Docker image to use for Freebayes freebayes-docker: 'maxulysse/freebayes:1.2.5' # Docker image to use for Platypus platypus-docker: 'quay.io/biocontainers/platypus-variant:0.8.1.1--htslib1.7_1' # Docker image to use for hap.py happy-docker: 'donfreed12/hap.py:v0.3.9' # Docker image to use for bedtools bedtools-docker: 'quay.io/biocontainers/bedtools:2.27.0--1' # Docker image to use for bedops bedops-docker: 'quay.io/biocontainers/bedops:2.4.35--0' # Docker image to use for sveval R package sveval-docker: 'jmonlong/sveval:version-2.0.0' # Docker image to use for gatk gatk-docker: 'broadinstitute/gatk:4.1.1.0' # Docker image to use for gatk3 gatk3-docker: 'broadinstitute/gatk3:3.8-1' # Docker image to use for snpEff snpEff-docker: 'quay.io/biocontainers/snpeff:5.0--hdfd78af_1' # Docker image to use for picard picard-docker: 'broadinstitute/picard:2.21.9' # Docker image to use for whatshap whatshap-docker: 'quay.io/biocontainers/whatshap:0.18--py37h6bb024c_0' # Docker image to use for eagle eagle-docker: 'quay.io/cmarkello/eagle' # Docker image to use for vcf2shebang vcf2shebang-docker: 'quay.io/cmarkello/vcf2shebang_grch38:latest' # Docker image to use for cadd cadd-docker: 'quay.io/cmarkello/cadd_1.6:latest' # Docker image to use for cadd editor caddeditor-docker: 'quay.io/cmarkello/cadd_editor:latest' # Docker image to use for bmtb bmtb-docker: 'quay.io/cmarkello/bmtb_grch38:latest' # Docker image to use for vcftools vcftools-docker: 'biocontainers/vcftools:v0.1.16-1-deb_cv1' # Docker image to use for vt vt-docker: 'quay.io/biocontainers/vt:0.57721--heae7c10_3' # Docker image to use for deepvariant deepvariant-docker: 'google/deepvariant:1.1.0' # Docker image to use for glnexus glnexus-docker: 'quay.io/mlin/glnexus:v1.2.7' # Docker image to use for abra2 abra2-docker: 'dceoy/abra2:latest' # Docker image to use for deeptrio deeptrio-docker: 'google/deepvariant:deeptrio-1.1.0' # Docker image to use for mosaicism detection mosaicism-docker: 'quay.io/cmarkello/mosaicism_detector:latest' ############################## ### vg_construct Arguments ### # Number of times to iterate normalization when --normalized used in construction normalize-iterations: 10 ########################## ### vg_index Arguments ### # Options to pass to vg prune. # (limit to general parameters, currently -k, -e, s. # Rest decided by toil-vg via other options like prune-mode) prune-opts: [] # Options to pass to vg gcsa indexing gcsa-opts: [] # Options to pass to vg minimizer indexing minimizer-opts: [] # Randomly phase unphased variants when constructing GBWT force-phasing: True ######################## ### vg_map Arguments ### # Toggle whether reads are split into chunks single-reads-chunk: False # Number of reads per chunk to use when splitting up fastq. # (only applies if single-reads-chunk is False) # Each chunk will correspond to a vg map job reads-per-chunk: 50000000 # Core arguments for vg mapping (do not include file names or -t/--threads) # Note -i/--interleaved will be ignored. use the --interleaved option # on the toil-vg command line instead map-opts: [] # Core arguments for vg multipath mapping (do not include file names or -t/--threads) mpmap-opts: ['--output-fmt', 'GAM'] # Core arguments for vg giraffe mapping (do not include file names or -t/--threads) giraffe-opts: [] ######################## ### vg_msga Arguments ### # Core arguments for vg msgaing (do not include file names or -t/--threads) msga-opts: [] # Number of steps to conext expand target regions before aligning with msga msga-context: 2000 ######################### ### vg_call Arguments ### # Options to pass to vg filter when running vg call. (do not include file names or -t/--threads) filter-opts: [] # Options to pass to vg augment. (do not include any file names or -t/--threads or -a/--augmentation-mode) augment-opts: [] # Options to pass to vg pack. (do not include any file names or -t/--threads) pack-opts: [] # Options to pass to vg call. (do not include file/contig/sample names or -t/--threads) call-opts: [] ######################### ### vcfeval Arguments ### # Options to pass to rgt vcfeval. (do not include filenaems or threads or BED) vcfeval-opts: ['--ref-overlap'] ######################### ### sim and mapeval Arguments ### # Options to pass to vg sim (should not include -x, -n, -s or -a) sim-opts: ['--read-length', '150', '--frag-len', '570', '--frag-std-dev', '165', '--sub-rate', '0.01', '--indel-rate', '0.002'] # Options to pass to bwa bwa-opts: [] # Options to pass to minimap2 minimap2-opts: ['-ax', 'sr'] """) def generate_config(whole_genome = False): return whole_genome_config if whole_genome is True else default_config def make_opts_list(x_opts): opts_list = list([a for a in x_opts.split(' ') if len(a)]) # get rid of any -t or --threads while we're at it for t in ['-t', '--threads']: if t in opts_list: pos = opts_list.index(t) del opts_list[pos:pos+2] return opts_list def apply_config_file_args(args): """ Merge args from the config file and the parser, giving priority to the parser. """ # turn --*_opts from strings to lists to be consistent with config file for x_opts in ['map_opts', 'call_opts', 'recall_opts', 'filter_opts', 'recall_filter_opts', 'genotype_opts', 'vcfeval_opts', 'sim_opts', 'bwa_opts', 'minimap2_opts', 'gcsa_opts', 'minimizer_opts', 'mpmap_opts', 'giraffe_opts', 'augment_opts', 'pack_opts', 'prune_opts']: if x_opts in list(args.__dict__.keys()) and type(args.__dict__[x_opts]) is str: args.__dict__[x_opts] = make_opts_list(args.__dict__[x_opts]) # do the same thing for more_mpmap_opts which is a list of strings if 'more_mpmap_opts' in list(args.__dict__.keys()) and args.__dict__['more_mpmap_opts']: for i, m_opts in enumerate(args.__dict__['more_mpmap_opts']): if isinstance(m_opts, str): args.__dict__['more_mpmap_opts'][i] = make_opts_list(m_opts) # If no config file given, we generate a default one wg_config = 'whole_genome_config' in list(args.__dict__.keys()) and args.whole_genome_config if 'config' not in list(args.__dict__.keys()) or args.config is None: config = generate_config(whole_genome = wg_config) else: if wg_config: raise RuntimeError('--config and --whole_genome_config cannot be used together') require(os.path.exists(args.config), 'Config, {}, not found. Please run ' '"toil-vg generate-config > {}" to create.'.format(args.config, args.config)) with open(args.config) as conf: config = conf.read() # Parse config parsed_config = {x.replace('-', '_'): y for x, y in list(yaml.safe_load(config).items())} if 'prune_opts_2' in parsed_config: raise RuntimeError('prune-opts-2 from config no longer supported') options = argparse.Namespace(**parsed_config) # Add in options from the program arguments to the arguments in the config file # program arguments that are also present in the config file will overwrite the # arguments in the config file for args_key in args.__dict__: # Add in missing program arguments to config option list and # overwrite config options with corresponding options that are not None in program arguments if (args.__dict__[args_key] is not None) or (args_key not in list(options.__dict__.keys())): options.__dict__[args_key] = args.__dict__[args_key] return options def config_subparser(parser): """ Create a subparser for config. Should pass in results of subparsers.add_parser() """ parser.add_argument("--whole_genome", action="store_true", help="Make config tuned to process a whole genome on 32-core instances") parser.add_argument("--config", type=argparse.FileType('w'), default=sys.stdout, help="config file to write to") def config_main(options): """ config just prints out a file """ options.config.write(generate_config(options.whole_genome))
{ "content_hash": "d5f304f18d3d1e4a28267e20520975df", "timestamp": "", "source": "github", "line_count": 757, "max_line_length": 127, "avg_line_length": 31.27212681638045, "alnum_prop": 0.6946310142356271, "repo_name": "vgteam/toil-vg", "id": "df0090d061a5a285d0e6a305a758bbe5c5f22c35", "size": "23698", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/toil_vg/vg_config.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "685" }, { "name": "Makefile", "bytes": "5736" }, { "name": "Python", "bytes": "997222" }, { "name": "Shell", "bytes": "56495" } ], "symlink_target": "" }
package org.apache.storm.starter.bolt; import org.apache.storm.topology.BasicOutputCollector; import org.apache.storm.topology.OutputFieldsDeclarer; import org.apache.storm.topology.base.BaseBasicBolt; import org.apache.storm.tuple.Tuple; public class PrinterBolt extends BaseBasicBolt { @Override public void execute(Tuple tuple, BasicOutputCollector collector) { System.out.println(tuple); } @Override public void declareOutputFields(OutputFieldsDeclarer ofd) { } }
{ "content_hash": "f433a4e5af8e8fba0f331204e49b84d0", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 70, "avg_line_length": 23.09090909090909, "alnum_prop": 0.7677165354330708, "repo_name": "kishorvpatil/incubator-storm", "id": "8364222a8b759cee09c0bb43c6bc0eb78e69bbf9", "size": "1292", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "examples/storm-starter/src/jvm/org/apache/storm/starter/bolt/PrinterBolt.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "54084" }, { "name": "CSS", "bytes": "12597" }, { "name": "Clojure", "bytes": "360353" }, { "name": "Fancy", "bytes": "6234" }, { "name": "FreeMarker", "bytes": "3512" }, { "name": "HTML", "bytes": "193952" }, { "name": "Java", "bytes": "12231046" }, { "name": "JavaScript", "bytes": "74893" }, { "name": "M4", "bytes": "1522" }, { "name": "Makefile", "bytes": "1302" }, { "name": "PowerShell", "bytes": "3405" }, { "name": "Python", "bytes": "1039019" }, { "name": "Ruby", "bytes": "15824" }, { "name": "Shell", "bytes": "24486" }, { "name": "Thrift", "bytes": "31772" }, { "name": "XSLT", "bytes": "1365" } ], "symlink_target": "" }
cask 'adobe-illustrator-cc-fr' do version :latest sha256 :no_check url 'http://trials3.adobe.com/AdobeProducts/ILST/19/osx10-64/Illustrator_19_LS20.dmg', user_agent: :fake, cookies: { 'MM_TRIALS' => '1234' } name 'Adobe Illustrator CC 2015' homepage 'https://www.adobe.com/products/illustrator.html' license :commercial conflicts_with cask: 'adobe-illustrator-cc' preflight do deployment_xml = "#{staged_path}/Adobe Illustrator CC 2015/Deployment/deployment.xml" File.open(deployment_xml) do |xml_before| contents = xml_before.read.gsub!('>en_US<', '>fr_FR<') File.open(deployment_xml, 'w+') { |xml_after| xml_after.write(contents) } end system '/usr/bin/sudo', '-E', '--', "#{staged_path}/Adobe Illustrator CC 2015/Install.app/Contents/MacOS/Install", '--mode=silent', "--deploymentFile=#{deployment_xml}" end uninstall_preflight do system '/usr/bin/sudo', '-E', '--', "#{staged_path}/Adobe Illustrator CC 2015/Install.app/Contents/MacOS/Install", '--mode=silent', "--deploymentFile=#{staged_path}/Adobe\ Illustrator\ CC\ 2015/Deployment/uninstall.xml" end uninstall rmdir: '/Applications/Utilities/Adobe Installers' end
{ "content_hash": "243e384422d470604136a9d49add726f", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 223, "avg_line_length": 40, "alnum_prop": 0.6891666666666667, "repo_name": "toonetown/homebrew-cask-versions", "id": "db1ebe79b8cd2123222939b7fcd4dc39ba5b8d1b", "size": "1200", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "Casks/adobe-illustrator-cc-fr.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ruby", "bytes": "222679" }, { "name": "Shell", "bytes": "4466" } ], "symlink_target": "" }
@interface KWDeviceInfoTest : XCTestCase @end @implementation KWDeviceInfoTest - (void)testItShouldDetectWhenRunningOnSimulator { #if TARGET_IPHONE_SIMULATOR BOOL isSimulator = [KWDeviceInfo isSimulator]; XCTAssertTrue(isSimulator, @"expected simulator device to be positive"); #else BOOL isSimulator = [KWDeviceInfo isSimulator]; XCTAssertFalse(isSimulator, @"expected simulator device to be negative"); #endif // #if TARGET_IPHONE_SIMULATOR } - (void)testItShouldDetectWhenRunningOnDevice { #if TARGET_IPHONE_SIMULATOR BOOL isPhysical = [KWDeviceInfo isPhysical]; XCTAssertFalse(isPhysical, @"expected physical device to be negative"); #else BOOL isPhysical = [KWDeviceInfo isPhysical]; XCTAssertTrue(isPhysical, @"expected physical device to be positive"); #endif // #if TARGET_IPHONE_SIMULATOR } @end #endif // #if KW_TESTS_ENABLED
{ "content_hash": "b61f834504d7b00fc3f600525cd541ae", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 77, "avg_line_length": 30.137931034482758, "alnum_prop": 0.7654462242562929, "repo_name": "howandhao/Kiwi", "id": "3b0b451f387b1829376683594bd00c650dec3231", "size": "1052", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Tests/KWDeviceInfoTest.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1490" }, { "name": "C++", "bytes": "1088" }, { "name": "Makefile", "bytes": "983" }, { "name": "Objective-C", "bytes": "536143" }, { "name": "Ruby", "bytes": "1183" }, { "name": "Shell", "bytes": "697" } ], "symlink_target": "" }
import java.io.*; public class FileIOC implements FileIO { private String textInFileName; private String binaryInFileName; public FileReader openInputFile(String fname) { FileReader fr = null; this.textInFileName = fname; try { fr = new FileReader(fname); } catch (FileNotFoundException e) { System.out.println("FileNotFoundException " + e); } return fr; } public BinaryOut openBinaryOutputFile(){ String binaryOutFileName = this.textInFileName.replace(".txt", ".zip"); if(Huff.DEBUG) System.out.println("In openBinaryOutputFile: new file name is " + binaryOutFileName); return new BinaryOut(binaryOutFileName); } public BinaryIn openBinaryInputFile(String fname) { this.binaryInFileName = fname; return new BinaryIn(fname); } public FileWriter openOutputFile() { FileWriter fw = null; String textOutFileName = this.binaryInFileName.replace(".zip", ".txt"); try { fw = new FileWriter(textOutFileName); } catch (IOException e) { System.out.println("openOutFile: FileNotFoundException: " + e); } return fw; } }
{ "content_hash": "2032945c2583c495f713e75ab51961df", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 97, "avg_line_length": 22.839285714285715, "alnum_prop": 0.6082877247849883, "repo_name": "rootulp/school", "id": "67edfb6643e1d259a38c86bf66fe6ec2474c357e", "size": "2243", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "cs102/PATEL8/FileIOC.java", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "45936" }, { "name": "C++", "bytes": "1652" }, { "name": "CSS", "bytes": "5716" }, { "name": "HTML", "bytes": "9052" }, { "name": "Java", "bytes": "384378" }, { "name": "JavaScript", "bytes": "26961" }, { "name": "PHP", "bytes": "50618" }, { "name": "Python", "bytes": "60717" }, { "name": "Ruby", "bytes": "35802" } ], "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> <meta http-equiv="Content-Type" content="text/html" charset="iso-8859-1"> <title>Uses of Class org.apache.commons.net.smtp.AuthenticatingSMTPClient (Commons Net 3.3 API)</title> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.commons.net.smtp.AuthenticatingSMTPClient (Commons Net 3.3 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/commons/net/smtp/AuthenticatingSMTPClient.html" title="class in org.apache.commons.net.smtp">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/commons/net/smtp/class-use/AuthenticatingSMTPClient.html" target="_top">Frames</a></li> <li><a href="AuthenticatingSMTPClient.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class org.apache.commons.net.smtp.AuthenticatingSMTPClient" class="title">Uses of Class<br>org.apache.commons.net.smtp.AuthenticatingSMTPClient</h2> </div> <div class="classUseContainer">No usage of org.apache.commons.net.smtp.AuthenticatingSMTPClient</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../org/apache/commons/net/smtp/AuthenticatingSMTPClient.html" title="class in org.apache.commons.net.smtp">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?org/apache/commons/net/smtp/class-use/AuthenticatingSMTPClient.html" target="_top">Frames</a></li> <li><a href="AuthenticatingSMTPClient.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2001-2013 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved.</small></p> </body> </html>
{ "content_hash": "21cc9be77852ccc54fd6c37794f34f3b", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 167, "avg_line_length": 40.095652173913045, "alnum_prop": 0.6068098026458469, "repo_name": "S43-Proftaakgroep/PTS4", "id": "d18434991006ca48d1b89f899a7fba2e8d5211f4", "size": "4611", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "CIMS/commons-net-3.3/apidocs/org/apache/commons/net/smtp/class-use/AuthenticatingSMTPClient.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "26329" }, { "name": "HTML", "bytes": "27593104" }, { "name": "Java", "bytes": "468525" }, { "name": "JavaScript", "bytes": "59674" } ], "symlink_target": "" }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class GameOver : MonoBehaviour { public Image Background; public Text ScoreLabel; public Text ComboLabel; public Text PerfectLabel; public Text GoodLabel; public Text BadLabel; public Text MissLabel; public Text ScoreText; public Text ComboText; public Text PerfectText; public Text GoodText; public Text BadText; public Text MissText; public Text Judgement; public Button RetryButton; public Text RetryButtonText; public Button BackButton; public Text BackButtonText; public Image BigCover; public Image SmallCover; public Image EndCover; Leap.Controller leap; long TotalScore; long ScoreNow; int MaxCombo; int ComboNow; int PerfectCount; int PerfectNow; int GoodCount; int GoodNow; int BadCount; int BadNow; int MissCount; int MissNow; bool ShowUI; bool DisplayDone; Color CoverColor; float Timer; bool Retrying = false; bool Backing = false; bool RBDone = false; // Use this for initialization void Start () { TotalScore = long.Parse (PlayerPrefs.GetString ("ScoreCount")); MaxCombo = PlayerPrefs.GetInt ("ComboCount"); PerfectCount = PlayerPrefs.GetInt ("PerfectCount"); GoodCount = PlayerPrefs.GetInt ("GoodCount"); BadCount = PlayerPrefs.GetInt ("BadCount"); MissCount = PlayerPrefs.GetInt ("MissCount"); Judgement.text = PlayerPrefs.GetString ("Judgement"); if (Judgement.text == "A") Judgement.color = new Color (58 / 255f, 183 / 255f, 239 / 255f); else if (Judgement.text == "B") Judgement.color = new Color (191 / 255f, 255 / 255f, 160 / 255f); else if (Judgement.text == "C") Judgement.color = new Color (251 / 255f, 208 / 255f, 114 / 255f); else if (Judgement.text == "D") Judgement.color = new Color (249 / 255f, 90 / 255f, 101 / 255f); ScoreNow = ComboNow = PerfectNow = GoodNow = BadNow = MissNow = 0; ShowUI = false; CoverColor = new Color (BigCover.color.r, BigCover.color.g, BigCover.color.b, 1); RetryButton.onClick.AddListener (Retry); BackButton.onClick.AddListener (Back); ScoreLabel.fontSize = ComboLabel.fontSize = PerfectLabel.fontSize = GoodLabel.fontSize = BadLabel.fontSize = MissLabel.fontSize = ScoreText.fontSize = ComboText.fontSize = PerfectText.fontSize = GoodText.fontSize = BadText.fontSize = MissText.fontSize = (int)(Screen.width / 22.5f); Judgement.fontSize = (int)(Screen.width * 0.35f); RetryButtonText.fontSize = BackButtonText.fontSize = (int)(Screen.width / 50f); float pos_x = -Screen.width / 3f, pos_y = Screen.height / 40f, pos_xx = pos_x + Screen.width / 4.5f; ScoreLabel.rectTransform.anchoredPosition = new Vector2 (pos_x, pos_y * 13); ComboLabel.rectTransform.anchoredPosition = new Vector2 (pos_x, pos_y * 9); PerfectLabel.rectTransform.anchoredPosition = new Vector2 (pos_x, pos_y * 3); GoodLabel.rectTransform.anchoredPosition = new Vector2 (pos_x, -pos_y * 1); BadLabel.rectTransform.anchoredPosition = new Vector2 (pos_x, -pos_y * 5); MissLabel.rectTransform.anchoredPosition = new Vector2 (pos_x, -pos_y * 9); ScoreText.rectTransform.anchoredPosition = new Vector2 (pos_xx, pos_y * 13); ComboText.rectTransform.anchoredPosition = new Vector2 (pos_xx, pos_y * 9); PerfectText.rectTransform.anchoredPosition = new Vector2 (pos_xx, pos_y * 3); GoodText.rectTransform.anchoredPosition = new Vector2 (pos_xx, -pos_y * 1); BadText.rectTransform.anchoredPosition = new Vector2 (pos_xx, -pos_y * 5); MissText.rectTransform.anchoredPosition = new Vector2 (pos_xx, -pos_y * 9); Judgement.rectTransform.anchoredPosition = new Vector2 (Screen.width / 4f, Screen.height / 10f); RetryButton.image.rectTransform.anchoredPosition = new Vector2 (Screen.width / 4f - Screen.width / 15f, -pos_y * 10f); BackButton.image.rectTransform.anchoredPosition = new Vector2 (Screen.width / 4f + Screen.width / 15f, -pos_y * 10f); RetryButton.image.rectTransform.sizeDelta = BackButton.image.rectTransform.sizeDelta = new Vector2 (Screen.width / 10f, Screen.width / 10f / 2.75f); SmallCover.rectTransform.sizeDelta = new Vector2 (Screen.width * 0.8f, Screen.height); Timer = 10f; leap = new Leap.Controller (); leap.EnableGesture (Leap.Gesture.GestureType.TYPE_SWIPE); //leap.Config.SetFloat ("Gesture.Swipe.MinLength", 200.0f); //leap.Config.SetFloat ("Gesture.Swipe.MinVelocity", 1050f); //leap.Config.Save (); /*TotalScore = 1000000; MaxCombo = 512; PerfectCount = 500; GoodCount = 200; BadCount = 10; MissCount = 5; Judgement.text = "S";*/ } // Update is called once per frame void Update () { if (RBDone) { if (Retrying) Application.LoadLevel ("InGame"); else Application.LoadLevel ("SelectMusic"); return; } if (Retrying || Backing) { if (CoverColor.a < 0) { Debug.Log (1); //BigCover = Instantiate (CoverPrefab); EndCover.rectTransform.sizeDelta = new Vector2 (Screen.width * 2, Screen.height * 2); CoverColor = new Color (EndCover.color.r, EndCover.color.g, EndCover.color.b, 0); } else { Debug.Log (2); CoverColor.a += Time.deltaTime * 2f; EndCover.color = CoverColor; if (CoverColor.a >= 1) RBDone = true; } return; } if (!ShowUI) { CoverColor.a -= Time.deltaTime * 2; BigCover.color = CoverColor; if (CoverColor.a <= 0) { ShowUI = true; CoverColor.a = 1f; CoverColor.r = CoverColor.g = CoverColor.b = 50 / 255f; Destroy (BigCover); } } if (!DisplayDone) { ScoreText.text = ScoreNow.ToString (); ComboText.text = ComboNow.ToString (); PerfectText.text = PerfectNow.ToString (); GoodText.text = GoodNow.ToString (); BadText.text = BadNow.ToString (); MissText.text = MissNow.ToString (); } if (DisplayDone) { if (Timer > 1) Timer = 0.5f; else if (Timer >= 0) Timer -= Time.deltaTime; Leap.Frame frame = leap.Frame (); foreach (Leap.Gesture gesture in frame.Gestures()) { if (gesture.Type == Leap.Gesture.GestureType.TYPE_SWIPE) { Leap.SwipeGesture swipeGesture = new Leap.SwipeGesture (gesture); Leap.Vector gestureDirection = swipeGesture.Direction; //float x = gestureDirection.x; float y = gestureDirection.y; Debug.Log (y); if (y > 0.7) Retry (); if (y < -0.7) Back (); } } if (Input.GetKey (KeyCode.DownArrow) || Input.GetKey (KeyCode.Escape) || Input.GetKey (KeyCode.S) || Input.GetKey (KeyCode.B)) { Back (); } if (Input.GetKey (KeyCode.UpArrow) || Input.GetKey (KeyCode.W) || Input.GetKey (KeyCode.R)) { Retry (); } } if (DisplayDone && Timer < 0 && CoverColor.a > 0) { CoverColor.a -= Time.deltaTime * 2; SmallCover.color = CoverColor; if (CoverColor.a <= 0) Destroy (SmallCover); } } void FixedUpdate() { DisplayDone = true; CounterPlus (ref ScoreNow, TotalScore, 10); CounterPlus (ref ComboNow, MaxCombo, 20); CounterPlus (ref PerfectNow, PerfectCount, 20); CounterPlus (ref GoodNow, GoodCount, 20); CounterPlus (ref BadNow, BadCount, 20); CounterPlus (ref MissNow, MissCount, 20); } void CounterPlus (ref int Counter, int max, int step) { if (Counter < max) { if (max - Counter >= step) Counter += (max - Counter) / step; else Counter++; DisplayDone = false; } } void CounterPlus (ref long Counter, long max, int step) { if (Counter < max) { if (max - Counter >= step) Counter += (max - Counter) / step; else Counter++; DisplayDone = false; } } void Retry () { Retrying = true; } void Back () { Backing = true; } }
{ "content_hash": "0a95794a6b188068746ace8090e32b01", "timestamp": "", "source": "github", "line_count": 253, "max_line_length": 150, "avg_line_length": 29.90118577075099, "alnum_prop": 0.6806345009914078, "repo_name": "39M/LMix", "id": "5194effd62b43a0066edd0d7ccb36ba43393af34", "size": "7567", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Scenes/GameOver/Scripts/GameOver.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "230012" }, { "name": "GLSL", "bytes": "25725" } ], "symlink_target": "" }
package org.mybatis.generator.codegen.ibatis2.sqlmap.elements; import java.util.Iterator; import org.mybatis.generator.api.IntrospectedColumn; import org.mybatis.generator.api.dom.xml.Attribute; import org.mybatis.generator.api.dom.xml.TextElement; import org.mybatis.generator.api.dom.xml.XmlElement; import org.mybatis.generator.codegen.ibatis2.Ibatis2FormattingUtilities; /** * * @author Jeff Butler * */ public class BaseColumnListElementGenerator extends AbstractXmlElementGenerator { public BaseColumnListElementGenerator() { super(); } @Override public void addElements(XmlElement parentElement) { XmlElement answer = new XmlElement("sql"); //$NON-NLS-1$ answer.addAttribute(new Attribute("id", //$NON-NLS-1$ introspectedTable.getBaseColumnListId())); context.getCommentGenerator().addComment(answer); StringBuilder sb = new StringBuilder(); Iterator<IntrospectedColumn> iter = introspectedTable.getNonBLOBColumns().iterator(); while (iter.hasNext()) { sb.append(Ibatis2FormattingUtilities.getSelectListPhrase(iter.next())); if (iter.hasNext()) { sb.append(", "); //$NON-NLS-1$ } if (sb.length() > 80) { answer.addElement(new TextElement(sb.toString())); sb.setLength(0); } } if (sb.length() > 0) { answer.addElement((new TextElement(sb.toString()))); } if (context.getPlugins().sqlMapBaseColumnListElementGenerated(answer, introspectedTable)) { parentElement.addElement(answer); } } }
{ "content_hash": "7c8f25c9df136a66ef7847134fb83559", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 93, "avg_line_length": 26.87272727272727, "alnum_prop": 0.7368064952638701, "repo_name": "cxjava/mybatis-generator-core", "id": "c8b64bd1355c78695e9985902e794fc1bfbf67ed", "size": "2101", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/main/java/org/mybatis/generator/codegen/ibatis2/sqlmap/elements/BaseColumnListElementGenerator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "207" }, { "name": "Java", "bytes": "1328408" } ], "symlink_target": "" }
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2015-2016 The Bitcoin Unlimited developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_RECEIVECOINSDIALOG_H #define BITCOIN_QT_RECEIVECOINSDIALOG_H #include "guiutil.h" #include <QDialog> #include <QHeaderView> #include <QItemSelection> #include <QKeyEvent> #include <QMenu> #include <QPoint> #include <QVariant> class OptionsModel; class PlatformStyle; class WalletModel; namespace Ui { class ReceiveCoinsDialog; } QT_BEGIN_NAMESPACE class QModelIndex; QT_END_NAMESPACE /** Dialog for requesting payment of bitcoins */ class ReceiveCoinsDialog : public QDialog { Q_OBJECT public: enum ColumnWidths { DATE_COLUMN_WIDTH = 130, LABEL_COLUMN_WIDTH = 120, AMOUNT_MINIMUM_COLUMN_WIDTH = 160, MINIMUM_COLUMN_WIDTH = 130 }; explicit ReceiveCoinsDialog(const PlatformStyle *platformStyle, QWidget *parent = 0); ~ReceiveCoinsDialog(); void setModel(WalletModel *model); public Q_SLOTS: void clear(); void reject(); void accept(); protected: virtual void keyPressEvent(QKeyEvent *event); private: Ui::ReceiveCoinsDialog *ui; GUIUtil::TableViewLastColumnResizingFixer *columnResizingFixer; WalletModel *model; QMenu *contextMenu; const PlatformStyle *platformStyle; void copyColumnToClipboard(int column); virtual void resizeEvent(QResizeEvent *event); private Q_SLOTS: void on_receiveButton_clicked(); void on_showRequestButton_clicked(); void on_removeRequestButton_clicked(); void on_recentRequestsView_doubleClicked(const QModelIndex &index); void recentRequestsView_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected); void updateDisplayUnit(); void showMenu(const QPoint &point); void copyLabel(); void copyMessage(); void copyAmount(); }; #endif // BITCOIN_QT_RECEIVECOINSDIALOG_H
{ "content_hash": "272341dcafed4c86ce35ff33b9bc8628", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 111, "avg_line_length": 25.675, "alnum_prop": 0.7361246348588121, "repo_name": "marlengit/BitcoinUnlimited", "id": "e87ab85f3c882bb86ebf1695d102428f5a7c5892", "size": "2054", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/qt/receivecoinsdialog.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "673068" }, { "name": "C++", "bytes": "4721435" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50621" }, { "name": "Java", "bytes": "2100" }, { "name": "M4", "bytes": "171508" }, { "name": "Makefile", "bytes": "98953" }, { "name": "Objective-C", "bytes": "5785" }, { "name": "Objective-C++", "bytes": "7360" }, { "name": "Protocol Buffer", "bytes": "2308" }, { "name": "Python", "bytes": "756383" }, { "name": "QMake", "bytes": "2020" }, { "name": "Roff", "bytes": "3821" }, { "name": "Shell", "bytes": "36574" } ], "symlink_target": "" }
module Mnemosyne module Probes module Grape module EndpointRun class Probe < ::Mnemosyne::Probe subscribe 'endpoint_run.grape' def call(trace, _name, start, finish, _id, payload) start = ::Mnemosyne::Clock.to_tick(start) finish = ::Mnemosyne::Clock.to_tick(finish) endpoint = payload[:endpoint] return unless endpoint meta = { endpoint: extract_name(endpoint), format: extract_format(payload[:env]) } span = ::Mnemosyne::Span.new 'app.controller.request.grape', start: start, finish: finish, meta: meta trace << span end private def extract_name(endpoint) endpoint.options[:for].to_s end def extract_format(env) env['api.format'] end end end end register 'Grape::Endpoint', 'grape/endpoint', Grape::EndpointRun::Probe.new end end
{ "content_hash": "37e0b03938dc43d0506272d8065a99fd", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 72, "avg_line_length": 24.13953488372093, "alnum_prop": 0.5317919075144508, "repo_name": "jgraichen/mnemosyne-ruby", "id": "05f46cc620688d7c006f8b03f7dd3939c9d58dff", "size": "1069", "binary": false, "copies": "1", "ref": "refs/heads/fl/view-component", "path": "lib/mnemosyne/probes/grape/endpoint_run.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "59871" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
class ResultPresenter attr_reader :title, :keys, :values def initialize(title, result_hash) @title = title if result_hash @exist = true @keys = [] @values = [] @result_hash = result_hash each_pair do |key, value| @keys << key @values << value end else @exist = false @result_hash = {} end end def key_javascript_array @keys.to_json end def value_javascript_array @values.to_json end def each_pair @result_hash.each_pair do |key, value| next if ['_id', 'created_at', 'query_id'].include? key yield key, value end end def exist? @exist end end
{ "content_hash": "0e1aa158f8d010ca7bb2d58e870beb5d", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 60, "avg_line_length": 17.692307692307693, "alnum_prop": 0.5594202898550724, "repo_name": "rrusk/scoop-query-composer", "id": "70f7c9f35a4478e69142cd224b08437dcc8c138e", "size": "690", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/result_presenter.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "28888" }, { "name": "CoffeeScript", "bytes": "21732" }, { "name": "JavaScript", "bytes": "296994" }, { "name": "Perl", "bytes": "331" }, { "name": "Ruby", "bytes": "158823" }, { "name": "Shell", "bytes": "1434" } ], "symlink_target": "" }
namespace AM.Condo { using System.Collections.Generic; using System.Linq; /// <summary> /// Represents a set of extension methods for the <see cref="string"/> class. /// </summary> public static class StringExtensions { private const char Delimiter = ';'; #region Methods /// <summary> /// Splits the specified <paramref name="values"/> into an array of values using the common semi-colon delimited /// property list from MSBuild. /// </summary> /// <param name="values"> /// The value to split. /// </param> /// <returns> /// An array of individual values retrieved from the semi-colon delimited list. /// </returns> public static string[] PropertySplit(this string values) { return (values ?? string.Empty).Trim(Delimiter).Split(Delimiter).Where(value => value.Length > 0).ToArray(); } /// <summary> /// Joins the specified <paramref name="values"/> as a semi-colon delimited list. /// </summary> /// <param name="values"> /// The values to join. /// </param> /// <returns> /// A single string represented the collection of values as a semi-colon delimited list. /// </returns> public static string PropertyJoin(this IEnumerable<string> values) { if (values == null) { return string.Empty; } return string.Join(Delimiter.ToString(), values.Select(b => b.Replace(Delimiter, ' '))); } #endregion } }
{ "content_hash": "38cc2db19c69a70733df835fc6c0318a", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 120, "avg_line_length": 33.38775510204081, "alnum_prop": 0.558679706601467, "repo_name": "pulsebridge/condo", "id": "921bfac9c51e6f1d90e476b351661e4e676d73ac", "size": "2085", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "src/AM.Condo/Extensions/StringExtensions.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "496" }, { "name": "C#", "bytes": "438936" }, { "name": "HTML", "bytes": "2072" }, { "name": "PowerShell", "bytes": "14869" }, { "name": "Shell", "bytes": "10952" } ], "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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.videointelligence.v1p1beta1.model; /** * Video frame level annotation results for explicit content. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Video Intelligence API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudVideointelligenceV1ExplicitContentFrame extends com.google.api.client.json.GenericJson { /** * Likelihood of the pornography content.. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String pornographyLikelihood; /** * Time-offset, relative to the beginning of the video, corresponding to the video frame for this * location. * The value may be {@code null}. */ @com.google.api.client.util.Key private String timeOffset; /** * Likelihood of the pornography content.. * @return value or {@code null} for none */ public java.lang.String getPornographyLikelihood() { return pornographyLikelihood; } /** * Likelihood of the pornography content.. * @param pornographyLikelihood pornographyLikelihood or {@code null} for none */ public GoogleCloudVideointelligenceV1ExplicitContentFrame setPornographyLikelihood(java.lang.String pornographyLikelihood) { this.pornographyLikelihood = pornographyLikelihood; return this; } /** * Time-offset, relative to the beginning of the video, corresponding to the video frame for this * location. * @return value or {@code null} for none */ public String getTimeOffset() { return timeOffset; } /** * Time-offset, relative to the beginning of the video, corresponding to the video frame for this * location. * @param timeOffset timeOffset or {@code null} for none */ public GoogleCloudVideointelligenceV1ExplicitContentFrame setTimeOffset(String timeOffset) { this.timeOffset = timeOffset; return this; } @Override public GoogleCloudVideointelligenceV1ExplicitContentFrame set(String fieldName, Object value) { return (GoogleCloudVideointelligenceV1ExplicitContentFrame) super.set(fieldName, value); } @Override public GoogleCloudVideointelligenceV1ExplicitContentFrame clone() { return (GoogleCloudVideointelligenceV1ExplicitContentFrame) super.clone(); } }
{ "content_hash": "285fb3d250b0dc6c10f2de1388e60d2d", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 182, "avg_line_length": 35.01063829787234, "alnum_prop": 0.7441507140686722, "repo_name": "googleapis/google-api-java-client-services", "id": "5a1b7452512aabf1175debddcdcd0f40367f15a6", "size": "3291", "binary": false, "copies": "5", "ref": "refs/heads/main", "path": "clients/google-api-services-videointelligence/v1p1beta1/1.26.0/com/google/api/services/videointelligence/v1p1beta1/model/GoogleCloudVideointelligenceV1ExplicitContentFrame.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// // MHComment.h // MHDevelopExample // // Created by CoderMikeHe on 17/2/8. // Copyright © 2017年 CoderMikeHe. All rights reserved. // #import <Foundation/Foundation.h> #import "MHUser.h" @interface MHComment : NSObject /** 视频的id */ @property (nonatomic , copy) NSString *mediabase_id; /** 评论、回复id */ @property (nonatomic , copy) NSString * commentId; /** 创建时间 */ @property (nonatomic , copy) NSString *creatTime; /** 回复用户模型 */ @property (nonatomic , strong) MHUser *toUser; /** 来源用户模型 */ @property (nonatomic , strong) MHUser *fromUser; /** 话题内容 */ @property (nonatomic, copy) NSString *text; /** 获取富文本 */ - (NSAttributedString *)attributedText; @end
{ "content_hash": "caf5e91fe08d24b890e181f298a27cab", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 55, "avg_line_length": 18.555555555555557, "alnum_prop": 0.6766467065868264, "repo_name": "CoderMikeHe/MHDevelopExample_Objective_C", "id": "069f01e103db6a1593eb3166f64362b3dfc06c4f", "size": "737", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MHDevelopExample/MHDevelopExample/Classes/Comment/Base/Model/MHComment.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "513" }, { "name": "C++", "bytes": "739" }, { "name": "HTML", "bytes": "4010" }, { "name": "Objective-C", "bytes": "1896438" }, { "name": "Ruby", "bytes": "5092" } ], "symlink_target": "" }
int main(int argc, char *argv[]) { return NSApplicationMain(argc, (const char **)argv); }
{ "content_hash": "99a64822bac17a49a51d25a92c9a0f70", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 54, "avg_line_length": 30.666666666666668, "alnum_prop": 0.6739130434782609, "repo_name": "google/macops", "id": "01633c735463b64c016876d5974006cab6603e0f", "size": "134", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "deprecation_notifier/DeprecationNotifier/main.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "1775" }, { "name": "Makefile", "bytes": "19923" }, { "name": "Objective-C", "bytes": "20064" }, { "name": "Python", "bytes": "404292" }, { "name": "Ruby", "bytes": "8289" }, { "name": "Shell", "bytes": "3514" } ], "symlink_target": "" }
package org.wso2.carbon.device.mgt.analytics.dashboard.dao.impl; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceWithDetails; import org.wso2.carbon.device.mgt.analytics.dashboard.bean.DeviceCountByGroup; import org.wso2.carbon.device.mgt.analytics.dashboard.bean.BasicFilterSet; import org.wso2.carbon.device.mgt.analytics.dashboard.bean.ExtendedFilterSet; import org.wso2.carbon.device.mgt.analytics.dashboard.dao.AbstractGadgetDataServiceDAO; import org.wso2.carbon.device.mgt.analytics.dashboard.dao.GadgetDataServiceDAOConstants; import org.wso2.carbon.device.mgt.analytics.dashboard.exception.*; import org.wso2.carbon.device.mgt.common.PaginationResult; import org.wso2.carbon.device.mgt.core.dao.util.DeviceManagementDAOUtil; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class GenericGadgetDataServiceDAOImpl extends AbstractGadgetDataServiceDAO { @Override public PaginationResult getNonCompliantDeviceCountsByFeatures(int startIndex, int resultCount) throws InvalidStartIndexValueException, InvalidResultCountValueException, SQLException { if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { throw new InvalidStartIndexValueException("Start index should be equal to " + GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); } if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { throw new InvalidResultCountValueException("Result count should be equal to " + GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); } Connection con; PreparedStatement stmt = null; ResultSet rs = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); List<DeviceCountByGroup> filteredNonCompliantDeviceCountsByFeatures = new ArrayList<>(); int totalRecordsCount = 0; try { con = this.getConnection(); String sql = "SELECT FEATURE_CODE, COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? GROUP BY FEATURE_CODE " + "ORDER BY DEVICE_COUNT DESC LIMIT ?, ?"; stmt = con.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setInt(2, startIndex); stmt.setInt(3, resultCount); // executing query rs = stmt.executeQuery(); // fetching query results DeviceCountByGroup filteredNonCompliantDeviceCountByFeature; while (rs.next()) { filteredNonCompliantDeviceCountByFeature = new DeviceCountByGroup(); filteredNonCompliantDeviceCountByFeature.setGroup(rs.getString("FEATURE_CODE")); filteredNonCompliantDeviceCountByFeature.setDisplayNameForGroup(rs.getString("FEATURE_CODE")); filteredNonCompliantDeviceCountByFeature.setDeviceCount(rs.getInt("DEVICE_COUNT")); filteredNonCompliantDeviceCountsByFeatures.add(filteredNonCompliantDeviceCountByFeature); } // fetching total records count sql = "SELECT COUNT(FEATURE_CODE) AS NON_COMPLIANT_FEATURE_COUNT FROM (SELECT DISTINCT FEATURE_CODE FROM " + GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ?) " + "NON_COMPLIANT_FEATURE_CODE"; stmt = con.prepareStatement(sql); stmt.setInt(1, tenantId); // executing query rs = stmt.executeQuery(); // fetching query results while (rs.next()) { totalRecordsCount = rs.getInt("NON_COMPLIANT_FEATURE_COUNT"); } } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } PaginationResult paginationResult = new PaginationResult(); paginationResult.setData(filteredNonCompliantDeviceCountsByFeatures); paginationResult.setRecordsTotal(totalRecordsCount); return paginationResult; } @Override public PaginationResult getDevicesWithDetails(ExtendedFilterSet extendedFilterSet, int startIndex, int resultCount) throws InvalidPotentialVulnerabilityValueException, InvalidStartIndexValueException, InvalidResultCountValueException, SQLException { if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { throw new InvalidStartIndexValueException("Start index should be equal to " + GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); } if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { throw new InvalidResultCountValueException("Result count should be equal to " + GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); } Map<String, Object> filters = this.extractDatabaseFiltersFromBean(extendedFilterSet); Connection con; PreparedStatement stmt = null; ResultSet rs = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); List<DeviceWithDetails> filteredDevicesWithDetails = new ArrayList<>(); int totalRecordsCount = 0; try { con = this.getConnection(); String sql, advancedSqlFiltering = ""; // appending filters if exist, to support advanced filtering options // [1] appending filter columns, if exist if (filters != null && filters.size() > 0) { for (String column : filters.keySet()) { advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; } } sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_1 + " WHERE TENANT_ID = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?"; stmt = con.prepareStatement(sql); // [2] appending filter column values, if exist stmt.setInt(1, tenantId); if (filters != null && filters.values().size() > 0) { int i = 2; for (Object value : filters.values()) { if (value instanceof Integer) { stmt.setInt(i, (Integer) value); } else if (value instanceof String) { stmt.setString(i, (String) value); } i++; } stmt.setInt(i, startIndex); stmt.setInt(++i, resultCount); } else { stmt.setInt(2, startIndex); stmt.setInt(3, resultCount); } // executing query rs = stmt.executeQuery(); // fetching query results DeviceWithDetails filteredDeviceWithDetails; while (rs.next()) { filteredDeviceWithDetails = new DeviceWithDetails(); filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); filteredDevicesWithDetails.add(filteredDeviceWithDetails); } // fetching total records count sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. DatabaseView.DEVICES_VIEW_1 + " WHERE TENANT_ID = ?"; stmt = con.prepareStatement(sql); stmt.setInt(1, tenantId); // executing query rs = stmt.executeQuery(); // fetching query results while (rs.next()) { totalRecordsCount = rs.getInt("DEVICE_COUNT"); } } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } PaginationResult paginationResult = new PaginationResult(); paginationResult.setData(filteredDevicesWithDetails); paginationResult.setRecordsTotal(totalRecordsCount); return paginationResult; } @Override public PaginationResult getFeatureNonCompliantDevicesWithDetails(String featureCode, BasicFilterSet basicFilterSet, int startIndex, int resultCount) throws InvalidFeatureCodeValueException, InvalidStartIndexValueException, InvalidResultCountValueException, SQLException { if (featureCode == null || featureCode.isEmpty()) { throw new InvalidFeatureCodeValueException("Feature code should not be either null or empty."); } if (startIndex < GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX) { throw new InvalidStartIndexValueException("Start index should be equal to " + GadgetDataServiceDAOConstants.Pagination.MIN_START_INDEX + " or greater than that."); } if (resultCount < GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT) { throw new InvalidResultCountValueException("Result count should be equal to " + GadgetDataServiceDAOConstants.Pagination.MIN_RESULT_COUNT + " or greater than that."); } Map<String, Object> filters = this.extractDatabaseFiltersFromBean(basicFilterSet); Connection con; PreparedStatement stmt = null; ResultSet rs = null; int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); List<DeviceWithDetails> filteredDevicesWithDetails = new ArrayList<>(); int totalRecordsCount = 0; try { con = this.getConnection(); String sql, advancedSqlFiltering = ""; // appending filters if exist, to support advanced filtering options // [1] appending filter columns, if exist if (filters != null && filters.size() > 0) { for (String column : filters.keySet()) { advancedSqlFiltering = advancedSqlFiltering + "AND " + column + " = ? "; } } sql = "SELECT DEVICE_ID, DEVICE_IDENTIFICATION, PLATFORM, OWNERSHIP, CONNECTIVITY_STATUS FROM " + GadgetDataServiceDAOConstants.DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? AND FEATURE_CODE = ? " + advancedSqlFiltering + "ORDER BY DEVICE_ID ASC LIMIT ?, ?"; stmt = con.prepareStatement(sql); // [2] appending filter column values, if exist stmt.setInt(1, tenantId); stmt.setString(2, featureCode); if (filters != null && filters.values().size() > 0) { int i = 3; for (Object value : filters.values()) { if (value instanceof Integer) { stmt.setInt(i, (Integer) value); } else if (value instanceof String) { stmt.setString(i, (String) value); } i++; } stmt.setInt(i, startIndex); stmt.setInt(++i, resultCount); } else { stmt.setInt(3, startIndex); stmt.setInt(4, resultCount); } // executing query rs = stmt.executeQuery(); // fetching query results DeviceWithDetails filteredDeviceWithDetails; while (rs.next()) { filteredDeviceWithDetails = new DeviceWithDetails(); filteredDeviceWithDetails.setDeviceId(rs.getInt("DEVICE_ID")); filteredDeviceWithDetails.setDeviceIdentification(rs.getString("DEVICE_IDENTIFICATION")); filteredDeviceWithDetails.setPlatform(rs.getString("PLATFORM")); filteredDeviceWithDetails.setOwnershipType(rs.getString("OWNERSHIP")); filteredDeviceWithDetails.setConnectivityStatus(rs.getString("CONNECTIVITY_STATUS")); filteredDevicesWithDetails.add(filteredDeviceWithDetails); } // fetching total records count sql = "SELECT COUNT(DEVICE_ID) AS DEVICE_COUNT FROM " + GadgetDataServiceDAOConstants. DatabaseView.DEVICES_VIEW_2 + " WHERE TENANT_ID = ? AND FEATURE_CODE = ?"; stmt = con.prepareStatement(sql); stmt.setInt(1, tenantId); stmt.setString(2, featureCode); // executing query rs = stmt.executeQuery(); // fetching query results while (rs.next()) { totalRecordsCount = rs.getInt("DEVICE_COUNT"); } } finally { DeviceManagementDAOUtil.cleanupResources(stmt, rs); } PaginationResult paginationResult = new PaginationResult(); paginationResult.setData(filteredDevicesWithDetails); paginationResult.setRecordsTotal(totalRecordsCount); return paginationResult; } }
{ "content_hash": "6031c16580a496944134dd433abbadd1", "timestamp": "", "source": "github", "line_count": 280, "max_line_length": 120, "avg_line_length": 49.49285714285714, "alnum_prop": 0.6264251695771396, "repo_name": "Shabirmean/carbon-device-mgt", "id": "4a0deb7d247c98af585235ebb46eb7346f906f52", "size": "14530", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "components/device-mgt/org.wso2.carbon.device.mgt.analytics.dashboard/src/main/java/org/wso2/carbon/device/mgt/analytics/dashboard/dao/impl/GenericGadgetDataServiceDAOImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "546748" }, { "name": "HTML", "bytes": "293990" }, { "name": "Java", "bytes": "3607849" }, { "name": "JavaScript", "bytes": "3063887" }, { "name": "PLSQL", "bytes": "25132" } ], "symlink_target": "" }
<img src="{src}" class="product-image">
{ "content_hash": "f8b3d5fd1acaa8c5663bc23ff1f7a7ef", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 39, "avg_line_length": 39, "alnum_prop": 0.6666666666666666, "repo_name": "eschltd/barbaareducatie.nl", "id": "a26928633d76669f6dfe7a2aa2cd27692745ec22", "size": "39", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "templates/product-image.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "19688" }, { "name": "HTML", "bytes": "7393" }, { "name": "JavaScript", "bytes": "9264" } ], "symlink_target": "" }
'use strict'; var request = require('request'); /** * Check if the service/request have an error and try to format it. */ function formatErrorIfExists(cb) { return function(error, response, body) { // If we have an error return it. if (error) { cb(error, body, response); return; } try { body = JSON.parse(body); } catch (e) {} // If we have a response and it contains an error if (body && (body.error || body.error_code)) { error = body; body = null; } // If we still don't have an error and there was an error... if (!error && (response.statusCode < 200 || response.statusCode >= 300)) { error = { code: response.statusCode, error: body }; if (error.code === 401 || error.code === 403) error.error = 'Unauthorized: Access is denied due to invalid credentials'; body = null; } cb(error, body, response); }; } /** * Question Prediction API Wrapper * * @param {Object} options The context where 'auth' and 'url' are */ function NaturalLanguageClassifier(options) { this._options = options || {}; this.url = options.url.replace(/\/$/, ''); this.auth = 'Basic ' + new Buffer(options.username + ':' + options.password).toString('base64'); } NaturalLanguageClassifier.prototype.classify = function(params, callback) { var options = { method: 'POST', url: this.url + '/v1/classifiers/' + this._options.classifier_id + '/classify', body: params, json: true, headers: { 'Authorization': this.auth } }; return request(options, formatErrorIfExists(callback)); }; module.exports = NaturalLanguageClassifier;
{ "content_hash": "aa58bc0a5c9b1d230f8f09b5913d17e8", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 98, "avg_line_length": 24.794117647058822, "alnum_prop": 0.6150652431791221, "repo_name": "obarrot/georges", "id": "5a6b24570d4f1c2e3942adab40ad909f74078b86", "size": "2301", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "natural-language-classifier.js", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "130982" }, { "name": "HTML", "bytes": "4133" }, { "name": "JavaScript", "bytes": "13432" } ], "symlink_target": "" }
#include "MethodCall.h" #include <stdlib.h> int ProcdescMain() { MethodCall* call = [MethodCall alloc]; int n = [call plusX:1 andY:3]; int* x = malloc(sizeof(int)); return n; } int call_nslog() { MethodCall* call = [MethodCall alloc]; NSLog(@"%s", "printing"); int* x = malloc(sizeof(int)); return 0; }
{ "content_hash": "97004152e31eb15d834e3b2e0fe8448c", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 40, "avg_line_length": 17.944444444444443, "alnum_prop": 0.6253869969040248, "repo_name": "xennygrimmato/infer", "id": "7d5b091d84a09643218ccd524f19f0993d3b7362", "size": "631", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "infer/tests/codetoanalyze/objc/errors/procdescs/main.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "172910" }, { "name": "C++", "bytes": "126294" }, { "name": "CMake", "bytes": "784" }, { "name": "Java", "bytes": "977706" }, { "name": "LLVM", "bytes": "9227" }, { "name": "M4", "bytes": "21742" }, { "name": "Makefile", "bytes": "32782" }, { "name": "OCaml", "bytes": "2581189" }, { "name": "Objective-C", "bytes": "132584" }, { "name": "Objective-C++", "bytes": "4065" }, { "name": "PAWN", "bytes": "89" }, { "name": "Perl", "bytes": "245" }, { "name": "Python", "bytes": "175009" }, { "name": "Rust", "bytes": "356969" }, { "name": "Shell", "bytes": "40459" } ], "symlink_target": "" }
ALTER TABLE ONLY lines ALTER COLUMN id DROP DEFAULT;
{ "content_hash": "491f6239a3c05e95b7febfe92d229c7d", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 52, "avg_line_length": 52, "alnum_prop": 0.8269230769230769, "repo_name": "RealImage/QLedger", "id": "34984fd51b71046cde43f503a52ce021945b8289", "size": "52", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "migrations/postgres/20170607017_alter_table_lines_column_id_set_default.down.sql", "mode": "33188", "license": "mit", "language": [ { "name": "Dockerfile", "bytes": "580" }, { "name": "Go", "bytes": "92651" }, { "name": "PLpgSQL", "bytes": "1091" }, { "name": "Shell", "bytes": "548" } ], "symlink_target": "" }
package io.crate.types; import io.crate.Streamer; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import java.io.IOException; public class DoubleType extends DataType<Double> implements FixedWidthType, Streamer<Double>, DataTypeFactory { public static final DoubleType INSTANCE = new DoubleType(); public static final int ID = 6; private DoubleType() {} @Override public int id() { return ID; } @Override public String getName() { return "double"; } @Override public Streamer<?> streamer() { return this; } @Override public Double value(Object value) { if (value == null) { return null; } if (value instanceof Double) { return (Double) value; } if (value instanceof String) { return Double.valueOf((String)value); } if (value instanceof BytesRef) { return Double.valueOf(((BytesRef)value).utf8ToString()); } return ((Number)value).doubleValue(); } @Override public int compareValueTo(Double val1, Double val2) { return Double.compare(val1, val2); } @Override public Double readValueFrom(StreamInput in) throws IOException { return in.readBoolean() ? null : in.readDouble(); } @Override public void writeValueTo(StreamOutput out, Object v) throws IOException { out.writeBoolean(v == null); if (v != null) { out.writeDouble(((Number) v).doubleValue()); } } @Override public DataType<?> create() { return INSTANCE; } @Override public int fixedSize() { return 16; // 8 object overhead + 8 for double } }
{ "content_hash": "db7abdd3612b88774ccd959e67be1030", "timestamp": "", "source": "github", "line_count": 78, "max_line_length": 111, "avg_line_length": 23.73076923076923, "alnum_prop": 0.6115613182063749, "repo_name": "husky-koglhof/crate", "id": "c9dde8cdf2e755230b1bc9d163defd740a46d44a", "size": "2872", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "core/src/main/java/io/crate/types/DoubleType.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2809" }, { "name": "GAP", "bytes": "70644" }, { "name": "Java", "bytes": "7402024" }, { "name": "Python", "bytes": "5286" }, { "name": "Shell", "bytes": "11354" } ], "symlink_target": "" }
/*****************************************************************************\ * WrFFrP.c: * * * * XPM library * * Write a pixmap and possibly its mask to an XPM file * * * * Developed by Arnaud Le Hors * \*****************************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "XpmI.h" int XpmWriteFileFromPixmap(display, filename, pixmap, shapemask, attributes) Display *display; char *filename; Pixmap pixmap; Pixmap shapemask; XpmAttributes *attributes; { XImage *ximage = NULL; XImage *shapeimage = NULL; unsigned int width = 0; unsigned int height = 0; int ErrorStatus; /* get geometry */ if (attributes && attributes->valuemask & XpmSize) { width = attributes->width; height = attributes->height; } /* get the ximages */ if (pixmap) xpmCreateImageFromPixmap(display, pixmap, &ximage, &width, &height); if (shapemask) xpmCreateImageFromPixmap(display, shapemask, &shapeimage, &width, &height); /* write to the file */ ErrorStatus = XpmWriteFileFromImage(display, filename, ximage, shapeimage, attributes); /* destroy the ximages */ if (ximage) XDestroyImage(ximage); if (shapeimage) XDestroyImage(shapeimage); return (ErrorStatus); }
{ "content_hash": "4a5d59111e31c561d90dc9594f3f0b2f", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 79, "avg_line_length": 30.944444444444443, "alnum_prop": 0.4637941352483543, "repo_name": "easion/os_sdk", "id": "87ceb8890908bcdbbc0eb1a33768aa9106b43c55", "size": "2997", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "xlibs/libXpm-3.5.4.2/src/WrFFrP.c", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "980392" }, { "name": "Awk", "bytes": "1743" }, { "name": "Bison", "bytes": "113274" }, { "name": "C", "bytes": "60384056" }, { "name": "C++", "bytes": "6888586" }, { "name": "CSS", "bytes": "3092" }, { "name": "Component Pascal", "bytes": "295471" }, { "name": "D", "bytes": "275403" }, { "name": "Erlang", "bytes": "130334" }, { "name": "Groovy", "bytes": "15362" }, { "name": "JavaScript", "bytes": "437486" }, { "name": "Logos", "bytes": "6575" }, { "name": "Makefile", "bytes": "145054" }, { "name": "Max", "bytes": "4350" }, { "name": "Nu", "bytes": "1315315" }, { "name": "Objective-C", "bytes": "209666" }, { "name": "PHP", "bytes": "246706" }, { "name": "Perl", "bytes": "1767429" }, { "name": "Prolog", "bytes": "1387207" }, { "name": "Python", "bytes": "14909" }, { "name": "R", "bytes": "46561" }, { "name": "Ruby", "bytes": "290155" }, { "name": "Scala", "bytes": "184297" }, { "name": "Shell", "bytes": "5748626" }, { "name": "TeX", "bytes": "346362" }, { "name": "XC", "bytes": "6266" } ], "symlink_target": "" }
namespace { const double kTopMarginInInch = 0.25; const double kBottomMarginInInch = 0.56; const double kLeftMarginInInch = 0.25; const double kRightMarginInInch = 0.25; } // namespace gfx::Size GetPdfPaperSizeDeviceUnitsGtk( printing::PrintingContextLinux* context) { GtkPageSetup* page_setup = gtk_page_setup_new(); gfx::SizeF paper_size( gtk_page_setup_get_paper_width(page_setup, GTK_UNIT_INCH), gtk_page_setup_get_paper_height(page_setup, GTK_UNIT_INCH)); g_object_unref(page_setup); const printing::PrintSettings& settings = context->settings(); return gfx::Size(paper_size.width() * settings.device_units_per_inch(), paper_size.height() * settings.device_units_per_inch()); } void InitPrintSettingsGtk(GtkPrintSettings* settings, GtkPageSetup* page_setup, printing::PrintSettings* print_settings) { DCHECK(settings); DCHECK(page_setup); DCHECK(print_settings); const char* printer_name = gtk_print_settings_get_printer(settings); std::u16string name = printer_name ? base::UTF8ToUTF16(printer_name) : std::u16string(); print_settings->set_device_name(name); gfx::Size physical_size_device_units; gfx::Rect printable_area_device_units; int dpi = gtk_print_settings_get_resolution(settings); if (dpi) { // Initialize page_setup_device_units_. physical_size_device_units.SetSize( gtk_page_setup_get_paper_width(page_setup, GTK_UNIT_INCH) * dpi, gtk_page_setup_get_paper_height(page_setup, GTK_UNIT_INCH) * dpi); printable_area_device_units.SetRect( gtk_page_setup_get_left_margin(page_setup, GTK_UNIT_INCH) * dpi, gtk_page_setup_get_top_margin(page_setup, GTK_UNIT_INCH) * dpi, gtk_page_setup_get_page_width(page_setup, GTK_UNIT_INCH) * dpi, gtk_page_setup_get_page_height(page_setup, GTK_UNIT_INCH) * dpi); } else { // Use default values if we cannot get valid values from the print dialog. dpi = printing::kPixelsPerInch; double page_width_in_pixel = printing::kLetterWidthInch * dpi; double page_height_in_pixel = printing::kLetterHeightInch * dpi; physical_size_device_units.SetSize(static_cast<int>(page_width_in_pixel), static_cast<int>(page_height_in_pixel)); printable_area_device_units.SetRect( static_cast<int>(kLeftMarginInInch * dpi), static_cast<int>(kTopMarginInInch * dpi), page_width_in_pixel - (kLeftMarginInInch + kRightMarginInInch) * dpi, page_height_in_pixel - (kTopMarginInInch + kBottomMarginInInch) * dpi); } print_settings->set_dpi(dpi); // Note: With the normal GTK print dialog, when the user selects the landscape // orientation, all that does is change the paper size. Which seems to be // enough to render the right output and send it to the printer. // The orientation value stays as portrait and does not actually affect // printing. // Thus this is only useful in print preview mode, where we manually set the // orientation and change the paper size ourselves. GtkPageOrientation orientation = gtk_print_settings_get_orientation(settings); // Set before SetPrinterPrintableArea to make it flip area if necessary. print_settings->SetOrientation(orientation == GTK_PAGE_ORIENTATION_LANDSCAPE); DCHECK_EQ(print_settings->device_units_per_inch(), dpi); print_settings->SetPrinterPrintableArea(physical_size_device_units, printable_area_device_units, true); }
{ "content_hash": "ac36dca69a53efc4f748a9d52e1436a5", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 80, "avg_line_length": 44.45, "alnum_prop": 0.6931946006749157, "repo_name": "ric2b/Vivaldi-browser", "id": "0ebed5603f82763f95092e3c151144843e0f2e50", "size": "4050", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "chromium/ui/gtk/printing/printing_gtk_util.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
 import { IWeapon } from "./weapons"; export class Character { public health: number; public maxHealth: number; public name: string; public weapon: IWeapon; public attack(damage: number) { this.health -= damage; } public isDead(): boolean{ return this.health <= 0; } } export class Hero extends Character { public badGuysKilled: number; public money: number; public maxHealth: number; } export class Monster extends Character { constructor(_name: string, _health: ()=> number, _weapon: IWeapon) { super(); this.name = _name; this.weapon = _weapon; this.health = _health(); } reward(): any { return { money: Math.floor((Math.random() * 10) * 2), message : `${this.name} dies a horrible death` }; } }
{ "content_hash": "791fca8feeb6aed9e05499c08801189e", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 76, "avg_line_length": 25.425, "alnum_prop": 0.4837758112094395, "repo_name": "DustinEwers/typescript-demos", "id": "819401a374260ab794188e47eecd5cd898c6899f", "size": "1019", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tsDemo/tsDemo/Scripts/game/characters.ts", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "98" }, { "name": "C#", "bytes": "26508" }, { "name": "CSS", "bytes": "16876" }, { "name": "HTML", "bytes": "13116" }, { "name": "JavaScript", "bytes": "1148675" }, { "name": "TypeScript", "bytes": "43447" } ], "symlink_target": "" }
// -*- C++ -*- //============================================================================= /** * @file streams.h * * $Id: streams.h 82445 2008-07-28 13:40:01Z johnnyw $ * * @author Irfan Pyarali * * This file contains the portability ugliness for the Standard C++ * Library. As implementations of the "standard" emerge, this file * will need to be updated. * * This files deals with the streams includes. * * */ //============================================================================= #ifndef ACE_STREAMS_H #define ACE_STREAMS_H #include /**/ "ace/pre.h" #include /**/ "ace/config-all.h" #if !defined (ACE_LACKS_PRAGMA_ONCE) # pragma once #endif /* ACE_LACKS_PRAGMA_ONCE */ // Do this so the #pragma warning in the MSVC headers do not // affect our #pragma warning settings #if defined (_MSC_VER) #pragma warning(push) #endif /* _MSC_VER*/ #if !defined (ACE_LACKS_IOSTREAM_TOTALLY) # if defined (ACE_HAS_STANDARD_CPP_LIBRARY) && \ (ACE_HAS_STANDARD_CPP_LIBRARY != 0) # if defined (_MSC_VER) # pragma warning(disable: 4018 4114 4146 4245) # pragma warning(disable: 4663 4664 4665 4511 4512) # endif /* _MSC_VER */ # if defined (ACE_USES_OLD_IOSTREAMS) # include /**/ <iostream.h> # include /**/ <fstream.h> // This has been commented as it is not needed and causes problems with Qt. // (brunsch) But has been uncommented since it should be included. Qt // probably should have some sort of macro that will prevent including this // when it is used. # include /**/ <iomanip.h> # else # include /**/ <iostream> # include /**/ <fstream> # include /**/ <istream> # include /**/ <ostream> # include /**/ <streambuf> # include /**/ <iomanip> # include /**/ <ios> # endif /* ACE_USES_OLD_IOSTREAMS */ # if defined (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB) && \ (ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB != 0) # if !defined (ACE_USES_OLD_IOSTREAMS) // Make these available in the global name space using std::ios; using std::ios_base; using std::streambuf; using std::istream; using std::ostream; using std::iostream; using std::filebuf; using std::ifstream; using std::ofstream; using std::fstream; using std::cin; using std::cout; using std::cerr; using std::clog; using std::endl; using std::ends; using std::flush; using std::ws; using std::resetiosflags; using std::setfill; using std::setiosflags; using std::setprecision; using std::setw; using std::dec; using std::hex; using std::oct; # endif /* ! ACE_USES_OLD_IOSTREAMS */ # endif /* ACE_USES_STD_NAMESPACE_FOR_STDCPP_LIB */ # if defined (_MSC_VER) # pragma warning(4: 4018 4114 4146 4245) # pragma warning(4: 4663 4664 4665 4512 4511) # endif /* _MSC_VER */ # else /* ! ACE_HAS_STANDARD_CPP_LIBRARY */ # include /**/ <fstream.h> # include /**/ <iostream.h> # include /**/ <iomanip.h> # if defined (ACE_WIN32) && !defined(__MINGW32__) # if defined(_MSC_VER) // VSB # include /**/ <ios.h> # include /**/ <streamb.h> # include /**/ <istream.h> # include /**/ <ostream.h> # endif /* _MSC_VER */ # endif /* ACE_WIN32 && !__MINGW32__ */ # endif /* ! ACE_HAS_STANDARD_CPP_LIBRARY */ #endif /* ! ACE_LACKS_IOSTREAM_TOTALLY */ // Do this so the #pragma warning in the MSVC headers do not // affect our #pragma warning settings #if defined (_MSC_VER) #pragma warning(pop) #endif /* _MSC_VER */ #include /**/ "ace/post.h" #endif /* ACE_STREAMS_H */
{ "content_hash": "07a39b0b8084da6f68963930b069397f", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 79, "avg_line_length": 26.89855072463768, "alnum_prop": 0.5700431034482759, "repo_name": "Huawei/eSDK_eLTE_SDK_Windows", "id": "396a67c712e5d4dbf9ac31688ca6056c0972e335", "size": "3712", "binary": false, "copies": "652", "ref": "refs/heads/master", "path": "src/platform/SDK/include/ACE_wrappers/include/ace/streams.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "45600" }, { "name": "C", "bytes": "1941730" }, { "name": "C++", "bytes": "9810262" }, { "name": "CMake", "bytes": "3613" }, { "name": "Makefile", "bytes": "209539" }, { "name": "Objective-C", "bytes": "250083" }, { "name": "Protocol Buffer", "bytes": "9363" } ], "symlink_target": "" }
<?php // src/Anneaux/PortailBundle/Entity/Author.php namespace Anneaux\PortailBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Gedmo\Mapping\Annotation as Gedmo; /** * @ORM\Entity(repositoryClass="Anneaux\PortailBundle\Entity\AuthorRepository") * @ORM\Table(name="author") */ class Author { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string", length=60) */ protected $firstname; /** * @ORM\Column(type="string", length=60) */ protected $lastname; /** * @Gedmo\Slug(fields={"lastname", "firstname", "id"}) * @ORM\Column(type="string", length=255) */ protected $slug; /** * @ORM\Column(type="string", length=255) */ protected $photo; /** * @ORM\Column(type="string", length=60) */ protected $country; /** * @ORM\Column(type="text") */ protected $bio; /** * @ORM\Column(type="string", length=255) */ protected $job; /** * @ORM\Column(type="datetime") */ protected $created; /** * @ORM\ManyToMany(targetEntity="Article", mappedBy="authors") **/ protected $articles; /** * @ORM\ManyToMany(targetEntity="Tag", inversedBy="authors") * @ORM\JoinTable(name="authors_tags") **/ protected $tags; /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set firstname * * @param string $firstname * @return Author */ public function setFirstname($firstname) { $this->firstname = $firstname; return $this; } /** * Get firstname * * @return string */ public function getFirstname() { return $this->firstname; } /** * Set lastname * * @param string $lastname * @return Author */ public function setLastname($lastname) { $this->lastname = $lastname; return $this; } /** * Get lastname * * @return string */ public function getLastname() { return $this->lastname; } /** * Set photo * * @param string $photo * @return Author */ public function setPhoto($photo) { $this->photo = $photo; return $this; } /** * Get photo * * @return string */ public function getPhoto() { return $this->photo; } /** * Set country * * @param string $country * @return Author */ public function setCountry($country) { $this->country = $country; return $this; } /** * Get country * * @return string */ public function getCountry() { return $this->country; } /** * Set bio * * @param string $bio * @return Author */ public function setBio($bio) { $this->bio = $bio; return $this; } /** * Get bio * * @return string */ public function getBio() { return $this->bio; } /** * Set job * * @param string $job * @return Author */ public function setJob($job) { $this->job = $job; return $this; } /** * Get job * * @return string */ public function getJob() { return $this->job; } /** * Set created * * @ORM\PrePersist * * @param \DateTime $created * @return Article */ public function setCreated() { $this->created = new \DateTime(); return $this; } /** * Get created * * @return \DateTime */ public function getCreated() { return $this->created; } /** * Constructor */ public function __construct() { $this->articles = new \Doctrine\Common\Collections\ArrayCollection(); $this->tags = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Add articles * * @param \Anneaux\PortailBundle\Entity\Article $articles * @return Author */ public function addArticle(\Anneaux\PortailBundle\Entity\Article $articles) { $this->articles[] = $articles; return $this; } /** * Remove articles * * @param \Anneaux\PortailBundle\Entity\Article $articles */ public function removeArticle(\Anneaux\PortailBundle\Entity\Article $articles) { $this->articles->removeElement($articles); } /** * Get articles * * @return \Doctrine\Common\Collections\Collection */ public function getArticles() { return $this->articles; } /** * Add tags * * @param \Anneaux\PortailBundle\Entity\Tag $tags * @return Author */ public function addTag(\Anneaux\PortailBundle\Entity\Tag $tags) { $this->tags[] = $tags; return $this; } /** * Remove tags * * @param \Anneaux\PortailBundle\Entity\Tag $tags */ public function removeTag(\Anneaux\PortailBundle\Entity\Tag $tags) { $this->tags->removeElement($tags); } /** * Get tags * * @return \Doctrine\Common\Collections\Collection */ public function getTags() { return $this->tags; } /** * Set slug * * @param string $slug * @return Author */ public function setSlug($slug) { $this->slug = $slug; return $this; } /** * Get slug * * @return string */ public function getSlug() { return $this->slug; } }
{ "content_hash": "c4153a7f264fd17de701f35e4b293d26", "timestamp": "", "source": "github", "line_count": 342, "max_line_length": 80, "avg_line_length": 15.628654970760234, "alnum_prop": 0.5560336763330215, "repo_name": "jacbac/anneaux", "id": "ea89073d17cd8284421f9d6f84532f38d8196b95", "size": "5345", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Anneaux/PortailBundle/Entity/Author.php", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "48623" }, { "name": "PHP", "bytes": "78440" }, { "name": "Perl", "bytes": "2647" } ], "symlink_target": "" }
let fs = require('fs'); describe('check that start page has a title', function () { // execute before every test beforeEach(function () { browser.ignoreSynchronization = true; // Important using Protractor without AngularJS browser.get('https://www.google.de/'); }); // tests are here it('should have a title', function () { expect(browser.getTitle()).toEqual('Google'); }); it('should enter in search and check the search result', function () { browser.takeScreenshot().then(png => { let stream = fs.createWriteStream('./var/screens/startpage.png'); stream.write(new Buffer(png, 'base64')); stream.end(); }); }); });
{ "content_hash": "ff34d37a33d0a9f6fb12bc7c9d96f8eb", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 95, "avg_line_length": 33.18181818181818, "alnum_prop": 0.5958904109589042, "repo_name": "rebel-l/experiment-protractor", "id": "be7aef25c17c0e1a84f9bc656e31e369e4618a5f", "size": "730", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/phantomjs/googleStartpage-spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1705" } ], "symlink_target": "" }
package io.cattle.platform.servicediscovery.api.action; import io.cattle.platform.api.action.ActionHandler; import io.cattle.platform.core.addon.ComposeConfig; import io.cattle.platform.core.constants.CommonStatesConstants; import io.cattle.platform.core.constants.ServiceConstants; import io.cattle.platform.core.model.Stack; import io.cattle.platform.core.model.Service; import io.cattle.platform.json.JsonMapper; import io.cattle.platform.object.ObjectManager; import io.cattle.platform.object.util.DataAccessor; import io.cattle.platform.servicediscovery.api.service.ServiceDiscoveryApiService; import io.github.ibuildthecloud.gdapi.request.ApiRequest; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.inject.Inject; public class StackExportConfigActionHandler implements ActionHandler { @Inject ObjectManager objectManager; @Inject JsonMapper jsonMapper; @Inject ServiceDiscoveryApiService svcDiscoveryServer; @Override public String getName() { return ServiceConstants.PROCESS_STACK_EXPORT_CONFIG; } @Override public Object perform(String name, Object obj, ApiRequest request) { if (!(obj instanceof Stack)) { return null; } Stack stack = (Stack) obj; List<? extends Long> serviceIds = DataAccessor.fromMap(request.getRequestObject()) .withKey(ServiceConstants.FIELD_SERVICE_IDS).asList(jsonMapper, Long.class); List<? extends Service> services = objectManager.mappedChildren(stack, Service.class); List<Service> toExport = new ArrayList<>(); for (Service service : services) { // export only non-removed requested services if ((serviceIds == null || serviceIds.isEmpty()) || serviceIds.contains(service.getId())) { if (service.getRemoved() == null && !service.getState().equals(CommonStatesConstants.REMOVED)) { toExport.add(service); } } } Map.Entry<String, String> composeConfig = svcDiscoveryServer.buildComposeConfig(toExport, stack); return new ComposeConfig(composeConfig.getKey(), composeConfig.getValue()); } }
{ "content_hash": "f46be3fdb7d31824571cca0b050de7bb", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 112, "avg_line_length": 37.1, "alnum_prop": 0.7138364779874213, "repo_name": "jimengliu/cattle", "id": "2f61764db57cb59fd47eff1939e2e279717394ff", "size": "2226", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "code/iaas/service-discovery/api/src/main/java/io/cattle/platform/servicediscovery/api/action/StackExportConfigActionHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "FreeMarker", "bytes": "15475" }, { "name": "Java", "bytes": "6117577" }, { "name": "Python", "bytes": "809691" }, { "name": "Shell", "bytes": "48232" } ], "symlink_target": "" }
package org.wildfly.security.sasl.digest; import java.net.URI; import java.security.spec.KeySpec; import javax.security.auth.callback.CallbackHandler; import org.wildfly.security.auth.client.AuthenticationConfiguration; import org.wildfly.security.auth.client.AuthenticationContext; import org.wildfly.security.auth.client.ClientUtils; import org.wildfly.security.auth.client.MatchRule; import org.wildfly.security.password.Password; import org.wildfly.security.password.PasswordFactory; import org.wildfly.security.password.interfaces.ClearPassword; import org.wildfly.security.password.interfaces.DigestPassword; import org.wildfly.security.password.spec.ClearPasswordSpec; import org.wildfly.security.password.spec.DigestPasswordSpec; import org.wildfly.security.sasl.util.SaslMechanismInformation; import org.wildfly.security.sasl.util.UsernamePasswordHashUtil; /** * @author Kabir Khan */ public class DigestCallbackHandlerUtils { static CallbackHandler createClearPwdClientCallbackHandler(final String username, final String password, final String sentRealm) throws Exception { PasswordFactory passwordFactory = PasswordFactory.getInstance(ClearPassword.ALGORITHM_CLEAR); return createClientCallbackHandler(username, passwordFactory.generatePassword(new ClearPasswordSpec(password.toCharArray())), sentRealm); } static CallbackHandler createDigestPwdClientCallbackHandler(final String username, final String password, final String realm, final String sentRealm) throws Exception { byte[] urpHash = new UsernamePasswordHashUtil().generateHashedURP(username, realm, password.toCharArray()); KeySpec keySpec = new DigestPasswordSpec(username, realm, urpHash); PasswordFactory passwordFactory = PasswordFactory.getInstance(DigestPassword.ALGORITHM_DIGEST_MD5); return createClientCallbackHandler(username, passwordFactory.generatePassword(keySpec), sentRealm); } private static CallbackHandler createClientCallbackHandler(final String username, final Password password, final String sentRealm) throws Exception { final AuthenticationContext context = AuthenticationContext.empty() .with( MatchRule.ALL, AuthenticationConfiguration.EMPTY .useName(username) .usePassword(password) .useRealm(sentRealm) .allowSaslMechanisms(SaslMechanismInformation.Names.DIGEST_MD5)); return ClientUtils.getCallbackHandler(new URI("seems://irrelevant"), context); } }
{ "content_hash": "ea889572e12e61b807d6110d3bfe9b7d", "timestamp": "", "source": "github", "line_count": 52, "max_line_length": 172, "avg_line_length": 50.82692307692308, "alnum_prop": 0.7578509269769201, "repo_name": "sguilhen/wildfly-elytron", "id": "d86ffd4b81298d5d74b43c97e81e4fafcb676f56", "size": "3349", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/wildfly/security/sasl/digest/DigestCallbackHandlerUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "5054222" }, { "name": "Shell", "bytes": "983" } ], "symlink_target": "" }
CaptchaGenerator ================ Font 'Helve Cursive' by toto (http://www.dafont.com/helve-cursive.font) A simple PHP class for the production of a captcha. Example available. This is my first attempt at a library, so go easy on me! I've tried to make this as simple as possible. I'm aware there may be a problem with very high volume servers using this, but this is generally marginal as the server load would need to be colossal! This class does require write access to the hosts /tmp/ directory to write the captcha image. Only a single image is created 'captcha.png' which is overwrited on subsequent requests. Some basic testing is present (as much as you can for an image!) Basic Usage: <?php $obj = new CaptchaGenerator(); //Creates object, default parameters $obj->saveCanvas(); //Saves captcha image to /tmp/ $obj->getSolution(); //returns solution to captcha ?> By making use of the session variables, the solution can be stored for later comparison. Creating a new Captcha OVERWRITES the existing one and changes the solution. See example (index.php) for basic usage. Default parameters for constructor are: __construct($length = 8. $difficulty = 10) Length should be between 1 and 8 Difficulty should be between 1 and 10 Any suggestions regarding improvements please contact me.
{ "content_hash": "4035efcf509b3261d0f6415d1860c5f5", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 71, "avg_line_length": 28.47826086956522, "alnum_prop": 0.7603053435114504, "repo_name": "Galatoni/CaptchaGenerator", "id": "c99b9b2295c5223abc334efd7e7bd71cefcd3c83", "size": "1310", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "5242" } ], "symlink_target": "" }
<?php namespace Behat\SahiClient\Accessor\Form; use Behat\SahiClient\Accessor\AbstractDomAccessor; /** * Button Element Accessor. * * @author Konstantin Kudryashov <[email protected]> */ class ButtonAccessor extends AbstractDomAccessor { /** * {@inheritdoc} */ public function getType() { return 'button'; } }
{ "content_hash": "dc08a216ecd3a0df8d2120379a321469", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 53, "avg_line_length": 15.391304347826088, "alnum_prop": 0.6610169491525424, "repo_name": "Behat/SahiClient", "id": "507ad57ffc23c187e05d613bfb53a09517b76e65", "size": "591", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/Behat/SahiClient/Accessor/Form/ButtonAccessor.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "107497" } ], "symlink_target": "" }
/* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_HAL_DCMI_EX_H #define __STM32F4xx_HAL_DCMI_EX_H #ifdef __cplusplus extern "C" { #endif #if defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) ||\ defined(STM32F429xx) || defined(STM32F439xx) || defined(STM32F446xx) || defined(STM32F469xx) ||\ defined(STM32F479xx) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal_def.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @addtogroup DCMIEx * @brief DCMI HAL module driver * @{ */ /* Exported types ------------------------------------------------------------*/ /** @defgroup DCMIEx_Exported_Types DCMI Extended Exported Types * @{ */ /** * @brief DCMIEx Embedded Synchronisation CODE Init structure definition */ typedef struct { uint8_t FrameStartCode; /*!< Specifies the code of the frame start delimiter. */ uint8_t LineStartCode; /*!< Specifies the code of the line start delimiter. */ uint8_t LineEndCode; /*!< Specifies the code of the line end delimiter. */ uint8_t FrameEndCode; /*!< Specifies the code of the frame end delimiter. */ }DCMI_CodesInitTypeDef; /** * @brief DCMI Init structure definition */ typedef struct { uint32_t SynchroMode; /*!< Specifies the Synchronization Mode: Hardware or Embedded. This parameter can be a value of @ref DCMI_Synchronization_Mode */ uint32_t PCKPolarity; /*!< Specifies the Pixel clock polarity: Falling or Rising. This parameter can be a value of @ref DCMI_PIXCK_Polarity */ uint32_t VSPolarity; /*!< Specifies the Vertical synchronization polarity: High or Low. This parameter can be a value of @ref DCMI_VSYNC_Polarity */ uint32_t HSPolarity; /*!< Specifies the Horizontal synchronization polarity: High or Low. This parameter can be a value of @ref DCMI_HSYNC_Polarity */ uint32_t CaptureRate; /*!< Specifies the frequency of frame capture: All, 1/2 or 1/4. This parameter can be a value of @ref DCMI_Capture_Rate */ uint32_t ExtendedDataMode; /*!< Specifies the data width: 8-bit, 10-bit, 12-bit or 14-bit. This parameter can be a value of @ref DCMI_Extended_Data_Mode */ DCMI_CodesInitTypeDef SyncroCode; /*!< Specifies the code of the frame start delimiter. */ uint32_t JPEGMode; /*!< Enable or Disable the JPEG mode. This parameter can be a value of @ref DCMI_MODE_JPEG */ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) uint32_t ByteSelectMode; /*!< Specifies the data to be captured by the interface This parameter can be a value of @ref DCMIEx_Byte_Select_Mode */ uint32_t ByteSelectStart; /*!< Specifies if the data to be captured by the interface is even or odd This parameter can be a value of @ref DCMIEx_Byte_Select_Start */ uint32_t LineSelectMode; /*!< Specifies the line of data to be captured by the interface This parameter can be a value of @ref DCMIEx_Line_Select_Mode */ uint32_t LineSelectStart; /*!< Specifies if the line of data to be captured by the interface is even or odd This parameter can be a value of @ref DCMIEx_Line_Select_Start */ #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ }DCMI_InitTypeDef; /** * @} */ /* Exported constants --------------------------------------------------------*/ #if defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /** @defgroup DCMIEx_Exported_Constants DCMI Exported Constants * @{ */ /** @defgroup DCMIEx_Byte_Select_Mode DCMI Byte Select Mode * @{ */ #define DCMI_BSM_ALL ((uint32_t)0x00000000) /*!< Interface captures all received data */ #define DCMI_BSM_OTHER ((uint32_t)DCMI_CR_BSM_0) /*!< Interface captures every other byte from the received data */ #define DCMI_BSM_ALTERNATE_4 ((uint32_t)DCMI_CR_BSM_1) /*!< Interface captures one byte out of four */ #define DCMI_BSM_ALTERNATE_2 ((uint32_t)(DCMI_CR_BSM_0 | DCMI_CR_BSM_1)) /*!< Interface captures two bytes out of four */ /** * @} */ /** @defgroup DCMIEx_Byte_Select_Start DCMI Byte Select Start * @{ */ #define DCMI_OEBS_ODD ((uint32_t)0x00000000) /*!< Interface captures first data from the frame/line start, second one being dropped */ #define DCMI_OEBS_EVEN ((uint32_t)DCMI_CR_OEBS) /*!< Interface captures second data from the frame/line start, first one being dropped */ /** * @} */ /** @defgroup DCMIEx_Line_Select_Mode DCMI Line Select Mode * @{ */ #define DCMI_LSM_ALL ((uint32_t)0x00000000) /*!< Interface captures all received lines */ #define DCMI_LSM_ALTERNATE_2 ((uint32_t)DCMI_CR_LSM) /*!< Interface captures one line out of two */ /** * @} */ /** @defgroup DCMIEx_Line_Select_Start DCMI Line Select Start * @{ */ #define DCMI_OELS_ODD ((uint32_t)0x00000000) /*!< Interface captures first line from the frame start, second one being dropped */ #define DCMI_OELS_EVEN ((uint32_t)DCMI_CR_OELS) /*!< Interface captures second line from the frame start, first one being dropped */ /** * @} */ /** * @} */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /** @defgroup DCMIEx_Private_Macros DCMI Extended Private Macros * @{ */ #define IS_DCMI_BYTE_SELECT_MODE(MODE)(((MODE) == DCMI_BSM_ALL) || \ ((MODE) == DCMI_BSM_OTHER) || \ ((MODE) == DCMI_BSM_ALTERNATE_4) || \ ((MODE) == DCMI_BSM_ALTERNATE_2)) #define IS_DCMI_BYTE_SELECT_START(POLARITY)(((POLARITY) == DCMI_OEBS_ODD) || \ ((POLARITY) == DCMI_OEBS_EVEN)) #define IS_DCMI_LINE_SELECT_MODE(MODE)(((MODE) == DCMI_LSM_ALL) || \ ((MODE) == DCMI_LSM_ALTERNATE_2)) #define IS_DCMI_LINE_SELECT_START(POLARITY)(((POLARITY) == DCMI_OELS_ODD) || \ ((POLARITY) == DCMI_OELS_EVEN)) #endif /* STM32F446xx || STM32F469xx || STM32F479xx */ /** * @} */ /* Private functions ---------------------------------------------------------*/ #endif /* STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\ STM32F479xx */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif #endif /* __STM32F4xx_HAL_DCMI_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
{ "content_hash": "d069e39ed61ffc49bc8ba9d1ed765b09", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 150, "avg_line_length": 44.15425531914894, "alnum_prop": 0.4918684495843874, "repo_name": "janhieber/HTWAA_car_32b", "id": "3131dec96dfa28cdc54b71f5967efc676ff407c6", "size": "10399", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "Test_GPIO/Drivers/STM32F4xx_HAL_Driver/Inc/stm32f4xx_hal_dcmi_ex.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "5121548" }, { "name": "C", "bytes": "84604891" }, { "name": "C++", "bytes": "557070" }, { "name": "HTML", "bytes": "11659" }, { "name": "Python", "bytes": "288" } ], "symlink_target": "" }
module HerokuLineItemBilling module API def api @heroku ||= PlatformAPI.connect_oauth(ENV['HEROKU_API_TOKEN']) end end end
{ "content_hash": "532182b290d311082fce480a05effcfb", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 68, "avg_line_length": 20, "alnum_prop": 0.6928571428571428, "repo_name": "IFTTT/heroku_line_item_billing", "id": "a734cabf33dc8291057a3d459e6f5414a66ecf9c", "size": "140", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/heroku_line_item_billing/api.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "7503" } ], "symlink_target": "" }
({ getMessageFromSuperSuperCmp: function() { return "Message From Super Super Component Helper Method"; }, getSuperAwesomeMessage: function() { return "Super Awesome Message from Super Super Component Helper Method"; } })
{ "content_hash": "5f53fbf985da251ac64583a6ed535f22", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 80, "avg_line_length": 28.333333333333332, "alnum_prop": 0.6784313725490196, "repo_name": "forcedotcom/aura", "id": "37e088352f857fdd3dc45dd0c68c8c3abe06ca7d", "size": "255", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "aura-components/src/test/components/componentTest/helperSuperSuper/helperSuperSuperHelper.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "775275" }, { "name": "GAP", "bytes": "10087" }, { "name": "HTML", "bytes": "978392" }, { "name": "Java", "bytes": "9663384" }, { "name": "JavaScript", "bytes": "19433132" }, { "name": "Python", "bytes": "7340" }, { "name": "Shell", "bytes": "20990" }, { "name": "XSLT", "bytes": "1579" } ], "symlink_target": "" }
var wikitree = require('./wikitree'), utils = require('./utils'); /** * Create a person from the given `user_id` */ var Person = wikitree.Person = function(data){ this._data = data; // Create person objects for any attached family members var relatives = ['Parents', 'Spouses', 'Children', 'Siblings']; for(var i = 0; i < relatives.length; i++){ var type = relatives[i]; if(data[type]){ for(var p in data[type]){ this._data[type][p] = new Person(data[type][p]); } } } }; Person.prototype.getFirstName = function(){ return this._data.FirstName; }; Person.prototype.getRealName = function(){ return this._data.RealName; }; Person.prototype.getMiddleName = function(){ return this._data.MiddleName; }; Person.prototype.getLastNameCurrent = function(){ return this._data.LastNameCurrent; }; Person.prototype.getLastNameAtBirth = function(){ return this._data.LastNameAtBirth; }; Person.prototype.getDisplayName = function(){ return this.getFirstName() + ' ' + this.getLastNameCurrent(); }; Person.prototype.getLongNamePrivate = function(){ return this._data.LongNamePrivate; }; Person.prototype.getGender = function(){ return this._data.Gender; }; Person.prototype.getBirthDate = function(){ return this._data.BirthDate; }; Person.prototype.getBirthDateDisplay = function(){ return utils.getDateDisplayString(this.getBirthDate()); }; Person.prototype.getBirthLocation = function(){ return this._data.BirthLocation; }; Person.prototype.getDeathDate = function(){ return this._data.DeathDate; }; Person.prototype.getDeathDateDisplay = function(){ return utils.getDateDisplayString(this.getDeathDate()); }; Person.prototype.getDeathLocation = function(){ return this._data.DeathLocation; }; Person.prototype.getFather = function(){ if(this._data.Father && this._data.Parents){ return this._data.Parents[this._data.Father]; } }; Person.prototype.getFatherId = function(){ return this._data.Father; }; Person.prototype.getMother = function(){ if(this._data.Mother && this._data.Parents){ return this._data.Parents[this._data.Mother]; } }; Person.prototype.getMotherId = function(){ return this._data.Mother; }; Person.prototype.getChildren = function(){ return this._data.Children; }; Person.prototype.getSpouses = function(){ return this._data.Spouses; }; Person.prototype.getSpouse = function(){ var spouses = this.getSpouses(); for(var a in spouses){ return spouses[a]; } }; Person.prototype.getSiblings= function(){ return this._data.Siblings; }; Person.prototype.getId = function(){ return this._data.Id; }; Person.prototype.getPrivacy = function(){ return this._data.Privacy; }; Person.prototype.toJSON = function(){ return this._data; }; Person.prototype.isLiving = function(){ return this._data.IsLiving == 1; }; /** * This is not the person's name but the identifier * used in URLs; e.g. Smith-3624 */ Person.prototype.getName = function(){ return this._data.Name; }; /** * Get the URL to the person's profile page on wikitree.com */ Person.prototype.getProfileUrl = function(){ return 'http://www.wikitree.com/wiki/' + this.getName(); }; /** * Retrieve the a URL for the person's photo. Size * may be 75, 300, or 500. Defaults to 300. */ Person.prototype.getPhotoUrl = function(size){ if(this._data.Photo){ if([75,300,500].indexOf(size) === -1){ size = 300; } return 'http://www.wikitree.com/photo.php/thumb/a/ad/' + this._data.Photo + '/' + size + 'px-' + this._data.Photo; } }; /** * Sets this person's mother to be the specified person. */ Person.prototype.setMother = function(person){ var id = person.getId(), oldId = this._data.Mother; // Store the new mother id this._data.Mother = id; // If the Perants map does not exist yet then create it if(!this._data.Parents){ this._data.Parents = {}; } // If the object does exist and there was a previous mother then remove her else if(oldId) { delete this._data.Parents[oldId]; } // Add the new mother to the parents object this._data.Parents[id] = person; }; /** * Sets this person's father to be the specified person. */ Person.prototype.setFather = function(person){ var id = person.getId(), oldId = this._data.Father; // Store the new father id this._data.Father = id; // If the Perants map does not exist yet then create it if(!this._data.Parents){ this._data.Parents = {}; } // If the object does exist and there was a previous father then remove her else if(oldId) { delete this._data.Parents[oldId]; } // Add the new father to the parents object this._data.Parents[id] = person; }; /** * This method replaces the current list of children with the new list. */ Person.prototype.setChildren = function(children){ this._data.Children = children; };
{ "content_hash": "aa7664866edea9748373cd8410d0e4c0", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 118, "avg_line_length": 22.901869158878505, "alnum_prop": 0.6786370128545195, "repo_name": "justincy/wikitree-javascript-sdk", "id": "b9c0d1ebecda620c527d4a08c9d933d60819e3e8", "size": "4901", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Person.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "6723" }, { "name": "JavaScript", "bytes": "114218" } ], "symlink_target": "" }
namespace gpu { namespace gles2 { // This is used to keep the source code for a shader. This is because in order // to emluate GLES2 the shaders will have to be re-written before passed to // the underlying OpenGL. But, when the user calls glGetShaderSource they // should get the source they passed in, not the re-written source. class GPU_EXPORT Shader : public base::RefCounted<Shader> { public: enum TranslatedShaderSourceType { kANGLE, kGL, // GL or GLES }; enum ShaderState { kShaderStateWaiting, kShaderStateCompileRequested, kShaderStateCompiled, // Signifies compile happened, not valid compile. }; static const int kUndefinedShaderVersion = -1; void RequestCompile(scoped_refptr<ShaderTranslatorInterface> translator, TranslatedShaderSourceType type); void DoCompile(); void RefreshTranslatedShaderSource(); ShaderState shader_state() const { return shader_state_; } GLuint service_id() const { return marked_for_deletion_ ? 0 : service_id_; } GLenum shader_type() const { return shader_type_; } int shader_version() const { return shader_version_; } const std::string& source() const { return source_; } void set_source(const std::string& source) { source_ = source; } const std::string& translated_source() const { return translated_source_; } std::string last_compiled_source() const { return last_compiled_source_; } std::string last_compiled_signature() const { if (translator_.get()) { return last_compiled_source_ + translator_->GetStringForOptionsThatWouldAffectCompilation(); } return last_compiled_source_; } const sh::Attribute* GetAttribInfo(const std::string& name) const; const sh::Uniform* GetUniformInfo(const std::string& name) const; const sh::Varying* GetVaryingInfo(const std::string& name) const; const sh::InterfaceBlock* GetInterfaceBlockInfo( const std::string& name) const; const sh::OutputVariable* GetOutputVariableInfo( const std::string& name) const; // If the original_name is not found, return NULL. const std::string* GetAttribMappedName( const std::string& original_name) const; // If the original_name is not found, return NULL. const std::string* GetUniformMappedName( const std::string& original_name) const; // If the original_name is not found, return NULL. const std::string* GetVaryingMappedName( const std::string& original_name) const; // If the original_name is not found, return NULL. const std::string* GetInterfaceBlockMappedName( const std::string& original_name) const; // If the original_name is not found, return NULL. const std::string* GetOutputVariableMappedName( const std::string& original_name) const; // If the hashed_name is not found, return NULL. const std::string* GetOriginalNameFromHashedName( const std::string& hashed_name) const; const std::string* GetMappedName( const std::string& original_name) const; const std::string& log_info() const { return log_info_; } bool valid() const { return shader_state_ == kShaderStateCompiled && valid_; } bool IsDeleted() const { return marked_for_deletion_; } bool InUse() const { DCHECK_GE(use_count_, 0); return use_count_ != 0; } // Used by program cache. const AttributeMap& attrib_map() const { return attrib_map_; } // Used by program cache. const UniformMap& uniform_map() const { return uniform_map_; } // Used by program cache. const VaryingMap& varying_map() const { return varying_map_; } const OutputVariableList& output_variable_list() const { return output_variable_list_; } // Used by program cache. const InterfaceBlockMap& interface_block_map() const { return interface_block_map_; } // Used by program cache. void set_attrib_map(const AttributeMap& attrib_map) { // copied because cache might be cleared attrib_map_ = AttributeMap(attrib_map); } // Used by program cache. void set_uniform_map(const UniformMap& uniform_map) { // copied because cache might be cleared uniform_map_ = UniformMap(uniform_map); } // Used by program cache. void set_varying_map(const VaryingMap& varying_map) { // copied because cache might be cleared varying_map_ = VaryingMap(varying_map); } // Used by program cache. void set_interface_block_map(const InterfaceBlockMap& interface_block_map) { // copied because cache might be cleared interface_block_map_ = InterfaceBlockMap(interface_block_map); } void set_output_variable_list( const OutputVariableList& output_variable_list) { // copied because cache might be cleared output_variable_list_ = output_variable_list; } private: friend class base::RefCounted<Shader>; friend class ShaderManager; Shader(GLuint service_id, GLenum shader_type); ~Shader(); // Must be called only if we currently own the context. Forces the deletion // of the underlying shader service id. void Destroy(); void IncUseCount(); void DecUseCount(); void MarkForDeletion(); void DeleteServiceID(); int use_count_; // The current state of the shader. ShaderState shader_state_; // The shader has been marked for deletion. bool marked_for_deletion_; // The shader this Shader is tracking. GLuint service_id_; // Type of shader - GL_VERTEX_SHADER or GL_FRAGMENT_SHADER. GLenum shader_type_; // Version of the shader. Can be kUndefinedShaderVersion or version returned // by ANGLE. int shader_version_; // Translated source type when shader was last requested to be compiled. TranslatedShaderSourceType source_type_; // Translator to use, set when shader was last requested to be compiled. scoped_refptr<ShaderTranslatorInterface> translator_; // True if compilation succeeded. bool valid_; // The shader source as passed to glShaderSource. std::string source_; // The source the last compile used. std::string last_compiled_source_; // The translated shader source. std::string translated_source_; // The shader translation log. std::string log_info_; // The type info when the shader was last compiled. AttributeMap attrib_map_; UniformMap uniform_map_; VaryingMap varying_map_; InterfaceBlockMap interface_block_map_; OutputVariableList output_variable_list_; // The name hashing info when the shader was last compiled. NameMap name_map_; }; // Tracks the Shaders. // // NOTE: To support shared resources an instance of this class will // need to be shared by multiple GLES2Decoders. class GPU_EXPORT ShaderManager { public: ShaderManager(); ~ShaderManager(); // Must call before destruction. void Destroy(bool have_context); // Creates a shader for the given shader ID. Shader* CreateShader( GLuint client_id, GLuint service_id, GLenum shader_type); // Gets an existing shader info for the given shader ID. Returns NULL if none // exists. Shader* GetShader(GLuint client_id); // Gets a client id for a given service id. bool GetClientId(GLuint service_id, GLuint* client_id) const; void Delete(Shader* shader); // Mark a shader as used void UseShader(Shader* shader); // Unmark a shader as used. If it has been deleted and is not used // then we free the shader. void UnuseShader(Shader* shader); // Check if a Shader is owned by this ShaderManager. bool IsOwned(Shader* shader); private: friend class Shader; // Info for each shader by service side shader Id. typedef base::hash_map<GLuint, scoped_refptr<Shader> > ShaderMap; ShaderMap shaders_; void RemoveShader(Shader* shader); DISALLOW_COPY_AND_ASSIGN(ShaderManager); }; } // namespace gles2 } // namespace gpu #endif // GPU_COMMAND_BUFFER_SERVICE_SHADER_MANAGER_H_
{ "content_hash": "337c15971339dfb3062314b8c6554e5c", "timestamp": "", "source": "github", "line_count": 294, "max_line_length": 79, "avg_line_length": 26.877551020408163, "alnum_prop": 0.7014679827891673, "repo_name": "highweb-project/highweb-webcl-html5spec", "id": "31a86e8d6b12e231b0ca0501b8e6257436f76ce1", "size": "8498", "binary": false, "copies": "2", "ref": "refs/heads/highweb-20160310", "path": "gpu/command_buffer/service/shader_manager.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import _ from "lodash"; import Stream from "mithril/stream"; import { ConfigJSON, GroupJSON, HistoryJSON, MaterialRevisionJSON, ModificationJSON, PipelineActivityJSON, StageConfigJSON, StageJSON } from "models/pipeline_activity/pipeline_activity_json"; const TimeFormatter = require("helpers/time_formatter"); function toBool(str: string | boolean) { if (typeof str === "undefined") { return false; } if (typeof str === "boolean") { return str; } return str.trim().toLowerCase() === "true"; } export class StageConfig { name: Stream<string>; isAutoApproved: Stream<boolean>; constructor(name: string, isAutoApproved: boolean) { this.name = Stream(name); this.isAutoApproved = Stream(isAutoApproved); } static fromJSON(stage: StageConfigJSON) { return new StageConfig(stage.name, toBool(stage.isAutoApproved)); } } export class StageConfigs extends Array<StageConfig> { constructor(...stageConfigs: StageConfig[]) { super(...stageConfigs); Object.setPrototypeOf(this, Object.create(StageConfigs.prototype)); } static fromJSON(stages: StageConfigJSON[]) { return new StageConfigs(...stages.map(StageConfig.fromJSON)); } isAutoApproved(name: string): boolean { return this.find((stage: StageConfig) => stage.name() === name)!.isAutoApproved(); } } export class Config { stages: Stream<StageConfigs>; constructor(stages: StageConfigs) { this.stages = Stream(stages); } static fromJSON(config: ConfigJSON) { return new Config(StageConfigs.fromJSON(config.stages)); } } export class Modification { user: Stream<string>; revision: Stream<string>; date: Stream<string>; comment: Stream<string>; modifiedFiles: Stream<string[]>; constructor(user: string, revision: string, date: string, comment: string, modifiedFiles: string[]) { this.user = Stream(user); this.revision = Stream(revision); this.date = Stream(date); this.comment = Stream(comment); this.modifiedFiles = Stream(modifiedFiles); } static fromJSON(modification: ModificationJSON) { return new Modification(modification.user, modification.revision, modification.date, modification.comment, modification.modifiedFiles); } } class Modifications extends Array<Modification> { constructor(...modifications: Modification[]) { super(...modifications); Object.setPrototypeOf(this, Object.create(Modifications.prototype)); } static fromJSON(modifications: ModificationJSON[]) { return new Modifications(...modifications.map(Modification.fromJSON)); } } export class MaterialRevision { revision: Stream<string>; revisionHref: Stream<string>; user: Stream<string>; date: Stream<string>; changed: Stream<boolean>; modifications: Stream<Modifications>; folder: Stream<string>; scmType: Stream<string>; location: Stream<string>; action: Stream<string>; constructor(revision: string, revision_href: string, user: string, date: string, changed: boolean, modifications: Modifications, folder: string, scmType: string, location: string, action: string) { this.revision = Stream(revision); this.revisionHref = Stream(revision_href); this.user = Stream(user); this.date = Stream(date); this.changed = Stream(changed); this.modifications = Stream(modifications); this.folder = Stream(folder); this.scmType = Stream(scmType); this.location = Stream(location); this.action = Stream(action); } static fromJSON(materialRevision: MaterialRevisionJSON) { return new MaterialRevision(materialRevision.revision, materialRevision.revision_href, materialRevision.user, materialRevision.date, toBool(materialRevision.changed), Modifications.fromJSON(materialRevision.modifications), materialRevision.folder, materialRevision.scmType, materialRevision.location, materialRevision.action); } } class MaterialRevisions extends Array<MaterialRevision> { constructor(...materialRevisions: MaterialRevision[]) { super(...materialRevisions); Object.setPrototypeOf(this, Object.create(MaterialRevisions.prototype)); } static fromJSON(materialRevisions: MaterialRevisionJSON[]) { return new MaterialRevisions(...materialRevisions.map(MaterialRevision.fromJSON)); } } export class Stage { stageName: Stream<string>; stageId: Stream<number>; stageStatus: Stream<string>; stageLocator: Stream<string>; getCanRun: Stream<boolean>; getCanCancel: Stream<boolean>; scheduled: Stream<boolean>; stageCounter: Stream<number>; approvedBy: Stream<string | undefined>; errorMessage: Stream<string | undefined>; constructor(stageName: string, stageId: number, stageStatus: string, stageLocator: string, getCanRun: boolean, getCanCancel: boolean, scheduled: boolean, stageCounter: number, approvedBy?: string, errorMessage?: string) { this.stageName = Stream(stageName); this.stageId = Stream(stageId); this.stageStatus = Stream(stageStatus); this.stageLocator = Stream(stageLocator); this.getCanRun = Stream(getCanRun); this.getCanCancel = Stream(getCanCancel); this.scheduled = Stream(scheduled); this.stageCounter = Stream(stageCounter); this.approvedBy = Stream(approvedBy); this.errorMessage = Stream(errorMessage); } static fromJSON(stage: StageJSON) { return new Stage(stage.stageName, stage.stageId, stage.stageStatus, stage.stageLocator, toBool(stage.getCanRun), toBool(stage.getCanCancel), toBool(stage.scheduled), stage.stageCounter, stage.approvedBy, stage.errorMessage); } pipelineName() { return this.stageLocator().split("/")[0]; } pipelineCounter() { return this.stageLocator().split("/")[1]; } isBuilding(): boolean { return this.stageStatus() === "Building"; } } export class Stages extends Array<Stage> { constructor(...stages: Stage[]) { super(...stages); Object.setPrototypeOf(this, Object.create(Stages.prototype)); } static fromJSON(stages: StageJSON[]) { return new Stages(...stages.map(Stage.fromJSON)); } } export class PipelineRunInfo { pipelineId: Stream<number>; label: Stream<string>; counterOrLabel: Stream<string>; scheduledDate: Stream<string>; scheduledTimestamp: Stream<Date>; buildCauseBy: Stream<string>; modificationDate: Stream<string>; materialRevisions: Stream<MaterialRevisions>; stages: Stream<Stages>; revision: Stream<string>; comment: Stream<string>; constructor(pipelineId: number, label: string, counterOrLabel: string, scheduled_date: string, scheduled_timestamp: Date, buildCauseBy: string, modification_date: string, materialRevisions: MaterialRevisions, stages: Stages, revision: string, comment: string | null) { this.pipelineId = Stream(pipelineId); this.label = Stream(label); this.counterOrLabel = Stream(counterOrLabel); this.scheduledDate = Stream(scheduled_date); this.scheduledTimestamp = Stream(scheduled_timestamp); this.buildCauseBy = Stream(buildCauseBy); this.modificationDate = Stream(modification_date); this.materialRevisions = Stream(materialRevisions); this.stages = Stream(stages); this.revision = Stream(revision); this.comment = Stream(comment ? comment : ""); } static fromJSON(pipelineRunInfo: HistoryJSON) { return new PipelineRunInfo(pipelineRunInfo.pipelineId, pipelineRunInfo.label, pipelineRunInfo.counterOrLabel, pipelineRunInfo.scheduled_date, parseDate(pipelineRunInfo.scheduled_timestamp), pipelineRunInfo.buildCauseBy, pipelineRunInfo.modification_date, MaterialRevisions.fromJSON(pipelineRunInfo.materialRevisions), Stages.fromJSON(pipelineRunInfo.stages), pipelineRunInfo.revision, pipelineRunInfo.comment); } } class PipelineHistory extends Array<PipelineRunInfo> { constructor(...pipelineRunInfos: PipelineRunInfo[]) { super(...pipelineRunInfos); Object.setPrototypeOf(this, Object.create(PipelineHistory.prototype)); } static fromJSON(history: HistoryJSON[]) { return new PipelineHistory(...history.map(PipelineRunInfo.fromJSON)); } } export class Group { config: Stream<Config>; history: Stream<PipelineHistory>; constructor(config: Config, history: PipelineHistory) { this.config = Stream(config); this.history = Stream(history); } static fromJSON(group: GroupJSON): Group { return new Group(Config.fromJSON(group.config), PipelineHistory.fromJSON(group.history)); } } class Groups extends Array<Group> { constructor(...groups: Group[]) { super(...groups); Object.setPrototypeOf(this, Object.create(Groups.prototype)); } static fromJSON(groups: GroupJSON[]) { return new Groups(...groups.map(Group.fromJSON)); } } export class PipelineActivity { pipelineName: Stream<string>; paused: Stream<boolean>; pauseCause: Stream<string>; pauseBy: Stream<string>; canForce: Stream<boolean>; nextLabel: Stream<string>; groups: Stream<Groups>; forcedBuild: Stream<boolean>; showForceBuildButton: Stream<boolean>; canPause: Stream<boolean>; count: Stream<number>; start: Stream<number>; perPage: Stream<number>; constructor(pipelineName: string, nextLabel: string, canPause: boolean, paused: boolean, pauseCause: string, pauseBy: string, canForce: boolean, forcedBuild: boolean, showForceBuildButton: boolean, count: number, start: number, perPage: number, groups: Groups) { this.pipelineName = Stream(pipelineName); this.paused = Stream(paused); this.pauseCause = Stream(pauseCause); this.pauseBy = Stream(pauseBy); this.canForce = Stream(canForce); this.nextLabel = Stream(nextLabel); this.groups = Stream(groups); this.forcedBuild = Stream(forcedBuild); this.showForceBuildButton = Stream(showForceBuildButton); this.canPause = Stream(canPause); this.count = Stream(count); this.start = Stream(start); this.perPage = Stream(perPage); } static fromJSON(data: PipelineActivityJSON) { return new PipelineActivity(data.pipelineName, data.nextLabel, toBool(data.canPause), toBool(data.paused), data.pauseCause, data.pauseBy, toBool(data.canForce), toBool(data.forcedBuild), toBool(data.showForceBuildButton), data.count, data.start, data.perPage, Groups.fromJSON(data.groups)); } } function parseDate(dateAsStringOrNumber: string | number | null) { if (!dateAsStringOrNumber) { return undefined; } if (_.isNumber(dateAsStringOrNumber)) { return new Date(dateAsStringOrNumber); } return TimeFormatter.toDate(dateAsStringOrNumber); }
{ "content_hash": "fa019b1ba82708bfaef11317c809a180", "timestamp": "", "source": "github", "line_count": 397, "max_line_length": 103, "avg_line_length": 29.309823677581864, "alnum_prop": 0.661911309728429, "repo_name": "marques-work/gocd", "id": "6fa747dcef280f1d4149044010b3cfcc58dbdc9c", "size": "12237", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "server/src/main/webapp/WEB-INF/rails/webpack/models/pipeline_activity/pipeline_activity.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "466" }, { "name": "CSS", "bytes": "807605" }, { "name": "FreeMarker", "bytes": "9759" }, { "name": "Groovy", "bytes": "2317159" }, { "name": "HTML", "bytes": "641338" }, { "name": "Java", "bytes": "21014983" }, { "name": "JavaScript", "bytes": "2539248" }, { "name": "NSIS", "bytes": "23525" }, { "name": "PowerShell", "bytes": "691" }, { "name": "Ruby", "bytes": "1907011" }, { "name": "Shell", "bytes": "169586" }, { "name": "TSQL", "bytes": "200114" }, { "name": "TypeScript", "bytes": "3423163" }, { "name": "XSLT", "bytes": "203240" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //https://github.com/TelerikAcademy/CSharp-Part-1/tree/master/Topics/04.%20Console-In-and-Out/homework namespace _03.Circle { class Program { static void Main(string[] args) { double radius = double.Parse(Console.ReadLine()); double perimeter = 2 * Math.PI * radius; double area = Math.PI * radius * radius; Console.WriteLine("{0:0.00} {1:F2}", perimeter, area); } } }
{ "content_hash": "d25e24a5afa124f1f13d9caa93dbc9eb", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 102, "avg_line_length": 26.045454545454547, "alnum_prop": 0.6282722513089005, "repo_name": "singularity0/CSharpBasics", "id": "c95de62ae37e14d49235de09bab4df692fbdb2e6", "size": "575", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ConsoleInOut/03.Circle.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "140889" } ], "symlink_target": "" }
<?php namespace Plumber\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class RollbackCommand extends PlumberCommand { protected function configure() { $this ->setName( 'plumber:rollback' ) ->setDescription( 'Deploys a project to another server' ) ->addArgument( 'versions_back', InputArgument::OPTIONAL, 'How many versions do you want to go back?' ) ->setHelp(<<<EOF The <info>plumber:deploy</info> command deploys a project on a server using rsync: <info>php src/console plumber:deploy</info> You can find out more here https://github.com/fiunchinho/Plumber/. EOF ) ; } protected function execute(InputInterface $input, OutputInterface $output) { $plumber = $this->getPlumber(); $rollback_folder = $plumber->rollback( 'prod', ( $input->getArgument('versions_back')?: 1 ) ); $output->writeln( 'You\'ve made a rollback to the release: ' . $rollback_folder ); } }
{ "content_hash": "2ea8ffd64bc123796df84f9936e3afaa", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 102, "avg_line_length": 32.10526315789474, "alnum_prop": 0.6434426229508197, "repo_name": "fiunchinho/Plumber", "id": "2f01f7c78117cd7fd9fcaa13c3659676b2b4a422", "size": "1220", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Plumber/Command/RollbackCommand.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "23582" }, { "name": "Perl", "bytes": "1051" } ], "symlink_target": "" }
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using System.Collections; namespace DaydreamElements.Common { /// Class that can scale the pages of a PagedScrollRect based on the page's offset. public class ScaleScrollEffect : BaseScrollEffect { [Range(0.0f, 1.0f)] [Tooltip("The scale of the page when it is one page-length away.")] public float minScale; public override void ApplyEffect(BaseScrollEffect.UpdateData updateData) { // Calculate the difference. float difference = updateData.scrollOffset - updateData.pageOffset; // Calculate the scale for this page. float ratioScrolled = Mathf.Abs(difference) / updateData.spacing; float scale = ((1.0f - ratioScrolled) * (1.0f - minScale)) + minScale; scale = Mathf.Clamp(scale, 0.0f, 1.0f); // Update the scale. updateData.page.localScale = new Vector3(scale, scale, scale); } } }
{ "content_hash": "d01cd2e0b4a3811afbdcc937d38f463f", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 85, "avg_line_length": 39.31578947368421, "alnum_prop": 0.7161981258366801, "repo_name": "googlevr/media-app-template", "id": "141893aa44db6162f4ca6066b18b9716f9b6c383", "size": "1496", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Assets/DaydreamElements/Common/Scripts/PaginatedScrolling/PaginatedScrolling/ScrollEffects/ScaleScrollEffect.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "1144113" }, { "name": "GLSL", "bytes": "3377" }, { "name": "HLSL", "bytes": "1157" }, { "name": "Objective-C", "bytes": "951" }, { "name": "Objective-C++", "bytes": "1439" }, { "name": "ShaderLab", "bytes": "88348" } ], "symlink_target": "" }
.class Landroid/service/wallpaper/WallpaperService$Engine$1; .super Lcom/android/internal/view/BaseSurfaceHolder; .source "WallpaperService.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Landroid/service/wallpaper/WallpaperService$Engine; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x0 name = null .end annotation # instance fields .field final synthetic this$1:Landroid/service/wallpaper/WallpaperService$Engine; # direct methods .method constructor <init>(Landroid/service/wallpaper/WallpaperService$Engine;)V .locals 1 .parameter .prologue .line 221 iput-object p1, p0, Landroid/service/wallpaper/WallpaperService$Engine$1;->this$1:Landroid/service/wallpaper/WallpaperService$Engine; invoke-direct {p0}, Lcom/android/internal/view/BaseSurfaceHolder;-><init>()V .line 223 const/4 v0, 0x2 iput v0, p0, Landroid/service/wallpaper/WallpaperService$Engine$1;->mRequestedFormat:I .line 224 return-void .end method # virtual methods .method public isCreating()Z .locals 1 .prologue .line 244 iget-object v0, p0, Landroid/service/wallpaper/WallpaperService$Engine$1;->this$1:Landroid/service/wallpaper/WallpaperService$Engine; iget-boolean v0, v0, Landroid/service/wallpaper/WallpaperService$Engine;->mIsCreating:Z return v0 .end method .method public onAllowLockCanvas()Z .locals 1 .prologue .line 228 iget-object v0, p0, Landroid/service/wallpaper/WallpaperService$Engine$1;->this$1:Landroid/service/wallpaper/WallpaperService$Engine; iget-boolean v0, v0, Landroid/service/wallpaper/WallpaperService$Engine;->mDrawingAllowed:Z return v0 .end method .method public onRelayoutContainer()V .locals 3 .prologue .line 233 iget-object v1, p0, Landroid/service/wallpaper/WallpaperService$Engine$1;->this$1:Landroid/service/wallpaper/WallpaperService$Engine; iget-object v1, v1, Landroid/service/wallpaper/WallpaperService$Engine;->mCaller:Lcom/android/internal/os/HandlerCaller; const/16 v2, 0x2710 invoke-virtual {v1, v2}, Lcom/android/internal/os/HandlerCaller;->obtainMessage(I)Landroid/os/Message; move-result-object v0 .line 234 .local v0, msg:Landroid/os/Message; iget-object v1, p0, Landroid/service/wallpaper/WallpaperService$Engine$1;->this$1:Landroid/service/wallpaper/WallpaperService$Engine; iget-object v1, v1, Landroid/service/wallpaper/WallpaperService$Engine;->mCaller:Lcom/android/internal/os/HandlerCaller; invoke-virtual {v1, v0}, Lcom/android/internal/os/HandlerCaller;->sendMessage(Landroid/os/Message;)V .line 235 return-void .end method .method public onUpdateSurface()V .locals 3 .prologue .line 239 iget-object v1, p0, Landroid/service/wallpaper/WallpaperService$Engine$1;->this$1:Landroid/service/wallpaper/WallpaperService$Engine; iget-object v1, v1, Landroid/service/wallpaper/WallpaperService$Engine;->mCaller:Lcom/android/internal/os/HandlerCaller; const/16 v2, 0x2710 invoke-virtual {v1, v2}, Lcom/android/internal/os/HandlerCaller;->obtainMessage(I)Landroid/os/Message; move-result-object v0 .line 240 .local v0, msg:Landroid/os/Message; iget-object v1, p0, Landroid/service/wallpaper/WallpaperService$Engine$1;->this$1:Landroid/service/wallpaper/WallpaperService$Engine; iget-object v1, v1, Landroid/service/wallpaper/WallpaperService$Engine;->mCaller:Lcom/android/internal/os/HandlerCaller; invoke-virtual {v1, v0}, Lcom/android/internal/os/HandlerCaller;->sendMessage(Landroid/os/Message;)V .line 241 return-void .end method .method public setFixedSize(II)V .locals 0 .parameter "width" .parameter "height" .prologue .line 250 invoke-super {p0, p1, p2}, Lcom/android/internal/view/BaseSurfaceHolder;->setFixedSize(II)V .line 251 return-void .end method .method public setKeepScreenOn(Z)V .locals 0 .parameter "screenOn" .prologue .line 255 return-void .end method
{ "content_hash": "52b2a4610ba2ba9c2ad4485fa3f8c370", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 137, "avg_line_length": 28.95744680851064, "alnum_prop": 0.7479794268919912, "repo_name": "baidurom/devices-g520", "id": "32dd04ca38d88756c02677f3dbd58ddfa3334680", "size": "4083", "binary": false, "copies": "2", "ref": "refs/heads/coron-4.1", "path": "framework.jar.out/smali/android/service/wallpaper/WallpaperService$Engine$1.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "12575" }, { "name": "Python", "bytes": "1261" }, { "name": "Shell", "bytes": "2159" } ], "symlink_target": "" }
class MaxWinnerTree : public BinaryTree{ public: MaxWinnerTree(); ~MaxWinnerTree() {} //initialize the maxwinner tree void initialize(int objects, int capacity); //replay to rebuild the winner tree void replay(BinaryTreeNode* n); //find the bin with given objectsize, returns the binarytree node BinaryTreeNode* find(int objectSize); protected: int numberOfPlayers; };
{ "content_hash": "927c524f5331eda44dc67891e015a01a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 67, "avg_line_length": 31.53846153846154, "alnum_prop": 0.7097560975609756, "repo_name": "atthehotcorner/coursework", "id": "846cd4370a0d60285c858d1733de7ab0b6397939", "size": "562", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data-structures-COP3530/bin-packing/MaxWinnerTree.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "3404" }, { "name": "C", "bytes": "3470" }, { "name": "C++", "bytes": "352100" }, { "name": "Java", "bytes": "73801" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>float: 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.13.0 / float - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> float <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-05-13 02:27:09 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-13 02:27:09 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-gmp 4 Virtual package relying on a GMP lib system installation coq 8.13.0 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.14.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.14.0 Official release 4.14.0 ocaml-config 2 OCaml Switch Configuration ocaml-options-vanilla 1 Ensure that OCaml is compiled with no special options enabled ocamlfind 1.9.3 A library manager for OCaml zarith 1.12 Implements arithmetic and logical operations over arbitrary-precision integers # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq-contribs/float&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/Float&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: floating-point arithmetic&quot; &quot;category: Computer Science/Data Types and Data Structures&quot; &quot;date: 2001&quot; ] authors: [ &quot;Laurent Théry&quot; &quot;Sylvie Boldo&quot; ] bug-reports: &quot;https://github.com/coq-contribs/float/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/float.git&quot; synopsis: &quot;Library for floating-point numbers&quot; description: &quot;A library for floating-point numbers.&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/float/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=864ddc054ccfc786ab0f9feb4d1a88d1&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-float.8.8.0 coq.8.13.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.13.0). The following dependencies couldn&#39;t be met: - coq-float -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.10 base of this switch (use `--unlock-base&#39; to force) 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-float.8.8.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": "03e8d79e9682bc2c8c1b8244b1867532", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 159, "avg_line_length": 41.35928143712575, "alnum_prop": 0.5372810192558274, "repo_name": "coq-bench/coq-bench.github.io", "id": "ad23e56756d7bb5f8e032d17214a8c6ad8631234", "size": "6933", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.14.0-2.0.10/released/8.13.0/float/8.8.0.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
#import "NSObject-Protocol.h" @protocol IDEBotLogEditorScopeBarDelegate <NSObject> - (void)logEditorScopeBar:(id)arg1 searchTextChanged:(id)arg2; - (void)logEditorScopeBar:(id)arg1 showAllResultsChanged:(BOOL)arg2; - (void)logEditorScopeBar:(id)arg1 stateChanged:(int)arg2; @end
{ "content_hash": "5f8df23d93689a14d13a942068b23285", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 68, "avg_line_length": 28.3, "alnum_prop": 0.7950530035335689, "repo_name": "liyong03/YLCleaner", "id": "7c5ae1f6c04e780fdf4ea1d89a5cd55cf3017fcc", "size": "423", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "YLCleaner/Xcode-RuntimeHeaders/IDELogNavigator/IDEBotLogEditorScopeBarDelegate-Protocol.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "158958" }, { "name": "C++", "bytes": "612673" }, { "name": "Objective-C", "bytes": "10594281" }, { "name": "Ruby", "bytes": "675" } ], "symlink_target": "" }
require 'mechanize' require 'yaml' STATIONS_FILE = File.expand_path "#{__FILE__}/../../stations.yaml" HOME_URL = 'https://www.select-a-spot.com/bart/' WAITING_LIST_URL = 'https://www.select-a-spot.com/bart/waiting_lists/' class BartWaitingList attr_reader :page def initialize(email, password) @page = get_waiting_list_page email, password end def get_waiting_list_position(station) station_name = get_station_name station regexp = %r{position (?<position>\d+)[a-zA-Z<>/"= ]+at <span class="bold">#{station_name}<\/span>} match = @page.body.match regexp Integer match[:position] rescue nil end private def get_waiting_list_page(email, password) # mechanize agent # http://stackoverflow.com/questions/6918277/ruby-mechanize-web-scraper-library-returns-file-instead-of-page agent = Mechanize.new do |a| a.post_connect_hooks << lambda do |_,_,response,_| if response.content_type.nil? || response.content_type.empty? response.content_type = 'text/html' end end end # fetch the home page page = agent.get HOME_URL # get the login form form = page.form # submit login form form.username email form.password password form.submit # now that we're logged in, return the waiting list page agent.get WAITING_LIST_URL end def get_station_name(station) station_names = {} YAML.load_file(STATIONS_FILE).each do |key, value| station_names[key.to_sym] = value end return station_names[station] end end
{ "content_hash": "ac6c9fa8a60619098eb952f54cda24f1", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 112, "avg_line_length": 25.540983606557376, "alnum_prop": 0.665596919127086, "repo_name": "brianokeefe/bart_waiting_list", "id": "e2fdc6d2532b5be6751eef5d012c572a85faf0c9", "size": "1558", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/bart_waiting_list.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "4226" } ], "symlink_target": "" }
/* Options Framework Admin Styles */ #optionsframework { max-width:840px; background:#fff; } #optionsframework h3 { cursor: default; background-color: #f1f1f1; border-bottom: 1px solid #ddd; } #optionsframework p { margin-bottom:0; padding-bottom:10px; } #optionsframework .section { padding:10px 10px 0; } #optionsframework .group { padding-bottom:40px; } #optionsframework .section .controls { float: left; min-width:350px; width: 54%; padding-right:2%; } #optionsframework .section .explain { max-width:38%; float: left; font-size: 12px; line-height:16px; color: #777; } #optionsframework .controls input[type=text] { width:100%; } #optionsframework .section-checkbox .controls { width: 98%; } #optionsframework .section-checkbox .explain { max-width:94%; } #optionsframework .controls select, #optionsframework .controls textarea { margin-bottom:10px; width:100%; } #optionsframework .section-radio label, #optionsframework .section-multicheck label { float:left; max-width:90%; line-height: 16px; margin-bottom: 5px; } #optionsframework input.checkbox, #optionsframework input.of-radio { margin: 0 10px 5px 0; float:left; clear:both; } #optionsframework .section-typography .controls { float:none; width:auto; } #optionsframework .section-typography .explain { float:none; width:auto; } #optionsframework .controls .of-typography-size { width:80px; float:left } #optionsframework .controls .of-typography-unit { width:50px; margin-left:5px; float:left } #optionsframework .controls .of-typography-face { width:100px; margin-left:5px; float:left } #optionsframework .controls .of-typography-style { width:80px; margin-left:5px; margin-right:5px; float:left } #optionsframework .of-background-properties { clear:both; margin-top: 18px; } #optionsframework .controls .of-background-repeat { width:125px; margin-right:5px; float:left } #optionsframework .controls .of-background-position { width:125px; margin-right:5px; float:left } #optionsframework .controls .of-background-attachment { width:125px; margin-right:5px; float:left } #optionsframework .section-background .wp-picker-container { margin-bottom:10px; } #optionsframework .controls .of-radio-img-img { border:3px solid #f9f9f9; margin:0 5px 10px 0; display:none; cursor:pointer; float:left; } #optionsframework .controls .of-radio-img-selected { border:3px solid #ccc } #optionsframework .controls .of-radio-img-img:hover { opacity:.8; } #optionsframework .controls .of-border-width { width:80px; float:left } #optionsframework .controls .of-border-style { width:120px; float:left } #optionsframework .hide { display:none; } #optionsframework .of-option-image { max-width:340px; margin:3px 0 18px 0; } #optionsframework .mini .controls select, #optionsframework .section .mini .controls { width: 140px; } #optionsframework .mini .controls input, #optionsframework .mini .controls { min-width:140px; width: 140px; } #optionsframework .mini .explain { max-width:74%; } /* Editor */ #optionsframework .section-editor .explain { max-width: 98%; float:none; margin-bottom:5px; } /* Image Uploader */ #optionsframework .controls input.upload { width:80%; } #optionsframework .screenshot { float:left; margin-left:1px; position:relative; width:344px; margin-top:3px; } #optionsframework .screenshot img { background:#fafafa; border-color:#ccc #eee #eee #ccc; border-style:solid; border-width:1px; float:left; max-width:334px; padding:4px; margin-bottom:10px; } #optionsframework .screenshot .remove-image { background:url("../images/ico-delete.png") no-repeat; border:medium none; bottom:4px; display:block; float:left; height:16px; padding:0; position:absolute; left:-4px; text-indent:-9999px; width:16px; } #optionsframework .screenshot .no_image .file_link { margin-left: 20px; } #optionsframework .screenshot .no_image .remove-button { bottom: 0px; } #optionsframework .reset-button { float:left; cursor:pointer; } /* Bottom Section */ #optionsframework-submit { padding: 7px 10px; border-top: 1px solid #ddd; background-color: #f1f1f1; } #optionsframework .button-primary { float:right; } #optionsframework .section:after { content: ""; display: table; } #optionsframework .section:after { clear: both; }
{ "content_hash": "349ccd0b5ea6b841446d8a4e0ebb8d69", "timestamp": "", "source": "github", "line_count": 218, "max_line_length": 86, "avg_line_length": 19.69724770642202, "alnum_prop": 0.7345132743362832, "repo_name": "ramjack/rjfs-franchise-old", "id": "f62613302eb0870742da61b33fb9db155c48bf77", "size": "4294", "binary": false, "copies": "50", "ref": "refs/heads/master", "path": "lib/inc/css/optionsframework.css", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "201161" }, { "name": "JavaScript", "bytes": "14607" }, { "name": "PHP", "bytes": "226729" } ], "symlink_target": "" }
// Defines conversions between generic types and structs to map query strings // to struct objects. package runtime import ( "fmt" "reflect" "strconv" "strings" "k8s.io/apimachinery/pkg/conversion" ) // DefaultFieldSelectorConversion auto-accepts metav1 values for name and namespace. func DefaultMetaV1FieldSelectorConversion(label, value string) (string, string, error) { switch label { case "metadata.name": return label, value, nil case "metadata.namespace": return label, value, nil default: return "", "", fmt.Errorf("%q is not a known field selector: only %q, %q", label, "metadata.name", "metadata.namespace") } } // JSONKeyMapper uses the struct tags on a conversion to determine the key value for // the other side. Use when mapping from a map[string]* to a struct or vice versa. func JSONKeyMapper(key string, sourceTag, destTag reflect.StructTag) (string, string) { if s := destTag.Get("json"); len(s) > 0 { return strings.SplitN(s, ",", 2)[0], key } if s := sourceTag.Get("json"); len(s) > 0 { return key, strings.SplitN(s, ",", 2)[0] } return key, key } // DefaultStringConversions are helpers for converting []string and string to real values. var DefaultStringConversions = []interface{}{ Convert_Slice_string_To_string, Convert_Slice_string_To_int, Convert_Slice_string_To_bool, Convert_Slice_string_To_int64, } func Convert_Slice_string_To_string(input *[]string, out *string, s conversion.Scope) error { if len(*input) == 0 { *out = "" } *out = (*input)[0] return nil } func Convert_Slice_string_To_int(input *[]string, out *int, s conversion.Scope) error { if len(*input) == 0 { *out = 0 } str := (*input)[0] i, err := strconv.Atoi(str) if err != nil { return err } *out = i return nil } // Conver_Slice_string_To_bool will convert a string parameter to boolean. // Only the absence of a value, a value of "false", or a value of "0" resolve to false. // Any other value (including empty string) resolves to true. func Convert_Slice_string_To_bool(input *[]string, out *bool, s conversion.Scope) error { if len(*input) == 0 { *out = false return nil } switch strings.ToLower((*input)[0]) { case "false", "0": *out = false default: *out = true } return nil } func Convert_Slice_string_To_int64(input *[]string, out *int64, s conversion.Scope) error { if len(*input) == 0 { *out = 0 } str := (*input)[0] i, err := strconv.ParseInt(str, 10, 64) if err != nil { return err } *out = i return nil }
{ "content_hash": "4a0c82dff49a7fe9dc7e4a3b52bbbdf4", "timestamp": "", "source": "github", "line_count": 97, "max_line_length": 122, "avg_line_length": 25.742268041237114, "alnum_prop": 0.6816179415298358, "repo_name": "kadel/kedge", "id": "d818727609c8a9b9e695a2e26e4d1a140b0b5b25", "size": "3066", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "vendor/k8s.io/kubernetes/staging/src/k8s.io/apimachinery/pkg/runtime/conversion.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "205742" }, { "name": "Makefile", "bytes": "3723" }, { "name": "Shell", "bytes": "25907" } ], "symlink_target": "" }
package com.yogee.zhebuy.modules.sys.dao; import com.yogee.zhebuy.common.persistence.TreeDao; import com.yogee.zhebuy.common.persistence.annotation.MyBatisDao; import com.yogee.zhebuy.modules.sys.entity.Area; import java.util.List; import java.util.Map; /** * 区域DAO接口 * @author ThinkGem * @version 2014-05-16 */ @MyBatisDao public interface AreaDao extends TreeDao<Area> { List<Area> getByType(Area area); List<Area> getByScope(Area area); Area findComplainPhone(String cityId); }
{ "content_hash": "9842e94e5b7b6c4fdc87008d98a446f6", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 65, "avg_line_length": 19.46153846153846, "alnum_prop": 0.7509881422924901, "repo_name": "sunye520/zhebuy", "id": "ebbff618236a43fc007d371069b6359c221f1f25", "size": "626", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/yogee/zhebuy/modules/sys/dao/AreaDao.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "7506" }, { "name": "Batchfile", "bytes": "8608" }, { "name": "CSS", "bytes": "1778032" }, { "name": "HTML", "bytes": "4972204" }, { "name": "Java", "bytes": "4429124" }, { "name": "JavaScript", "bytes": "14081354" }, { "name": "PHP", "bytes": "16120" }, { "name": "PLSQL", "bytes": "73115" } ], "symlink_target": "" }
import numpy as np from sklearn.metrics import cohen_kappa_score as kappa # noqa from sklearn.metrics import mean_squared_error as mse from sklearn.metrics import mean_absolute_error as mae # noqa from sklearn.metrics import r2_score as r2 # noqa from ..const import EPS def mape(y, p): """Mean Absolute Percentage Error (MAPE). Args: y (numpy.array): target p (numpy.array): prediction Returns: e (numpy.float64): MAPE """ filt = np.abs(y) > EPS return np.mean(np.abs(1 - p[filt] / y[filt])) def rmse(y, p): """Root Mean Squared Error (RMSE). Args: y (numpy.array): target p (numpy.array): prediction Returns: e (numpy.float64): RMSE """ # check and get number of samples assert y.shape == p.shape return np.sqrt(mse(y, p)) def gini(y, p): """Normalized Gini Coefficient. Args: y (numpy.array): target p (numpy.array): prediction Returns: e (numpy.float64): normalized Gini coefficient """ # check and get number of samples assert y.shape == p.shape n_samples = y.shape[0] # sort rows on prediction column # (from largest to smallest) arr = np.array([y, p]).transpose() true_order = arr[arr[:, 0].argsort()][::-1, 0] pred_order = arr[arr[:, 1].argsort()][::-1, 0] # get Lorenz curves l_true = np.cumsum(true_order) / np.sum(true_order) l_pred = np.cumsum(pred_order) / np.sum(pred_order) l_ones = np.linspace(1 / n_samples, 1, n_samples) # get Gini coefficients (area between curves) g_true = np.sum(l_ones - l_true) g_pred = np.sum(l_ones - l_pred) # normalize to true Gini coefficient return g_pred / g_true
{ "content_hash": "1e2cb45ebd890b7c505c0f6701d587b3", "timestamp": "", "source": "github", "line_count": 74, "max_line_length": 62, "avg_line_length": 23.56756756756757, "alnum_prop": 0.6100917431192661, "repo_name": "jeongyoonlee/Kaggler", "id": "c049c64cdedc895ed0045cbb35a493481112cbee", "size": "1744", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kaggler/metrics/regression.py", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1155" }, { "name": "C++", "bytes": "7971" }, { "name": "Cython", "bytes": "46033" }, { "name": "Python", "bytes": "125376" } ], "symlink_target": "" }
#include "regionstyles.h" #include "tgl.h" #include "tcolorfunctions.h" #include "trandom.h" //#include "tsystem.h" //#include "tvectorrenderdata.h" #include "colorfxutils.h" //#include "tgl.h" //#include "tregionoutline.h" //#include "tpalette.h" //#include "tvectorimage.h" //#include "tstroke.h" #include "tflash.h" #include "tregion.h" #include "tcurves.h" //#include "drawutil.h" #include "tmathutil.h" #include "tstencilcontrol.h" //*************************************************************************** // MovingModifier implementation //*************************************************************************** TOutlineStyle::RegionOutlineModifier *MovingModifier::clone() const { return new MovingModifier(*this); } //------------------------------------------------------------ void MovingModifier::modify(TRegionOutline &outline) const { TRegionOutline::Boundary::iterator regIt = outline.m_exterior.begin(); TRegionOutline::Boundary::iterator regItEnd = outline.m_exterior.end(); TRegionOutline::PointVector::iterator pIt; TRegionOutline::PointVector::iterator pItEnd; for (; regIt != regItEnd; ++regIt) { pIt = regIt->begin(); pItEnd = regIt->end(); for (; pIt != pItEnd; ++pIt) { pIt->x += m_move.x; pIt->y += m_move.y; } } regIt = outline.m_interior.begin(); regItEnd = outline.m_interior.end(); for (; regIt != regItEnd; ++regIt) { pIt = regIt->begin(); pItEnd = regIt->end(); for (; pIt != pItEnd; ++pIt) { pIt->x += m_move.x; pIt->y += m_move.y; } } } //*************************************************************************** // MovingSolidColor implementation //*************************************************************************** MovingSolidColor::MovingSolidColor(const TPixel32 &color, const TPointD &move) : TSolidColorStyle(color) { m_regionOutlineModifier = new MovingModifier(move); } //------------------------------------------------------------ TColorStyle *MovingSolidColor::clone() const { return new MovingSolidColor(*this); } //------------------------------------------------------------ void MovingSolidColor::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); delete m_regionOutlineModifier; MovingModifier *mov = new MovingModifier(TPointD()); mov->loadData(is); m_regionOutlineModifier = mov; } //------------------------------------------------------------ void MovingSolidColor::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); assert(m_regionOutlineModifier); ((MovingModifier *)m_regionOutlineModifier)->saveData(os); } //------------------------------------------------------------ int MovingSolidColor::getParamCount() const { return 2; } //----------------------------------------------------------------------------- TColorStyle::ParamType MovingSolidColor::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString MovingSolidColor::getParamNames(int index) const { assert(0 <= index && index < 2); return index == 0 ? QCoreApplication::translate("MovingSolidColor", "Horiz Offset") : QCoreApplication::translate("MovingSolidColor", "Vert Offset"); } //----------------------------------------------------------------------------- void MovingSolidColor::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 2); min = -100.0; max = 100.0; } //----------------------------------------------------------------------------- double MovingSolidColor::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 2); if (index) return ((MovingModifier *)m_regionOutlineModifier)->getMovePoint().y; else return ((MovingModifier *)m_regionOutlineModifier)->getMovePoint().x; } //----------------------------------------------------------------------------- void MovingSolidColor::setParamValue(int index, double value) { assert(0 <= index && index < 2); TPointD oldMove = ((MovingModifier *)m_regionOutlineModifier)->getMovePoint(); if (!index) { if (oldMove.x != value) { delete m_regionOutlineModifier; oldMove.x = value; m_regionOutlineModifier = new MovingModifier(oldMove); updateVersionNumber(); } } else { if (oldMove.y != value) { delete m_regionOutlineModifier; oldMove.y = value; m_regionOutlineModifier = new MovingModifier(oldMove); updateVersionNumber(); } } } //------------------------------------------------------------ void MovingSolidColor::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { TSolidColorStyle::drawRegion(cf, true, boundary); } //------------------------------------------------------------ void MovingSolidColor::drawRegion(TFlash &flash, const TRegion *r) const { SFlashUtils rdf(r); rdf.computeRegionOutline(); m_regionOutlineModifier->modify(rdf.m_ro); flash.setFillColor(getMainColor()); rdf.drawRegionOutline(flash, false); } //*************************************************************************** // ShadowStyle implementation //*************************************************************************** ShadowStyle::ShadowStyle(const TPixel32 &bgColor, const TPixel32 &shadowColor, const TPointD &shadowDirection, double len, double density) : TSolidColorStyle(bgColor) , m_shadowColor(shadowColor) , m_shadowDirection(normalize(shadowDirection)) , m_len(len) , m_density(density) {} //------------------------------------------------------------ TColorStyle *ShadowStyle::clone() const { return new ShadowStyle(*this); } //------------------------------------------------------------ void ShadowStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_shadowDirection.x >> m_shadowDirection.y; is >> m_density; is >> m_shadowColor; is >> m_len; } //------------------------------------------------------------ void ShadowStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_shadowDirection.x << m_shadowDirection.y; os << m_density; os << m_shadowColor; os << m_len; } //------------------------------------------------------------ int ShadowStyle::getParamCount() const { return 3; } //----------------------------------------------------------------------------- TColorStyle::ParamType ShadowStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString ShadowStyle::getParamNames(int index) const { assert(0 <= index && index < 3); switch (index) { case 0: return QCoreApplication::translate("ShadowStyle", "Angle"); case 1: return QCoreApplication::translate("ShadowStyle", "Density"); case 2: return QCoreApplication::translate("ShadowStyle", "Length"); default: return QString(); } assert(0); return QString(); } //----------------------------------------------------------------------------- void ShadowStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 3); switch (index) { case 0: min = 0.0; max = 360.0; break; case 1: min = 0.0; max = 1.0; break; case 2: min = 0.0; max = 100.0; break; } } //----------------------------------------------------------------------------- double ShadowStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 3); double degree; switch (index) { case 0: degree = asin(m_shadowDirection.y); if (m_shadowDirection.x < 0) degree = M_PI - degree; if (degree < 0) degree += M_2PI; return degree * M_180_PI; case 1: return m_density; case 2: return m_len; } assert(0); return 0.0; } //----------------------------------------------------------------------------- void ShadowStyle::setParamValue(int index, double value) { assert(0 <= index && index < 3); double degree; switch (index) { case 0: degree = value * M_PI_180; m_shadowDirection.x = cos(degree); m_shadowDirection.y = sin(degree); break; case 1: m_density = value; break; case 2: m_len = value; break; } } //------------------------------------------------------------ void ShadowStyle::drawPolyline(const TColorFunction *cf, std::vector<T3DPointD> &polyline, TPointD shadowDirection) const { int i; int stepNumber; double distance; TPointD v1, v2, diff, midPoint, ratio; double len; TPixel32 color; if (cf) color = (*(cf))(m_shadowColor); else color = m_shadowColor; tglColor(color); // glEnable(GL_BLEND); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //// <-- tglEnableBlending(); TRegionOutline::PointVector::iterator it; TRegionOutline::PointVector::iterator it_b = polyline.begin(); TRegionOutline::PointVector::iterator it_e = polyline.end(); v1.x = polyline.back().x; v1.y = polyline.back().y; for (it = it_b; it != it_e; ++it) { v2.x = it->x; v2.y = it->y; if (v1 == v2) continue; diff = normalize(rotate90(v2 - v1)); len = diff * shadowDirection; if (len > 0) { distance = tdistance(v1, v2) * m_density; ratio = (v2 - v1) * (1.0 / distance); midPoint = v1; stepNumber = (int)distance; for (i = 0; i < stepNumber; i++) { glBegin(GL_LINE_STRIP); tglColor(TPixel32(color.r, color.g, color.b, 0)); tglVertex(midPoint); tglColor(color); tglVertex(midPoint + (shadowDirection * len * m_len * 0.5)); tglColor(TPixel32(color.r, color.g, color.b, 0)); tglVertex(midPoint + (shadowDirection * len * m_len)); midPoint += ratio; glEnd(); } } v1 = v2; } // tglColor(TPixel32::White); } //------------------------------------------------------------ void ShadowStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &regionOutline) const { TStencilControl *stenc = TStencilControl::instance(); TPixel32 backgroundColor = TSolidColorStyle::getMainColor(); if (cf) backgroundColor = (*(cf))(backgroundColor); ////stenc->beginMask(); /* glBegin(GL_QUADS); glVertex2d (regionOutline.m_bbox.getP00().x, regionOutline.m_bbox.getP00().y); glVertex2d (regionOutline.m_bbox.getP01().x, regionOutline.m_bbox.getP01().y); glVertex2d (regionOutline.m_bbox.getP11().x, regionOutline.m_bbox.getP11().y); glVertex2d (regionOutline.m_bbox.getP10().x, regionOutline.m_bbox.getP10().y); glEnd(); */ ////stenc->endMask(); ////stenc->enableMask(TStencilControl::SHOW_INSIDE); if (backgroundColor.m == 0) { // only to create stencil mask TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); appStyle.drawRegion(0, false, regionOutline); } else { stenc->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); TSolidColorStyle::drawRegion(cf, antiAliasing, regionOutline); } stenc->endMask(); stenc->enableMask(TStencilControl::SHOW_INSIDE); TRegionOutline::Boundary::iterator regions_it; TRegionOutline::Boundary::iterator regions_it_b = regionOutline.m_exterior.begin(); TRegionOutline::Boundary::iterator regions_it_e = regionOutline.m_exterior.end(); for (regions_it = regions_it_b; regions_it != regions_it_e; ++regions_it) drawPolyline(cf, *regions_it, m_shadowDirection); stenc->enableMask(TStencilControl::SHOW_OUTSIDE); regions_it_b = regionOutline.m_interior.begin(); regions_it_e = regionOutline.m_interior.end(); for (regions_it = regions_it_b; regions_it != regions_it_e; ++regions_it) drawPolyline(cf, *regions_it, -m_shadowDirection); // tglColor(TPixel32::White); stenc->disableMask(); } //------------------------------------------------------------ /* int ShadowStyle::drawPolyline(TFlash& flash, std::vector<T3DPointD> &polyline, TPointD shadowDirection, const bool isDraw) const { int i; int stepNumber; double distance; TPointD v1,v2,diff,midPoint,ratio; double len; TRegionOutline::PointVector::iterator it; TRegionOutline::PointVector::iterator it_b = polyline.begin(); TRegionOutline::PointVector::iterator it_e = polyline.end(); std::vector<TSegment> segmentArray; v1.x = polyline.back().x; v1.y = polyline.back().y; for(it = it_b; it!= it_e; ++it) { v2.x = it->x; v2.y = it->y; if (v1==v2) continue; diff = normalize(rotate90(v2-v1)); len=diff*shadowDirection; if(len>0) { distance = tdistance(v1,v2)*m_density; ratio= (v2-v1)*(1.0/distance); midPoint=v1; stepNumber= (int)distance; for(i=0; i<stepNumber;i++ ) { std::vector<TSegment> sa; TPointD p0=midPoint; TPointD p1=midPoint+(shadowDirection*len*m_len*0.5); TPointD p2=midPoint+(shadowDirection*len*m_len); segmentArray.push_back(TSegment(p1,p0)); segmentArray.push_back(TSegment(p1,p2)); midPoint += ratio; } } v1=v2; } if ( isDraw && segmentArray.size()>0 ) { flash.setLineColor(m_shadowColor); flash.drawSegments(segmentArray, true); } if ( segmentArray.size()>0 ) return 1; return 0; } void ShadowStyle::drawRegion( TFlash& flash, const TRegion* r) const { SFlashUtils rdf(r); rdf.computeRegionOutline(); TRegionOutline::Boundary::iterator regions_it; TRegionOutline::Boundary::iterator regions_it_b = rdf.m_ro.m_exterior->begin(); TRegionOutline::Boundary::iterator regions_it_e = rdf.m_ro.m_exterior->end(); // In the GL version the shadow lines are not croped into the filled region. // This is the reason why I don't calculate the number of shadow lines. // int nbDraw=0; // for( regions_it = regions_it_b ; regions_it!= regions_it_e; ++regions_it) // nbDraw+=drawPolyline(flash,*regions_it, m_shadowDirection,false); // regions_it_b = rdf.m_ro.m_interior->begin(); // regions_it_e = rdf.m_ro.m_interior->end(); // for( regions_it = regions_it_b ; regions_it!= regions_it_e; ++regions_it) // nbDraw+=drawPolyline(flash,*regions_it,-m_shadowDirection,false); // Only the bbox rectangle is croped. flash.drawRegion(*r,1); flash.setFillColor(getMainColor()); flash.drawRectangle(rdf.m_ro.m_bbox); regions_it_b = rdf.m_ro.m_exterior->begin(); regions_it_e = rdf.m_ro.m_exterior->end(); for( regions_it = regions_it_b ; regions_it!= regions_it_e; ++regions_it) drawPolyline(flash,*regions_it, m_shadowDirection); regions_it_b = rdf.m_ro.m_interior->begin(); regions_it_e = rdf.m_ro.m_interior->end(); for( regions_it = regions_it_b ; regions_it!= regions_it_e; ++regions_it) drawPolyline(flash,*regions_it,-m_shadowDirection); } */ //------------------------------------------------------------ TPixel32 ShadowStyle::getColorParamValue(int index) const { return index == 0 ? m_shadowColor : TSolidColorStyle::getMainColor(); } //------------------------------------------------------------ void ShadowStyle::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) m_shadowColor = color; else { TSolidColorStyle::setMainColor(color); } } //------------------------------------------------------------ void ShadowStyle::makeIcon(const TDimension &d) { double oldVal = getParamValue(TColorStyle::double_tag(), 1); setParamValue(1, oldVal * 0.25); TColorStyle::makeIcon(d); setParamValue(1, oldVal); } //*************************************************************************** // ShadowStyle2 implementation //*************************************************************************** ShadowStyle2::ShadowStyle2(const TPixel32 &bgColor, const TPixel32 &shadowColor, const TPointD &shadowDirection, double shadowLength) : TSolidColorStyle(bgColor) , m_shadowColor(shadowColor) , m_shadowLength(shadowLength) , m_shadowDirection(normalize(shadowDirection)) {} //------------------------------------------------------------ TColorStyle *ShadowStyle2::clone() const { return new ShadowStyle2(*this); } //------------------------------------------------------------ void ShadowStyle2::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_shadowDirection.x >> m_shadowDirection.y; is >> m_shadowLength; is >> m_shadowColor; } //------------------------------------------------------------ void ShadowStyle2::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_shadowDirection.x << m_shadowDirection.y; os << m_shadowLength; os << m_shadowColor; } //------------------------------------------------------------ int ShadowStyle2::getParamCount() const { return 2; } //----------------------------------------------------------------------------- TColorStyle::ParamType ShadowStyle2::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString ShadowStyle2::getParamNames(int index) const { assert(0 <= index && index < 2); return index == 0 ? QCoreApplication::translate("ShadowStyle2", "Angle") : QCoreApplication::translate("ShadowStyle2", "Size"); } //----------------------------------------------------------------------------- void ShadowStyle2::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 2); if (index == 0) { min = 0.0; max = 360.0; } else { min = 0.0; max = 500.0; } } //----------------------------------------------------------------------------- double ShadowStyle2::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 2); if (index == 1) return m_shadowLength; double degree = asin(m_shadowDirection.y); if (m_shadowDirection.x < 0) degree = M_PI - degree; if (degree < 0) degree += M_2PI; return degree * M_180_PI; } //----------------------------------------------------------------------------- static int nbDiffVerts(const std::vector<TPointD> &pv) { std::vector<TPointD> lpv; bool isMissing[4] = {true, true, true, true}; if (pv.size() == 0) return 0; lpv.push_back(pv[0]); isMissing[0] = false; for (int i = 1; i < (int)pv.size(); i++) { bool isDiff = true; for (int j = 0; j < (int)lpv.size() && isDiff; j++) isDiff = lpv[j] == pv[i] ? false : isDiff; if (isDiff) { lpv.push_back(pv[i]); isMissing[i] = false; } } return lpv.size(); } void ShadowStyle2::setParamValue(int index, double value) { assert(0 <= index && index < 2); if (index == 1) { m_shadowLength = value; } else { double degree = value * M_PI_180; m_shadowDirection.x = cos(degree); m_shadowDirection.y = sin(degree); } } //------------------------------------------------------------ namespace { void drawShadowLine(TPixel32 shadowColor, TPixel32 color, TPointD v1, TPointD v2, TPointD diff1, TPointD diff2) { v1 = v1 + diff1; v2 = v2 + diff2; diff1 = -diff1; diff2 = -diff2; double r1, r2; double t = 0.0; glBegin(GL_QUAD_STRIP); for (; t <= 1; t += 0.1) { r1 = t * t * t; r2 = 1 - r1; TPixel32 c((int)(color.r * r2 + shadowColor.r * r1), (int)(color.g * r2 + shadowColor.g * r1), (int)(color.b * r2 + shadowColor.b * r1), (int)(color.m * r2 + shadowColor.m * r1)); tglColor(c); tglVertex(v1 + t * diff1); tglVertex(v2 + t * diff2); } glEnd(); } int drawShadowLine(TFlash &flash, TPixel32 shadowColor, TPixel32 color, TPointD v1, TPointD v2, TPointD diff1, TPointD diff2, const bool isDraw = true) { int nbDraw = 0; v1 = v1 + diff1; v2 = v2 + diff2; diff1 = -diff1; diff2 = -diff2; TPointD vv1, vv2, ovv1, ovv2; TPixel32 oc; double r1, r2; double t = 0.0; bool isFirst = true; flash.setThickness(0.0); SFlashUtils sfu; for (; t <= 1; t += 0.1) { if (isFirst) { r1 = t * t * t; r2 = 1 - r1; oc = TPixel32((int)(color.r * r2 + shadowColor.r * r1), (int)(color.g * r2 + shadowColor.g * r1), (int)(color.b * r2 + shadowColor.b * r1), (int)(color.m * r2 + shadowColor.m * r1)); ovv1 = v1 + t * diff1; ovv2 = v2 + t * diff2; isFirst = false; } else { r1 = t * t * t; r2 = 1 - r1; TPixel32 c((int)(color.r * r2 + shadowColor.r * r1), (int)(color.g * r2 + shadowColor.g * r1), (int)(color.b * r2 + shadowColor.b * r1), (int)(color.m * r2 + shadowColor.m * r1)); vv1 = (v1 + t * diff1); vv2 = (v2 + t * diff2); std::vector<TPointD> pv; pv.push_back(ovv1); pv.push_back(ovv2); pv.push_back(vv2); pv.push_back(vv1); int nbDV = nbDiffVerts(pv); if (nbDV >= 3 && nbDV <= 4) nbDraw++; if (isDraw) sfu.drawGradedPolyline(flash, pv, oc, c); oc = c; ovv1 = vv1; ovv2 = vv2; } } return nbDraw; } } //------------------------------------------------------------ void ShadowStyle2::drawPolyline(const TColorFunction *cf, const std::vector<T3DPointD> &polyline, TPointD shadowDirection) const { if (polyline.empty()) return; TPointD v0, v1, diff; double len1, len2; TPixel32 color, shadowColor; if (cf) color = (*(cf))(TSolidColorStyle::getMainColor()); else color = TSolidColorStyle::getMainColor(); if (cf) shadowColor = (*(cf))(m_shadowColor); else shadowColor = m_shadowColor; tglColor(shadowColor); // glEnable(GL_BLEND); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //// <-- tglEnableBlending(); TRegionOutline::PointVector::const_iterator it; TRegionOutline::PointVector::const_iterator it_b = polyline.begin(); TRegionOutline::PointVector::const_iterator it_e = polyline.end(); int size = polyline.size(); std::vector<double> lens(size); v0.x = polyline.back().x; v0.y = polyline.back().y; int count = 0; for (it = it_b; it != it_e; ++it) { v1.x = it->x; v1.y = it->y; if (v1 != v0) { diff = normalize(rotate90(v1 - v0)); len1 = diff * shadowDirection; if (len1 < 0) len1 = 0; lens[count++] = len1; } else lens[count++] = 0; v0 = v1; } double firstVal = lens.front(); for (count = 0; count != size - 1; count++) { lens[count] = (lens[count] + lens[count + 1]) * 0.5; } lens[size - 1] = (lens[size - 1] + firstVal) * 0.5; for (count = 0; count != size - 1; count++) { v0.x = polyline[count].x; v0.y = polyline[count].y; v1.x = polyline[count + 1].x; v1.y = polyline[count + 1].y; len1 = lens[count]; len2 = lens[count + 1]; if (v0 != v1 && len1 >= 0 && len2 >= 0 && (len1 + len2) > 0) drawShadowLine(shadowColor, color, v0, v1, shadowDirection * len1 * m_shadowLength, shadowDirection * len2 * m_shadowLength); } v0.x = polyline[count].x; v0.y = polyline[count].y; v1.x = polyline.front().x; v1.y = polyline.front().y; len1 = lens[count]; len2 = lens[0]; if (v0 != v1 && len1 >= 0 && len2 >= 0 && (len1 + len2) > 0) drawShadowLine(shadowColor, color, v0, v1, shadowDirection * len1 * m_shadowLength, shadowDirection * len2 * m_shadowLength); // tglColor(TPixel32::White); } //------------------------------------------------------------ TPixel32 ShadowStyle2::getColorParamValue(int index) const { return index == 0 ? m_shadowColor : TSolidColorStyle::getMainColor(); } //------------------------------------------------------------ void ShadowStyle2::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) m_shadowColor = color; else { TSolidColorStyle::setMainColor(color); } } //------------------------------------------------------------ void ShadowStyle2::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { TStencilControl *stenc = TStencilControl::instance(); TPixel32 backgroundColor = TSolidColorStyle::getMainColor(); if (cf) backgroundColor = (*(cf))(backgroundColor); if (backgroundColor.m == 0) { // only to create stencil mask TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); // does not draw on screen appStyle.drawRegion(0, false, boundary); } else { // create stencil mask and draw on screen stenc->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); TSolidColorStyle::drawRegion(cf, antiAliasing, boundary); } stenc->endMask(); stenc->enableMask(TStencilControl::SHOW_INSIDE); TRegionOutline::Boundary::iterator regions_it; TRegionOutline::Boundary::iterator regions_it_b = boundary.m_exterior.begin(); TRegionOutline::Boundary::iterator regions_it_e = boundary.m_exterior.end(); for (regions_it = regions_it_b; regions_it != regions_it_e; ++regions_it) drawPolyline(cf, *regions_it, m_shadowDirection); // tglColor(TPixel32::White); stenc->disableMask(); } //------------------------------------------------------------ int ShadowStyle2::drawPolyline(TFlash &flash, std::vector<T3DPointD> &polyline, TPointD shadowDirection, const bool isDraw) const { int nbDraw = 0; TPointD v0, v1, diff; double len1, len2; TPixel32 color, shadowColor; color = TSolidColorStyle::getMainColor(); shadowColor = m_shadowColor; TRegionOutline::PointVector::iterator it; TRegionOutline::PointVector::iterator it_b = polyline.begin(); TRegionOutline::PointVector::iterator it_e = polyline.end(); int size = polyline.size(); std::vector<double> lens(size); v0.x = polyline.back().x; v0.y = polyline.back().y; int count = 0; for (it = it_b; it != it_e; ++it) { v1.x = it->x; v1.y = it->y; if (v1 != v0) { diff = normalize(rotate90(v1 - v0)); len1 = diff * shadowDirection; if (len1 < 0) len1 = 0; lens[count++] = len1; } else lens[count++] = 0; v0 = v1; } double firstVal = lens.front(); for (count = 0; count != size - 1; count++) { lens[count] = (lens[count] + lens[count + 1]) * 0.5; } lens[size - 1] = (lens[size - 1] + firstVal) * 0.5; for (count = 0; count != size - 1; count++) { v0.x = polyline[count].x; v0.y = polyline[count].y; v1.x = polyline[count + 1].x; v1.y = polyline[count + 1].y; len1 = lens[count]; len2 = lens[count + 1]; if (v0 != v1 && len1 >= 0 && len2 >= 0 && (len1 + len2) > 0) nbDraw += drawShadowLine(flash, shadowColor, color, v0, v1, shadowDirection * len1 * m_shadowLength, shadowDirection * len2 * m_shadowLength, isDraw); } v0.x = polyline[count].x; v0.y = polyline[count].y; v1.x = polyline.front().x; v1.y = polyline.front().y; len1 = lens[count]; len2 = lens[0]; if (v0 != v1 && len1 >= 0 && len2 >= 0 && (len1 + len2) > 0) nbDraw += drawShadowLine(flash, shadowColor, color, v0, v1, shadowDirection * len1 * m_shadowLength, shadowDirection * len2 * m_shadowLength, isDraw); return nbDraw; } //------------------------------------------------------------ void ShadowStyle2::drawRegion(TFlash &flash, const TRegion *r) const { SFlashUtils rdf(r); rdf.computeRegionOutline(); TRegionOutline::Boundary::iterator regions_it; TRegionOutline::Boundary::iterator regions_it_b = rdf.m_ro.m_exterior.begin(); TRegionOutline::Boundary::iterator regions_it_e = rdf.m_ro.m_exterior.end(); int nbDraw = 0; for (regions_it = regions_it_b; regions_it != regions_it_e; ++regions_it) nbDraw += drawPolyline(flash, *regions_it, m_shadowDirection, false); flash.drawRegion(*r, nbDraw + 1); flash.setFillColor(getMainColor()); flash.drawRectangle(rdf.m_ro.m_bbox); for (regions_it = regions_it_b; regions_it != regions_it_e; ++regions_it) drawPolyline(flash, *regions_it, m_shadowDirection); } //*************************************************************************** // RubberModifier implementation //*************************************************************************** TOutlineStyle::RegionOutlineModifier *RubberModifier::clone() const { return new RubberModifier(*this); } //------------------------------------------------------------ void RubberModifier::modify(TRegionOutline &outline) const { double deformSize = 40.0 + (100 - m_deform) * 0.60; TRegionOutline::Boundary::iterator regions_it; TRegionOutline::Boundary::iterator regions_it_b = outline.m_exterior.begin(); TRegionOutline::Boundary::iterator regions_it_e = outline.m_exterior.end(); for (regions_it = regions_it_b; regions_it != regions_it_e; ++regions_it) { RubberDeform rd(&regions_it[0]); rd.deform(deformSize); } regions_it_b = outline.m_interior.begin(); regions_it_e = outline.m_interior.end(); for (regions_it = regions_it_b; regions_it != regions_it_e; ++regions_it) { RubberDeform rd(&regions_it[0]); rd.deform(deformSize); } } //*************************************************************************** // TRubberFillStyle implementation //*************************************************************************** TRubberFillStyle::TRubberFillStyle(const TPixel32 &color, double deform) : TSolidColorStyle(color) { m_regionOutlineModifier = new RubberModifier(deform); } //------------------------------------------------------------ TColorStyle *TRubberFillStyle::clone() const { return new TRubberFillStyle(*this); } //------------------------------------------------------------ void TRubberFillStyle::makeIcon(const TDimension &d) { // Saves the values of member variables and sets the right icon values RubberModifier *prm = (RubberModifier *)(m_regionOutlineModifier); double LDeform = prm->getDeform(); prm->setDeform(LDeform); TColorStyle::makeIcon(d); // Loads the original values prm->setDeform(LDeform); } //------------------------------------------------------------ int TRubberFillStyle::getParamCount() const { return 1; } //----------------------------------------------------------------------------- TColorStyle::ParamType TRubberFillStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString TRubberFillStyle::getParamNames(int index) const { assert(0 <= index && index < 1); return QCoreApplication::translate("TRubberFillStyle", "Intensity"); } //----------------------------------------------------------------------------- void TRubberFillStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 1); min = 0.; max = 100.0; } //----------------------------------------------------------------------------- double TRubberFillStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 1); return ((RubberModifier *)m_regionOutlineModifier)->getDeform(); } //----------------------------------------------------------------------------- void TRubberFillStyle::setParamValue(int index, double value) { assert(0 <= index && index < 1); double oldDeform = ((RubberModifier *)m_regionOutlineModifier)->getDeform(); if (oldDeform != value) { delete m_regionOutlineModifier; m_regionOutlineModifier = new RubberModifier(value); updateVersionNumber(); } } //------------------------------------------------------------ void TRubberFillStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); delete m_regionOutlineModifier; RubberModifier *rub = new RubberModifier(0.0); rub->loadData(is); m_regionOutlineModifier = rub; } //------------------------------------------------------------ void TRubberFillStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); assert(m_regionOutlineModifier); ((RubberModifier *)m_regionOutlineModifier)->saveData(os); } //------------------------------------------------------------ void TRubberFillStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { TSolidColorStyle::drawRegion(cf, true, boundary); } void TRubberFillStyle::drawRegion(TFlash &flash, const TRegion *r) const { SFlashUtils rdf(r); rdf.computeRegionOutline(); m_regionOutlineModifier->modify(rdf.m_ro); flash.setFillColor(getMainColor()); rdf.drawRegionOutline(flash); // If Valentina prefers the angled version use this // rdf.drawRegionOutline(flash,false); } //*************************************************************************** // TPointShadowFillStyle implementation //*************************************************************************** TPointShadowFillStyle::TPointShadowFillStyle(const TPixel32 &bgColor, const TPixel32 &shadowColor, const TPointD &shadowDirection, double density, double shadowSize, double pointSize) : TSolidColorStyle(bgColor) , m_shadowColor(shadowColor) , m_shadowDirection(normalize(shadowDirection)) , m_shadowSize(shadowSize) , m_density(density) , m_pointSize(pointSize) {} //----------------------------------------------------------------------------- TColorStyle *TPointShadowFillStyle::clone() const { return new TPointShadowFillStyle(*this); } //----------------------------------------------------------------------------- int TPointShadowFillStyle::getParamCount() const { return 4; } //----------------------------------------------------------------------------- TColorStyle::ParamType TPointShadowFillStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString TPointShadowFillStyle::getParamNames(int index) const { assert(0 <= index && index < 4); QString value; switch (index) { case 0: value = QCoreApplication::translate("TPointShadowFillStyle", "Angle"); break; case 1: value = QCoreApplication::translate("TPointShadowFillStyle", "Density"); break; case 2: value = QCoreApplication::translate("TPointShadowFillStyle", "Size"); break; case 3: value = QCoreApplication::translate("TPointShadowFillStyle", "Point Size"); break; } return value; } //----------------------------------------------------------------------------- void TPointShadowFillStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 4); switch (index) { case 0: min = 0.0; max = 360.0; break; case 1: min = 0.0; max = 1.0; break; case 2: min = 0.0; max = 100.0; break; case 3: min = 0.01; max = 100.0; break; } } //----------------------------------------------------------------------------- double TPointShadowFillStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 4); double degree = 0.0; switch (index) { case 0: degree = asin(m_shadowDirection.y); if (m_shadowDirection.x < 0) degree = M_PI - degree; if (degree < 0) degree += M_2PI; return degree * M_180_PI; case 1: return m_density; case 2: return m_shadowSize; case 3: return m_pointSize; } // never return 0; } //----------------------------------------------------------------------------- void TPointShadowFillStyle::setParamValue(int index, double value) { assert(0 <= index && index < 4); double degree = 0.0; switch (index) { case 0: degree = value * M_PI_180; m_shadowDirection.x = cos(degree); m_shadowDirection.y = sin(degree); break; case 1: m_density = value; break; case 2: m_shadowSize = value; break; case 3: m_pointSize = value; break; } } //------------------------------------------------------------ void TPointShadowFillStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_shadowDirection.x >> m_shadowDirection.y; is >> m_density; is >> m_shadowSize; is >> m_pointSize; is >> m_shadowColor; } //------------------------------------------------------------ void TPointShadowFillStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_shadowDirection.x << m_shadowDirection.y; os << m_density; os << m_shadowSize; os << m_pointSize; os << m_shadowColor; } //------------------------------------------------------------ TPixel32 TPointShadowFillStyle::getColorParamValue(int index) const { return index == 0 ? m_shadowColor : TSolidColorStyle::getMainColor(); } //------------------------------------------------------------ void TPointShadowFillStyle::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) m_shadowColor = color; else { TSolidColorStyle::setMainColor(color); } } //------------------------------------------------------------ double TPointShadowFillStyle::triangleArea(const TPointD &a, const TPointD &b, const TPointD &c) const { double ab = tdistance(a, b); double ac = tdistance(a, c); double bc = tdistance(b, c); double s = (ab + bc + ac) / 2.0; return sqrt(s * (s - ab) * (s - ac) * (s - bc)); } //------------------------------------------------------------ void TPointShadowFillStyle::shadowOnEdge_parallel(const TPointD &p0, const TPointD &p1, const TPointD &p2, TRandom &rnd) const { if (p0 == p1 || p1 == p2) return; TPointD diff = normalize(rotate90(p1 - p0)); double len1 = diff * m_shadowDirection; diff = normalize(rotate90(p2 - p1)); double len2 = diff * m_shadowDirection; if (len1 >= 0 && len2 >= 0 && (len1 + len2) > 0) { TPointD la = p1 + m_shadowDirection * len1 * m_shadowSize; TPointD lb = p2 + m_shadowDirection * len2 * m_shadowSize; double t = triangleArea(p1, p2, lb) + triangleArea(p2, lb, la); int nb = (int)(m_density * t); for (int i = 0; i < nb; i++) { double q = rnd.getUInt(1001) / 1000.0; double r = rnd.getUInt(1001) / 1000.0; r = r * r; TPointD u = p1 + (p2 - p1) * q; u = u + r * (len1 * (1.0 - q) + len2 * q) * m_shadowDirection * m_shadowSize; tglColor(TPixel32(m_shadowColor.r, m_shadowColor.g, m_shadowColor.b, (int)((1.0 - r) * (double)m_shadowColor.m))); tglVertex(u); } } } //------------------------------------------------------------ int TPointShadowFillStyle::shadowOnEdge_parallel( TFlash &flash, const TPointD &p0, const TPointD &p1, const TPointD &p2, TRandom &rnd, const double radius, const bool isDraw) const { int nbDraw = 0; if (p0 == p1 || p1 == p2) return 0; TPointD diff = normalize(rotate90(p1 - p0)); double len1 = diff * m_shadowDirection; len1 = std::max(0.0, len1); diff = normalize(rotate90(p2 - p1)); double len2 = diff * m_shadowDirection; len2 = std::max(0.0, len2); if ((len1 + len2) > 0) { TPointD la = p1 + m_shadowDirection * len1 * m_shadowSize; TPointD lb = p2 + m_shadowDirection * len2 * m_shadowSize; double t = triangleArea(p1, p2, lb) + triangleArea(p2, lb, la); int nb = (int)(m_density * t); for (int i = 0; i < nb; i++) { double q = rnd.getUInt(1001) / 1000.0; double r = rnd.getUInt(1001) / 1000.0; r = r * r; TPointD u = p1 + (p2 - p1) * q; u = u + r * (len1 * (1.0 - q) + len2 * q) * m_shadowDirection * m_shadowSize; nbDraw++; if (isDraw) { flash.setFillColor(TPixel32(m_shadowColor.r, m_shadowColor.g, m_shadowColor.b, (int)((1.0 - r) * 255))); flash.drawEllipse(u, radius, radius); // flash.drawDot(u,radius); } } } return nbDraw; } //------------------------------------------------------------ void TPointShadowFillStyle::deleteSameVerts( TRegionOutline::Boundary::iterator &rit, std::vector<T3DPointD> &pv) const { pv.clear(); if (rit->size() <= 0) return; TRegionOutline::PointVector::iterator it_beg = rit->begin(); TRegionOutline::PointVector::iterator it_end = rit->end(); TRegionOutline::PointVector::iterator it = it_beg; pv.push_back(*it); it++; for (; it != it_end; it++) { if (tdistance(*it, pv.back()) > TConsts::epsilon) { pv.push_back(*it); } } if (pv.size() > 2) { if (tdistance(*(pv.begin()), pv.back()) <= TConsts::epsilon) pv.pop_back(); } } //------------------------------------------------------------ void TPointShadowFillStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { TStencilControl *stenc = TStencilControl::instance(); TPixel32 backgroundColor = TSolidColorStyle::getMainColor(); if (cf) backgroundColor = (*(cf))(backgroundColor); if (backgroundColor.m == 0) { // only to create stencil mask TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); // does not draw on screen appStyle.drawRegion(0, false, boundary); } else { // create stencil mask and draw on screen stenc->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); TSolidColorStyle::drawRegion(cf, antiAliasing, boundary); } stenc->endMask(); stenc->enableMask(TStencilControl::SHOW_INSIDE); GLfloat pointSizeSave; glGetFloatv(GL_POINT_SIZE, &pointSizeSave); GLfloat sizes[2]; glGetFloatv(GL_POINT_SIZE_RANGE, sizes); // glEnable(GL_BLEND); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // glEnable(GL_POINT_SMOOTH); // glPointSize((float)(sizes[0]+(sizes[1]-sizes[0])*m_pointSize*0.01)); tglEnablePointSmooth( (float)(sizes[0] + (sizes[1] - sizes[0]) * m_pointSize * 0.01)); TRegionOutline::Boundary::iterator regions_it; TRegionOutline::Boundary::iterator regions_it_b = boundary.m_exterior.begin(); TRegionOutline::Boundary::iterator regions_it_e = boundary.m_exterior.end(); TPixel32 color; if (cf) color = (*(cf))(m_shadowColor); else color = m_shadowColor; TRandom rnd; for (regions_it = regions_it_b; regions_it != regions_it_e; ++regions_it) { std::vector<T3DPointD> pv; deleteSameVerts(regions_it, pv); if (pv.size() < 3) continue; std::vector<T3DPointD>::iterator it_beg = pv.begin(); std::vector<T3DPointD>::iterator it_end = pv.end(); std::vector<T3DPointD>::iterator it_last = it_end - 1; std::vector<T3DPointD>::iterator it0, it1, it2; glBegin(GL_POINTS); for (it1 = it_beg; it1 != it_end; it1++) { it0 = it1 == it_beg ? it_last : it1 - 1; it2 = it1 == it_last ? it_beg : it1 + 1; shadowOnEdge_parallel(TPointD(it0->x, it0->y), TPointD(it1->x, it1->y), TPointD(it2->x, it2->y), rnd); } glEnd(); } glPointSize(pointSizeSave); stenc->disableMask(); } //------------------------------------------------------------ void TPointShadowFillStyle::drawRegion(TFlash &flash, const TRegion *r) const { SFlashUtils rdf(r); rdf.computeRegionOutline(); TRegionOutline::Boundary::iterator regions_it; TRegionOutline::Boundary::iterator regions_it_b = rdf.m_ro.m_exterior.begin(); TRegionOutline::Boundary::iterator regions_it_e = rdf.m_ro.m_exterior.end(); TPixel32 color = m_shadowColor; TRandom rnd; rnd.reset(); double sizes[2] = {0.15, 10.0}; double radius = (sizes[0] + (sizes[1] - sizes[0]) * m_pointSize * 0.01); int nbDraw = 0; for (regions_it = regions_it_b; regions_it != regions_it_e; ++regions_it) { std::vector<T3DPointD> pv; deleteSameVerts(regions_it, pv); if (pv.size() < 3) continue; std::vector<T3DPointD>::iterator it_beg = pv.begin(); std::vector<T3DPointD>::iterator it_end = pv.end(); std::vector<T3DPointD>::iterator it_last = it_end - 1; std::vector<T3DPointD>::iterator it0, it1, it2; for (it1 = it_beg; it1 != it_end; it1++) { it0 = it1 == it_beg ? it_last : it1 - 1; it2 = it1 == it_last ? it_beg : it1 + 1; nbDraw += shadowOnEdge_parallel( flash, TPointD(it0->x, it0->y), TPointD(it1->x, it1->y), TPointD(it2->x, it2->y), rnd, radius, false); } } rnd.reset(); flash.drawRegion(*r, nbDraw + 1); // +1 bbox flash.setFillColor(getMainColor()); flash.drawRectangle(rdf.m_ro.m_bbox); flash.setThickness(0.0); for (regions_it = regions_it_b; regions_it != regions_it_e; ++regions_it) { std::vector<T3DPointD> pv; deleteSameVerts(regions_it, pv); if (pv.size() < 3) continue; std::vector<T3DPointD>::iterator it_beg = pv.begin(); std::vector<T3DPointD>::iterator it_end = pv.end(); std::vector<T3DPointD>::iterator it_last = it_end - 1; std::vector<T3DPointD>::iterator it0, it1, it2; for (it1 = it_beg; it1 != it_end; it1++) { it0 = it1 == it_beg ? it_last : it1 - 1; it2 = it1 == it_last ? it_beg : it1 + 1; shadowOnEdge_parallel(flash, TPointD(it0->x, it0->y), TPointD(it1->x, it1->y), TPointD(it2->x, it2->y), rnd, radius, true); } } } //*************************************************************************** // TDottedFillStyle implementation //*************************************************************************** TDottedFillStyle::TDottedFillStyle(const TPixel32 &bgColor, const TPixel32 &pointColor, const double dotSize, const double dotDist, const bool isShifted) : TSolidColorStyle(bgColor) , m_pointColor(pointColor) , m_dotSize(dotSize) , m_dotDist(dotDist) , m_isShifted(isShifted) {} //------------------------------------------------------------ TDottedFillStyle::TDottedFillStyle(const TPixel32 &color) : TSolidColorStyle(TPixel32(0, 0, 200)) , m_pointColor(color) , m_dotSize(3.0) , m_dotDist(15.0) , m_isShifted(true) {} //------------------------------------------------------------ TColorStyle *TDottedFillStyle::clone() const { return new TDottedFillStyle(*this); } //------------------------------------------------------------ int TDottedFillStyle::getParamCount() const { return 2; } //----------------------------------------------------------------------------- TColorStyle::ParamType TDottedFillStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString TDottedFillStyle::getParamNames(int index) const { assert(0 <= index && index < 2); return index == 0 ? QCoreApplication::translate("TDottedFillStyle", "Dot Size") : QCoreApplication::translate("TDottedFillStyle", "Dot Distance"); } //----------------------------------------------------------------------------- void TDottedFillStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 2); if (index == 0) { min = 0.001; max = 30.0; } else { min = 2.0; max = 100.0; } } //----------------------------------------------------------------------------- double TDottedFillStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 2); if (!index) return m_dotSize; else return m_dotDist; } //----------------------------------------------------------------------------- void TDottedFillStyle::setParamValue(int index, double value) { assert(0 <= index && index < 2); if (!index) { m_dotSize = value; } else { m_dotDist = value; } } //------------------------------------------------------------ void TDottedFillStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_dotSize; is >> m_dotDist; is >> m_pointColor; } //------------------------------------------------------------ void TDottedFillStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_dotSize; os << m_dotDist; os << m_pointColor; } //------------------------------------------------------------ TPixel32 TDottedFillStyle::getColorParamValue(int index) const { return index == 0 ? m_pointColor : TSolidColorStyle::getMainColor(); } //------------------------------------------------------------ void TDottedFillStyle::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) m_pointColor = color; else { TSolidColorStyle::setMainColor(color); } } //------------------------------------------------------------ void TDottedFillStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { double LDotDist = std::max(m_dotDist, 0.1); // double LDotSize=m_dotSize; bool LIsShifted = m_isShifted; const bool isTransparent = m_pointColor.m < 255; TStencilControl *stenc = TStencilControl::instance(); TPixel32 backgroundColor = TSolidColorStyle::getMainColor(); if (cf) backgroundColor = (*(cf))(backgroundColor); if (backgroundColor.m == 0) { // only to create stencil mask TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); // does not draw on screen appStyle.drawRegion(0, false, boundary); } else { // create stencil mask and draw on screen stenc->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); TSolidColorStyle::drawRegion(cf, antiAliasing, boundary); } stenc->endMask(); stenc->enableMask(TStencilControl::SHOW_INSIDE); if (isTransparent) { // glEnable(GL_BLEND); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //// <-- tglEnableBlending(); } TPixel32 color; if (cf) color = (*(cf))(m_pointColor); else color = m_pointColor; tglColor(color); int i = 0; for (double y = boundary.m_bbox.y0; y <= boundary.m_bbox.y1; y += LDotDist, ++i) { double x = LIsShifted && (i % 2) == 1 ? boundary.m_bbox.x0 + LDotDist / 2.0 : boundary.m_bbox.x0; for (; x <= boundary.m_bbox.x1; x += LDotDist) tglDrawDisk(TPointD(x, y), m_dotSize); // tglDrawCircle(TPointD(x,y),m_dotSize); } if (isTransparent) { // tglColor(TPixel32::White); // glDisable(GL_BLEND); } stenc->disableMask(); } //------------------------------------------------------------ int TDottedFillStyle::nbClip(const double LDotDist, const bool LIsShifted, const TRectD &bbox) const { int nbClipLayers = 1; // the bbox rectangle int i = 0; for (double y = bbox.y0; y <= bbox.y1; y += LDotDist, ++i) { double x = LIsShifted && (i % 2) == 1 ? bbox.x0 + LDotDist / 2.0 : bbox.x0; for (; x <= bbox.x1; x += LDotDist) nbClipLayers++; } return nbClipLayers; } //------------------------------------------------------------ void TDottedFillStyle::drawRegion(TFlash &flash, const TRegion *r) const { double LDotDist = std::max(m_dotDist, 0.1); double LDotSize = m_dotSize; bool LIsShifted = m_isShifted; TRectD bbox(r->getBBox()); flash.setFillColor(TPixel::Black); flash.drawRegion(*r, true); int nClip = nbClip(LDotDist, LIsShifted, bbox); flash.drawRegion(*r, nClip); flash.setFillColor(getMainColor()); flash.drawRectangle(bbox); flash.setFillColor(m_pointColor); int i = 0; for (double y = bbox.y0; y <= bbox.y1; y += LDotDist, ++i) { double x = LIsShifted && (i % 2) == 1 ? bbox.x0 + LDotDist / 2.0 : bbox.x0; for (; x <= bbox.x1; x += LDotDist) flash.drawEllipse(TPointD(x, y), LDotSize, LDotSize); } } //*************************************************************************** // TCheckedFillStyle implementation //*************************************************************************** TCheckedFillStyle::TCheckedFillStyle(const TPixel32 &bgColor, const TPixel32 &pointColor, const double HDist, const double HAngle, const double VDist, const double VAngle, const double Thickness) : TSolidColorStyle(bgColor) , m_pointColor(pointColor) , m_HDist(HDist) , m_HAngle(HAngle) , m_VDist(VDist) , m_VAngle(VAngle) , m_Thickness(Thickness) {} //------------------------------------------------------------ TCheckedFillStyle::TCheckedFillStyle(const TPixel32 &color) : TSolidColorStyle(TPixel32::Transparent) , m_pointColor(color) , m_HDist(15.0) , m_HAngle(0.0) , m_VDist(15.0) , m_VAngle(0.0) , m_Thickness(6.0) {} //------------------------------------------------------------ TColorStyle *TCheckedFillStyle::clone() const { return new TCheckedFillStyle(*this); } //------------------------------------------------------------ int TCheckedFillStyle::getParamCount() const { return 5; } //----------------------------------------------------------------------------- TColorStyle::ParamType TCheckedFillStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString TCheckedFillStyle::getParamNames(int index) const { assert(0 <= index && index < 5); QString value; switch (index) { case 0: value = QCoreApplication::translate("TCheckedFillStyle", "Horiz Dist"); break; case 1: value = QCoreApplication::translate("TCheckedFillStyle", "Horiz Angle"); break; case 2: value = QCoreApplication::translate("TCheckedFillStyle", "Vert Dist"); break; case 3: value = QCoreApplication::translate("TCheckedFillStyle", "Vert Angle"); break; case 4: value = QCoreApplication::translate("TCheckedFillStyle", "Thickness"); break; } return value; } //----------------------------------------------------------------------------- void TCheckedFillStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 5); switch (index) { case 0: min = 1.0; max = 100.0; break; case 1: min = -45.0; max = 45.0; break; case 2: min = 1.0; max = 100.0; break; case 3: min = -45.0; max = 45.0; break; case 4: min = 0.5; max = 100.0; break; } } //----------------------------------------------------------------------------- double TCheckedFillStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 5); switch (index) { case 0: return m_HDist; case 1: return m_HAngle; case 2: return m_VDist; case 3: return m_VAngle; case 4: return m_Thickness; } return 0.0; } //----------------------------------------------------------------------------- void TCheckedFillStyle::setParamValue(int index, double value) { assert(0 <= index && index < 5); switch (index) { case 0: m_HDist = value; break; case 1: m_HAngle = value; break; case 2: m_VDist = value; break; case 3: m_VAngle = value; break; case 4: m_Thickness = value; break; } } //------------------------------------------------------------ void TCheckedFillStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_HDist; is >> m_HAngle; is >> m_VDist; is >> m_VAngle; is >> m_Thickness; is >> m_pointColor; } //------------------------------------------------------------ void TCheckedFillStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_HDist; os << m_HAngle; os << m_VDist; os << m_VAngle; os << m_Thickness; os << m_pointColor; } //------------------------------------------------------------ void TCheckedFillStyle::getHThickline(const TPointD &lc, const double lx, TPointD &p0, TPointD &p1, TPointD &p2, TPointD &p3) const { double l = m_Thickness / cos(degree2rad(m_HAngle)); l *= 0.5; p0 = TPointD(lc.x, lc.y - l); p1 = TPointD(lc.x, lc.y + l); double y = lc.y + lx * tan(degree2rad(m_HAngle)); p2 = TPointD(lc.x + lx, y + l); p3 = TPointD(lc.x + lx, y - l); } //------------------------------------------------------------ void TCheckedFillStyle::getVThickline(const TPointD &lc, const double ly, TPointD &p0, TPointD &p1, TPointD &p2, TPointD &p3) const { double l = m_Thickness / cos(degree2rad(-m_VAngle)); l *= 0.5; p0 = TPointD(lc.x - l, lc.y); p1 = TPointD(lc.x + l, lc.y); double x = lc.x + ly * tan(degree2rad(-m_VAngle)); p2 = TPointD(x + l, lc.y + ly); p3 = TPointD(x - l, lc.y + ly); } //------------------------------------------------------------ TPixel32 TCheckedFillStyle::getColorParamValue(int index) const { return index == 0 ? m_pointColor : TSolidColorStyle::getMainColor(); } //------------------------------------------------------------ void TCheckedFillStyle::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) m_pointColor = color; else { TSolidColorStyle::setMainColor(color); } } //------------------------------------------------------------ void TCheckedFillStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { TStencilControl *stenc = TStencilControl::instance(); TPixel32 backgroundColor = TSolidColorStyle::getMainColor(); if (cf) backgroundColor = (*(cf))(backgroundColor); if (backgroundColor.m == 0) { // only to create stencil mask TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); // does not draw on screen appStyle.drawRegion(0, false, boundary); } else { // create stencil mask and draw on screen stenc->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); TSolidColorStyle::drawRegion(cf, antiAliasing, boundary); } stenc->endMask(); stenc->enableMask(TStencilControl::SHOW_INSIDE); const bool isTransparent = m_pointColor.m < 255; if (isTransparent) { // glEnable(GL_BLEND); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //// <-- tglEnableBlending(); } glBegin(GL_QUADS); TPixel32 color; if (cf) color = (*(cf))(m_pointColor); else color = m_pointColor; tglColor(color); // Horizontal Lines double lx = boundary.m_bbox.x1 - boundary.m_bbox.x0; double ly = boundary.m_bbox.y1 - boundary.m_bbox.y0; double beg = boundary.m_bbox.y0; double end = boundary.m_bbox.y1; beg = m_HAngle <= 0 ? beg : beg - lx * tan(degree2rad(m_HAngle)); end = m_HAngle >= 0 ? end : end - lx * tan(degree2rad(m_HAngle)); double dist = m_HDist / cos(degree2rad(m_HAngle)); for (double y = beg; y <= end; y += dist) { TPointD p0, p1, p2, p3; getHThickline(TPointD(boundary.m_bbox.x0, y), lx, p0, p1, p2, p3); tglVertex(p0); tglVertex(p1); tglVertex(p2); tglVertex(p3); } // Vertical Lines beg = boundary.m_bbox.x0; end = boundary.m_bbox.x1; beg = (-m_VAngle) <= 0 ? beg : beg - ly * tan(degree2rad(-m_VAngle)); end = (-m_VAngle) >= 0 ? end : end - ly * tan(degree2rad(-m_VAngle)); dist = m_VDist / cos(degree2rad(-m_VAngle)); for (double x = beg; x <= end; x += dist) { TPointD p0, p1, p2, p3; getVThickline(TPointD(x, boundary.m_bbox.y0), ly, p0, p1, p2, p3); tglVertex(p0); tglVertex(p1); tglVertex(p2); tglVertex(p3); } glEnd(); if (isTransparent) { // tglColor(TPixel32::White); // glDisable(GL_BLEND); } stenc->disableMask(); } //------------------------------------------------------------ int TCheckedFillStyle::nbClip(const TRectD &bbox) const { int nbClip = 1; // the bbox rectangle double lx = bbox.x1 - bbox.x0; double ly = bbox.y1 - bbox.y0; double beg = bbox.y0; double end = bbox.y1; beg = m_HAngle <= 0 ? beg : beg - lx * tan(degree2rad(m_HAngle)); end = m_HAngle >= 0 ? end : end - lx * tan(degree2rad(m_HAngle)); double dist = m_HDist / cos(degree2rad(m_HAngle)); for (double y = beg; y <= end; y += dist) nbClip++; // Vertical lines beg = bbox.x0; end = bbox.x1; beg = (-m_VAngle) <= 0 ? beg : beg - ly * tan(degree2rad(-m_VAngle)); end = (-m_VAngle) >= 0 ? end : end - ly * tan(degree2rad(-m_VAngle)); dist = m_VDist / cos(degree2rad(-m_VAngle)); for (double x = beg; x <= end; x += dist) nbClip++; return nbClip; } //------------------------------------------------------------ void TCheckedFillStyle::drawRegion(TFlash &flash, const TRegion *r) const { TRectD bbox(r->getBBox()); // flash.drawRegion(*r,true); flash.drawRegion(*r, nbClip(bbox)); flash.setFillColor(getMainColor()); flash.drawRectangle(bbox); flash.setFillColor(m_pointColor); // Horizontal Lines double lx = bbox.x1 - bbox.x0; double ly = bbox.y1 - bbox.y0; double beg = bbox.y0; double end = bbox.y1; beg = m_HAngle <= 0 ? beg : beg - lx * tan(degree2rad(m_HAngle)); end = m_HAngle >= 0 ? end : end - lx * tan(degree2rad(m_HAngle)); double dist = m_HDist / cos(degree2rad(m_HAngle)); for (double y = beg; y <= end; y += dist) { TPointD p0, p1, p2, p3; getHThickline(TPointD(bbox.x0, y), lx, p0, p1, p2, p3); std::vector<TPointD> v; v.push_back(p0); v.push_back(p1); v.push_back(p2); v.push_back(p3); flash.drawPolyline(v); } // Vertical lines beg = bbox.x0; end = bbox.x1; beg = (-m_VAngle) <= 0 ? beg : beg - ly * tan(degree2rad(-m_VAngle)); end = (-m_VAngle) >= 0 ? end : end - ly * tan(degree2rad(-m_VAngle)); dist = m_VDist / cos(degree2rad(-m_VAngle)); for (double x = beg; x <= end; x += dist) { TPointD p0, p1, p2, p3; getVThickline(TPointD(x, bbox.y0), ly, p0, p1, p2, p3); std::vector<TPointD> v; v.push_back(p0); v.push_back(p1); v.push_back(p2); v.push_back(p3); flash.drawPolyline(v); } } //*************************************************************************** // ArtisticModifier implementation //*************************************************************************** void ArtisticModifier::modify(TRegionOutline &outline) const { TRegionOutline::Boundary::iterator regIt = outline.m_exterior.begin(); TRegionOutline::Boundary::iterator regItEnd = outline.m_exterior.end(); TRegionOutline::PointVector::iterator pIt; TRegionOutline::PointVector::iterator pItEnd; TRandom rnd; double counter = 0; double maxcounter = 0; for (; regIt != regItEnd; ++regIt) { pIt = regIt->begin(); pItEnd = regIt->end(); for (; pIt != pItEnd; ++pIt) { if (counter >= maxcounter) { double tmp = (201 - m_period) * (rnd.getFloat() + 1); maxcounter = tmp * tmp; counter = 0; } if (pIt != regIt->begin()) { double distance = (pIt->x - (pIt - 1)->x) * (pIt->x - (pIt - 1)->x) + (pIt->y - (pIt - 1)->y) * (pIt->y - (pIt - 1)->y); counter += distance; } double wave = 1; if (maxcounter) wave = sin(M_2PI * counter / maxcounter); pIt->x += m_move.x * wave; pIt->y += m_move.y * wave; } } regIt = outline.m_interior.begin(); regItEnd = outline.m_interior.end(); for (; regIt != regItEnd; ++regIt) { pIt = regIt->begin(); pItEnd = regIt->end(); for (; pIt != pItEnd; ++pIt) { pIt->x += (0.5 - rnd.getFloat()) * m_move.x; pIt->y += (0.5 - rnd.getFloat()) * m_move.y; } } } //------------------------------------------------------------ TOutlineStyle::RegionOutlineModifier *ArtisticModifier::clone() const { return new ArtisticModifier(*this); } //*************************************************************************** // ArtisticSolidColor implementation //*************************************************************************** ArtisticSolidColor::ArtisticSolidColor(const TPixel32 &color, const TPointD &move, double period) : TSolidColorStyle(color) { m_regionOutlineModifier = new ArtisticModifier(move, period); } //------------------------------------------------------------ TColorStyle *ArtisticSolidColor::clone() const { return new ArtisticSolidColor(*this); } //------------------------------------------------------------ void ArtisticSolidColor::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); delete m_regionOutlineModifier; ArtisticModifier *mov = new ArtisticModifier(TPointD(), double()); mov->loadData(is); m_regionOutlineModifier = mov; } //------------------------------------------------------------ void ArtisticSolidColor::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); assert(m_regionOutlineModifier); ((ArtisticModifier *)m_regionOutlineModifier)->saveData(os); } //------------------------------------------------------------ int ArtisticSolidColor::getParamCount() const { return 3; } //----------------------------------------------------------------------------- TColorStyle::ParamType ArtisticSolidColor::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString ArtisticSolidColor::getParamNames(int index) const { assert(0 <= index && index < 3); QString value; switch (index) { case 0: value = QCoreApplication::translate("ArtisticSolidColor", "Horiz Offset"); break; case 1: value = QCoreApplication::translate("ArtisticSolidColor", "Vert Offset"); break; case 2: value = QCoreApplication::translate("ArtisticSolidColor", "Noise"); break; } return value; } //----------------------------------------------------------------------------- void ArtisticSolidColor::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 3); switch (index) { case 0: min = 0.0; max = 20.0; break; case 1: min = 0.0; max = 20.0; break; case 2: min = 0.0; max = 200.0; break; } } //----------------------------------------------------------------------------- double ArtisticSolidColor::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 3); double value; switch (index) { case 0: value = ((ArtisticModifier *)m_regionOutlineModifier)->getMovePoint().x; break; case 1: value = ((ArtisticModifier *)m_regionOutlineModifier)->getMovePoint().y; break; case 2: value = ((ArtisticModifier *)m_regionOutlineModifier)->getPeriod(); break; } return value; } //----------------------------------------------------------------------------- void ArtisticSolidColor::setParamValue(int index, double value) { assert(0 <= index && index < 3); TPointD oldMove = ((ArtisticModifier *)m_regionOutlineModifier)->getMovePoint(); double oldPeriod = ((ArtisticModifier *)m_regionOutlineModifier)->getPeriod(); switch (index) { case 0: if (oldMove.x != value) { delete m_regionOutlineModifier; oldMove.x = value; m_regionOutlineModifier = new ArtisticModifier(oldMove, oldPeriod); updateVersionNumber(); } break; case 1: if (oldMove.y != value) { delete m_regionOutlineModifier; oldMove.y = value; m_regionOutlineModifier = new ArtisticModifier(oldMove, oldPeriod); updateVersionNumber(); } break; case 2: if (oldPeriod != value) { delete m_regionOutlineModifier; oldPeriod = value; m_regionOutlineModifier = new ArtisticModifier(oldMove, oldPeriod); updateVersionNumber(); } break; } } //------------------------------------------------------------ void ArtisticSolidColor::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { TSolidColorStyle::drawRegion(cf, true, boundary); } //------------------------------------------------------------ void ArtisticSolidColor::drawRegion(TFlash &flash, const TRegion *r) const { SFlashUtils rdf(r); rdf.computeRegionOutline(); m_regionOutlineModifier->modify(rdf.m_ro); flash.setFillColor(getMainColor()); rdf.drawRegionOutline(flash, false); } //*************************************************************************** // TChalkFillStyle implementation //*************************************************************************** TChalkFillStyle::TChalkFillStyle(const TPixel32 &color0, const TPixel32 &color1, const double density, const double size) : TSolidColorStyle(color1) , m_color0(color0) , m_density(density) , m_size(size) {} //------------------------------------------------------------ TChalkFillStyle::TChalkFillStyle(const TPixel32 &color0, const TPixel32 &color1) : TSolidColorStyle(color0) , m_color0(color1) , m_density(25.0) , m_size(1.0) {} //------------------------------------------------------------ TColorStyle *TChalkFillStyle::clone() const { return new TChalkFillStyle(*this); } //------------------------------------------------------------ int TChalkFillStyle::getParamCount() const { return 2; } //----------------------------------------------------------------------------- TColorStyle::ParamType TChalkFillStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString TChalkFillStyle::getParamNames(int index) const { assert(0 <= index && index < 2); QString value; switch (index) { case 0: value = QCoreApplication::translate("TChalkFillStyle", "Density"); break; case 1: value = QCoreApplication::translate("TChalkFillStyle", "Dot Size"); break; } return value; } //----------------------------------------------------------------------------- void TChalkFillStyle::loadData(int ids, TInputStreamInterface &is) { if (ids != 1133) throw TException("Chalk Fill style: unknown obsolete format"); TSolidColorStyle::loadData(is); is >> m_color0 >> m_density >> m_size; m_density = m_density / 1000; if (m_density > 100) m_density = 100; } //----------------------------------------------------------------------------- void TChalkFillStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 2); switch (index) { case 0: min = 0; max = 100.0; break; case 1: min = 0.0; max = 10.0; break; } } //----------------------------------------------------------------------------- double TChalkFillStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 2); double value; switch (index) { case 0: value = m_density; break; case 1: value = m_size; break; } return value; } //----------------------------------------------------------------------------- void TChalkFillStyle::setParamValue(int index, double value) { assert(0 <= index && index < 2); switch (index) { case 0: m_density = value; break; case 1: m_size = value; break; } } //------------------------------------------------------------ void TChalkFillStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_color0; is >> m_density; is >> m_size; } //------------------------------------------------------------ void TChalkFillStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_color0; os << m_density; os << m_size; } //------------------------------------------------------------ TPixel32 TChalkFillStyle::getColorParamValue(int index) const { return index == 0 ? m_color0 : TSolidColorStyle::getMainColor(); } //------------------------------------------------------------ void TChalkFillStyle::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) m_color0 = color; else { TSolidColorStyle::setMainColor(color); } } //------------------------------------------------------------ void TChalkFillStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { // const bool isTransparent=m_color0.m<255; // TRegionOutline::Boundary& exter=*(boundary.m_exterior); // TRegionOutline::Boundary& inter=*(boundary.m_interior); TPixel32 color0; if (cf) color0 = (*(cf))(m_color0); else color0 = m_color0; TStencilControl *stenc = TStencilControl::instance(); TPixel32 backgroundColor = TSolidColorStyle::getMainColor(); if (cf) backgroundColor = (*(cf))(backgroundColor); if (backgroundColor.m == 0) { // only to create stencil mask TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); // does not draw on screen appStyle.drawRegion(0, false, boundary); } else { // create stencil mask and draw on screen stenc->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); TSolidColorStyle::drawRegion(cf, antiAliasing, boundary); } stenc->endMask(); stenc->enableMask(TStencilControl::SHOW_INSIDE); int chalkId = glGenLists(1); glNewList(chalkId, GL_COMPILE); glBegin(GL_QUADS); glVertex2d(m_size, m_size); glVertex2d(-m_size, m_size); glVertex2d(-m_size, -m_size); glVertex2d(m_size, -m_size); glEnd(); glEndList(); TRandom rnd; double lx = boundary.m_bbox.x1 - boundary.m_bbox.x0; double ly = boundary.m_bbox.y1 - boundary.m_bbox.y0; // cioe' imposta una densita' tale, per cui in una regione che ha bbox 200x200 // inserisce esattamente m_density punti int pointNumber = (int)(m_density * ((lx * ly) * 0.02)); for (int i = 0; i < pointNumber; i++) { TPixel32 tmpcolor = color0; double shiftx = boundary.m_bbox.x0 + rnd.getFloat() * lx; double shifty = boundary.m_bbox.y0 + rnd.getFloat() * ly; tmpcolor.m = (UCHAR)(tmpcolor.m * rnd.getFloat()); tglColor(tmpcolor); glPushMatrix(); glTranslated(shiftx, shifty, 0.0); glCallList(chalkId); glPopMatrix(); } // glEnd(); e questo che era??? glDeleteLists(chalkId, 1); stenc->disableMask(); } //------------------------------------------------------------ void TChalkFillStyle::drawRegion(TFlash &flash, const TRegion *r) const { TPixel32 bgColor = TSolidColorStyle::getMainColor(); double minDensity; double maxDensity; getParamRange(0, minDensity, maxDensity); double r1 = (m_density - minDensity) / (maxDensity - minDensity); double r2 = 1.0 - r1; TPixel32 color((int)(bgColor.r * r2 + m_color0.r * r1), (int)(bgColor.g * r2 + m_color0.g * r1), (int)(bgColor.b * r2 + m_color0.b * r1), (int)(bgColor.m * r2 + m_color0.m * r1)); flash.setFillColor(color); flash.drawRegion(*r); /* SFlashUtils rdf(r); rdf.computeRegionOutline(); TRandom rnd; const bool isTransparent=m_color0.m<255; TRegionOutline::Boundary& exter=*(rdf.m_ro.m_exterior); TRegionOutline::Boundary& inter=*(rdf.m_ro.m_interior); TPixel32 color0=m_color0; double lx=rdf.m_ro.m_bbox.x1-rdf.m_ro.m_bbox.x0; double ly=rdf.m_ro.m_bbox.y1-rdf.m_ro.m_bbox.y0; // cioe' imposta una densita' tale, per cui in una regione che ha bbox 200x200 // inserisce esattamente m_density punti int pointNumber= (int)(m_density*((lx*ly)*0.000025)); flash.drawRegion(*r,pointNumber+1); // -1 i don't know why flash.setFillColor(getMainColor()); flash.drawRectangle(TRectD(TPointD(rdf.m_ro.m_bbox.x0,rdf.m_ro.m_bbox.y0), TPointD(rdf.m_ro.m_bbox.x1,rdf.m_ro.m_bbox.y1))); flash.setThickness(0.0); for( int i=0;i< pointNumber; i++ ) { TPixel32 tmpcolor=color0; double shiftx=rdf.m_ro.m_bbox.x0+rnd.getFloat()*lx; double shifty=rdf.m_ro.m_bbox.y0+rnd.getFloat()*ly; tmpcolor.m=(UCHAR)(tmpcolor.m*rnd.getFloat()); flash.setFillColor(tmpcolor); flash.pushMatrix(); TTranslation tM(shiftx, shifty); flash.multMatrix(tM); flash.drawRectangle(TRectD(TPointD(-1,-1),TPointD(1,1))); flash.popMatrix(); } */ } //*************************************************************************** // TChessFillStyle implementation //*************************************************************************** TChessFillStyle::TChessFillStyle(const TPixel32 &bgColor, const TPixel32 &pointColor, const double HDist, const double VDist, const double Angle) : TSolidColorStyle(bgColor) , m_pointColor(pointColor) , m_HDist(HDist) , m_VDist(VDist) , m_Angle(Angle) {} //------------------------------------------------------------ TChessFillStyle::TChessFillStyle(const TPixel32 &color) : TSolidColorStyle(TPixel32::White) , m_pointColor(color) , m_HDist(10.0) , m_VDist(10.0) , m_Angle(0.0) {} //------------------------------------------------------------ TColorStyle *TChessFillStyle::clone() const { return new TChessFillStyle(*this); } //------------------------------------------------------------ int TChessFillStyle::getParamCount() const { return 3; } //----------------------------------------------------------------------------- TColorStyle::ParamType TChessFillStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString TChessFillStyle::getParamNames(int index) const { assert(0 <= index && index < 3); QString value; switch (index) { case 0: value = QCoreApplication::translate("TChessFillStyle", "Horiz Size"); break; case 1: value = QCoreApplication::translate("TChessFillStyle", "Vert Size"); break; case 2: value = QCoreApplication::translate("TChessFillStyle", "Angle"); break; } return value; } //----------------------------------------------------------------------------- void TChessFillStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 3); switch (index) { case 0: min = 1.0; max = 100.0; break; case 1: min = 1.0; max = 100.0; break; case 2: min = -45.0; max = 45.0; break; } } //----------------------------------------------------------------------------- double TChessFillStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 3); switch (index) { case 0: return m_HDist; case 1: return m_VDist; case 2: return m_Angle; } return 0.0; } //----------------------------------------------------------------------------- void TChessFillStyle::setParamValue(int index, double value) { assert(0 <= index && index < 3); switch (index) { case 0: m_HDist = value; break; case 1: m_VDist = value; break; case 2: m_Angle = value; break; } } //------------------------------------------------------------ void TChessFillStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_HDist; is >> m_VDist; is >> m_Angle; is >> m_pointColor; } //------------------------------------------------------------ void TChessFillStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_HDist; os << m_VDist; os << m_Angle; os << m_pointColor; } //------------------------------------------------------------ TPixel32 TChessFillStyle::getColorParamValue(int index) const { return index == 0 ? m_pointColor : TSolidColorStyle::getMainColor(); } //------------------------------------------------------------ void TChessFillStyle::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) m_pointColor = color; else { TSolidColorStyle::setMainColor(color); } } //------------------------------------------------------------ void TChessFillStyle::makeGrid(TRectD &bbox, TRotation &rotM, std::vector<TPointD> &grid, int &nbClip) const { double lx = bbox.x1 - bbox.x0; double ly = bbox.y1 - bbox.y0; TPointD center = TPointD((bbox.x1 + bbox.x0) * 0.5, (bbox.y1 + bbox.y0) * 0.5); double l = (lx + ly) / 1.3; double l2 = l / 2; bool isFirst = true; for (double y = -l2; y < (l2 + m_VDist); y += m_VDist) { double x = isFirst ? -l2 : -l2 + m_HDist; isFirst = !isFirst; for (; x < (l2 + m_HDist); x += 2 * m_HDist) { grid.push_back(rotM * TPointD(x, y) + center); nbClip++; } } } //------------------------------------------------------------ void TChessFillStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { // const bool isTransparent=m_pointColor.m<255; TStencilControl *stenc = TStencilControl::instance(); TPixel32 backgroundColor = TSolidColorStyle::getMainColor(); if (cf) backgroundColor = (*(cf))(backgroundColor); if (backgroundColor.m == 0) { // only to create stencil mask TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); // does not draw on screen appStyle.drawRegion(0, false, boundary); } else { // create stencil mask and draw on screen stenc->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); TSolidColorStyle::drawRegion(cf, antiAliasing, boundary); } stenc->endMask(); stenc->enableMask(TStencilControl::SHOW_INSIDE); TPixel32 color; if (cf) color = (*(cf))(m_pointColor); else color = m_pointColor; tglColor(color); TPointD vert[4]; vert[0].x = -0.5; vert[0].y = 0.5; vert[1].x = -0.5; vert[1].y = -0.5; vert[2].x = 0.5; vert[2].y = -0.5; vert[3].x = 0.5; vert[3].y = 0.5; TRotation rotM(m_Angle); TScale scaleM(m_HDist, m_VDist); for (int i = 0; i < 4; i++) vert[i] = rotM * scaleM * vert[i]; int chessId = glGenLists(1); glNewList(chessId, GL_COMPILE); glBegin(GL_QUADS); glVertex2d(vert[0].x, vert[0].y); glVertex2d(vert[1].x, vert[1].y); glVertex2d(vert[2].x, vert[2].y); glVertex2d(vert[3].x, vert[3].y); glEnd(); glEndList(); int nbClip = 1; std::vector<TPointD> grid; makeGrid(boundary.m_bbox, rotM, grid, nbClip); std::vector<TPointD>::const_iterator it = grid.begin(); std::vector<TPointD>::const_iterator ite = grid.end(); for (; it != ite; it++) { glPushMatrix(); glTranslated(it->x, it->y, 0.0); glCallList(chessId); glPopMatrix(); } stenc->disableMask(); glDeleteLists(chessId, 1); } //------------------------------------------------------------ void TChessFillStyle::drawRegion(TFlash &flash, const TRegion *r) const { TRectD bbox(r->getBBox()); TPointD vert[4]; vert[0].x = -0.5; vert[0].y = 0.5; vert[1].x = -0.5; vert[1].y = -0.5; vert[2].x = 0.5; vert[2].y = -0.5; vert[3].x = 0.5; vert[3].y = 0.5; TRotation rotM(m_Angle); TScale scaleM(m_HDist, m_VDist); for (int i = 0; i < 4; i++) vert[i] = rotM * scaleM * vert[i]; int nbClip = 1; // just for the getMainColor() rectangle std::vector<TPointD> grid; makeGrid(bbox, rotM, grid, nbClip); // flash.drawRegion(*r,true); flash.drawRegion(*r, nbClip); flash.setFillColor(getMainColor()); flash.drawRectangle(bbox); flash.setFillColor(m_pointColor); std::vector<TPointD>::const_iterator it = grid.begin(); std::vector<TPointD>::const_iterator ite = grid.end(); for (; it != ite; it++) { TTranslation trM(it->x, it->y); std::vector<TPointD> lvert; lvert.push_back(trM * vert[0]); lvert.push_back(trM * vert[1]); lvert.push_back(trM * vert[2]); lvert.push_back(trM * vert[3]); flash.drawPolyline(lvert); } } //*************************************************************************** // TStripeFillStyle implementation //*************************************************************************** TStripeFillStyle::TStripeFillStyle(const TPixel32 &bgColor, const TPixel32 &pointColor, const double Dist, const double Angle, const double Thickness) : TSolidColorStyle(bgColor) , m_pointColor(pointColor) , m_Dist(Dist) , m_Angle(Angle) , m_Thickness(Thickness) {} //------------------------------------------------------------ TStripeFillStyle::TStripeFillStyle(const TPixel32 &color) : TSolidColorStyle(TPixel32::Transparent) , m_pointColor(color) , m_Dist(15.0) , m_Angle(0.0) , m_Thickness(6.0) {} //------------------------------------------------------------ TColorStyle *TStripeFillStyle::clone() const { return new TStripeFillStyle(*this); } //------------------------------------------------------------ int TStripeFillStyle::getParamCount() const { return 3; } //----------------------------------------------------------------------------- TColorStyle::ParamType TStripeFillStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString TStripeFillStyle::getParamNames(int index) const { assert(0 <= index && index < 3); QString value; switch (index) { case 0: value = QCoreApplication::translate("TStripeFillStyle", "Distance"); break; case 1: value = QCoreApplication::translate("TStripeFillStyle", "Angle"); break; case 2: value = QCoreApplication::translate("TStripeFillStyle", "Thickness"); break; } return value; } //----------------------------------------------------------------------------- void TStripeFillStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 3); switch (index) { case 0: min = 1.0; max = 100.0; break; case 1: min = -90.0; max = 90.0; break; case 2: min = 0.5; max = 100.0; break; } } //----------------------------------------------------------------------------- double TStripeFillStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 3); switch (index) { case 0: return m_Dist; case 1: return m_Angle; case 2: return m_Thickness; } return 0.0; } //----------------------------------------------------------------------------- void TStripeFillStyle::setParamValue(int index, double value) { assert(0 <= index && index < 3); switch (index) { case 0: m_Dist = value; break; case 1: m_Angle = value; break; case 2: m_Thickness = value; break; } } //------------------------------------------------------------ void TStripeFillStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_Dist; is >> m_Angle; is >> m_Thickness; is >> m_pointColor; } //------------------------------------------------------------ void TStripeFillStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_Dist; os << m_Angle; os << m_Thickness; os << m_pointColor; } void TStripeFillStyle::getThickline(const TPointD &lc, const double lx, TPointD &p0, TPointD &p1, TPointD &p2, TPointD &p3) const { double l = m_Thickness / cos(degree2rad(m_Angle)); l *= 0.5; p0 = TPointD(lc.x, lc.y - l); p1 = TPointD(lc.x, lc.y + l); double y = lc.y + lx * tan(degree2rad(m_Angle)); p2 = TPointD(lc.x + lx, y + l); p3 = TPointD(lc.x + lx, y - l); } //------------------------------------------------------------ TPixel32 TStripeFillStyle::getColorParamValue(int index) const { return index == 0 ? m_pointColor : TSolidColorStyle::getMainColor(); } //------------------------------------------------------------ void TStripeFillStyle::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) m_pointColor = color; else { TSolidColorStyle::setMainColor(color); } } //------------------------------------------------------------ inline void trim(TPointD &p0, TPointD &p1, double y0, double y1) { if (p0.y < y0) { // Trim the first extreme of the segment at y0 double t = (y0 - p0.y) / (p1.y - p0.y); p0.x = p0.x + t * (p1.x - p0.x); p0.y = y0; } else if (p0.y > y1) { // The same, at y1 double t = (y1 - p0.y) / (p1.y - p0.y); p0.x = p0.x + t * (p1.x - p0.x); p0.y = y1; } // Same for p1 if (p1.y < y0) { double t = (y0 - p1.y) / (p0.y - p1.y); p1.x = p1.x + t * (p0.x - p1.x); p1.y = y0; } else if (p1.y > y1) { double t = (y1 - p1.y) / (p0.y - p1.y); p1.x = p1.x + t * (p0.x - p1.x); p1.y = y1; } } //------------------------------------------------------------ void TStripeFillStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { const bool isTransparent = m_pointColor.m < 255; TStencilControl *stenc = TStencilControl::instance(); TPixel32 backgroundColor = TSolidColorStyle::getMainColor(); if (cf) backgroundColor = (*(cf))(backgroundColor); if (backgroundColor.m == 0) { // only to create stencil mask TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); appStyle.drawRegion(0, false, boundary); } else { stenc->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); TSolidColorStyle::drawRegion(cf, antiAliasing, boundary); } stenc->endMask(); stenc->enableMask(TStencilControl::SHOW_INSIDE); if (isTransparent) { // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // glEnable(GL_BLEND); //// <-- tglEnableBlending(); } TPixel32 color; if (cf) color = (*(cf))(m_pointColor); else color = m_pointColor; tglColor(color); // Horizontal Lines if (fabs(m_Angle) != 90) { double lx = boundary.m_bbox.x1 - boundary.m_bbox.x0; // double ly=boundary.m_bbox.y1-boundary.m_bbox.y0; double beg = boundary.m_bbox.y0; double end = boundary.m_bbox.y1; beg = m_Angle <= 0 ? beg : beg - lx * tan(degree2rad(m_Angle)); end = m_Angle >= 0 ? end : end - lx * tan(degree2rad(m_Angle)); double dist = m_Dist / cos(degree2rad(m_Angle)); double y; TStencilControl *stenc2 = TStencilControl::instance(); stenc2->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); glBegin(GL_QUADS); for (y = beg; y <= end; y += dist) { TPointD p0, p1, p2, p3; getThickline(TPointD(boundary.m_bbox.x0, y), lx, p0, p1, p2, p3); tglVertex(p0); tglVertex(p1); tglVertex(p2); tglVertex(p3); } glEnd(); stenc2->endMask(); stenc2->enableMask(TStencilControl::SHOW_OUTSIDE); if (m_Angle != 0) // ANTIALIASING { // glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // glEnable(GL_BLEND); // glEnable(GL_LINE_SMOOTH); tglEnableLineSmooth(); // NOTE: Trimming the fat lines is necessary outside the (-60, 60) angles // interval // seemingly due to a bug in MAC-Leopard's openGL implementation... glBegin(GL_LINES); for (y = beg; y <= end; y += dist) { TPointD p0, p1, p2, p3; getThickline(TPointD(boundary.m_bbox.x0, y), lx, p0, p1, p2, p3); trim(p1, p2, boundary.m_bbox.y0, boundary.m_bbox.y1); tglVertex(p1); tglVertex(p2); trim(p0, p3, boundary.m_bbox.y0, boundary.m_bbox.y1); tglVertex(p0); tglVertex(p3); } glEnd(); } stenc2->disableMask(); } else { double beg = boundary.m_bbox.x0; double end = boundary.m_bbox.x1; double y0 = boundary.m_bbox.y0; double y1 = boundary.m_bbox.y1; glBegin(GL_QUADS); for (double x = beg; x <= end; x += m_Dist) { TPointD p0(x, y0); TPointD p1(x + m_Thickness, y0); TPointD p2(x, y1); TPointD p3(x + m_Thickness, y1); tglVertex(p0); tglVertex(p1); tglVertex(p3); tglVertex(p2); } glEnd(); } // tglColor(TPixel32::White); stenc->disableMask(); } //------------------------------------------------------------ int TStripeFillStyle::nbClip(const TRectD &bbox) const { int nbClip = 1; // the bbox rectangle if (fabs(m_Angle) != 90) { double lx = bbox.x1 - bbox.x0; // double ly=bbox.y1-bbox.y0; double beg = bbox.y0; double end = bbox.y1; beg = m_Angle <= 0 ? beg : beg - lx * tan(degree2rad(m_Angle)); end = m_Angle >= 0 ? end : end - lx * tan(degree2rad(m_Angle)); double dist = m_Dist / cos(degree2rad(m_Angle)); for (double y = beg; y <= end; y += dist) nbClip++; } else { double beg = bbox.x0; double end = bbox.x1; // double y0=bbox.y0; // double y1=bbox.y1; for (double x = beg; x <= end; x += m_Dist) nbClip++; } return nbClip; } //------------------------------------------------------------ void TStripeFillStyle::drawRegion(TFlash &flash, const TRegion *r) const { TRectD bbox(r->getBBox()); // flash.drawRegion(*r,true); flash.drawRegion(*r, nbClip(bbox)); // -1 i don't know why flash.setFillColor(getMainColor()); flash.drawRectangle(bbox); flash.setFillColor(m_pointColor); // Horizontal Lines if (fabs(m_Angle) != 90) { double lx = bbox.x1 - bbox.x0; // double ly=bbox.y1-bbox.y0; double beg = bbox.y0; double end = bbox.y1; beg = m_Angle <= 0 ? beg : beg - lx * tan(degree2rad(m_Angle)); end = m_Angle >= 0 ? end : end - lx * tan(degree2rad(m_Angle)); double dist = m_Dist / cos(degree2rad(m_Angle)); for (double y = beg; y <= end; y += dist) { TPointD p0, p1, p2, p3; getThickline(TPointD(bbox.x0, y), lx, p0, p1, p2, p3); std::vector<TPointD> v; v.push_back(p0); v.push_back(p1); v.push_back(p2); v.push_back(p3); flash.drawPolyline(v); } } else { double beg = bbox.x0; double end = bbox.x1; double y0 = bbox.y0; double y1 = bbox.y1; for (double x = beg; x <= end; x += m_Dist) { TPointD p0(x, y0); TPointD p1(x + m_Thickness, y0); TPointD p2(x, y1); TPointD p3(x + m_Thickness, y1); std::vector<TPointD> v; v.push_back(p0); v.push_back(p1); v.push_back(p3); v.push_back(p2); flash.drawPolyline(v); } } } //------------------------------------------------------------ void TStripeFillStyle::makeIcon(const TDimension &d) { // Saves the values of member variables and sets the right icon values double LDist = m_Dist; double LAngle = m_Angle; double LThickness = m_Thickness; m_Dist *= 1.33; m_Thickness *= 1.66; TColorStyle::makeIcon(d); m_Dist = LDist; m_Angle = LAngle; m_Thickness = LThickness; } //*************************************************************************** // TLinGradFillStyle implementation //*************************************************************************** TLinGradFillStyle::TLinGradFillStyle(const TPixel32 &bgColor, const TPixel32 &pointColor, const double Angle, const double XPos, const double YPos, const double Size) : TSolidColorStyle(bgColor) , m_pointColor(pointColor) , m_Angle(Angle) , m_XPos(XPos) , m_YPos(YPos) , m_Size(Size) {} //----------------------------------------------------------------------------- TLinGradFillStyle::TLinGradFillStyle(const TPixel32 &color) : TSolidColorStyle(TPixel32::White) , m_pointColor(color) , m_Angle(0.0) , m_XPos(0.0) , m_YPos(0.0) , m_Size(100.0) {} //----------------------------------------------------------------------------- TColorStyle *TLinGradFillStyle::clone() const { return new TLinGradFillStyle(*this); } //------------------------------------------------------------ int TLinGradFillStyle::getParamCount() const { return 4; } //----------------------------------------------------------------------------- TColorStyle::ParamType TLinGradFillStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString TLinGradFillStyle::getParamNames(int index) const { assert(0 <= index && index < 4); QString value; switch (index) { case 0: value = QCoreApplication::translate("TLinGradFillStyle", "Angle"); break; case 1: value = QCoreApplication::translate("TLinGradFillStyle", "X Position"); break; case 2: value = QCoreApplication::translate("TLinGradFillStyle", "Y Position"); break; case 3: value = QCoreApplication::translate("TLinGradFillStyle", "Smoothness"); break; } return value; } //----------------------------------------------------------------------------- void TLinGradFillStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 4); switch (index) { case 0: min = -180.0; max = 180.0; break; case 1: min = -100.0; max = 100.0; break; case 2: min = -100.0; max = 100.0; break; case 3: min = 1.0; max = 500.0; break; } } //----------------------------------------------------------------------------- double TLinGradFillStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 4); switch (index) { case 0: return m_Angle; case 1: return m_XPos; case 2: return m_YPos; case 3: return m_Size; } return 0.0; } //----------------------------------------------------------------------------- void TLinGradFillStyle::setParamValue(int index, double value) { assert(0 <= index && index < 4); switch (index) { case 0: m_Angle = value; break; case 1: m_XPos = value; break; case 2: m_YPos = value; break; case 3: m_Size = value; break; } } //------------------------------------------------------------ void TLinGradFillStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_Angle; is >> m_XPos; is >> m_YPos; is >> m_Size; is >> m_pointColor; } //------------------------------------------------------------ void TLinGradFillStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_Angle; os << m_XPos; os << m_YPos; os << m_Size; os << m_pointColor; } //------------------------------------------------------------ TPixel32 TLinGradFillStyle::getColorParamValue(int index) const { return index == 0 ? m_pointColor : TSolidColorStyle::getMainColor(); } //------------------------------------------------------------ void TLinGradFillStyle::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) m_pointColor = color; else { TSolidColorStyle::setMainColor(color); } } //------------------------------------------------------------ void TLinGradFillStyle::getRects(const TRectD &bbox, std::vector<TPointD> &r0, std::vector<TPointD> &r1, std::vector<TPointD> &r2) const { r0.clear(); r1.clear(); r2.clear(); TPointD p0, p1, p2, p3; double lx = bbox.x1 - bbox.x0; double ly = bbox.y1 - bbox.y0; TPointD center((bbox.x1 + bbox.x0) / 2.0, (bbox.y1 + bbox.y0) / 2.0); center = center + TPointD(m_XPos * 0.01 * lx * 0.5, m_YPos * 0.01 * ly * 0.5); double l = tdistance(TPointD(bbox.x0, bbox.y0), TPointD(bbox.x1, bbox.y1)); r0.push_back(TPointD(-m_Size - l, l)); r0.push_back(TPointD(-m_Size - l, -l)); r0.push_back(TPointD(-m_Size, -l)); r0.push_back(TPointD(-m_Size, l)); r1.push_back(TPointD(-m_Size, l)); r1.push_back(TPointD(-m_Size, -l)); r1.push_back(TPointD(m_Size, -l)); r1.push_back(TPointD(m_Size, l)); r2.push_back(TPointD(m_Size, l)); r2.push_back(TPointD(m_Size, -l)); r2.push_back(TPointD(m_Size + l, -l)); r2.push_back(TPointD(m_Size + l, l)); TRotation rotM(m_Angle); TTranslation traM(center); TAffine M(traM * rotM); for (int i = 0; i < 4; i++) { r0[i] = M * r0[i]; r1[i] = M * r1[i]; r2[i] = M * r2[i]; } } //------------------------------------------------------------ void TLinGradFillStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { // only to create stencil mask TStencilControl *stenc = TStencilControl::instance(); TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); // does not draw on screen appStyle.drawRegion(0, false, boundary); stenc->endMask(); // compute colors TPixel32 color1, color2; if (cf) { color1 = (*(cf))(TSolidColorStyle::getMainColor()); color2 = (*(cf))(m_pointColor); } else { color1 = TSolidColorStyle::getMainColor(); color2 = m_pointColor; } // compute points TRectD bbox(boundary.m_bbox); std::vector<TPointD> r0, r1, r2; getRects(bbox, r0, r1, r2); assert(r0.size() == 4); assert(r1.size() == 4); assert(r2.size() == 4); // draw stenc->enableMask(TStencilControl::SHOW_INSIDE); glBegin(GL_QUADS); tglColor(color2); int i = 0; for (; i < 4; tglVertex(r0[i++])) ; tglVertex(r1[0]); tglVertex(r1[1]); tglColor(color1); tglVertex(r1[2]); tglVertex(r1[3]); for (i = 0; i < 4; tglVertex(r2[i++])) ; glEnd(); stenc->disableMask(); } //------------------------------------------------------------ // It is the new version, which uses XPos, YPos, Smooth parameters. // There is a gap between the flat and graded regions. This is the reason, // why the old version (without XPos, YPos, Smooth parameters) is used. void TLinGradFillStyle::drawRegion(TFlash &flash, const TRegion *r) const { TRectD bbox(r->getBBox()); std::vector<TPointD> rect; TPointD center((bbox.x1 + bbox.x0) / 2.0, (bbox.y1 + bbox.y0) / 2.0); center = center + TPointD(m_XPos * 0.01 * (bbox.x1 - bbox.x0) * 0.5, m_YPos * 0.01 * (bbox.y1 - bbox.y0) * 0.5); double l = tdistance(TPointD(bbox.x0, bbox.y0), TPointD(bbox.x1, bbox.y1)); TAffine M(TTranslation(center) * TRotation(m_Angle)); rect.push_back(M * TPointD(-m_Size, l)); rect.push_back(M * TPointD(-m_Size, -l)); rect.push_back(M * TPointD(m_Size, -l)); rect.push_back(M * TPointD(m_Size, l)); flash.setThickness(0.0); SFlashUtils sfu; sfu.drawGradedRegion(flash, rect, m_pointColor, getMainColor(), *r); } /* // --- Old version --- void TLinGradFillStyle::drawRegion(TFlash& flash, const TRegion* r) const { flash.drawRegion(*r,1); TRectD bbox(r->getBBox()); TPointD p0,p1,p2,p3; p0=TPointD(bbox.x0,bbox.y0); p1=TPointD(bbox.x0,bbox.y1); p2=TPointD(bbox.x1,bbox.y0); p3=TPointD(bbox.x1,bbox.y1); std::vector<TPointD> pv; if ( fabs(m_Angle)!=90 ) { double tga=tan(degree2rad(fabs(m_Angle))); double lx=bbox.x1-bbox.x0; double ly=bbox.y1-bbox.y0; double ax=lx/(tga*tga+1); double bx=lx-ax; double mx=ax*tga; double rlylx=ly/lx; double ay=ax*rlylx; double by=bx*rlylx; double my=mx*rlylx; if ( m_Angle<=0.0) { p0=p0+TPointD(-my,by); p1=p1+TPointD(bx,mx); p2=p2+TPointD(-bx,-mx); p3=p3+TPointD(my,-by); } else { p0=p0+TPointD(bx,-mx); p1=p1+TPointD(-my,-by); p2=p2+TPointD(my,by); p3=p3+TPointD(-bx,mx); } pv.push_back(p0); pv.push_back(p1); pv.push_back(p3); pv.push_back(p2); } else { if ( m_Angle==-90 ) { pv.push_back(p1); pv.push_back(p3); pv.push_back(p2); pv.push_back(p0); } else { pv.push_back(p0); pv.push_back(p2); pv.push_back(p3); pv.push_back(p1); } } SFlashUtils sfu; sfu.drawGradedPolyline(flash,pv,m_pointColor,getMainColor()); } */ //*************************************************************************** // TRadGradFillStyle implementation //*************************************************************************** TRadGradFillStyle::TRadGradFillStyle(const TPixel32 &bgColor, const TPixel32 &pointColor, const double XPos, const double YPos, const double Radius, const double Smooth) : TSolidColorStyle(bgColor) , m_pointColor(pointColor) , m_XPos(XPos) , m_YPos(YPos) , m_Radius(Radius) , m_Smooth(Smooth) {} //----------------------------------------------------------------------------- TRadGradFillStyle::TRadGradFillStyle(const TPixel32 &color) : TSolidColorStyle(TPixel32::White) , m_pointColor(color) , m_XPos(0.0) , m_YPos(0.0) , m_Radius(50.0) , m_Smooth(50) {} //----------------------------------------------------------------------------- TColorStyle *TRadGradFillStyle::clone() const { return new TRadGradFillStyle(*this); } //------------------------------------------------------------ int TRadGradFillStyle::getParamCount() const { return 4; } //----------------------------------------------------------------------------- TColorStyle::ParamType TRadGradFillStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString TRadGradFillStyle::getParamNames(int index) const { assert(0 <= index && index < 4); QString value; switch (index) { case 0: value = QCoreApplication::translate("TRadGradFillStyle", "X Position"); break; case 1: value = QCoreApplication::translate("TRadGradFillStyle", "Y Position"); break; case 2: value = QCoreApplication::translate("TRadGradFillStyle", "Radius"); break; case 3: value = QCoreApplication::translate("TRadGradFillStyle", "Smoothness"); break; } return value; } //----------------------------------------------------------------------------- void TRadGradFillStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 4); switch (index) { case 0: min = -100.0; max = 100.0; break; case 1: min = -100.0; max = 100.0; break; case 2: min = 0.01; max = 100.0; break; case 3: min = 0.01; max = 100.0; break; } } //----------------------------------------------------------------------------- double TRadGradFillStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 4); switch (index) { case 0: return m_XPos; case 1: return m_YPos; case 2: return m_Radius; case 3: return m_Smooth; } return 0.0; } //----------------------------------------------------------------------------- void TRadGradFillStyle::setParamValue(int index, double value) { assert(0 <= index && index < 4); switch (index) { case 0: m_XPos = value; break; case 1: m_YPos = value; break; case 2: m_Radius = value; break; case 3: m_Smooth = value; break; } } //------------------------------------------------------------ void TRadGradFillStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_XPos; is >> m_YPos; is >> m_Radius; is >> m_Smooth; is >> m_pointColor; } //------------------------------------------------------------ void TRadGradFillStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_XPos; os << m_YPos; os << m_Radius; os << m_Smooth; os << m_pointColor; } //------------------------------------------------------------ TPixel32 TRadGradFillStyle::getColorParamValue(int index) const { return index == 0 ? m_pointColor : TSolidColorStyle::getMainColor(); } //------------------------------------------------------------ void TRadGradFillStyle::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) m_pointColor = color; else { TSolidColorStyle::setMainColor(color); } } //------------------------------------------------------------ void TRadGradFillStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { TStencilControl *stenc = TStencilControl::instance(); // only to create stencil mask TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); // does not draw on screen appStyle.drawRegion(0, false, boundary); stenc->endMask(); TPixel32 backgroundColor, color; if (cf) { backgroundColor = (*(cf))(TSolidColorStyle::getMainColor()); color = (*(cf))(m_pointColor); } else { backgroundColor = TSolidColorStyle::getMainColor(); color = m_pointColor; } TRectD bbox(boundary.m_bbox); double lx = bbox.x1 - bbox.x0; double ly = bbox.y1 - bbox.y0; double r2 = std::max(lx, ly) * 5.0; double r1 = 0.5 * std::max(lx, ly) * m_Radius * 0.01; double r0 = r1 * (100.0 - m_Smooth) * 0.01; TPointD center((bbox.x1 + bbox.x0) / 2.0, (bbox.y1 + bbox.y0) / 2.0); center = center + TPointD(m_XPos * 0.01 * lx * 0.5, m_YPos * 0.01 * ly * 0.5); const double dAngle = 5.0; std::vector<TPointD> sincos; for (double angle = 0.0; angle <= 360.0; angle += dAngle) sincos.push_back(TPointD(sin(degree2rad(angle)), cos(degree2rad(angle)))); stenc->enableMask(TStencilControl::SHOW_INSIDE); glBegin(GL_TRIANGLE_FAN); tglColor(color); tglVertex(center); int i = 0; for (; i < (int)sincos.size(); i++) tglVertex(center + TPointD(r0 * sincos[i].x, r0 * sincos[i].y)); glEnd(); if (fabs(r0 - r1) > TConsts::epsilon) { glBegin(GL_QUAD_STRIP); for (i = 0; i < (int)sincos.size(); i++) { tglColor(color); tglVertex(center + TPointD(r0 * sincos[i].x, r0 * sincos[i].y)); tglColor(backgroundColor); tglVertex(center + TPointD(r1 * sincos[i].x, r1 * sincos[i].y)); } glEnd(); } tglColor(backgroundColor); glBegin(GL_QUAD_STRIP); for (i = 0; i < (int)sincos.size(); i++) { tglVertex(center + TPointD(r1 * sincos[i].x, r1 * sincos[i].y)); tglVertex(center + TPointD(r2 * sincos[i].x, r2 * sincos[i].y)); } glEnd(); stenc->disableMask(); } //------------------------------------------------------------ void TRadGradFillStyle::drawRegion(TFlash &flash, const TRegion *r) const { TRectD bbox(r->getBBox()); double lx = bbox.x1 - bbox.x0; double ly = bbox.y1 - bbox.y0; double r1 = 0.5 * std::max(lx, ly) * m_Radius * 0.01; if (m_Smooth < 50) r1 *= (0.3 * ((100 - m_Smooth) / 50.0) + 0.7); TPointD center((bbox.x1 + bbox.x0) / 2.0, (bbox.y1 + bbox.y0) / 2.0); center = center + TPointD(m_XPos * 0.01 * lx * 0.5, m_YPos * 0.01 * ly * 0.5); flash.setThickness(0.0); TPixel32 mc(getMainColor()); flash.setGradientFill(false, m_pointColor, mc, m_Smooth); const double flashGrad = 16384.0; // size of gradient square TTranslation tM(center.x, center.y); TScale sM(2.0 * r1 / (flashGrad), 2.0 * r1 / (flashGrad)); flash.setFillStyleMatrix(tM * sM); flash.drawRegion(*r); } //*************************************************************************** // TCircleStripeFillStyle implementation //*************************************************************************** TCircleStripeFillStyle::TCircleStripeFillStyle( const TPixel32 &bgColor, const TPixel32 &pointColor, const double XPos, const double YPos, const double Dist, const double Thickness) : TSolidColorStyle(bgColor) , m_pointColor(pointColor) , m_XPos(XPos) , m_YPos(YPos) , m_Dist(Dist) , m_Thickness(Thickness) {} //------------------------------------------------------------ TCircleStripeFillStyle::TCircleStripeFillStyle(const TPixel32 &color) : TSolidColorStyle(TPixel32::Transparent) , m_pointColor(color) , m_XPos(0.0) , m_YPos(0.0) , m_Dist(15.0) , m_Thickness(3.0) {} //------------------------------------------------------------ TColorStyle *TCircleStripeFillStyle::clone() const { return new TCircleStripeFillStyle(*this); } //------------------------------------------------------------ int TCircleStripeFillStyle::getParamCount() const { return 4; } //----------------------------------------------------------------------------- TColorStyle::ParamType TCircleStripeFillStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString TCircleStripeFillStyle::getParamNames(int index) const { assert(0 <= index && index < 4); QString value; switch (index) { case 0: value = QCoreApplication::translate("TCircleStripeFillStyle", "X Position"); break; case 1: value = QCoreApplication::translate("TCircleStripeFillStyle", "Y Position"); break; case 2: value = QCoreApplication::translate("TCircleStripeFillStyle", "Distance"); break; case 3: value = QCoreApplication::translate("TCircleStripeFillStyle", "Thickness"); break; } return value; } //----------------------------------------------------------------------------- void TCircleStripeFillStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 4); switch (index) { case 0: min = -200.0; max = 200.0; break; case 1: min = -200.0; max = 200.0; break; case 2: min = 0.5; max = 100.0; break; case 3: min = 0.5; max = 100.0; break; } } //----------------------------------------------------------------------------- double TCircleStripeFillStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 4); switch (index) { case 0: return m_XPos; case 1: return m_YPos; case 2: return m_Dist; case 3: return m_Thickness; } return 0.0; } //----------------------------------------------------------------------------- void TCircleStripeFillStyle::setParamValue(int index, double value) { assert(0 <= index && index < 4); switch (index) { case 0: m_XPos = value; break; case 1: m_YPos = value; break; case 2: m_Dist = value; break; case 3: m_Thickness = value; break; } } //------------------------------------------------------------ void TCircleStripeFillStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_XPos; is >> m_YPos; is >> m_Dist; is >> m_Thickness; is >> m_pointColor; } //------------------------------------------------------------ void TCircleStripeFillStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_XPos; os << m_YPos; os << m_Dist; os << m_Thickness; os << m_pointColor; } //------------------------------------------------------------ TPixel32 TCircleStripeFillStyle::getColorParamValue(int index) const { return index == 0 ? m_pointColor : TSolidColorStyle::getMainColor(); } //------------------------------------------------------------ void TCircleStripeFillStyle::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) m_pointColor = color; else { TSolidColorStyle::setMainColor(color); } } //------------------------------------------------------------ void TCircleStripeFillStyle::getCircleStripeQuads( const TPointD &center, const double r1, const double r2, std::vector<TPointD> &pv) const { pv.clear(); const double dAng = 10.0; for (double ang = 0.0; ang <= 360; ang += dAng) { pv.push_back(center + TPointD(r1 * cos(degree2rad(ang)), r1 * sin(degree2rad(ang)))); pv.push_back(center + TPointD(r2 * cos(degree2rad(ang)), r2 * sin(degree2rad(ang)))); } } //------------------------------------------------------------ void TCircleStripeFillStyle::drawCircleStripe(const TPointD &center, const double r1, const double r2, const TPixel32 &col) const { std::vector<TPointD> pv; getCircleStripeQuads(center, r1, r2, pv); TStencilControl *stencil = TStencilControl::instance(); stencil->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); glBegin(GL_QUAD_STRIP); tglColor(col); int i = 0; for (; i < (int)pv.size(); i++) tglVertex(pv[i]); glEnd(); stencil->endMask(); stencil->enableMask(TStencilControl::SHOW_OUTSIDE); // glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // glEnable(GL_BLEND); // glEnable(GL_LINE_SMOOTH); tglEnableLineSmooth(); // Just for the antialiasing glBegin(GL_LINE_STRIP); tglColor(col); for (i = 0; i < (int)pv.size(); i += 2) tglVertex(pv[i]); glEnd(); glBegin(GL_LINE_STRIP); tglColor(col); for (i = 1; i < (int)pv.size(); i += 2) tglVertex(pv[i]); glEnd(); stencil->disableMask(); } //------------------------------------------------------------ void TCircleStripeFillStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { const bool isTransparent = m_pointColor.m < 255; TStencilControl *stenc = TStencilControl::instance(); TPixel32 backgroundColor = TSolidColorStyle::getMainColor(); if (cf) backgroundColor = (*(cf))(m_pointColor); TPixel32 foregroundColor; if (cf) foregroundColor = (*(cf))(m_pointColor); else foregroundColor = m_pointColor; if (backgroundColor.m == 0) { // only to create stencil mask TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); // does not draw on screen appStyle.drawRegion(0, false, boundary); } else { // create stencil mask and draw on screen stenc->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); TSolidColorStyle::drawRegion(cf, antiAliasing, boundary); } stenc->endMask(); stenc->enableMask(TStencilControl::SHOW_INSIDE); if (isTransparent) { // glEnable(GL_BLEND); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //// <-- tglEnableBlending(); } TRectD bbox = boundary.m_bbox; double lx = bbox.x1 - bbox.x0; double ly = bbox.y1 - bbox.y0; TPointD center((bbox.x1 + bbox.x0) * 0.5, (bbox.y1 + bbox.y0) * 0.5); center.x = center.x + m_XPos * 0.01 * 0.5 * lx; center.y = center.y + m_YPos * 0.01 * 0.5 * ly; double maxDist = 0.0; maxDist = std::max(tdistance(center, TPointD(bbox.x0, bbox.y0)), maxDist); maxDist = std::max(tdistance(center, TPointD(bbox.x0, bbox.y1)), maxDist); maxDist = std::max(tdistance(center, TPointD(bbox.x1, bbox.y0)), maxDist); maxDist = std::max(tdistance(center, TPointD(bbox.x1, bbox.y1)), maxDist); double halfThick = m_Thickness * 0.5; for (double d = 0; d <= maxDist; d += m_Dist) drawCircleStripe(center, d - halfThick, d + halfThick, foregroundColor); if (isTransparent) { // tglColor(TPixel32::White); // glDisable(GL_BLEND); } stenc->disableMask(); } //------------------------------------------------------------ void TCircleStripeFillStyle::drawRegion(TFlash &flash, const TRegion *r) const { TRectD bbox(r->getBBox()); double lx = bbox.x1 - bbox.x0; double ly = bbox.y1 - bbox.y0; TPointD center((bbox.x1 + bbox.x0) * 0.5, (bbox.y1 + bbox.y0) * 0.5); center.x = center.x + m_XPos * 0.01 * 0.5 * lx; center.y = center.y + m_YPos * 0.01 * 0.5 * ly; double maxDist = 0.0; maxDist = std::max(tdistance(center, TPointD(bbox.x0, bbox.y0)), maxDist); maxDist = std::max(tdistance(center, TPointD(bbox.x0, bbox.y1)), maxDist); maxDist = std::max(tdistance(center, TPointD(bbox.x1, bbox.y0)), maxDist); maxDist = std::max(tdistance(center, TPointD(bbox.x1, bbox.y1)), maxDist); int nbClip = 2; double d = m_Dist; for (; d <= maxDist; d += m_Dist) nbClip++; flash.setFillColor(TPixel::Black); flash.drawRegion(*r, nbClip); flash.setFillColor(getMainColor()); flash.drawRectangle(bbox); flash.setFillColor(m_pointColor); flash.setLineColor(m_pointColor); flash.setThickness(0.0); d = m_Thickness / 2.0; flash.drawEllipse(center, d, d); flash.setFillColor(TPixel32(0, 0, 0, 0)); flash.setLineColor(m_pointColor); flash.setThickness(m_Thickness / 2.0); for (d = m_Dist; d <= maxDist; d += m_Dist) flash.drawEllipse(center, d, d); } //*************************************************************************** // TMosaicFillStyle implementation //*************************************************************************** TMosaicFillStyle::TMosaicFillStyle(const TPixel32 &bgColor, const TPixel32 pointColor[4], const double size, const double deform, const double minThickness, const double maxThickness) : TSolidColorStyle(bgColor) , m_size(size) , m_deform(deform) , m_minThickness(minThickness) , m_maxThickness(maxThickness) { for (int i = 0; i < 4; i++) m_pointColor[i] = pointColor[i]; } //------------------------------------------------------------ TMosaicFillStyle::TMosaicFillStyle(const TPixel32 bgColor) : TSolidColorStyle(bgColor) , m_size(25.0) , m_deform(70.0) , m_minThickness(20) , m_maxThickness(40) { m_pointColor[0] = TPixel32::Blue; m_pointColor[1] = TPixel32::Green; m_pointColor[2] = TPixel32::Yellow; m_pointColor[3] = TPixel32::Cyan; } //------------------------------------------------------------ TColorStyle *TMosaicFillStyle::clone() const { return new TMosaicFillStyle(*this); } //------------------------------------------------------------ int TMosaicFillStyle::getParamCount() const { return 4; } //----------------------------------------------------------------------------- TColorStyle::ParamType TMosaicFillStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString TMosaicFillStyle::getParamNames(int index) const { assert(0 <= index && index < 4); QString value; switch (index) { case 0: value = QCoreApplication::translate("TMosaicFillStyle", "Size"); break; case 1: value = QCoreApplication::translate("TMosaicFillStyle", "Distortion"); break; case 2: value = QCoreApplication::translate("TMosaicFillStyle", "Min Thick"); break; case 3: value = QCoreApplication::translate("TMosaicFillStyle", "Max Thick"); break; } return value; } //----------------------------------------------------------------------------- void TMosaicFillStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 4); min = (index == 0) ? 2 : 0.001; max = 100.0; } //----------------------------------------------------------------------------- double TMosaicFillStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 4); double value; switch (index) { case 0: value = m_size; break; case 1: value = m_deform; break; case 2: value = m_minThickness; break; case 3: value = m_maxThickness; break; } return value; } //----------------------------------------------------------------------------- void TMosaicFillStyle::setParamValue(int index, double value) { assert(0 <= index && index < 4); switch (index) { case 0: m_size = value; break; case 1: m_deform = value; break; case 2: m_minThickness = value; break; case 3: m_maxThickness = value; break; } } //------------------------------------------------------------ void TMosaicFillStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_size; is >> m_deform; is >> m_minThickness; is >> m_maxThickness; is >> m_pointColor[0]; is >> m_pointColor[1]; is >> m_pointColor[2]; is >> m_pointColor[3]; } //------------------------------------------------------------ void TMosaicFillStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_size; os << m_deform; os << m_minThickness; os << m_maxThickness; os << m_pointColor[0]; os << m_pointColor[1]; os << m_pointColor[2]; os << m_pointColor[3]; } //------------------------------------------------------------ TPixel32 TMosaicFillStyle::getColorParamValue(int index) const { TPixel32 tmp; if (index == 0) tmp = TSolidColorStyle::getMainColor(); else if (index >= 1 && index <= 4) tmp = m_pointColor[index - 1]; else assert(!"bad color index"); return tmp; } //------------------------------------------------------------ void TMosaicFillStyle::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) TSolidColorStyle::setMainColor(color); else if (index >= 1 && index <= 4) m_pointColor[index - 1] = color; else assert(!"bad color index"); } //------------------------------------------------------------ void TMosaicFillStyle::preaprePos(const TRectD &box, std::vector<TPointD> &v, int &lX, int &lY, TRandom &rand) const { double dist = 5.0 + (60.0 - 5.0) * tcrop(m_size, 0.0, 100.0) * 0.01; lY = lX = 0; double ld = 0.4 * tcrop(m_deform, 0.0, 100.0) * 0.01; for (double y = box.y0 - dist; y <= (box.y1 + dist); y += dist, lY++) { lX = 0; for (double x = box.x0 - dist; x <= (box.x1 + dist); x += dist, lX++) { double dx = (rand.getInt(0, 2001) * 0.001 - 1.0) * ld * dist; double dy = (rand.getInt(0, 2001) * 0.001 - 1.0) * ld * dist; TPointD pos(x + dx, y + dy); v.push_back(pos); } } } //------------------------------------------------------------ bool TMosaicFillStyle::getQuad(const int ix, const int iy, const int lX, const int lY, std::vector<TPointD> &v, TPointD *pquad, TRandom &rand) const { if (ix < 0 || iy < 0 || ix >= (lX - 1) || iy >= (lY - 1)) return false; double dmin = tcrop(m_minThickness, 0.0, 100.0) * 0.01; double dmax = tcrop(m_maxThickness, 0.0, 100.0) * 0.01; TPointD &p1 = v[iy * lX + ix]; TPointD &p2 = v[iy * lX + ix + 1]; TPointD &p3 = v[(iy + 1) * lX + ix + 1]; TPointD &p4 = v[(iy + 1) * lX + ix]; double q1 = 0.5 * (dmin + (dmax - dmin) * rand.getInt(0, 101) * 0.01); double q2 = 0.5 * (dmin + (dmax - dmin) * rand.getInt(0, 101) * 0.01); double q3 = 0.5 * (dmin + (dmax - dmin) * rand.getInt(0, 101) * 0.01); double q4 = 0.5 * (dmin + (dmax - dmin) * rand.getInt(0, 101) * 0.01); pquad[0] = (1.0 - q1) * p1 + q1 * p3; pquad[1] = (1.0 - q2) * p2 + q2 * p4; pquad[2] = (1.0 - q3) * p3 + q3 * p1; pquad[3] = (1.0 - q4) * p4 + q4 * p2; return true; } //------------------------------------------------------------ void TMosaicFillStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { TStencilControl *stenc = TStencilControl::instance(); TPixel32 backgroundColor = TSolidColorStyle::getMainColor(); if (cf) backgroundColor = (*(cf))(backgroundColor); if (backgroundColor.m == 0) { // only to create stencil mask TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); // does not draw on screen appStyle.drawRegion(0, false, boundary); } else { // create stencil mask and draw on screen stenc->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); TSolidColorStyle::drawRegion(cf, antiAliasing, boundary); } stenc->endMask(); stenc->enableMask(TStencilControl::SHOW_INSIDE); // glEnable(GL_BLEND); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //// <-- tglEnableBlending(); TPixel32 color[4]; for (int i = 0; i < 4; i++) { if (cf) color[i] = (*(cf))(m_pointColor[i]); else color[i] = m_pointColor[i]; } TPixel32 currentColor; std::vector<TPointD> pos; int posLX, posLY; TRandom rand; TPointD quad[4]; preaprePos(boundary.m_bbox, pos, posLX, posLY, rand); glBegin(GL_QUADS); /* ma serve ? tglColor(getMainColor()); tglVertex(TPointD(boundary.m_bbox.x0,boundary.m_bbox.y0)); tglVertex(TPointD(boundary.m_bbox.x0,boundary.m_bbox.y1)); tglVertex(TPointD(boundary.m_bbox.x1,boundary.m_bbox.y1)); tglVertex(TPointD(boundary.m_bbox.x1,boundary.m_bbox.y0)); */ for (int y = 0; y < (posLY - 1); y++) for (int x = 0; x < (posLX - 1); x++) if (getQuad(x, y, posLX, posLY, pos, quad, rand)) { currentColor = color[rand.getInt(0, 4)]; if (currentColor.m != 0) { tglColor(currentColor); tglVertex(quad[0]); tglVertex(quad[1]); tglVertex(quad[2]); tglVertex(quad[3]); } } glEnd(); // tglColor(TPixel32::White); stenc->disableMask(); } //------------------------------------------------------------ void TMosaicFillStyle::drawRegion(TFlash &flash, const TRegion *r) const { TRectD bbox(r->getBBox()); std::vector<TPointD> pos; int posLX, posLY; TRandom rand; TPointD quad[4]; preaprePos(bbox, pos, posLX, posLY, rand); if (pos.size() <= 0) return; int nbClip = (posLX - 1) * (posLY - 1) + 1; flash.drawRegion(*r, nbClip); flash.setFillColor(TSolidColorStyle::getMainColor()); flash.setThickness(0); flash.drawRectangle(bbox); for (int y = 0; y < (posLY - 1); y++) for (int x = 0; x < (posLX - 1); x++) if (getQuad(x, y, posLX, posLY, pos, quad, rand)) { std::vector<TPointD> lvert; lvert.push_back(quad[0]); lvert.push_back(quad[1]); lvert.push_back(quad[2]); lvert.push_back(quad[3]); flash.setFillColor(m_pointColor[rand.getInt(0, 4)]); flash.drawPolyline(lvert); } } //*************************************************************************** // TPatchFillStyle implementation //*************************************************************************** TPatchFillStyle::TPatchFillStyle(const TPixel32 &bgColor, const TPixel32 pointColor[6], const double size, const double deform, const double thickness) : TSolidColorStyle(bgColor) , m_size(size) , m_deform(deform) , m_thickness(thickness) { for (int i = 0; i < 6; i++) m_pointColor[i] = pointColor[i]; } //----------------------------------------------------------------------------- TPatchFillStyle::TPatchFillStyle(const TPixel32 &bgColor) : TSolidColorStyle(bgColor), m_size(25.0), m_deform(50.0), m_thickness(30) { m_pointColor[0] = TPixel32::Red; m_pointColor[1] = TPixel32::Green; m_pointColor[2] = TPixel32::Yellow; m_pointColor[3] = TPixel32::Cyan; m_pointColor[4] = TPixel32::Magenta; m_pointColor[5] = TPixel32::White; } //----------------------------------------------------------------------------- TColorStyle *TPatchFillStyle::clone() const { return new TPatchFillStyle(*this); } //------------------------------------------------------------ int TPatchFillStyle::getParamCount() const { return 3; } //----------------------------------------------------------------------------- TColorStyle::ParamType TPatchFillStyle::getParamType(int index) const { assert(0 <= index && index < getParamCount()); return TColorStyle::DOUBLE; } //----------------------------------------------------------------------------- QString TPatchFillStyle::getParamNames(int index) const { assert(0 <= index && index < 3); QString value; switch (index) { case 0: value = QCoreApplication::translate("TPatchFillStyle", "Size"); break; case 1: value = QCoreApplication::translate("TPatchFillStyle", "Distortion"); break; case 2: value = QCoreApplication::translate("TPatchFillStyle", "Thickness"); break; } return value; } //----------------------------------------------------------------------------- void TPatchFillStyle::getParamRange(int index, double &min, double &max) const { assert(0 <= index && index < 3); min = (index == 0) ? 2 : 0.001; max = 100.0; } //----------------------------------------------------------------------------- double TPatchFillStyle::getParamValue(TColorStyle::double_tag, int index) const { assert(0 <= index && index < 3); double value; switch (index) { case 0: value = m_size; break; case 1: value = m_deform; break; case 2: value = m_thickness; break; } return value; } //----------------------------------------------------------------------------- void TPatchFillStyle::setParamValue(int index, double value) { assert(0 <= index && index < 3); switch (index) { case 0: m_size = value; break; case 1: m_deform = value; break; case 2: m_thickness = value; break; } } //------------------------------------------------------------ void TPatchFillStyle::loadData(TInputStreamInterface &is) { TSolidColorStyle::loadData(is); is >> m_size; is >> m_deform; is >> m_thickness; for (int i = 0; i < 6; i++) is >> m_pointColor[i]; } //------------------------------------------------------------ void TPatchFillStyle::saveData(TOutputStreamInterface &os) const { TSolidColorStyle::saveData(os); os << m_size; os << m_deform; os << m_thickness; for (int i = 0; i < 6; i++) os << m_pointColor[i]; } //------------------------------------------------------------ TPixel32 TPatchFillStyle::getColorParamValue(int index) const { TPixel32 tmp; if (index == 0) tmp = TSolidColorStyle::getMainColor(); else if (index >= 1 && index <= 6) tmp = m_pointColor[index - 1]; else assert(!"bad color index"); return tmp; } //------------------------------------------------------------ void TPatchFillStyle::setColorParamValue(int index, const TPixel32 &color) { if (index == 0) TSolidColorStyle::setMainColor(color); else if (index >= 1 && index <= 6) m_pointColor[index - 1] = color; else assert(!"bad color index"); } //------------------------------------------------------------ void TPatchFillStyle::preaprePos(const TRectD &box, std::vector<TPointD> &v, int &lX, int &lY, TRandom &rand) const { double q = tcrop(m_size, 0.0, 100.0) * 0.01; double r = 5.0 + (60.0 - 5.0) * q; double m = r * sqrt(3.0) / 2.0; lY = 5 + (int)((box.y1 - box.y0) / (2 * m)); int ix = 0; for (double x = box.x0 - r; x <= (box.x1 + r); ix++) { int nb = ix % 4; double y = (nb == 0 || nb == 1) ? box.y0 - 2 * m : box.y0 - m; for (int iy = 0; iy < lY; iy++, y += (2 * m)) v.push_back(TPointD(x, y)); x = (nb == 0 || nb == 2) ? x + r : x + r / 2.0; } lX = ix; double maxDeform = r * 0.6 * tcrop(m_deform, 0.0, 100.0) * 0.01; for (UINT i = 0; i < v.size(); i++) { v[i].x += (rand.getInt(0, 200) - 100) * 0.01 * maxDeform; v[i].y += (rand.getInt(0, 200) - 100) * 0.01 * maxDeform; } } //------------------------------------------------------------ bool TPatchFillStyle::getQuadLine(const TPointD &a, const TPointD &b, const double thickn, TPointD *quad) const { if (tdistance(a, b) < TConsts::epsilon) return false; TPointD ab(b - a); ab = normalize(ab); ab = rotate90(ab); ab = ab * thickn; quad[0] = a + ab; quad[1] = a - ab; quad[2] = b - ab; quad[3] = b + ab; return true; } //------------------------------------------------------------ void TPatchFillStyle::drawGLQuad(const TPointD *quad) const { glBegin(GL_QUADS); tglVertex(quad[0]); tglVertex(quad[1]); tglVertex(quad[2]); tglVertex(quad[3]); glEnd(); double r = tdistance(quad[0], quad[1]) / 2.0; tglDrawDisk(quad[0] * 0.5 + quad[1] * 0.5, r); tglDrawDisk(quad[2] * 0.5 + quad[3] * 0.5, r); } //------------------------------------------------------------ void TPatchFillStyle::drawRegion(const TColorFunction *cf, const bool antiAliasing, TRegionOutline &boundary) const { TStencilControl *stenc = TStencilControl::instance(); TPixel32 backgroundColor = TSolidColorStyle::getMainColor(); if (cf) backgroundColor = (*(cf))(backgroundColor); if (backgroundColor.m == 0) { // only to create stencil mask TSolidColorStyle appStyle(TPixel32::White); stenc->beginMask(); // does not draw on screen appStyle.drawRegion(0, false, boundary); } else { // create stencil mask and draw on screen stenc->beginMask(TStencilControl::DRAW_ALSO_ON_SCREEN); TSolidColorStyle::drawRegion(cf, antiAliasing, boundary); } stenc->endMask(); stenc->enableMask(TStencilControl::SHOW_INSIDE); // glEnable(GL_BLEND); // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //// <-- tglEnableBlending(); TPixel32 color[6]; for (int i = 0; i < 6; i++) if (cf) color[i] = (*(cf))(m_pointColor[i]); else color[i] = m_pointColor[i]; TPixel32 currentColor; std::vector<TPointD> pos; int posLX, posLY; TRandom rand; TPointD quad[4]; preaprePos(boundary.m_bbox, pos, posLX, posLY, rand); glBegin(GL_TRIANGLES); int x = 2; for (; x < (posLX - 2); x += 2) for (int y = 1; y < posLY; y++) { TPointD q[6]; if ((x % 4) == 2) { q[0] = pos[(x - 1) * posLY + y]; q[1] = pos[(x)*posLY + y]; q[2] = pos[(x + 1) * posLY + y]; q[3] = pos[(x + 2) * posLY + y]; q[4] = pos[(x + 1) * posLY + y - 1]; q[5] = pos[(x)*posLY + y - 1]; } else { q[0] = pos[(x - 1) * posLY + y - 1]; q[1] = pos[(x)*posLY + y - 1]; q[2] = pos[(x + 1) * posLY + y - 1]; q[3] = pos[(x + 2) * posLY + y - 1]; q[4] = pos[(x + 1) * posLY + y]; q[5] = pos[(x)*posLY + y]; } currentColor = color[rand.getInt(0, 6)]; if (currentColor.m != 0) { tglColor(currentColor); tglVertex(q[0]); tglVertex(q[1]); tglVertex(q[2]); tglVertex(q[2]); tglVertex(q[3]); tglVertex(q[4]); tglVertex(q[4]); tglVertex(q[5]); tglVertex(q[0]); tglVertex(q[0]); tglVertex(q[2]); tglVertex(q[4]); } } glEnd(); double thickn = tcrop(m_thickness, 0.0, 100.0) * 0.01 * 5.0; if (thickn > 0.001) tglColor(backgroundColor); for (x = 0; x < (posLX - 1); x++) { int nb = x % 4; for (int y = 0; y < posLY; y++) { if (getQuadLine(pos[x * posLY + y], pos[(x + 1) * posLY + y], thickn, quad)) drawGLQuad(quad); if (y > 0 && nb == 1) if (getQuadLine(pos[x * posLY + y], pos[(x + 1) * posLY + y - 1], thickn, quad)) drawGLQuad(quad); if (y < (posLY - 1) && nb == 3) if (getQuadLine(pos[x * posLY + y], pos[(x + 1) * posLY + y + 1], thickn, quad)) drawGLQuad(quad); } } // tglColor(TPixel32::White); stenc->disableMask(); } //------------------------------------------------------------ int TPatchFillStyle::nbClip(const int lX, const int lY, const std::vector<TPointD> &v) const { TPointD quad[4]; double thickn = tcrop(m_thickness, 0.0, 100.0) * 0.01 * 5.0; int nbC = 0; int x = 2; for (; x < (lX - 2); x += 2) for (int y = 1; y < lY; y++) nbC += 1; if (thickn > 0.001) for (x = 0; x < (lX - 1); x++) { int nb = x % 4; for (int y = 0; y < lY; y++) { if (getQuadLine(v[x * lY + y], v[(x + 1) * lY + y], thickn, quad)) nbC += 3; if (y > 0 && nb == 1) if (getQuadLine(v[x * lY + y], v[(x + 1) * lY + y - 1], thickn, quad)) nbC += 3; if (y < (lY - 1) && nb == 3) if (getQuadLine(v[x * lY + y], v[(x + 1) * lY + y + 1], thickn, quad)) nbC += 3; } } return nbC; } //------------------------------------------------------------ void TPatchFillStyle::drawFlashQuad(TFlash &flash, const TPointD *quad) const { std::vector<TPointD> lvert; lvert.push_back(quad[0]); lvert.push_back(quad[1]); lvert.push_back(quad[2]); lvert.push_back(quad[3]); flash.drawPolyline(lvert); double r = tdistance(quad[0], quad[1]) / 2.0; flash.drawEllipse(quad[0] * 0.5 + quad[1] * 0.5, r, r); flash.drawEllipse(quad[2] * 0.5 + quad[3] * 0.5, r, r); } //------------------------------------------------------------ void TPatchFillStyle::drawFlashTriangle(TFlash &flash, const TPointD &p1, const TPointD &p2, const TPointD &p3) const { std::vector<TPointD> lvert; lvert.push_back(p1); lvert.push_back(p2); lvert.push_back(p3); flash.drawPolyline(lvert); } //------------------------------------------------------------ void TPatchFillStyle::drawRegion(TFlash &flash, const TRegion *r) const { TRectD bbox(r->getBBox()); std::vector<TPointD> pos; int posLX, posLY; TRandom rand; TPointD quad[4]; preaprePos(bbox, pos, posLX, posLY, rand); if (pos.size() <= 0) return; flash.drawRegion(*r, nbClip(posLX, posLY, pos)); flash.setThickness(0.0); int x; for (x = 2; x < (posLX - 2); x += 2) for (int y = 1; y < posLY; y++) { std::vector<TPointD> lvert; if ((x % 4) == 2) { lvert.push_back(pos[(x - 1) * posLY + y]); lvert.push_back(pos[(x)*posLY + y]); lvert.push_back(pos[(x + 1) * posLY + y]); lvert.push_back(pos[(x + 2) * posLY + y]); lvert.push_back(pos[(x + 1) * posLY + y - 1]); lvert.push_back(pos[(x)*posLY + y - 1]); } else { lvert.push_back(pos[(x - 1) * posLY + y - 1]); lvert.push_back(pos[(x)*posLY + y - 1]); lvert.push_back(pos[(x + 1) * posLY + y - 1]); lvert.push_back(pos[(x + 2) * posLY + y - 1]); lvert.push_back(pos[(x + 1) * posLY + y]); lvert.push_back(pos[(x)*posLY + y]); } flash.setFillColor(m_pointColor[rand.getInt(0, 6)]); flash.drawPolyline(lvert); } flash.setFillColor(TSolidColorStyle::getMainColor()); flash.setThickness(0.0); double thickn = tcrop(m_thickness, 0.0, 100.0) * 0.01 * 5.0; if (thickn > 0.001) for (x = 0; x < (posLX - 1); x++) { int nb = x % 4; for (int y = 0; y < posLY; y++) { if (getQuadLine(pos[x * posLY + y], pos[(x + 1) * posLY + y], thickn, quad)) drawFlashQuad(flash, quad); if (y > 0 && nb == 1) if (getQuadLine(pos[x * posLY + y], pos[(x + 1) * posLY + y - 1], thickn, quad)) drawFlashQuad(flash, quad); if (y < (posLY - 1) && nb == 3) if (getQuadLine(pos[x * posLY + y], pos[(x + 1) * posLY + y + 1], thickn, quad)) drawFlashQuad(flash, quad); } } }
{ "content_hash": "472e448acf9501fb21cbc8d7a194939e", "timestamp": "", "source": "github", "line_count": 5012, "max_line_length": 80, "avg_line_length": 29.438946528332004, "alnum_prop": 0.5215319760349174, "repo_name": "damies13/opentoonz", "id": "9a9d472b39ec53de2228bf7fc288eedbc2d808ba", "size": "147548", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "toonz/sources/colorfx/regionstyles.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1473575" }, { "name": "C++", "bytes": "22868995" }, { "name": "CMake", "bytes": "98961" }, { "name": "CSS", "bytes": "94557" }, { "name": "FLUX", "bytes": "156349" }, { "name": "GLSL", "bytes": "24307" }, { "name": "HTML", "bytes": "71392" }, { "name": "JavaScript", "bytes": "2" }, { "name": "Lua", "bytes": "1882" }, { "name": "Objective-C", "bytes": "101128" }, { "name": "Objective-C++", "bytes": "1462" }, { "name": "QMake", "bytes": "11328" }, { "name": "Shell", "bytes": "54107" }, { "name": "Smarty", "bytes": "45980" } ], "symlink_target": "" }
from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('scheduling_partitioned', '0006_unique_indexes'), ] operations = [ # (case_id, alert_schedule_id) covered by unique(case_id, alert_schedule_id, recipient_type, recipient_id) migrations.AlterIndexTogether( name='casealertscheduleinstance', index_together=set([('domain', 'active', 'next_event_due'), ('active', 'next_event_due')]), ), # (case_id, timed_schedule_id) covered by unique(case_id, timed_schedule_id, recipient_type, recipient_id) migrations.AlterIndexTogether( name='casetimedscheduleinstance', index_together=set([('domain', 'active', 'next_event_due'), ('active', 'next_event_due')]), ), ]
{ "content_hash": "88619b01153a598df652e60fe57a237e", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 114, "avg_line_length": 38.904761904761905, "alnum_prop": 0.627906976744186, "repo_name": "dimagi/commcare-hq", "id": "5ef4182b59f5e30aae503e8fa1e51136b94a4b01", "size": "817", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "corehq/messaging/scheduling/scheduling_partitioned/migrations/0007_index_cleanup.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "82928" }, { "name": "Dockerfile", "bytes": "2341" }, { "name": "HTML", "bytes": "2589268" }, { "name": "JavaScript", "bytes": "5889543" }, { "name": "Jinja", "bytes": "3693" }, { "name": "Less", "bytes": "176180" }, { "name": "Makefile", "bytes": "1622" }, { "name": "PHP", "bytes": "2232" }, { "name": "PLpgSQL", "bytes": "66704" }, { "name": "Python", "bytes": "21779773" }, { "name": "Roff", "bytes": "150" }, { "name": "Shell", "bytes": "67473" } ], "symlink_target": "" }
:local .treeView{ flex: 1; background-color: var(--tree); overflow: hidden; list-style: none; color: #424243; text-align: left; font-size: 12px; font-family: 'Segoe UI', 'Roboto', 'Helvetica', 'Arial', sans-serif; font-weight: normal; } /* Scrollbar */ :local .treeView::-webkit-scrollbar { width: 0.3em; } :local .treeView::-webkit-scrollbar-thumb { background-color: rgba(64, 128, 128, 0.4); } :local .treeView::-webkit-scrollbar-track { background-color: transparent; } :local .treeView:hover { overflow: auto; } :local .treeView ul { box-shadow: none; outline: none; margin: 0; padding: 0; } :local .label{ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; align-content: center; } :local .hoverTarget { display: flex; align-items: center; height: 28px; } :local .hoverTarget:hover { color: black; background-color: rgba(12, 87, 193, 0.08); } :local .hoverTarget > svg, :local .hoverTarget > div { pointer-events: none; display: inline-block; } /* Document Selector */ :local .dropdown { background: var(--doc-manager); cursor: pointer; user-select: none; color: var(--doc-manager-font); border-bottom: 1px solid var(--doc-manager-bottom-border); } :local .dropdown > div { display: flex; align-items: center; height: 35px; } :local .dropdown > div:hover { background: var(--doc-manager-hover); color: var(--doc-manager-hover-font); } :local .newDoc > div { color: gray; } :local .newDoc:hover > div { color: black; } :local .newDoc > svg { height: auto; width: 16px; margin: 0px 7px; background: transparent; transition: 0.2s all ease; border-radius: 15px; color: gray; border: 1px solid transparent; } :local .newDoc:hover > svg { color: var(--doc-manager-add); background: white; border: 1px solid var(--doc-manager-add); } :local .dropdownDocItem > div { color: gray; width: 100%; text-align: left; } :local .dropdownDocItem:hover > div { color: black; } :local .dropdownDocItem > svg:last-of-type { opacity: 0; margin-right: 7px; height: auto; width: 20px; color: var(--doc-manager-remove); background: transparent; transition: 0.2s all ease; border-radius: 15px; border: 1px solid transparent; } :local .dropdownDocItem:hover > svg:last-of-type { opacity: 1; } :local .dropdownDocItem > svg:last-of-type:hover { opacity: 1; height: auto; width: 16px; fill: white; padding: 1px; border-radius: 15px; border: 1px solid white; background: var(--doc-manager-remove-hover); } :local .dropdownDocItem > svg:first-of-type { opacity: 0; height: auto; width: 20px; margin: 0px 7px; color: var(--doc-manager-remove); background: transparent; transition: 0.2s all ease; border: 1px solid transparent; border-radius: 15px; } :local .dropdownDocItem:hover > svg:first-of-type { opacity: 1; } :local .dropdownDocItem > svg:first-of-type:hover { color: white; background: var(--doc-manager-config-color-active); border-radius: 15px; border: 1px solid var(--doc-manager-config-color-active); }
{ "content_hash": "63a701f95c7f8c2b92be8f0e98c6d341", "timestamp": "", "source": "github", "line_count": 150, "max_line_length": 72, "avg_line_length": 22.026666666666667, "alnum_prop": 0.635593220338983, "repo_name": "pastahito/remus", "id": "a72843079c96b61440abcd4de0cb3323a39acef5", "size": "3304", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/renderer_process/app/components/treeView/treeView.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6693" }, { "name": "HTML", "bytes": "460" }, { "name": "JavaScript", "bytes": "52380" } ], "symlink_target": "" }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace Microsoft.Extensions.EnvironmentAbstractions { internal interface IDirectory { bool Exists(string path); ITemporaryDirectory CreateTemporaryDirectory(); IEnumerable<string> EnumerateFiles(string path, string searchPattern); IEnumerable<string> EnumerateFileSystemEntries(string path); IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern); string GetDirectoryFullName(string path); void CreateDirectory(string path); void Delete(string path, bool recursive); void Move(string source, string destination); } }
{ "content_hash": "28aab370ed24bcc24138702fc06139c9", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 101, "avg_line_length": 30.357142857142858, "alnum_prop": 0.7364705882352941, "repo_name": "svick/cli", "id": "04526de37265651077366e9471400393d315752c", "size": "852", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Microsoft.DotNet.InternalAbstractions/IDirectory.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2069" }, { "name": "C#", "bytes": "2047296" }, { "name": "F#", "bytes": "476" }, { "name": "Groovy", "bytes": "4206" }, { "name": "HTML", "bytes": "36204" }, { "name": "PowerShell", "bytes": "48497" }, { "name": "Shell", "bytes": "60962" }, { "name": "Visual Basic", "bytes": "1309" } ], "symlink_target": "" }
<!DOCTYPE HTML> <html> <head> <style> head, style {display: block;} [contenteditable] {-webkit-user-modify: read-write-plaintext-only;} style:first-of-type {visibility:hidden;} style:last-of-type {padding: 20px; font-size: 1.5em; white-space: pre; font-family: monospace; background-color: rgba(255,255,255,0.5);} html {min-height:100%;} div {border: 3px solid #ddaa00; padding: 3px; line-height: 2rem; min-height: 2rem;} div div {border-color: #333;} div>div {border-style: dotted;} div:nth-of-type(2){border-style: dashed;} .a {background-color: #fff;} .b {background-color: #ccc;} .c {background-color: #999;} </style> <style contenteditable> body > div { display: flex; flex-wrap: wrap; align-content: space-between; } div > div:nth-of-type(odd) { flex: 1 0 220px; } </style> <title>Flexbox</title> </head> <body> <div id="container"> <div class="box a">Alphabet</div> <div class="box b">Banana</div> <div class="box c">Crayons</div> <div class="box a">Dinosaurs</div> <div class="box b">Eggplant</div> <div class="box c">Foundation</div> <div class="box a">Ghosts</div> <div class="box b">Happy</div> <div class="box c">Igloo</div> <div class="box a">Janitors</div> <div class="box b">Kittens</div> <div class="box c">Lasso</div> <div class="box a">Magic 8-ball</div> <div class="box b">Nincompoop</div> <div class="box c">Orange</div> <div class="box a">Petunia</div> <div class="box b">Quality</div> <div class="box c">Rancid</div> <div class="box a">Shoelace</div> <div class="box b">Terydactyl</div> <div class="box c">Umbrella</div> <div class="box a">Valentine</div> <div class="box b">Westward</div> <div class="box c">Xylophone</div> </div> </body> </html>
{ "content_hash": "1dd1ddafd75e0f54107ebb9ab67e0ad8", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 136, "avg_line_length": 29.16393442622951, "alnum_prop": 0.641371557054525, "repo_name": "estelle/flexbox", "id": "3c0b42f5aa0ad254a815e1298833e6b312721341", "size": "1779", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "flexfiles/align2.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33290" }, { "name": "HTML", "bytes": "298707" }, { "name": "JavaScript", "bytes": "20640" } ], "symlink_target": "" }
using System; using System.IO; namespace Microsoft.Build.Logging.StructuredLogger { public class ErrorReporting { private static readonly string logFilePath = Path.Combine(GetRootPath(), "LoggerExceptions.txt"); private static string GetRootPath() { #if NETCORE var path = Path.GetTempPath(); #else var path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); #endif path = Path.Combine(path, "Microsoft", "MSBuildStructuredLog"); return path; } public static void ReportException(Exception ex) { if (ex == null) { return; } try { Directory.CreateDirectory(Path.GetDirectoryName(logFilePath)); // if the log has gotten too big, delete it if (File.Exists(logFilePath) && new FileInfo(logFilePath).Length > 10000000) { File.Delete(logFilePath); } File.AppendAllText(logFilePath, ex.ToString()); } catch (Exception) { } } } }
{ "content_hash": "e1e112062375b6a120c6ab6808ae81de", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 105, "avg_line_length": 27.347826086956523, "alnum_prop": 0.519872813990461, "repo_name": "KirillOsenkov/MSBuildStructuredLog", "id": "f83f13f46211a3a357e10dd6a0b1fb2cf00c355f", "size": "1260", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "src/StructuredLogger/ErrorReporting.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "356" }, { "name": "C#", "bytes": "1208283" }, { "name": "PowerShell", "bytes": "1174" }, { "name": "Shell", "bytes": "419" } ], "symlink_target": "" }