text:
package common.api.bitTracking

import common.api.bitTracking.BitTrackingMode.BitTrackingMode
import common.components.DaoComponents
import common.models.BitTrackingSettings
import common.models.bitTrackingFormData.BitTrackingFormData
import common.ref.MtrConfigRef
import javax.inject.Inject
import play.api.Logger
import play.api.cache.SyncCacheApi
import play.api.db.Database

import scala.collection.mutable

class BitTrackingState @Inject()(daoComponents: DaoComponents, configRef: MtrConfigRef, cache: SyncCacheApi) {

    private val numberFormatString: String = "%,d"

    private def getBitTrackingLocation(suffix: String): String = s"bitTracking.$suffix"

    private val BIT_TRACKING_MODE_SUFFIX: String = "bitTrackingMode"

    def getCurrentBitTrackingMode: BitTrackingMode = {
        val bitTrackingSettingsOpt: Option[BitTrackingSettings] = daoComponents.bitTrackingSettingsDAO.get(configRef.guildId)
        if (bitTrackingSettingsOpt.isDefined)
            BitTrackingMode(bitTrackingSettingsOpt.get.currentMode)
        else
            BitTrackingMode(0)
    }

    private val PAUSED_SUFFIX: String = "paused"

    private val PAUSED_LOCATION: String = getBitTrackingLocation(PAUSED_SUFFIX)

    def getIsPaused: Boolean = cache.getOrElseUpdate(PAUSED_LOCATION)(false)

    def setIsPaused(isPaused: Boolean): Unit = cache.set(PAUSED_LOCATION, isPaused)

    def getGameMessage: String = {
        val bitTrackingSettingsOpt: Option[BitTrackingSettings] = daoComponents.bitTrackingSettingsDAO.get(configRef.guildId)
        if (bitTrackingSettingsOpt.isDefined)
            bitTrackingSettingsOpt.get.bitGameMessage
        else
            "bot.bitTracking.settingsNotFound"
    }

    def getBitsMessage: String = {
        val bitTrackingSettingsOpt: Option[BitTrackingSettings] = daoComponents.bitTrackingSettingsDAO.get(configRef.guildId)
        if (bitTrackingSettingsOpt.isDefined)
            bitTrackingSettingsOpt.get.bitsMessage
        else
            "bot.bitTracking.settingsNotFound"
    }

    def getGoalMessage: String = {
        val bitTrackingSettingsOpt: Option[BitTrackingSettings] = daoComponents.bitTrackingSettingsDAO.get(configRef.guildId)
        if (bitTrackingSettingsOpt.isDefined)
            bitTrackingSettingsOpt.get.goalMessage
        else
            "bot.bitTracking.settingsNotFound"
    }

    private val TO_NEXT_GOAL_SUFFIX: String = "toNextGoal"

    private val TO_NEXT_GOAL_LOCATION: String = getBitTrackingLocation(TO_NEXT_GOAL_SUFFIX)

    def getToNextGoal: Int = cache.getOrElseUpdate(TO_NEXT_GOAL_LOCATION)(0)

    def setToNextGoal(toNextGoal: Int): Unit = cache.set(TO_NEXT_GOAL_LOCATION, toNextGoal)

    def addToNextGoal(delta: Int): Unit = setToNextGoal(getToNextGoal + delta)

    private val GOAL_AMOUNT_SUFFIX: String = "goalAmount"

    private val GOAL_AMOUNT_LOCATION: String = getBitTrackingLocation(GOAL_AMOUNT_SUFFIX)

    def getGoalAmount: Int = cache.getOrElseUpdate(GOAL_AMOUNT_LOCATION)(10000)

    def setGoalAmount(goalAmount: Int): Unit = cache.set(GOAL_AMOUNT_LOCATION, goalAmount)

    private val GOAL_COUNT_SUFFIX: String = "goalCount"

    private val GOAL_COUNT_LOCATION: String = getBitTrackingLocation(GOAL_COUNT_SUFFIX)

    def getGoalCount: Int = cache.getOrElseUpdate(GOAL_COUNT_LOCATION)(0)

    def setGoalCount(goalCount: Int): Unit = cache.set(GOAL_COUNT_LOCATION, goalCount)

    def addToGoalCount(delta: Int): Unit = setGoalCount(getGoalCount + delta)

    private val INCREMENT_AMOUNT_SUFFIX: String = "incrementAmount"

    private val INCREMENT_AMOUNT_LOCATION: String = getBitTrackingLocation(INCREMENT_AMOUNT_SUFFIX)

    def getIncrementAmount: Int = cache.getOrElseUpdate(INCREMENT_AMOUNT_LOCATION)(1)

    def setIncrementAmount(incrementAmount: Int): Unit = cache.set(INCREMENT_AMOUNT_LOCATION, incrementAmount)

    def addToGoalAmount(delta: Int): Unit = setGoalAmount(getGoalAmount + delta)

    private val GOAL_INCREMENT_AMOUNT_SUFFIX: String = "goalIncrementAmount"

    private val GOAL_INCREMENT_AMOUNT_LOCATION: String = getBitTrackingLocation(GOAL_INCREMENT_AMOUNT_SUFFIX)

    def getGoalIncrementAmount: Int = cache.getOrElseUpdate(GOAL_INCREMENT_AMOUNT_LOCATION)(0)

    def setGoalIncrementAmount(incrementAmount: Int): Unit = cache.set(GOAL_INCREMENT_AMOUNT_LOCATION, incrementAmount)

    def getBitTrackingFormData: BitTrackingFormData = BitTrackingFormData(
        configRef.guildId,
        getCurrentBitTrackingMode.id,
        getIsPaused,
        getGameMessage,
        getBitsMessage,
        getGoalMessage,
        getToNextGoal,
        getGoalAmount,
        getGoalCount,
        getIncrementAmount,
        getGoalIncrementAmount
    )

    def setBitTrackingFormData(bitTrackingFormData: BitTrackingFormData): Unit = {
        setIsPaused(bitTrackingFormData.isPaused)
        setToNextGoal(bitTrackingFormData.toNextGoal)
        setGoalAmount(bitTrackingFormData.goalAmount)
        setGoalCount(bitTrackingFormData.goalCount)
        setIncrementAmount(bitTrackingFormData.incrementAmount)
        setGoalIncrementAmount(bitTrackingFormData.goalIncrementAmount)
    }

    def getFormattingVariables: mutable.LinkedHashMap[String, Object] = mutable.LinkedHashMap(
        GOAL_AMOUNT_SUFFIX -> getGoalAmount.asInstanceOf[Object],
        TO_NEXT_GOAL_SUFFIX -> getToNextGoal.asInstanceOf[Object],
        GOAL_COUNT_SUFFIX -> getGoalCount.asInstanceOf[Object],
        INCREMENT_AMOUNT_SUFFIX -> getIncrementAmount.asInstanceOf[Object],
        GOAL_INCREMENT_AMOUNT_SUFFIX -> getGoalIncrementAmount.asInstanceOf[Object]
    )

    def getGoalMessageVariables(delta: Int = 0): mutable.LinkedHashMap[String, Object] = getFormattingVariables += ("delta" -> delta.asInstanceOf[Object])

    private def variableMapStr(map: mutable.LinkedHashMap[String, Object]): String = map.keys.mkString("{", "}, {", "}")

    def getFormattingVariablesString: String = variableMapStr(getFormattingVariables)

    def getGoalFormattingVariablesString: String = variableMapStr(getGoalMessageVariables())

}


text: projetos para arduino UNO

redpajama_set_name: RedPajamaGithub


text:
import { moduleFor, test } from 'ember-qunit';

moduleFor('route:example', 'Unit | Route | example', {
  // Specify the other units that are required for this test.
  needs: ['service:redux']
});

test('it exists', function(assert) {
  let route = this.subject();
  assert.ok(route);
});


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>apple on Reflections</title>
    <link>http://blog.shiv.me/tags/apple/</link>
    <description>Recent content in apple on Reflections</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <copyright>Copyright 2016 &copy; Shivanand Velmurugan</copyright>
    <lastBuildDate>Sun, 21 Jul 2013 00:00:00 +0000</lastBuildDate><atom:link href="http://blog.shiv.me/tags/apple/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>How to apologize to your users</title>
      <link>http://blog.shiv.me/2013/07/21/how-to-apologize-to-your-users/</link>
      <pubDate>Sun, 21 Jul 2013 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2013/07/21/how-to-apologize-to-your-users/</guid>
      <description>There has been an increase in security breaches this year. This past week, two services I use were compromised - Tumblr and Apple Developer Connection. Both services informed me of the security breach, and one made me feel like they cared, and the other one didn&rsquo;t. Perhaps I am reading too much into this, but at the very least, it illustrates how important language is, in conveying how much we care.</description>
    </item>

    <item>
      <title>RIP Steve Jobs</title>
      <link>http://blog.shiv.me/2011/10/05/rip-steve-jobs/</link>
      <pubDate>Wed, 05 Oct 2011 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2011/10/05/rip-steve-jobs/</guid>
      <description>DeWitt Clinton once wrote
 What are the hallmarks of a great engineer? A great engineer is characterized by their intelligence, versatility, creativity, loyalty, passion, experience, vision, dedication, composure, humility, and ability.
 Apart from the &ldquo;humility&rdquo; part, which he never cared for, Steve Jobs was the epitome of that description. We shall miss you Mr. Jobs, especially for that keen sense of doing something perfectly.
RIP Steve Jobs, the maker of beautiful things.</description>
    </item>

    <item>
      <title>iPad and friends</title>
      <link>http://blog.shiv.me/2011/05/01/ipad-and-friends/</link>
      <pubDate>Sun, 01 May 2011 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2011/05/01/ipad-and-friends/</guid>
      <description>It&rsquo;s been a year since I sold my kidneys for an iPad. It&rsquo;s been fun. It has replaced every other device I own (ie, a couple of PCs and the nexus one). It&rsquo;s an outright winner, when it comes to reading, especially long-form articles, and books alike. It has become my go-to machine for everyday news, twitter/facebook, and even for browsing my favorite photographers.
It have however remained strictly in the realm of content consumption &ndash; until now.</description>
    </item>

    <item>
      <title>You cribbing bunch of morons</title>
      <link>http://blog.shiv.me/2011/04/27/you-cribbing-bunch-of-morons/</link>
      <pubDate>Wed, 27 Apr 2011 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2011/04/27/you-cribbing-bunch-of-morons/</guid>
      <description>And now you&rsquo;ve done it!! Bah! I thought it was so cool that I could plot of heat map of my location for a full year. With all the cribbing around the internets about how the iphone is not secure because it stores data (ie a cache of your location data), Apple has decided to squash this wonderful &ldquo;easter egg&rdquo;.
 Sometime in the next few weeks Apple will release a free iOS software update that:</description>
    </item>

    <item>
      <title>No matter what we say</title>
      <link>http://blog.shiv.me/2011/03/04/no-matter-what-we-say/</link>
      <pubDate>Fri, 04 Mar 2011 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2011/03/04/no-matter-what-we-say/</guid>
      <description>If you weren&rsquo;t in a hole the past few days, you would have heard about the iPad 2 launch. Here&rsquo;s Conan&rsquo;s take on it.
I must say, the cover is a thing of engineering beauty. Kudos on that, Apple, and thanks for screwing over several thousands of your iPad 1 customers, who forked up 9.5 Billion in revenue in 9 months.</description>
    </item>

    <item>
      <title>iCaved</title>
      <link>http://blog.shiv.me/2010/05/29/icaved/</link>
      <pubDate>Sat, 29 May 2010 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2010/05/29/icaved/</guid>
      <description>I did it. I said I wouldn&rsquo;t. I said I will hold out for purely ethical reasons, but it is very hard to resist the iPad. The first impression in-store is simply &ndash; awesome. This of course is not a surprise and is something that one can expect from apple these days.
Warning: This is a long post ..
Here are some thoughts, after a day of use:
 It&rsquo;s fast.</description>
    </item>

    <item>
      <title>The day-after the "big" day</title>
      <link>http://blog.shiv.me/2010/05/14/the-day-after-the-big-day/</link>
      <pubDate>Fri, 14 May 2010 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2010/05/14/the-day-after-the-big-day/</guid>
      <description>I turned 30 yesterday.
A whole day has passed since I left my 20s. They say it is a big day. They say it is a dreaded day. It was neither. Just busy (which is good).
I chanced upon [Douglas Adams' post][1] from 1999:
&gt; 1. everything that&rsquo;s already in the world when you&rsquo;re born is just normal;
&gt; 2. anything that gets invented between then and before you turn thirty is incredibly exciting and creative and with any luck you can make a career out of it;</description>
    </item>

    <item>
      <title>So long and thanks for the "jailed" iphone</title>
      <link>http://blog.shiv.me/2010/03/16/so-long-and-thanks-for-the-jailed-iphone/</link>
      <pubDate>Tue, 16 Mar 2010 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2010/03/16/so-long-and-thanks-for-the-jailed-iphone/</guid>
      <description>[caption id=&ldquo;attachment_737&rdquo; align=&ldquo;alignnone&rdquo; width=&ldquo;300&rdquo;] So long oppression[/caption]
Thanks for the iPhone, Mr. Jobs. There is a new way to protest the iPhone. I don&rsquo;t have to sign petitions anymore. I can now take my $500 elsewhere, for a slightly more open experience. I didn&rsquo;t ask for much, but I don&rsquo;t have to wait on your whim any longer (no offense meant to you personally, Mr Jobs).</description>
    </item>

    <item>
      <title>iPad is iBad petition</title>
      <link>http://blog.shiv.me/2010/02/04/ipad-is-ibad-petition/</link>
      <pubDate>Thu, 04 Feb 2010 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2010/02/04/ipad-is-ibad-petition/</guid>
      <description>http://www.defectivebydesign.org/ipad
If you think that the iPad is promoting DRM of apps that will lead computing in a direction that will undermine the freedom that we currently are enjoying, freedom the seeds of which have been sown over the last few decades, the visit the link above and sign the petition.</description>
    </item>

    <item>
      <title>\[Jason\] The Case Against Apple--in Five Parts</title>
      <link>http://blog.shiv.me/2009/08/08/%5Cjason%5C-the-case-against-apple-in-five-parts/</link>
      <pubDate>Sat, 08 Aug 2009 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2009/08/08/%5Cjason%5C-the-case-against-apple-in-five-parts/</guid>
      <description>Hi Jason,
I was writing a post very much on the same lines, when I read your mail. I&rsquo;m on my 3rd ipod, 1st iphone and 2nd MBP (one which I ordered just last week). I don&rsquo;t think I can in the right mind buy another iphone or ipod for the amount of control that apple gets.
1. Absolutely. This is a no-brainer, that I&rsquo;m frankly surprised that Steve Jobs does not see?</description>
    </item>

    <item>
      <title>That queasy feeling</title>
      <link>http://blog.shiv.me/2008/01/29/that-queasy-feeling/</link>
      <pubDate>Tue, 29 Jan 2008 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2008/01/29/that-queasy-feeling/</guid>
      <description>A few days ago, I returned the Ipod touch that I had for exactly 11 days, coz Apple chose to charge me $20. Apart from me being a cheap bas***d, I had this queasy feeling in my gut, about apple products. I felt an unexplainable rage towards Apple, Jobs and the fanboys. I am usually a very moderate person, and it really surprised me that I could harbor such crazy extremism and frustration.</description>
    </item>

    <item>
      <title>IPod touch 1.1.1 firmware link</title>
      <link>http://blog.shiv.me/2008/01/15/ipod-touch-1.1.1-firmware-link/</link>
      <pubDate>Tue, 15 Jan 2008 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2008/01/15/ipod-touch-1.1.1-firmware-link/</guid>
      <description>Since Apple&rsquo;s is so bent upon disappointing their customers, by introducing paid firmware upgrades, I needed to ensure that I have the option to jail break, my new ipod touch (if need be). (update: the firmware upgrade itself is not paid. Only the newapps are paid). I am going to wait until they release their SDK in February before I jailbreak mine.
I found a link to the 1.1.1 firmware (thanks to Rupert and who-ever posted this).</description>
    </item>

    <item>
      <title>Apple iMplant</title>
      <link>http://blog.shiv.me/2005/10/26/apple-implant/</link>
      <pubDate>Wed, 26 Oct 2005 00:00:00 +0000</pubDate>

      <guid>http://blog.shiv.me/2005/10/26/apple-implant/</guid>
      <description>Have you heard about the latest ipod.
http://www.bbspot.com/News/2005/01/new_ipod_implant.html
http://news.com.com/5208-7354-0.html?forumID=1&amp;threadID=4129&amp;messageID=24004&amp;start=-1
This is amazing.. Imagine being able to have a device implanted in your body, with which you cantrol with your thought, and which will use your brain as a hardrive, and use blood sugar as a battery cell.
Eerie thought envelop me, when I think of what could be?!! Living the matrix ?!!
It is not only the body heat that can be a source of energy (like in &ldquo;The Matrix&rdquo;), even human blood sugar can be harnesed!</description>
    </item>

  </channel>
</rss>


text:
layout: post
title: Visitor pattern
excerpt: ""
categories: articles
tags: [design-patterns]
modified: 2016-11-03
---

## Intent

- Allow to define new operations for a class hierarchy _without_ modifying the hierarchy

## Structure

![visitor-pattern-structure]({{ site.url }}/images/patterns/design-patterns/visitor/structure.png)

- The concrete implementations of `accept(Visitor v)` methods only need to call `v.visit(this)`, then the callee `Visitor` will carry out the necessary operation on the caller `Component`. This is the _double dispatch_ technique, where the result of the call depends on the request and the types of _two_ receivers, e.g., `Component` and `Visitor` in this case.
- Each `Visitor` supports a specific group of operations on the `Component` class hierarchy. Thus, new group of operations can be added via new `Visitor` without changing the `Component` hierarchy at all.

# Applicable contexts

- A class hierarchy rarely changes, but its services usually do.

# Benefits

- Allow to extend the services of a whole class hierarchy without changing the hierarchy, because the extension can be done by adding new visitors
- Allow to modify the services of a whole class hierarchy without changing the hierarchy, because the modification can be done by adapting the corresponding visitors

# Risks

- The pattern is quite complicated to understand. Using this pattern might make it hard for other team members to get familiar with the code.
- Adding new classes to the hierarchy causes changes to the whole visitor hierarchy, because new classes require new `visit()` methods in the `Visitor` interface and thus in all the existing visitors
- If this pattern is used with the Composite pattern and the Composite contains a cycle in it, the accept-visit loop might be repeated forever.

# Example

- [github/Visitor](https://github.com/khanhpdt/design-patterns/tree/master/src/main/java/vn/khanhpdt/playgrounds/designpatterns/visitor)

# References

[1] Visitor, [The GOF book](https://amzn.com/0201633612)

[2] Visitor, Chapter 29, [Design Patterns In Java](https://amzn.com/0321333020)


text:
module Graphics.Rendering.OpenGL.Raw.ATI.ElementArray (
  -- * Enums
  gl_ELEMENT_ARRAY_ATI,
  gl_ELEMENT_ARRAY_POINTER_ATI,
  gl_ELEMENT_ARRAY_TYPE_ATI,
  -- * Functions
  glDrawElementArrayATI,
  glDrawRangeElementArrayATI,
  glElementPointerATI
) where

import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions


text:
===========
 aniso8601
===========

----------------------------------
Another ISO 8601 parser for Python
----------------------------------

Features
========
* Pure Python implementation
* Python 3 support
* No extra dependencies
* Logical behavior

 - Parse a time, get a `datetime.time <http://docs.python.org/2/library/datetime.html#datetime.time>`_
 - Parse a date, get a `datetime.date <http://docs.python.org/2/library/datetime.html#datetime.date>`_
 - Parse a datetime, get a `datetime.datetime <http://docs.python.org/2/library/datetime.html#datetime.datetime>`_
 - Parse a duration, get a `datetime.timedelta <http://docs.python.org/2/library/datetime.html#datetime.timedelta>`_
 - Parse an interval, get a tuple of dates or datetimes
 - Parse a repeating interval, get a date or datetime `generator <http://www.python.org/dev/peps/pep-0255/>`_

* UTC offset represented as fixed-offset tzinfo
* No regular expressions

Installation
============

The recommended installation method is to use pip::

  $ pip install aniso8601

Alternatively, you can download the source (git repository hosted at `Bitbucket <https://bitbucket.org/nielsenb/aniso8601>`_) and install directly::

  $ python setup.py install

Use
===

Parsing datetimes
-----------------

To parse a typical ISO 8601 datetime string::

  >>> import aniso8601
  >>> aniso8601.parse_datetime('1977-06-10T12:00:00Z')
  datetime.datetime(1977, 6, 10, 12, 0, tzinfo=+0:00:00 UTC)

Alternative delimiters can be specified, for example, a space::

  >>> aniso8601.parse_datetime('1977-06-10 12:00:00Z', delimiter=' ')
  datetime.datetime(1977, 6, 10, 12, 0, tzinfo=+0:00:00 UTC)

UTC offsets are supported::

  >>> aniso8601.parse_datetime('1979-06-05T08:00:00-08:00')
  datetime.datetime(1979, 6, 5, 8, 0, tzinfo=-8:00:00 UTC)

If a UTC offset is not specified, the returned datetime will be naive::

  >>> aniso8601.parse_datetime('1983-01-22T08:00:00')
  datetime.datetime(1983, 1, 22, 8, 0)

Parsing dates
-------------

To parse a date represented in an ISO 8601 string::

  >>> import aniso8601
  >>> aniso8601.parse_date('1984-04-23')
  datetime.date(1984, 4, 23)

Basic format is supported as well::

  >>> aniso8601.parse_date('19840423')
  datetime.date(1984, 4, 23)

To parse a date using the ISO 8601 week date format::

  >>> aniso8601.parse_date('1986-W38-1')
  datetime.date(1986, 9, 15)

To parse an ISO 8601 ordinal date::

  >>> aniso8601.parse_date('1988-132')
  datetime.date(1988, 5, 11)

Parsing times
-------------

To parse a time formatted as an ISO 8601 string::

  >>> import aniso8601
  >>> aniso8601.parse_time('11:31:14')
  datetime.time(11, 31, 14)

As with all of the above, basic format is supported::

  >>> aniso8601.parse_time('113114')
  datetime.time(11, 31, 14)

A UTC offset can be specified for times::

  >>> aniso8601.parse_time('17:18:19-02:30')
  datetime.time(17, 18, 19, tzinfo=-2:30:00 UTC)
  >>> aniso8601.parse_time('171819Z')
  datetime.time(17, 18, 19, tzinfo=+0:00:00 UTC)

Reduced accuracy is supported::

  >>> aniso8601.parse_time('21:42')
  datetime.time(21, 42)
  >>> aniso8601.parse_time('22')
  datetime.time(22, 0)

A decimal fraction is always allowed on the lowest order element of an ISO 8601 formatted time::

  >>> aniso8601.parse_time('22:33.5')
  datetime.time(22, 33, 30)
  >>> aniso8601.parse_time('23.75')
  datetime.time(23, 45)

Parsing durations
-----------------

To parse a duration formatted as an ISO 8601 string::

  >>> import aniso8601
  >>> aniso8601.parse_duration('P1Y2M3DT4H54M6S')
  datetime.timedelta(428, 17646)

Reduced accuracy is supported::

  >>> aniso8601.parse_duration('P1Y')
  datetime.timedelta(365)

A decimal fraction is allowed on the lowest order element::

  >>> aniso8601.parse_duration('P1YT3.5M')
  datetime.timedelta(365, 210)

The decimal fraction can be specified with a comma instead of a full-stop::

  >>> aniso8601.parse_duration('P1YT3,5M')
  datetime.timedelta(365, 210)

Parsing a duration from a combined date and time is supported as well::

  >>> aniso8601.parse_duration('P0001-01-02T01:30:5')
  datetime.timedelta(397, 5405)

Parsing intervals
-----------------

To parse an interval specified by a start and end::

  >>> import aniso8601
  >>> aniso8601.parse_interval('2007-03-01T13:00:00/2008-05-11T15:30:00')
  (datetime.datetime(2007, 3, 1, 13, 0), datetime.datetime(2008, 5, 11, 15, 30))

Intervals specified by a start time and a duration are supported::

  >>> aniso8601.parse_interval('2007-03-01T13:00:00Z/P1Y2M10DT2H30M')
  (datetime.datetime(2007, 3, 1, 13, 0, tzinfo=+0:00:00 UTC), datetime.datetime(2008, 5, 9, 15, 30, tzinfo=+0:00:00 UTC))

A duration can also be specified by a duration and end time::

  >>> aniso8601.parse_interval('P1M/1981-04-05')
  (datetime.date(1981, 4, 5), datetime.date(1981, 3, 6))

Notice that the result of the above parse is not in order from earliest to latest. If sorted intervals are required, simply use the 'sorted' keyword as shown below::

  >>> sorted(aniso8601.parse_interval('P1M/1981-04-05'))
  [datetime.date(1981, 3, 6), datetime.date(1981, 4, 5)]

The end of an interval is given as a datetime when required to maintain the resolution specified by a duration, even if the duration start is given as a date::

  >>> aniso8601.parse_interval('2014-11-12/PT4H54M6.5S')
  (datetime.date(2014, 11, 12), datetime.datetime(2014, 11, 12, 4, 54, 6, 500000))

Repeating intervals are supported as well, and return a generator::

  >>> aniso8601.parse_repeating_interval('R3/1981-04-05/P1D')
  <generator object date_generator at 0x7f698cdefc80>
  >>> list(aniso8601.parse_repeating_interval('R3/1981-04-05/P1D'))
  [datetime.date(1981, 4, 5), datetime.date(1981, 4, 6), datetime.date(1981, 4, 7)]

Repeating intervals are allowed to go in the reverse direction::

  >>> list(aniso8601.parse_repeating_interval('R2/PT1H2M/1980-03-05T01:01:00'))
  [datetime.datetime(1980, 3, 5, 1, 1), datetime.datetime(1980, 3, 4, 23, 59)]

Unbounded intervals are also allowed (Python 2)::

  >>> result = aniso8601.parse_repeating_interval('R/PT1H2M/1980-03-05T01:01:00')
  >>> result.next()
  datetime.datetime(1980, 3, 5, 1, 1)
  >>> result.next()
  datetime.datetime(1980, 3, 4, 23, 59)

or for Python 3::

  >>> result = aniso8601.parse_repeating_interval('R/PT1H2M/1980-03-05T01:01:00')
  >>> next(result)
  datetime.datetime(1980, 3, 5, 1, 1)
  >>> next(result)
  datetime.datetime(1980, 3, 4, 23, 59)

Note that you should never try to convert a generator produced by an unbounded interval to a list::

  >>> list(aniso8601.parse_repeating_interval('R/PT1H2M/1980-03-05T01:01:00'))
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "aniso8601/__init__.py", line 140, in date_generator_unbounded
      currentdate += timedelta
  OverflowError: date value out of range

Date and time resolution
------------------------

In some situations, it may be useful to figure out the resolution provided by an ISO 8601 date or time string. Two functions are provided for this purpose.

To get the resolution of a ISO 8601 time string::

  >>> aniso8601.get_time_resolution('11:31:14') == aniso8601.resolution.TimeResolution.Seconds
  True
  >>> aniso8601.get_time_resolution('11:31') == aniso8601.resolution.TimeResolution.Minutes
  True
  >>> aniso8601.get_time_resolution('11') == aniso8601.resolution.TimeResolution.Hours
  True

Similarly, for an ISO 8601 date string::

  >>> aniso8601.get_date_resolution('1981-04-05') == aniso8601.resolution.DateResolution.Day
  True
  >>> aniso8601.get_date_resolution('1981-04') == aniso8601.resolution.DateResolution.Month
  True
  >>> aniso8601.get_date_resolution('1981') == aniso8601.resolution.DateResolution.Year
  True

Tests
=====

To run the unit tests, in your source checkout, navigate to the source directory for the Python version being worked on (python2, python3) and type::

   $ python -m unittest discover aniso8601/tests/

Contributing
============

aniso8601 is an open source project hosted on `Bitbucket <https://bitbucket.org/nielsenb/aniso8601>`_.

Any and all bugs are welcome on our `issue tracker <https://bitbucket.org/nielsenb/aniso8601/issues>`_.
Of particular interest are valid ISO 8601 strings that don't parse, or invalid ones that do. At a minimum,
bug reports should include an example of the misbehaving string, as well as the expected result. Of course
patches containing unit tests (or fixed bugs) are welcome!

References
==========

* `ISO 8601:2004(E) <http://dotat.at/tmp/ISO_8601-2004_E.pdf>`_ (Caution, PDF link)
* `Wikipedia article on ISO 8601 <http://en.wikipedia.org/wiki/Iso8601>`_
* `Discussion on alternative ISO 8601 parsers for Python <https://groups.google.com/forum/#!topic/comp.lang.python/Q2w4R89Nq1w>`_


text:
set -ev

echo "TRAVIS_BRANCH: <$TRAVIS_BRANCH> - TRAVIS_TAG: <$TRAVIS_TAG>"

#Download dependencies
mvn -q help:evaluate -Dexpression=project.version --settings settings.xml
# Capture execution of maven command - It looks like grep cannot be used like this on travis
export VERSION_SNAPSHOT=$(mvn help:evaluate -Dexpression=project.version --settings settings.xml |grep '^[0-9].*')

echo "Current version extracted from pom.xml: $VERSION_SNAPSHOT"
export VERSION_PREFIX=$(expr "$VERSION_SNAPSHOT" : "\(.*\)-SNAP.*")

git config --global user.email "you@example.com"
git config --global user.name "Your Name"

if [ "${TRAVIS_PULL_REQUEST}" = "false" -a "$TRAVIS_BRANCH" = "master" ]
then
	#We are on master without PR
	export RELEASE_CANDIDATE_VERSION=$VERSION_PREFIX

	echo "Release candidate version: $RELEASE_CANDIDATE_VERSION"

	echo "Setting new version - (old: $VERSION_SNAPSHOT)"

	#Download dependencies
	mvn -q release:help --settings settings.xml
    mvn --batch-mode -e release:prepare release:perform --settings settings.xml

	##echo $RELEASE_CANDIDATE_VERSION > RELEASE_CANDIDATE_VERSION
else
	mvn -q install:help --settings settings.xml
	mvn install --settings settings.xml
fi


text:
<?php
 interface HTTP_OAuth_Store_Consumer_Interface
 {
     public function setRequestToken($token, $tokenSecret, $providerName, $sessionID);
     public function getRequestToken($providerName, $sessionID);
     public function getAccessToken($consumerUserID, $providerName);
     public function setAccessToken(HTTP_OAuth_Store_Data $data);
     public function removeAccessToken(HTTP_OAuth_Store_Data $data);
 }


text:
package com.it5z.resinteractprotect.managers;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.plugin.java.JavaPlugin;

public class MessageManager {
	private String prefix;
	private ConsoleCommandSender console;

	public MessageManager(ManagerBase plugin) {
		prefix = ((JavaPlugin)plugin).getDescription().getPrefix();
		console = Bukkit.getConsoleSender();
	}

	public void sendMessage(String string, CommandSender sender) {
		sender.sendMessage(ChatColor.AQUA + "[" + prefix + "] " + ChatColor.RESET + string);
	}

	public void sendConsoleMessage(String string) {
		console.sendMessage(ChatColor.AQUA + "[" + prefix + "] " + ChatColor.RESET + string);
	}
}


text:
import {RuleFailure} from 'tslint/lib/lint';
import {AbstractRule} from 'tslint/lib/rules';
import {RuleWalker} from 'tslint/lib/language/walker';
import * as ts from 'tslint/node_modules/typescript';

export class Rule extends AbstractRule {
  public static FAILURE_STRING = "missing type declaration";

  public apply(sourceFile: ts.SourceFile): RuleFailure[] {
    const typedefWalker = new TypedefWalker(sourceFile, this.getOptions());
    return this.applyWithWalker(typedefWalker);
  }
}

class TypedefWalker extends RuleWalker {
  hasReturnStatement: boolean;

  public visitFunctionDeclaration(node: ts.FunctionDeclaration) {
    this.hasReturnStatement = false;
    super.visitFunctionDeclaration(node);
    if (this.hasReturnStatement) {
      this.handleCallSignature(node);
    }
  }
  public visitFunctionExpression(node: ts.FunctionExpression) {
    let orig = this.hasReturnStatement;
    super.visitFunctionExpression(node);
    this.hasReturnStatement = orig;
  }
  public visitMethodDeclaration(node: ts.MethodDeclaration) {
    this.hasReturnStatement = false;
    super.visitMethodDeclaration(node);
    if (this.hasReturnStatement) {
      this.handleCallSignature(node);
    }
  }
  public visitReturnStatement(node: ts.ReturnStatement) {
    if (node.expression) {
      this.hasReturnStatement = true;
    }
    super.visitReturnStatement(node);
  }

  private handleCallSignature(node: ts.SignatureDeclaration) {
    // set accessors can't have a return type.
    if (node.kind !== ts.SyntaxKind.SetAccessor) {
      this.checkTypeAnnotation(node.type, node.name);
    }
  }

  private checkTypeAnnotation(typeAnnotation: ts.TypeNode, name?: ts.Node) {
    if (typeAnnotation == null) {
      let ns = "<name missing>";
      if (name != null && name.kind === ts.SyntaxKind.Identifier) {
        ns = (<ts.Identifier>name).text;
      }
      if (ns.charAt(0) === '_') return;
      let failure = this.createFailure(null, 1, "expected " + ns + " to have a return type");
      this.addFailure(failure);
    }
  }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Lousada</logradouro><bairro>Sé</bairro><cidade>São Paulo</cidade><uf>SP</uf><cep>01020040</cep></feed>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fantastock;

import javax.swing.JList;

/**
 *
 * @author Josh
 */
public class MyLeagues extends javax.swing.JFrame {

    LeagueHandler lh = new LeagueHandler();
    /**
     * Creates new form MyLeagues
     */
    public MyLeagues() {
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        currentLabel = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new JList(lh.getLeagues().toArray());

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        currentLabel.setText("Current Leagues:");

        jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jList1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(currentLabel)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 294, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(63, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(74, 74, 74)
                .addComponent(currentLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(71, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MyLeagues.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MyLeagues.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MyLeagues.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MyLeagues.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MyLeagues().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel currentLabel;
    private javax.swing.JList<String> jList1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}


text:
<?xml version="1.0"?>
<doc>
  <filename>level1/level2/xreluri10b.xml</filename>
  <!-- The above file is the WRONG one, placed here as a trap. -->
  <body>Mowing the lawn, wishing I had the right node-set.</body>
</doc>


text:
@interface HRRestModel (PrivateMethods)
+ (void)setAttributeValue:(id)attr forKey:(NSString *)key;
+ (NSMutableDictionary *)classAttributes;
+ (NSMutableDictionary *)mergedOptions:(NSDictionary *)options;
+ (NSOperation *)requestWithMethod:(HRRequestMethod)method path:(NSString *)path options:(NSDictionary *)options object:(id)obj;
@end

@implementation HRRestModel
static NSMutableDictionary *attributes;
+ (void)initialize {
    if(!attributes)
        attributes = [NSMutableDictionary new];
}

////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Class Attributes

// Given that we want to allow classes to define default attributes we need to create
// a classname-based dictionary store that maps a subclass name to a dictionary
// containing its attributes.
+ (NSMutableDictionary *)classAttributes {
    NSString *className = NSStringFromClass([self class]);

    NSMutableDictionary *newDict;
    NSMutableDictionary *dict = [attributes objectForKey:className];

    if(dict) {
        return dict;
    } else {
        newDict = [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:HRDataFormatJSON] forKey:@"format"];
        [attributes setObject:newDict forKey:className];
    }

    return newDict;
}

+ (NSObject *)delegate {
   return [[self classAttributes] objectForKey:kHRClassAttributesDelegateKey];
}

+ (void)setDelegate:(NSObject *)del {
    [self setAttributeValue:del forKey:kHRClassAttributesDelegateKey];
}

+ (NSURL *)baseURL {
   return [[self classAttributes] objectForKey:kHRClassAttributesBaseURLKey];
}

+ (void)setBaseURL:(NSURL *)uri {
    [self setAttributeValue:uri forKey:kHRClassAttributesBaseURLKey];
}

+ (NSDictionary *)headers {
    return [[self classAttributes] objectForKey:kHRClassAttributesHeadersKey];
}

+ (void)setHeaders:(NSDictionary *)hdrs {
    [self setAttributeValue:hdrs forKey:kHRClassAttributesHeadersKey];
}

+ (NSDictionary *)basicAuth {
    return [[self classAttributes] objectForKey:kHRClassAttributesBasicAuthKey];
}

+ (void)setBasicAuthWithUsername:(NSString *)username password:(NSString *)password {
    NSDictionary *authDict = [NSDictionary dictionaryWithObjectsAndKeys:username, kHRClassAttributesUsernameKey, password, kHRClassAttributesPasswordKey, nil];
    [self setAttributeValue:authDict forKey:kHRClassAttributesBasicAuthKey];
}

+ (HRDataFormat)format {
    return [[[self classAttributes] objectForKey:kHRClassAttributesFormatKey] intValue];
}

+ (void)setFormat:(HRDataFormat)format {
    [[self classAttributes] setValue:[NSNumber numberWithInt:format] forKey:kHRClassAttributesFormatKey];
}

+ (NSDictionary *)defaultParams {
    return [[self classAttributes] objectForKey:kHRClassAttributesDefaultParamsKey];
}

+ (void)setDefaultParams:(NSDictionary *)params {
    [self setAttributeValue:params forKey:kHRClassAttributesDefaultParamsKey];
}

+ (void)setAttributeValue:(id)attr forKey:(NSString *)key {
    [[self classAttributes] setObject:attr forKey:key];
}

////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - REST Methods

+ (NSOperation *)getPath:(NSString *)path withOptions:(NSDictionary *)options object:(id)obj {
    return [self requestWithMethod:HRRequestMethodGet path:path options:options object:obj];
}

+ (NSOperation *)postPath:(NSString *)path withOptions:(NSDictionary *)options object:(id)obj {
    return [self requestWithMethod:HRRequestMethodPost path:path options:options object:obj];
}

+ (NSOperation *)putPath:(NSString *)path withOptions:(NSDictionary *)options object:(id)obj {
    return [self requestWithMethod:HRRequestMethodPut path:path options:options object:obj];
}

+ (NSOperation *)deletePath:(NSString *)path withOptions:(NSDictionary *)options object:(id)obj {
    return [self requestWithMethod:HRRequestMethodDelete path:path options:options object:obj];
}

////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark - Private

+ (NSOperation *)requestWithMethod:(HRRequestMethod)method path:(NSString *)path options:(NSDictionary *)options object:(id)obj {
    NSMutableDictionary *opts = [self mergedOptions:options];
    return [HRRequestOperation requestWithMethod:method path:path options:opts object:obj];
}

+ (NSMutableDictionary *)mergedOptions:(NSDictionary *)options {
    NSMutableDictionary *defaultParams = [NSMutableDictionary dictionaryWithDictionary:[self defaultParams]];
    [defaultParams addEntriesFromDictionary:[options valueForKey:kHRClassAttributesParamsKey]];

    options = [NSMutableDictionary dictionaryWithDictionary:options];
    [(NSMutableDictionary *)options setObject:defaultParams forKey:kHRClassAttributesParamsKey];
    NSMutableDictionary *opts = [NSMutableDictionary dictionaryWithDictionary:[self classAttributes]];
    [opts addEntriesFromDictionary:options];
    [opts removeObjectForKey:kHRClassAttributesDefaultParamsKey];

    return opts;
}
@end


text:
$(document).ready(function() {

	// Bind help popovers
	$('input, select, textarea').popover({
		placement: 'right',
		trigger: 'focus',
		container: 'body'
	});

	$('#new-route-type-form').on('submit', function (evt) {

		evt.preventDefault();

		var data = GtfsEditor.Utils.serializeForm($(evt.target));

		var routeType = new GtfsEditor.RouteType();

		routeType.save(data, {error: function(){

			$('#route-type-modal').modal('hide');
			G.Utils.error('Route type save failed');

		},
		success: function(){

			$('#route-type-modal').modal('hide');
			//G.Utils.error('Route type save failed');
			location.reload();

		}});

	});

});


text:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen android:title="@string/print_settings_title" settings:keywords="@string/keywords_printing"
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:settings="http://schemas.android.com/apk/res/com.android.settings">
    <PreferenceCategory android:title="@string/print_print_jobs" android:key="print_jobs_category" android:order="0" />
    <PreferenceCategory android:title="@string/print_settings_title" android:key="print_services_category" android:order="1" />
</PreferenceScreen>


text:
using System;
using System.Linq;
using System.Collections.Generic;

using numl.Data;
using numl.Math.LinearAlgebra;
using numl.Math.Functions;
using numl.Model;
using numl.Math.Functions.Loss;
using numl.Supervised.NeuralNetwork.Optimization;

namespace numl.Supervised.NeuralNetwork
{
    /// A network.
    public partial class Network : Data.Graph
    {
        /// Gets or sets the in.
        /// <value>The in.</value>
        public Neuron[] In { get; set; }

        /// Gets or sets the out.
        /// <value>The out.</value>
        public Neuron[] Out { get; set; }

        ///
        /// Gets or sets the output function (optional).
        ///
        public IFunction OutputFunction { get; set; }

        ///
        /// Gets or sets the network loss function.
        ///
        public ILossFunction LossFunction { get; set; } = new L2Loss();

        ///
        /// Gets or sets the current loss of the network.
        ///
        public double Cost { get; set; } = 0d;

        ///
        /// Returns the number of layers in the network.
        ///
        public int Layers
        {
            get
            {
                return this.GetVertices().OfType<Neuron>()
                                         .Select(s => s.LayerId).Distinct().Count();
            }
        }

        ///
        /// Returns a new Network instance.
        ///
        public static Network New()
        {
            return new Network();
        }

        /// Gets a label.
        /// <param name="n">The Node to process.</param>
        /// <param name="d">The Descriptor to process.</param>
        /// <returns>The label.</returns>
        internal static string GetLabel(int n, Descriptor d)
        {
            var label = "";
            try { label = Enum.GetName(d.Label.Type, n); }
            // TODO: fix cheesy way of getting around IsEnum
            catch
            {
                if (d.Label is StringProperty && ((StringProperty)d.Label).AsEnum)
                    label = ((StringProperty)d.Label).Dictionary[n];
                else label = d.Label.Name;
            }

            return label;
        }

        #region Computation

        /// Forwards the given x coordinate.
        /// <exception cref="InvalidOperationException">Thrown when the requested operation is invalid.</exception>
        /// <param name="x">The Vector to process.</param>
        public void Forward(Vector x)
        {
            if (In.Length != x.Length + 1)
                throw new InvalidOperationException("Input nodes not aligned to input vector");

            // this should forward the input through the network
            // from the input nodes through the layers to the output layer

            // set input (with bias inputs)
            for (int i = 0; i < In.Length; i++)
                In[i].Input = (i == 0 ? 1.0 : x[i - 1]);
            // evaluate
            for (int i = 0; i < Out.Length; i++)
                Out[i].Evaluate();
        }

        /// Backpropagates the errors through the network given the supplied label.
        /// <param name="y">Label to process.</param>
        /// <param name="properties">Network training properties for use in learning.</param>
        /// <param name="networkTrainer">Network training method.</param>
        public void Back(double y, NetworkTrainingProperties properties, INetworkTrainer networkTrainer)
        {
            this.Back(Vector.Create(this.Out.Length, () => y), properties, networkTrainer);
        }

        /// Backpropagates the errors through the network given the supplied sequence label.
        /// <param name="y">Output vector to process.</param>
        /// <param name="properties">Network training properties for use in learning.</param>
        /// <param name="networkTrainer">Network training method.</param>
        /// <param name="update">Indicates whether to update the weights after computing the errors.</param>
        public void Back(Vector y, NetworkTrainingProperties properties, INetworkTrainer networkTrainer, bool update = true)
        {
            this.Cost = this.LossFunction.Compute(this.Output(), y);

            // CK
            // propagate error gradients
            for (int i = 0; i < Out.Length; i++)
                Out[i].Error(y[i], properties);

            if (update)
            {
                // reset weights
                for (int i = 0; i < Out.Length; i++)
                    Out[i].Update(properties, networkTrainer);
            }
        }

        ///
        /// Returns the predicted output sequence from the Network after forwarding.
        ///
        /// <param name="network">Current network.</param>
        /// <returns>Vector.</returns>
        public Vector Output()
        {
            Vector output = this.Out.Select(n => n.Output).ToVector();
            output = (this.OutputFunction != null ? this.OutputFunction.Compute(output) : output);
            return output;
        }

        ///
        /// Resets the neurons in the entire graph (see <see cref="Neuron.Reset(NetworkTrainingProperties)"/>).
        ///
        /// <param name="properties">Network training properties object.</param>
        public void ResetStates(NetworkTrainingProperties properties)
        {
            foreach (var node in this.GetVertices().OfType<Neuron>())
            {
                node.Reset(properties);
            }
        }

        #endregion

        #region Graph

        ///
        /// Adds the Neuron to the underlying graph.
        ///
        /// <param name="node">Neuron to add.</param>
        /// <returns></returns>
        public Neuron AddNode(Neuron node)
        {
            base.AddVertex(node);

            return node;
        }

        ///
        /// Removes the specified node from the network, including any connections.
        ///
        /// <param name="node">Neuron to remove from the network.</param>
        public void RemoveNode(Neuron node)
        {
            // remove this node from parent edges
            for (int i = 0; i < node.In.Count; i++)
            {
                Neuron inode = node.In.ElementAt(i).Source;
                for (int j = inode.Out.Count - 1; j >= 0; j--)
                {
                    if (inode.Out.ElementAt(j).Target == node)
                    {
                        inode.Out.RemoveAt(j);
                    }
                }
            }

            // remove this node from child edges
            for (int j = 0; j < node.Out.Count; j++)
            {
                Neuron onode = node.Out.ElementAt(j).Target;
                for (int i = onode.In.Count - 1; i >= 0; i--)
                {
                    if (onode.In.ElementAt(i).Source == node)
                    {
                        onode.In.RemoveAt(i);
                    }
                }
            }

            node.In?.Clear();
            node.Out?.Clear();

            base.RemoveVertex(node);
        }

        ///
        /// Adds the Edge to the underlying graph.
        ///
        /// <param name="edge">Edge to add.</param>
        /// <returns></returns>
        public Edge AddEdge(Edge edge)
        {
            base.AddEdge(edge);

            return edge;
        }

        #endregion

        ///
        /// Returns the Nodes from the specified layer, where 0 is the Input layer.
        ///
        /// <param name="layer">The layer index to retrieve Nodes from.</param>
        /// <returns></returns>
        public IEnumerable<Neuron> GetNodes(int layer)
        {
            return GetVertices().OfType<Neuron>().Where(n => n.LayerId == layer).ToArray();
        }
    }
}


text:
class Person {
    constructor(name) {
        this._name = name;
    }

    get name() {
        return this._name;
    }

    set name(name) {
        this._name = name;
    }

    resetName() {
        this.name = 'Opa';
    }
}

class Programmer extends Person {
    constructor(name, language) {
        super(name);
        this.language = language;
    }
/*
    resetName(hugo) {
        this.name = hugo;
    }
*/

    resetName() {
        super.resetName();
        this.name = "Mr. " + this.name;
    }

    code() {
        return this.name + " codes in " + this.language;
    }
}

const programmer = new Programmer('Erna', 'JavaScript');
console.log(programmer.code());
console.log(programmer instanceof Programmer); // true
console.log(programmer instanceof Person); // true

programmer.resetName();
console.log(programmer.code());


text:
#pragma once

#include <kitBase/robotModel/robotModelInterface.h>
#include <kitBase/robotModel/configuration.h>
#include <utils/timelineInterface.h>

#include <gmock/gmock.h>

namespace qrTest {

typedef QHash<QString, int> StringIntHash;

class RobotModelInterfaceMock : public kitBase::robotModel::RobotModelInterface
{
	Q_OBJECT

public:
	MOCK_CONST_METHOD0(robotId, QString());
	MOCK_CONST_METHOD0(name, QString());
	MOCK_CONST_METHOD0(friendlyName, QString());
	MOCK_CONST_METHOD0(kitId, QString());
	MOCK_CONST_METHOD0(priority, int());
	MOCK_CONST_METHOD0(interpretedModel, bool());

	MOCK_METHOD0(init, void());

	MOCK_METHOD0(connectToRobot, void());
	MOCK_METHOD0(stopRobot, void());
	MOCK_METHOD0(disconnectFromRobot, void());

	MOCK_CONST_METHOD0(connectionState, ConnectionState());

	MOCK_CONST_METHOD0(needsConnection, bool());

	MOCK_CONST_METHOD0(configuration
			, kitBase::robotModel::ConfigurationInterface const &());
	MOCK_METHOD0(mutableConfiguration,  kitBase::robotModel::ConfigurationInterface&());

	MOCK_CONST_METHOD0(availablePorts, QList< kitBase::robotModel::PortInfo>());
	MOCK_CONST_METHOD0(buttonCodes, StringIntHash());
	MOCK_CONST_METHOD0(configurablePorts, QList< kitBase::robotModel::PortInfo>());
	MOCK_CONST_METHOD1(allowedDevices, QList< kitBase::robotModel::DeviceInfo>(
			kitBase::robotModel::PortInfo const &port));

	MOCK_METHOD2(configureDevice, void( kitBase::robotModel::PortInfo const & port
			, kitBase::robotModel::DeviceInfo const &deviceInfo));

	MOCK_METHOD0(applyConfiguration, void());

	MOCK_CONST_METHOD0(convertibleBases, QList< kitBase::robotModel::DeviceInfo>());

	MOCK_METHOD0(timeline, utils::TimelineInterface &());

	MOCK_METHOD0(onInterpretationStarted, void());
};

}


text:
<!DOCTYPE html>

        <meta charset="utf-8" />

        <meta name="viewport" content="width=device-width" />
        <title>Verizon Wireless | Special Offers Landing</title>

        <link rel="stylesheet" href="css/styles.css">


text:
#include "hilbert_order.h"
#include "tiledb/common/common.h"
#include "tiledb/sm/array_schema/dimension.h"
#include "tiledb/sm/query/query_buffer.h"
#include "tiledb/sm/query/readers/result_coords.h"

namespace tiledb::sm::hilbert_order {

uint64_t map_to_uint64(
    const Dimension& dim,
    const QueryBuffer* buff,
    uint64_t c,
    int bits,
    uint64_t max_bucket_val) {
  auto d{buff->dimension_datum_at(dim, c)};
  return dim.map_to_uint64(
      d.datum().content(), d.datum().size(), bits, max_bucket_val);
}

template <class RCType>
uint64_t map_to_uint64(
    const Dimension& dim,
    const RCType& coord,
    uint32_t dim_idx,
    int bits,
    uint64_t max_bucket_val) {
  auto d{coord.dimension_datum(dim, dim_idx)};
  return dim.map_to_uint64(d.content(), d.size(), bits, max_bucket_val);
}

template uint64_t map_to_uint64<GlobalOrderResultCoords<uint8_t>>(
    const Dimension&,
    const GlobalOrderResultCoords<uint8_t>&,
    uint32_t,
    int,
    uint64_t);
template uint64_t map_to_uint64<GlobalOrderResultCoords<uint64_t>>(
    const Dimension&,
    const GlobalOrderResultCoords<uint64_t>&,
    uint32_t,
    int,
    uint64_t);
template uint64_t map_to_uint64<ResultCoords>(
    const Dimension&, const ResultCoords&, uint32_t, int, uint64_t);

}  // namespace tiledb::sm::hilbert_order


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.messaging.eventhubs;

import com.azure.core.amqp.models.AmqpAddress;
import com.azure.core.amqp.models.AmqpAnnotatedMessage;
import com.azure.core.amqp.models.AmqpMessageBody;
import com.azure.core.amqp.models.AmqpMessageHeader;
import com.azure.core.amqp.models.AmqpMessageId;
import com.azure.core.amqp.models.AmqpMessageProperties;
import com.azure.messaging.eventhubs.implementation.MessageUtils;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.messaging.ApplicationProperties;
import org.apache.qpid.proton.amqp.messaging.Data;
import org.apache.qpid.proton.amqp.messaging.DeliveryAnnotations;
import org.apache.qpid.proton.amqp.messaging.Header;
import org.apache.qpid.proton.amqp.messaging.MessageAnnotations;
import org.apache.qpid.proton.amqp.messaging.Properties;
import org.apache.qpid.proton.amqp.messaging.Section;
import org.apache.qpid.proton.message.Message;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Tests {@link MessageUtils}.
 */
public class MessageUtilsTest {
    private static final String MESSAGE = "My-message";
    private static final byte[] MESSAGE_BYTES = MESSAGE.getBytes(StandardCharsets.UTF_8);

    private AmqpAnnotatedMessage expected;

    @BeforeEach
    public void beforeEach() {
        final AmqpMessageBody messageBody = AmqpMessageBody.fromData(MESSAGE_BYTES);
        expected = new AmqpAnnotatedMessage(messageBody);
        expected.getApplicationProperties().put("app1", true);
        expected.getDeliveryAnnotations().put("delivery", false);
        expected.getFooter().put("footer1", 10);
        expected.getFooter().put("footer2", "bars");
        expected.getFooter().put("footer3", "zoom");
        expected.getMessageAnnotations().put("foo", "bar");
        expected.getMessageAnnotations().put("baz", 1L);

        expected.getHeader()
            .setTimeToLive(Duration.ofSeconds(830))
            .setPriority((short) 12)
            .setDurable(true)
            .setFirstAcquirer(false)
            .setDeliveryCount(19L);

        final Instant expiryTime = Instant.ofEpochSecond(1925644760L);
        final Instant creationTime = Instant.ofEpochSecond(1825644760L);
        expected.getProperties()
            .setTo(new AmqpAddress("my-to-address"))
            .setMessageId(new AmqpMessageId("message-ids"))
            .setUserId("user-id-foo".getBytes(StandardCharsets.UTF_8))
            .setAbsoluteExpiryTime(expiryTime.atOffset(ZoneOffset.UTC))
            .setCreationTime(creationTime.atOffset(ZoneOffset.UTC))
            .setReplyTo(new AmqpAddress("reply-to-address"))
            .setReplyToGroupId("reply-to-group")
            .setContentType("my-content")
            .setContentEncoding("my-encoding")
            .setSubject("my-new-subject")
            .setGroupSequence(353L)
            .setGroupId("groups-id2")
            .setCorrelationId(new AmqpMessageId("my-correlation"));
    }

    /**
     * Tests that a message can be converted.
     */
    @Test
    public void toProtonJMessage() {
        // Act
        final Message actual = MessageUtils.toProtonJMessage(expected);

        // Assert
        assertNotNull(actual);

        assertBody(actual);
        assertApplicationAnnotations(actual);
        assertDeliveryAnnotations(actual);
        assertMessageAnnotations(actual);
        assertHeader(actual);
        assertProperties(actual);
    }

    /**
     * Verifies that application properties is null when there are none set.
     */
    @Test
    public void toProtonJMessageNoApplicationProperties() {
        // Arrange
        expected.getApplicationProperties().clear();

        // Act
        final Message actual = MessageUtils.toProtonJMessage(expected);

        // Assert
        assertNotNull(actual);

        assertBody(actual);

        assertNull(actual.getApplicationProperties());
        assertDeliveryAnnotations(actual);
        assertMessageAnnotations(actual);
        assertHeader(actual);
        assertProperties(actual);
    }

    /**
     * Verifies that application properties is null when there are none set.
     */
    @Test
    public void toProtonJMessageNoDeliveryAnnotations() {
        // Arrange
        expected.getDeliveryAnnotations().clear();

        // Act
        final Message actual = MessageUtils.toProtonJMessage(expected);

        // Assert
        assertNotNull(actual);

        assertBody(actual);
        assertApplicationAnnotations(actual);
        assertNull(actual.getDeliveryAnnotations());
        assertMessageAnnotations(actual);
        assertHeader(actual);
        assertProperties(actual);
    }

    /**
     * Message annotations are null when not set.
     */
    @Test
    public void toProtonJMessageNoMessageAnnotations() {
        // Arrange
        expected.getMessageAnnotations().clear();

        // Act
        final Message actual = MessageUtils.toProtonJMessage(expected);

        // Assert
        assertNotNull(actual);

        assertBody(actual);
        assertApplicationAnnotations(actual);
        assertDeliveryAnnotations(actual);
        assertNull(actual.getMessageAnnotations());
        assertHeader(actual);
        assertProperties(actual);
    }

    /**
     * Tests that a message can be converted with no header properties set.
     */
    @Test
    public void toProtonJMessageNoHeaderPropertiesSet() {
        // Arrange
        expected.getHeader()
            .setDurable(null)
            .setPriority(null)
            .setDeliveryCount(null)
            .setDeliveryCount(null)
            .setTimeToLive(null);

        // Act
        final Message actual = MessageUtils.toProtonJMessage(expected);

        // Assert
        assertNotNull(actual);

        assertBody(actual);
        assertApplicationAnnotations(actual);
        assertDeliveryAnnotations(actual);
        assertMessageAnnotations(actual);
        assertNull(actual.getHeader());
        assertProperties(actual);
    }

    private void assertBody(Message actual) {
        final Section body = actual.getBody();
        assertTrue(body instanceof Data);
        assertArrayEquals(MESSAGE_BYTES, ((Data) body).getValue().getArray());
    }

    private void assertApplicationAnnotations(Message actual) {
        final ApplicationProperties applicationProperties = actual.getApplicationProperties();
        assertNotNull(applicationProperties);
        assertNotNull(applicationProperties.getValue());
        assertEquals(expected.getApplicationProperties().size(), applicationProperties.getValue().size());

        assertEquals(expected.getApplicationProperties().size(), applicationProperties.getValue().size());
        expected.getApplicationProperties().forEach(
            (key, value) -> assertEquals(value, applicationProperties.getValue().get(key)));
    }

    private void assertDeliveryAnnotations(Message actual) {
        final DeliveryAnnotations deliveryAnnotations = actual.getDeliveryAnnotations();
        assertNotNull(deliveryAnnotations);
        assertNotNull(deliveryAnnotations.getValue());
        assertMapSymbol(expected.getDeliveryAnnotations(), deliveryAnnotations.getValue());
    }

    private void assertMessageAnnotations(Message actual) {
        final MessageAnnotations messageAnnotations = actual.getMessageAnnotations();
        assertNotNull(messageAnnotations);
        assertNotNull(messageAnnotations.getValue());
        assertMapSymbol(expected.getMessageAnnotations(), messageAnnotations.getValue());
    }

    /**
     * Asserts the header.
     *
     * @param actual The actual message.
     */
    private void assertHeader(Message actual) {
        final Header header = actual.getHeader();
        final AmqpMessageHeader expectedHeader = expected.getHeader();
        assertNotNull(header);

        assertEquals(expectedHeader.isDurable(), header.getDurable());
        assertEquals(expectedHeader.isFirstAcquirer(), header.getFirstAcquirer());

        assertNotNull(header.getDeliveryCount());
        assertEquals(expectedHeader.getDeliveryCount(), header.getDeliveryCount().longValue());

        assertNotNull(header.getPriority());
        assertEquals(expectedHeader.getPriority(), header.getPriority().shortValue());
        assertEquals(expectedHeader.getTimeToLive().toMillis(), header.getTtl().longValue());
    }

    /**
     * Assert properties.
     *
     * @param actual Assert properties.
     */
    private void assertProperties(Message actual) {
        final Properties actualProperties = actual.getProperties();
        final AmqpMessageProperties expectedProperties = expected.getProperties();
        assertEquals(expectedProperties.getTo().toString(), actualProperties.getTo());
        assertEquals(expectedProperties.getMessageId().toString(), actualProperties.getMessageId());

        assertNotNull(actualProperties.getUserId());
        assertArrayEquals(expectedProperties.getUserId(), actualProperties.getUserId().getArray());

        final Instant expectedAbsoluteInstant = expectedProperties.getAbsoluteExpiryTime().toInstant();
        assertEquals(expectedAbsoluteInstant.toEpochMilli(), actual.getExpiryTime());
        assertEquals(expectedAbsoluteInstant, actualProperties.getAbsoluteExpiryTime().toInstant());

        final Instant expectedCreationInstant = expectedProperties.getCreationTime().toInstant();
        assertEquals(expectedCreationInstant.toEpochMilli(), actual.getCreationTime());
        assertEquals(expectedCreationInstant, actualProperties.getCreationTime().toInstant());

        assertEquals(expectedProperties.getReplyTo().toString(), actualProperties.getReplyTo());
        assertEquals(expectedProperties.getReplyToGroupId(), actualProperties.getReplyToGroupId());

        assertNotNull(actualProperties.getContentType());
        assertEquals(expectedProperties.getContentType(), actualProperties.getContentType().toString());

        assertNotNull(actualProperties.getContentEncoding());
        assertEquals(expectedProperties.getContentEncoding(), actualProperties.getContentEncoding().toString());

        assertEquals(expectedProperties.getSubject(), actualProperties.getSubject());

        assertNotNull(actualProperties.getGroupSequence());
        assertEquals(expectedProperties.getGroupSequence(), actualProperties.getGroupSequence().longValue());

        assertEquals(expectedProperties.getGroupId(), actualProperties.getGroupId());

        assertEquals(expectedProperties.getCorrelationId().toString(), actualProperties.getCorrelationId());
    }

    private static void assertMapSymbol(Map<String, Object> expected, Map<Symbol, Object> actual) {
        assertEquals(expected.size(), actual.size());

        expected.forEach((key, value) -> {
            final Symbol symbol = Symbol.valueOf(key);
            assertEquals(value, actual.get(symbol));
        });
    }
}


text:
package natscrypto

import (
	"fmt"
	"reflect"
	"testing"
	"time"

	"github.com/nats-io/nats"
	"github.com/stretchr/testify/assert"
)

var argInfoTests = []struct {
	cb              nats.Handler
	expectedType    reflect.Type
	expectedNumArgs int
	panics          bool
}{
	{
		cb:              (func(string, *Msg) {}),
		expectedType:    reflect.TypeOf(&Msg{}),
		expectedNumArgs: 2,
	},
	{
		cb:              (func(*Msg) {}),
		expectedType:    reflect.TypeOf(&Msg{}),
		expectedNumArgs: 1,
	},
	{
		cb:              (func() {}),
		expectedType:    nil,
		expectedNumArgs: 0,
	},
	{
		cb:     0,
		panics: true,
	},
}

func TestArgInfo(t *testing.T) {
	for _, tt := range argInfoTests {
		if tt.panics {
			assert.Panics(t, func() { argInfo(tt.cb) })
		} else {
			typ, numArgs := argInfo(tt.cb)
			assert.Equal(t, tt.expectedType, typ)
			assert.Equal(t, tt.expectedNumArgs, numArgs)
		}
	}
}

func TestEncodedConnConstructor(t *testing.T) {
	natsSrv := InitNatsTestServer(t)
	defer natsSrv.Shutdown()

	c := natsSrv.Connect(t)
	if c == nil {
		return
	}
	defer c.Close()

	ec, err := NewConn(c, "me", DummyEncrypter{})
	if err != nil {
		t.Errorf("Could not init the encrypted conn: %s", err)
		c.Close()
		return
	}
	ec.SetSubjectRecipients("test", []string{"riri", "fifi", "loulou"})

	_, err = NewEncodedConn(nil, "json")
	assert.Equal(t, ErrNilConnection, err)

	_, err = NewEncodedConn(ec, "unknown")
	assert.Equal(t, "natscrypto: No encoder registered for 'unknown'", err.Error())

	ec.CloseAll()
	_, err = NewEncodedConn(ec, "json")
	assert.Equal(t, nats.ErrConnectionClosed, err)

}

func TestEncodedConn(t *testing.T) {
	natsSrv := InitNatsTestServer(t)
	defer natsSrv.Shutdown()

	c := natsSrv.Connect(t)
	if c == nil {
		return
	}

	ec, err := NewConn(c, "me", DummyEncrypter{})
	if err != nil {
		t.Errorf("Could not init the encrypted conn: %s", err)
		c.Close()
		return
	}
	ec.SetSubjectRecipients("test", []string{"riri", "fifi", "loulou"})

	enc, err := NewEncodedConn(ec, "json")
	if err != nil {
		t.Errorf("Could not init the encoded conn: %s", err)
		ec.Close()
		return
	}
	defer enc.CloseAll()

	Run(t, "SubscribeSync", func(t *testing.T) {
		s, err := enc.SubscribeSync("test")
		assert.Nil(t, err)
		defer s.Unsubscribe()

		{
			question := QuestionMsg{Text: "A question", Integer: 12}
			assert.Nil(t, enc.Publish("test", &question))
			question.Text = "Another"
			assert.Nil(t, enc.Publish("test", &question))
			question.Integer = 42
			assert.Nil(t, enc.PublishRequest("test", "zereply", &question))
		}

		{
			var (
				subject  string
				reply    string
				question QuestionMsg
			)

			assert.Nil(t, s.Next(&question, time.Millisecond))
			assert.Equal(t, "A question", question.Text)
			assert.Equal(t, 12, question.Integer)

			assert.Nil(t, s.NextSubject(&subject, &question, time.Millisecond))
			assert.Equal(t, "test", subject)
			assert.Equal(t, "Another", question.Text)
			assert.Equal(t, 12, question.Integer)

			assert.Nil(t, s.NextSubjectReply(&subject, &reply, &question, time.Millisecond))
			assert.Equal(t, "test", subject)
			assert.Equal(t, "zereply", reply)
			assert.Equal(t, "Another", question.Text)
			assert.Equal(t, 42, question.Integer)
		}

	})
	Run(t, "SubscribeSync NextMsg error", func(t *testing.T) {
		s, err := enc.SubscribeSync("test")
		assert.Nil(t, err)
		defer s.Unsubscribe()

		var (
			subject  string
			reply    string
			question QuestionMsg
		)
		err = s.Next(&question, time.Millisecond)
		assert.Equal(t, "nats: timeout", err.Error())
		err = s.NextSubject(&subject, &question, time.Millisecond)
		assert.Equal(t, "nats: timeout", err.Error())
		err = s.NextSubjectReply(&subject, &reply, &question, time.Millisecond)
		assert.Equal(t, "nats: timeout", err.Error())
	})

	Run(t, "Subscribe Raw", func(t *testing.T) {
		var lastMsg *Msg
		cb := func(msg *Msg) {
			lastMsg = msg
		}
		s, err := enc.QueueSubscribe("test", "", cb)
		assert.Nil(t, err)
		defer s.Unsubscribe()

		question := QuestionMsg{Text: "Question", Integer: 38}
		assert.Nil(t, enc.Publish("test", &question))
		time.Sleep(time.Millisecond)
		assert.NotNil(t, lastMsg)
		assert.Equal(t, "test", lastMsg.Subject)
		assert.Equal(t, `{"Text":"Question","Integer":38}`, string(lastMsg.Data))
	})

	Run(t, "Subscribe invalid handler", func(t *testing.T) {
		_, err := enc.Subscribe("test", func() {})
		assert.Equal(t, "natscrypto: Handler requires at least one argument", err.Error())
		_, err = enc.Subscribe("test", func(a1, a2, a3, a4, a5 string) {})
		assert.Equal(t, "natscrypto: Handler requires at most 4 arguments", err.Error())
	})

	Run(t, "Subscribe value", func(t *testing.T) {
		var lastQuestion *QuestionMsg
		cb := func(q QuestionMsg) {
			lastQuestion = &q
		}
		s, err := enc.Subscribe("test", cb)
		assert.Nil(t, err)
		defer s.Unsubscribe()

		question := QuestionMsg{Text: "Question", Integer: 38}
		assert.Nil(t, enc.Publish("test", &question))
		time.Sleep(time.Millisecond)
		assert.NotNil(t, lastQuestion)
		assert.Equal(t, "Question", lastQuestion.Text)
		assert.Equal(t, 38, lastQuestion.Integer)
	})

	Run(t, "Subscribe subject/value", func(t *testing.T) {
		var (
			lastSubject  string
			lastQuestion *QuestionMsg
		)
		cb := func(subject string, q QuestionMsg) {
			lastSubject = subject
			lastQuestion = &q
		}
		s, err := enc.Subscribe("test", cb)
		assert.Nil(t, err)
		defer s.Unsubscribe()

		question := QuestionMsg{Text: "Question", Integer: 38}
		assert.Nil(t, enc.Publish("test", &question))
		time.Sleep(time.Millisecond)
		assert.NotNil(t, lastQuestion)
		assert.Equal(t, "test", lastSubject)
		assert.Equal(t, "Question", lastQuestion.Text)
		assert.Equal(t, 38, lastQuestion.Integer)
	})

	Run(t, "Subscribe subject/reply/value", func(t *testing.T) {
		var (
			lastSubject  string
			lastReply    string
			lastQuestion *QuestionMsg
		)
		cb := func(subject string, reply string, q *QuestionMsg) {
			lastSubject = subject
			lastReply = reply
			lastQuestion = q
		}
		s, err := enc.Subscribe("test", cb)
		assert.Nil(t, err)
		defer s.Unsubscribe()

		question := QuestionMsg{Text: "Question", Integer: 38}
		assert.Nil(t, enc.PublishRequest("test", "zereply", &question))
		time.Sleep(time.Millisecond)
		assert.NotNil(t, lastQuestion)
		assert.Equal(t, "test", lastSubject)
		assert.Equal(t, "zereply", lastReply)
		assert.Equal(t, "Question", lastQuestion.Text)
		assert.Equal(t, 38, lastQuestion.Integer)
	})

	Run(t, "Subscribe subject/reply/signer/value", func(t *testing.T) {
		var (
			lastSubject  string
			lastReply    string
			lastSigner   string
			lastQuestion *QuestionMsg
			hit          = make(chan bool, 1)
		)
		cb := func(subject string, reply string, signer string, q *QuestionMsg) {
			lastSubject = subject
			lastReply = reply
			lastSigner = signer
			lastQuestion = q
			hit <- true
		}
		s, err := enc.Subscribe("test", cb)
		assert.Nil(t, err)
		defer s.Unsubscribe()

		question := QuestionMsg{Text: "Question", Integer: 38}
		assert.Nil(t, enc.PublishRequest("test", "zereply", &question))
		timeout := TimeoutChan(time.Millisecond * 250)
		select {
		case <-timeout:
			t.Errorf("Callback not called")
		case <-hit:

			assert.NotNil(t, lastQuestion)
			assert.Equal(t, "test", lastSubject)
			assert.Equal(t, "zereply", lastReply)
			assert.Equal(t, "Question", lastQuestion.Text)
			assert.Equal(t, "me", lastSigner)
			assert.Equal(t, 38, lastQuestion.Integer)
		}
	})

	Run(t, "Request", func(t *testing.T) {
		go func() {
			s, err := enc.SubscribeSync("test")
			assert.Nil(t, err)
			defer s.Unsubscribe()

			var (
				subject, reply string
				question       QuestionMsg
			)

			assert.Nil(t, s.NextSubjectReply(&subject, &reply, &question, 10*time.Millisecond))
			assert.Nil(t,
				enc.Publish(reply, &AnswerMsg{Text: "The answer"}),
			)

			assert.Nil(t, s.NextSubjectReply(&subject, &reply, &question, 10*time.Millisecond))
			assert.Nil(t,
				enc.Publish(reply, &AnswerMsg{Text: "The answer"}),
			)
		}()

		time.Sleep(time.Millisecond)

		var answer AnswerMsg
		q := QuestionMsg{Text: "The question", Integer: 9}

		err := enc.Request("test", q, &answer, time.Second)
		assert.Nil(t, err)

		var msg Msg
		err = enc.Request("test", q, &msg, time.Second)
		assert.Nil(t, err)
		assert.Equal(t, `{"Text":"The answer"}`, string(msg.Data))

		err = enc.Request("test", 42, &msg, time.Microsecond)
		assert.Equal(t, "nats: timeout", err.Error())
	})

	Run(t, "SubscribeSync error handling", func(t *testing.T) {
		s, err := enc.SubscribeSync("test")
		if err != nil {
			t.Fatal(err)
		}
		defer func() { assert.Nil(t, s.Unsubscribe()) }()
		assert.Nil(t, enc.Conn.Publish("test", []byte("Invalid json")))

		var answer AnswerMsg
		err = s.Next(&answer, time.Second)
		assert.EqualError(t, err, "invalid character 'I' looking for beginning of value")
	})

	Run(t, "Subscribe error handling", func(t *testing.T) {
		var hit = false
		cb := func(answer AnswerMsg) {
			t.Error("Callback was called")
			hit = true
		}
		s, err := enc.Subscribe("test", cb)
		if err != nil {
			t.Fatal(err)
		}
		defer func() { assert.Nil(t, s.Unsubscribe()) }()
		s.SetDecryptErrorHandler(func(sub *Subscription, msg *Msg) *Msg {
			assert.EqualError(t, msg.Error, "invalid character 'I' looking for beginning of value")
			return nil
		})
		assert.Nil(t, enc.Conn.Publish("test", []byte("Invalid json")))

		time.Sleep(time.Millisecond)

		assert.False(t, hit)
	})
}

type BadEncoder struct{}

func (BadEncoder) Encode(string, interface{}) ([]byte, error) {
	return nil, fmt.Errorf("Encoding failed")
}

func (BadEncoder) Decode(string, []byte, interface{}) error {
	return fmt.Errorf("Decoding failed")
}

func TestEncoderErrors(t *testing.T) {
	natsSrv := InitNatsTestServer(t)
	defer natsSrv.Shutdown()

	c := natsSrv.Connect(t)
	if c == nil {
		return
	}

	ec, err := NewConn(c, "me", DummyEncrypter{})
	if err != nil {
		t.Errorf("Could not init the encrypted conn: %s", err)
		c.Close()
		return
	}
	ec.SetSubjectRecipients("test", []string{"riri", "fifi", "loulou"})

	nats.RegisterEncoder("bad", &BadEncoder{})
	enc, err := NewEncodedConn(ec, "bad")
	if err != nil {
		t.Errorf("Could not init the encoded conn: %s", err)
		ec.Close()
		return
	}
	defer enc.CloseAll()

	err = enc.Publish("test", 42)
	assert.Equal(t, "Encoding failed", err.Error())

	err = enc.PublishRequest("test", "reply", 42)
	assert.Equal(t, "Encoding failed", err.Error())

	var response int
	err = enc.Request("test", 42, &response, time.Second)
	assert.Equal(t, "Encoding failed", err.Error())
}

func TestRequestErrors(t *testing.T) {
	natsSrv := InitNatsTestServer(t)
	defer natsSrv.Shutdown()

	c := natsSrv.Connect(t)
	if c == nil {
		return
	}

	ec, err := NewConn(c, "me", DummyEncrypter{})
	if err != nil {
		t.Errorf("Could not init the encrypted conn: %s", err)
		c.Close()
		return
	}
	ec.SetSubjectRecipients("test", []string{"riri", "fifi", "loulou"})

	enc, err := NewEncodedConn(ec, "json")
	if err != nil {
		t.Errorf("Could not init the encoded conn: %s", err)
		ec.Close()
		return
	}
	defer enc.CloseAll()

	var response int
	err = enc.Request("test", 42, &response, time.Microsecond)
	assert.Equal(t, "nats: timeout", err.Error())
}

func TestSubscribeErrors(t *testing.T) {
	natsSrv := InitNatsTestServer(t)
	defer natsSrv.Shutdown()

	c := natsSrv.Connect(t)
	if c == nil {
		return
	}

	ec, err := NewConn(c, "me", DummyEncrypter{})
	if err != nil {
		t.Errorf("Could not init the encrypted conn: %s", err)
		c.Close()
		return
	}
	ec.SetSubjectRecipients("test", []string{"riri", "fifi", "loulou"})

	enc, err := NewEncodedConn(ec, "json")
	if err != nil {
		t.Errorf("Could not init the encoded conn: %s", err)
		ec.Close()
		return
	}
	defer enc.CloseAll()

	enc.Conn.Conn = nil
	_, err = enc.Subscribe("test", nil)
	assert.Equal(t, "nats: invalid connection", err.Error())

	_, err = enc.QueueSubscribe("test", "queue", func(*Msg) {})
	assert.Equal(t, "nats: invalid connection", err.Error())

	enc.Conn.Conn = c
}


text:
#include "circleWidget.h"

#include <QtCore/QVariant>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QLabel>
#include <QtGui/QPainter>

using namespace qReal;

CircleWidget::CircleWidget(const QSize &size, const QString &icon, QWidget *parent)
	: QWidget(parent)
{
	const QSize iconSize = size - QSize(25, 25);

	const QPixmap pixmap(icon);
	const int targetHeight = iconSize.height();
	const int targetWidth = iconSize.width();

	const int pictureHeight = pixmap.height();
	const int pictureWidth = pixmap.width();

	// Take picture aspect into account
	// TODO: move it into shared place and reuse in SdfIconEngineV2
	const QRect iconRect(QPoint(), iconSize);
	QRect resultingRect = iconRect;
	if (targetHeight * pictureWidth < pictureHeight * targetWidth) {
		resultingRect.setLeft(iconRect.left()
				+ (targetWidth - targetHeight * pictureWidth / pictureHeight) / 2);
		resultingRect.setRight(iconRect.right()
				- (targetWidth - targetHeight * pictureWidth / pictureHeight) / 2);
	} else if (targetHeight * pictureWidth > pictureHeight * targetWidth) {
		resultingRect.setTop(iconRect.top() + (targetHeight
				- targetWidth * pictureHeight / pictureWidth) / 2);
		resultingRect.setBottom(iconRect.bottom()
				- (targetHeight - targetWidth * pictureHeight / pictureWidth) / 2);
	}

	QLabel * const iconLabel = new QLabel;
	iconLabel->setFixedSize(resultingRect.size());
	iconLabel->setScaledContents(true);
	iconLabel->setPixmap(pixmap);

	QVBoxLayout * const circleLayout = new QVBoxLayout;
	circleLayout->setContentsMargins(0, 0, 0, 0);
	circleLayout->setSpacing(0);
	circleLayout->setMargin(0);
	circleLayout->addWidget(iconLabel, 0, Qt::AlignCenter);

	setFixedSize(size);
	setLayout(circleLayout);
}

void CircleWidget::paintEvent(QPaintEvent *event)
{
	QWidget::paintEvent(event);
	QPainter painter(this);
	painter.setRenderHint(QPainter::Antialiasing);

	const QColor backgroundColor = Qt::white;
	QPen borderPen(property("enabled").toBool() ? palette().foreground().color() : backgroundColor);
	borderPen.setWidth(3);
	const QBrush backgroundBrush(backgroundColor);
	painter.setBrush(backgroundBrush);
	painter.setPen(borderPen);
	painter.drawEllipse(QRect(QPoint(2, 2), size() - QSize(4, 4)));
}


text:
package com.nutricampus.app.repositorios;

import android.support.test.InstrumentationRegistry;

import com.nutricampus.app.database.RepositorioAnimal;
import com.nutricampus.app.database.RepositorioProle;
import com.nutricampus.app.entities.Animal;
import com.nutricampus.app.entities.Prole;

import org.junit.Before;
import org.junit.Test;

import java.util.Calendar;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public class RepositorioProleTesteIntegracao {
    private RepositorioProle repositorioProle;

    @Before
    public void setUp() throws Exception {
        repositorioProle = new RepositorioProle(InstrumentationRegistry.getTargetContext());
        RepositorioAnimal repositorioAnimal = new RepositorioAnimal(InstrumentationRegistry.getTargetContext());
        repositorioAnimal.inserirAnimal(new Animal("mimosa", 1, Calendar.getInstance(), true, 1));
    }

    @Test
    public void inserirProle() throws Exception {
        int result = repositorioProle.inserirProle(new Prole(1, Calendar.getInstance(), 0.1f, true));
        assertTrue(result > 1);
    }

    @Test
    public void buscarPorId() throws Exception {
        int result = repositorioProle.inserirProle(new Prole(1, Calendar.getInstance(), 0.1f, true));
        Prole prole = repositorioProle.buscarPorId(result);
        assertTrue(0.1f == prole.getPesoDeNascimento());
    }

    @Test
    public void buscarPorMatriz() throws Exception {
        repositorioProle.inserirProle(new Prole(1, Calendar.getInstance(), 0.1f, true));
        List<Prole> prole = repositorioProle.buscarPorMatriz(1);
        assertNotNull(prole);

        List<Prole> prole2 = repositorioProle.buscarPorMatriz(11);
        assertTrue(prole2.isEmpty());

    }

    @Test
    public void buscarPorAnimalPeriodo() throws Exception {
        repositorioProle.inserirProle(new Prole(1, Calendar.getInstance(), 0.1f, true));
        List<Prole> prole = repositorioProle.buscarPorAnimalPeriodo(1, Calendar.MONTH, Calendar.YEAR);
        assertNotNull(prole);
        prole = repositorioProle.buscarPorAnimalPeriodo(1, Calendar.MONTH, Calendar.YEAR + 2);
        assertTrue(prole.isEmpty());

    }

    @Test
    public void atualizarProle() throws Exception {
        Prole prole = new Prole(1, Calendar.getInstance(), 0.1f, true);
        int id = repositorioProle.inserirProle(prole);

        Prole prole2 = repositorioProle.buscarPorId(id);
        prole2.setNatimorto(false);
        repositorioProle.atualizarProle(prole2);

        assertEquals(false, repositorioProle.buscarPorId(id).isNatimorto());
        assertNotEquals(true, repositorioProle.buscarPorId(id).isNatimorto());

    }

    @Test
    public void removerProle() throws Exception {
        int id = repositorioProle.inserirProle(new Prole(1, Calendar.getInstance(), 0.1f, true));

        Prole prole2 = repositorioProle.buscarPorId(id);
        assertNotNull(prole2);

        repositorioProle.removerProle(prole2);

        Prole prole = repositorioProle.buscarPorId(id);
        assertNull(prole);

    }

}


text:
import React from 'react'
import { ScrollView } from 'react-native'
import PropTypes from 'prop-types'

import AppPortal from './AppPortalContainer'
import { HeaderNavigation } from '@components'

const AppPortalScreen = ( { navigation } ) => (
  <AppPortal navigation={navigation} />
)

AppPortalScreen.navigationOptions = ( { navigation } ) => ( {
  header: <HeaderNavigation navigation={navigation} title={'App Portal'} />,
} )

AppPortalScreen.propTypes = {
  navigation: PropTypes.object.isRequired,
}

export default AppPortalScreen


text:
use std::string::ToString;

use bson::{Bson, bson, doc};

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SingleDatabaseRole {
    Read,
    ReadWrite,
    DbAdmin,
    DbOwner,
    UserAdmin,
    ClusterAdmin,
    ClusterManager,
    ClusterMonitor,
    HostManager,
    Backup,
    Restore,
}

impl SingleDatabaseRole {
    fn to_str(&self) -> &'static str {
        match *self {
            SingleDatabaseRole::Read => "read",
            SingleDatabaseRole::ReadWrite => "readWrite",
            SingleDatabaseRole::DbAdmin => "dbAdmin",
            SingleDatabaseRole::DbOwner => "dbOwner",
            SingleDatabaseRole::UserAdmin => "userAdmin",
            SingleDatabaseRole::ClusterAdmin => "clusterAdmin",
            SingleDatabaseRole::ClusterManager => "clusterManager",
            SingleDatabaseRole::ClusterMonitor => "clusterMonitor",
            SingleDatabaseRole::HostManager => "hostManager",
            SingleDatabaseRole::Backup => "backup",
            SingleDatabaseRole::Restore => "restore",
        }
    }
}

impl ToString for SingleDatabaseRole {
    fn to_string(&self) -> String {
        self.to_str().into()
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AllDatabaseRole {
    Read,
    ReadWrite,
    UserAdmin,
    DbAdmin,
}

impl AllDatabaseRole {
    fn to_str(&self) -> &'static str {
        match *self {
            AllDatabaseRole::Read => "read",
            AllDatabaseRole::ReadWrite => "readWrite",
            AllDatabaseRole::UserAdmin => "userAdmin",
            AllDatabaseRole::DbAdmin => "dbAdmin",
        }
    }
}

impl ToString for AllDatabaseRole {
    fn to_string(&self) -> String {
        self.to_str().into()
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Role {
    All(AllDatabaseRole),
    Single {
        role: SingleDatabaseRole,
        db: String,
    },
}

impl From<Role> for Bson {
    fn from(role: Role) -> Bson {
        match role {
            Role::All(role) => role.to_string().into(),
            Role::Single { role, db } => {
                Bson::Document(doc! {
                  "role": role.to_string(),
                  "db": db
              })
            }
        }
    }
}

impl Role {
    pub fn to_bson(&self) -> Bson {
        self.clone().into()
    }

    #[deprecated(since = "0.2.4", note = "this method will be removed in the next major release")]
    pub fn to_bson_array(vec: Vec<Role>) -> Bson {
        Bson::Array(vec.iter().map(Self::to_bson).collect())
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<inset xmlns:android="http://schemas.android.com/apk/res/android"
       android:insetLeft="@dimen/abc_edit_text_inset_horizontal_material"
       android:insetRight="@dimen/abc_edit_text_inset_horizontal_material"
       android:insetTop="@dimen/abc_edit_text_inset_top_material"
       android:insetBottom="@dimen/abc_edit_text_inset_bottom_material">

    <selector>
        <!--
          This file is a copy of abc_edit_text_material (https://bit.ly/3k8fX7I).
          The item below with state_pressed="false" and state_focused="false" causes a NullPointerException.
          NullPointerException:tempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)'

          <item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>

          For more info, see https://bit.ly/3CdLStv (react-native/pull/29452) and https://bit.ly/3nxOMoR.
        -->
        <item android:state_enabled="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
        <item android:drawable="@drawable/abc_textfield_activated_mtrl_alpha"/>
    </selector>

</inset>