text:
"""Database functions that do comparisons or type conversions."""
from django.db import NotSupportedError
from django.db.models.expressions import Func, Value
from django.db.models.fields.json import JSONField
from django.utils.regex_helper import _lazy_re_compile

class Cast(Func):
    """Coerce an expression to a new field type."""
    function = 'CAST'
    template = '%(function)s(%(expressions)s AS %(db_type)s)'

    def __init__(self, expression, output_field):
        super().__init__(expression, output_field=output_field)

    def as_sql(self, compiler, connection, **extra_context):
        extra_context['db_type'] = self.output_field.cast_db_type(connection)
        return super().as_sql(compiler, connection, **extra_context)

    def as_sqlite(self, compiler, connection, **extra_context):
        db_type = self.output_field.db_type(connection)
        if db_type in {'datetime', 'time'}:
            # Use strftime as datetime/time don't keep fractional seconds.
            template = 'strftime(%%s, %(expressions)s)'
            sql, params = super().as_sql(compiler, connection, template=template, **extra_context)
            format_string = '%H:%M:%f' if db_type == 'time' else '%Y-%m-%d %H:%M:%f'
            params.insert(0, format_string)
            return sql, params
        elif db_type == 'date':
            template = 'date(%(expressions)s)'
            return super().as_sql(compiler, connection, template=template, **extra_context)
        return self.as_sql(compiler, connection, **extra_context)

    def as_mysql(self, compiler, connection, **extra_context):
        template = None
        output_type = self.output_field.get_internal_type()
        # MySQL doesn't support explicit cast to float.
        if output_type == 'FloatField':
            template = '(%(expressions)s + 0.0)'
        # MariaDB doesn't support explicit cast to JSON.
        elif output_type == 'JSONField' and connection.mysql_is_mariadb:
            template = "JSON_EXTRACT(%(expressions)s, '$')"
        return self.as_sql(compiler, connection, template=template, **extra_context)

    def as_postgresql(self, compiler, connection, **extra_context):
        # CAST would be valid too, but the :: shortcut syntax is more readable.
        # 'expressions' is wrapped in parentheses in case it's a complex
        # expression.
        return self.as_sql(compiler, connection, template='(%(expressions)s)::%(db_type)s', **extra_context)

    def as_oracle(self, compiler, connection, **extra_context):
        if self.output_field.get_internal_type() == 'JSONField':
            # Oracle doesn't support explicit cast to JSON.
            template = "JSON_QUERY(%(expressions)s, '$')"
            return super().as_sql(compiler, connection, template=template, **extra_context)
        return self.as_sql(compiler, connection, **extra_context)

class Coalesce(Func):
    """Return, from left to right, the first non-null expression."""
    function = 'COALESCE'

    def __init__(self, *expressions, **extra):
        if len(expressions) < 2:
            raise ValueError('Coalesce must take at least two expressions')
        super().__init__(*expressions, **extra)

    @property
    def empty_aggregate_value(self):
        for expression in self.get_source_expressions():
            result = expression.empty_aggregate_value
            if result is NotImplemented or result is not None:
                return result
        return None

    def as_oracle(self, compiler, connection, **extra_context):
        # Oracle prohibits mixing TextField (NCLOB) and CharField (NVARCHAR2),
        # so convert all fields to NCLOB when that type is expected.
        if self.output_field.get_internal_type() == 'TextField':
            clone = self.copy()
            clone.set_source_expressions([
                Func(expression, function='TO_NCLOB') for expression in self.get_source_expressions()
            ])
            return super(Coalesce, clone).as_sql(compiler, connection, **extra_context)
        return self.as_sql(compiler, connection, **extra_context)

class Collate(Func):
    function = 'COLLATE'
    template = '%(expressions)s %(function)s %(collation)s'
    # Inspired from https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
    collation_re = _lazy_re_compile(r'^[\w\-]+$')

    def __init__(self, expression, collation):
        if not (collation and self.collation_re.match(collation)):
            raise ValueError('Invalid collation name: %r.' % collation)
        self.collation = collation
        super().__init__(expression)

    def as_sql(self, compiler, connection, **extra_context):
        extra_context.setdefault('collation', connection.ops.quote_name(self.collation))
        return super().as_sql(compiler, connection, **extra_context)

class Greatest(Func):
    """
    Return the maximum expression.

    If any expression is null the return value is database-specific:
    On PostgreSQL, the maximum not-null expression is returned.
    On MySQL, Oracle, and SQLite, if any expression is null, null is returned.
    """
    function = 'GREATEST'

    def __init__(self, *expressions, **extra):
        if len(expressions) < 2:
            raise ValueError('Greatest must take at least two expressions')
        super().__init__(*expressions, **extra)

    def as_sqlite(self, compiler, connection, **extra_context):
        """Use the MAX function on SQLite."""
        return super().as_sqlite(compiler, connection, function='MAX', **extra_context)

class JSONObject(Func):
    function = 'JSON_OBJECT'
    output_field = JSONField()

    def __init__(self, **fields):
        expressions = []
        for key, value in fields.items():
            expressions.extend((Value(key), value))
        super().__init__(*expressions)

    def as_sql(self, compiler, connection, **extra_context):
        if not connection.features.has_json_object_function:
            raise NotSupportedError(
                'JSONObject() is not supported on this database backend.'
            )
        return super().as_sql(compiler, connection, **extra_context)

    def as_postgresql(self, compiler, connection, **extra_context):
        return self.as_sql(
            compiler,
            connection,
            function='JSONB_BUILD_OBJECT',
            **extra_context,
        )

    def as_oracle(self, compiler, connection, **extra_context):
        class ArgJoiner:
            def join(self, args):
                args = [' VALUE '.join(arg) for arg in zip(args[::2], args[1::2])]
                return ', '.join(args)

        return self.as_sql(
            compiler,
            connection,
            arg_joiner=ArgJoiner(),
            template='%(function)s(%(expressions)s RETURNING CLOB)',
            **extra_context,
        )

class Least(Func):
    """
    Return the minimum expression.

    If any expression is null the return value is database-specific:
    On PostgreSQL, return the minimum not-null expression.
    On MySQL, Oracle, and SQLite, if any expression is null, return null.
    """
    function = 'LEAST'

    def __init__(self, *expressions, **extra):
        if len(expressions) < 2:
            raise ValueError('Least must take at least two expressions')
        super().__init__(*expressions, **extra)

    def as_sqlite(self, compiler, connection, **extra_context):
        """Use the MIN function on SQLite."""
        return super().as_sqlite(compiler, connection, function='MIN', **extra_context)

class NullIf(Func):
    function = 'NULLIF'
    arity = 2

    def as_oracle(self, compiler, connection, **extra_context):
        expression1 = self.get_source_expressions()[0]
        if isinstance(expression1, Value) and expression1.value is None:
            raise ValueError('Oracle does not allow Value(None) for expression1.')
        return super().as_sql(compiler, connection, **extra_context)


text:
Project swift-compiler-crashes
==============================

This repo collects known test cases crashing the Swift compiler. All tests cases in the `crashes/` and `crashes-fuzzing/` directories are known to generate a compiler crash under Xcode 6.3 beta 2.

Help us towards a rock solid Swift compiler by contributing any compiler crashes you may encounter.

Happy Swifting! :-)

Contributor hall of fame
========================

| GitHub | Twitter | Cases contributed | First contribution |
| :----- | :------ | ----------------: | -----------------: |
| @practicalswift – practicalswift | @practicalswift | 69 cases (+ 24095 fuzzing) | Xcode6.0-Beta6 |
| @robrix – Rob Rix | @robrix | 23 cases | Xcode6.0-Beta6 |
| @airspeedswift – Airspeed Velocity | @airspeedswift | 11 cases | Xcode6.1.1-GM-Seed |
| @fluidsonic – Marc Knaup | @marcknaup | 7 cases | Xcode6.1-Beta3 |
| @zneak – Félix Cloutier | @zneakr | 7 cases | Xcode6.1.1-GM-Seed |
| @beltex – beltex | … | 6 cases | Xcode6.1.1-GM-Seed |
| @CodaFi – Robert Widmann | @CodaFi_ | 5 cases | Xcode6.4-Beta3 |
| @rnapier – Rob Napier | @cocoaphony | 4 cases | Xcode6.0-Beta7 |
| @rustedivan – Ivan Milles | @rustedivan | 4 cases | Xcode6.1.1-GM-Seed |
| @tmu – Teemu Kurppa | @Teemu | 4 cases | Xcode6.0-Beta6 |
| @jvasileff – John Vasileff | @jvasileff | 2 cases | Xcode6.0-Beta6 |
| @owensd – David Owens II | @owensd | 2 cases | Xcode6.0-Beta6 |
| @radex – Radek Pietruszewski | @radexp | 2 cases | Xcode6.1 |
| @0xc010d – Ievgen Solodovnykov | @0xc010d | 1 case | Xcode6.0-Beta6 |
| @adfernandes – Andrew Fernandes | … | 1 case | Xcode6.3-Beta2 |
| @AlexDenisov – Alexey Denisov | @1101_debian | 1 case | Xcode6.0-Beta6 |
| @ArtisOracle – Stefan Arambasich | @ArtisOracle | 1 case | Xcode6.1.1-GM-Seed |
| @champo – Juan Pablo Civile | @elchampo | 1 case | Xcode6.3-Beta2 |
| @hendriks73 – Hendrik Schreiber| @h_schreiber | 1 case | Xcode6.2-Beta4 |
| @invalidname – Chris Adamson | @invalidname | 1 case | Xcode6.2-Beta4 |
| @jansabbe – Jan Sabbe | @jansabbe | 1 case | Xcode6.0-Beta6 |
| @juangamnik – juangamnik | … | 1 case | Xcode6.1.1-GM-Seed |
| @julasamer – julasamer | … | 1 case | Xcode6.1-Beta1 |
| @martijnwalraven – Martijn Walrav | @martijnwalraven | 1 case | Xcode6.1-GM-Seed2 |
| @mattdaw – Matt Daw | @mattdaw | 1 case | Xcode6.1.1-GM-Seed |
| @mayoff – Rob Mayoff | @rmayoff | 1 case | Xcode6.1 |
| @valfer – Valerio Ferrucci | @valferweet | 1 case | Xcode6.1-GM-Seed2 |

Getting started
===============

```
$ git clone https://github.com/practicalswift/swift-compiler-crashes.git
$ cd swift-compiler-crashes/
$ ./test.sh

Running tests against: swiftlang-700.0.42.3 clang-700.0.53.3 (Xcode 7.0 (7A121l))
Using Xcode found at path: /Applications/Xcode-Beta.app/Contents/Developer/
Usage: ./test.sh [-v] [-q] [-c<columns>] [-l] [file ...]
Adding a new test case? The crash id to use for the next test case is 24894.

== Currently known crashes, set #1 (human reported crashes, crashes not found by fuzzing) ==

  ✘  00028 extension property defined in library (lib III)        (          )
  ✘  00037 no stacktrace (script)                                 (413e4852ec)
  ✘  00041 szone malloc should clear                              (e102a9700c)
  ✘  00055 no stacktrace                                          (71ed39dc63)
  ✘  00061 visit any struct type                                  (          )
  ✘  00226 swift lowering silgenfunction emitcurrythunk           (8b436372f5)
  ✘  12262 bitcast requires types of same width                   (1364fce874)
  ✘  21272 empty stacktrace                                       (c29ac5f71b)
  ✘  22725 swift constraints constraintsystem solvesimplified     (ad19c7dc73)
  ✘  23408 missing type in generic constraint                     (39901980cd)
  ✘  23409 circular typealias                                     (          )
  ✘  23637 constraints constraintsystem findbestsolution          (c7a6acddb1)
  ✘  23639 llvm jit runfunction (runtime)                         (          )
  ✘  23890 swift irgen irgenmodule emitsilfunction                (0452f61dc2)
  ✘  23892 swift archetypebuilder resolvearchetype                (ee5da696fd)
  ✘  23901 swift lowering silgenfunction emitclosurevalue         (dfc3f3efc8)
  ✘  23903 too complex to be solved in reasonable time (timeout)  (          )
  ✘  23906 swift irgen irgenfunction bindarchetype                (5caaa8b274)
  ✘  23908 slow type inference (timeout)                          (          )
  ✘  24170 llvm smallvectorimpl llvm fixnum 31u unsigned int oper (          )
  ✘  24171 swift silvisitor visit                                 (e7794b0d16)
  ✘  24241 call parameter type does not match function signature  (af6bad3e00)
  ✘  24245 swift constraints constraintsystem solve               (3837419e7a)
  ✘  24797 no stacktrace                                          (          )
  ✘  24798 no stacktrace                                          (          )
  ✘  24879 getmemberforbasetype                                   (3484e28f51)
  ✘  24881 swift typebase getcanonicaltype                        (2759e4cc1e)
  ✘  24885 no stack trace                                         (          )
  ✘  24886 no stack trace                                         (          )
  ✘  24887 no stack trace                                         (          )
  ✘  24888 swift lowering silgenfunction emitclosurevalue         (59fc21afe9)
  ✘  24889 too complex to be solved in reasonable time (timeout)  (          )
  ✘  24890 too complex to be solved in reasonable time (timeout)  (          )
  ✘  24891 using utsname struct (runtime)                         (          )

== Currently known crashes, set #2 (crashes found by fuzzing) ==

  ✘  00062 ioctl                                                  (c2604df217)
  ✘  00066 diagnoseunknowntype                                    (fbdd3b2fd2)
  ✘  00085 swift typechecker typecheckpattern                     (245c7905ed)
  ✘  00103 swift constraints constraintsystem diagnosefailurefrom (68522da995)
  ✘  00213 swift typechecker validatetype                         (bfdc427058)
  ✘  00288 swift typebase getcanonicaltype                        (aa092d118d)
  ✘  00331 llvm raw fd ostream write impl                         (58091285e8)
  ✘  00334 swift astvisitor                                       (b785ad4e87)
  ✘  00337 swift typechecker checksubstitutions                   (1069e83308)
  ✘  00343 connectedcomponentsdfs                                 (58c6f9f57c)
  ✘  00357 swift type transform                                   (3be0d8c671)
  ✘  00359 swift constraints constraintsystem getfixedtyperecursi (f8d02acc8f)
  ✘  00375 swift nominaltypedecl getdeclaredtypeincontext         (4b28aea3ee)
  ✘  00410 getselftypeforcontainer                                (851392ce0d)
  ✘  00416 swift typechecker conformstoprotocol                   (f519cac859)
  ✘  00423 swift archetypebuilder resolvearchetype                (db6f96523d)
  ✘  00476 swift typechecker validatedecl                         (a87e1f2869)
  ✘  00535 swift type transform                                   (86e897dbdd)
  ✘  00578 swift type walk                                        (d7b4807729)
  ✘  00626 swift lexer lexidentifier                              (11690e7512)
  ✘  00638 swift typechecker typecheckexpressionshallow           (d990f90dc9)
  ✘  00683 swift metatypetype get                                 (58efbb77bc)
  ✘  00770 swift astvisitor                                       (d87b09d28b)
  ✘  00805 swift constraints constraintsystem opengeneric         (41ab45fa8f)
  ✘  00857 std function func swift constraints constraintsystem s (fea0521a50)
  ✘  00994 swift typealiasdecl                                    (b60cf69fe3)
  ✘  01003 swift nominaltypedecl getdeclaredtypeincontext         (913e363a99)
  ✘  01005 swift nominaltype get                                  (233505ff2e)
  ✘  01307 swift clangmoduleunit getimportedmodules               (c331b406ec)
  ✘  01335 swift astvisitor                                       (715a99387c)
  ✘  01337 void                                                   (bd7229e0de)
  ✘  01495 swift functiontype get                                 (51c435205a)
  ✘  01520 llvm bitstreamcursor readrecord                        (3318ab8dd3)
  ✘  01773 swift typebase getcanonicaltype                        (477ab82bc4)
  ✘  01793 swift nominaltypedecl getdeclaredtypeincontext         (c1c42c8241)
  ✘  01908 std function func mapsignaturetype                     (03175eb47f)
  ✘  01949 llvm ondiskchainedhashtable swift modulefile decltable (c0383033ff)
  ✘  02038 llvm bitstreamcursor readvbr                           (043be64291)
  ✘  02108 swift type transform                                   (0dc0fbb5fa)
  ✘  02164 swift typechecker checksubstitutions                   (a2a2aefd91)
  ✘  02225 swift sourcemanager getmessage                         (5374847a78)
  ✘  02238 swift typechecker coercepatterntotype                  (f53d4eb4ce)
  ✘  02281 swift sourcemanager getmessage                         (a2de94e52c)
  ✘  02327 swift clangimporter lookupvalue                        (fb60865653)
  ✘  02345 swift sourcemanager getmessage                         (43f0bc1328)
  ✘  02358 swift parser skipsingle                                (cd7530689d)
  ✘  02380 swift sourcemanager getmessage                         (bf23e45bf8)
  ✘  02550 swift sourcemanager getmessage                         (b8e3e8e94a)
  ✘  03118 swift parser consumetoken                              (d0e49c31b2)
  ✘  03204 swift type transform                                   (109b4a069e)
  ✘  03326 swift archetypetype setnestedtypes                     (1b7608d10b)
  ✘  03387 swift constraints constraintsystem getfixedtyperecursi (4cd1c8f5e7)
  ✘  03562 swift classtype get                                    (57b34c988d)
  ✘  04450 swift typebase getcanonicaltype                        (0ccfd31be3)
  ✘  04592 swift constraints constraintsystem simplifyconstraint  (27f28bfc68)
     lots of fuzzing crashes omitted for README.md readability …
  ✓  23867 getselftypeforcontainer
  ✓  23868 swift astprinter printtextimpl
  ✓  23870 swift lexer lexidentifier
  ✓  23875 swift optional swift diagnostic operator
  ✓  23881 swift parser parsetype
  ✓  23882 swift expr walk
  ✓  23886 swift lexer kindofidentifier
  ✓  23889 swift lowering silgenfunction emitexprinto
  ✓  23891 llvm constantfoldgetelementptr
  ✓  23893 std 1 function func
  ✓  23894 swift irgen emitobjcexistentialdowncast
  ✓  23895 swift lowering typeconverter gettypelowering
  ✓  23898 swift silfunction maptypeintocontext
  ✓  23899 segfault
  ✓  23900 swift irgen irbuilder createstore
  ✓  23905 undefined symbols
  ✓  23907 phi node operands are not the same type
  ✓  23909 swift irgen emitscalarexistentialdowncast
  ✓  23910 no stacktrace
  ✓  23911 gettypemetadataaccessfunction
  ✓  23913 void
  ✓  23915 void
  ✓  23916 swift typechecker lookupconstructors
  ✓  23919 swift astvisitor
  ✓  23922 swift inflightdiagnostic
  ✓  23924 swift funcdecl isunaryoperator
  ✓  23931 swift nominaltypedecl getdeclaredtypeincontext
  ✓  23932 swift inflightdiagnostic
  ✓  23934 swift archetypebuilder potentialarchetype getnestedtyp
  ✓  23938 swift typechecker coercepatterntotype
  ✓  23939 checkredeclaration
  ✓  23941 swift typechecker checkinheritanceclause
  ✓  23943 swift removeshadoweddecls
  ✓  23951 swift inflightdiagnostic
  ✓  23964 swift typechecker coercetorvalue
  ✓  23967 llvm optional swift diagnostic operator
  ✓  23968 swift typechecker validategenericfuncsignature
  ✓  23973 swift declname declname
  ✓  23975 swift mangle mangler bindgenericparameters
  ✓  23978 swift typeloc iserror
  ✓  23979 swift archetypebuilder potentialarchetype getnestedtyp
  ✓  23982 void
  ✓  23985 swift lexer kindofidentifier
  ✓  23992 swift type walk
  ✓  23995 swift completegenerictyperesolver resolvedependentmemb
  ✓  24000 swift module lookupconformance
  ✓  24006 swift inflightdiagnostic
  ✓  24008 llvm ondiskchainedhashtable swift modulefile decltable
  ✓  24017 vtable
  ✓  24018 swift typeloc iserror
  ✓  24026 swift parser parsetype
  ✓  24033 swift generictypeparamtype get
  ✓  24045 swift typechecker computeaccessibility
  ✓  24046 swift diagnosticengine flushactivediagnostic
  ✓  24055 swift nominaltypedecl preparelookuptable
  ✓  24056 swift typeloc iserror
  ✓  24057 checkredeclaration
  ✓  24059 swift lexer leximpl
  ✓  24067 swift diagnosticengine flushactivediagnostic
  ✓  24078 llvm foldingset swift tupletype nodeequals
  ✓  24081 swift valuedecl overwritetype
  ✓  24085 swift archetypebuilder potentialarchetype getnestedtyp
  ✓  24086 swift nominaltypedecl getdeclaredtypeincontext
  ✓  24087 llvm optional swift diagnostic operator
  ✓  24093 swift nominaltypedecl getdeclaredtypeincontext
  ✓  24097 swift nominaltypedecl getdeclaredtypeincontext
  ✓  24098 swift inflightdiagnostic
  ✓  24129 swift parser skipsingle
  ✓  24132 swift archetypebuilder potentialarchetype getnestedtyp
  ✓  24145 swift parser addpatternvariablestoscope
  ✓  24149 swift typebase hasreferencesemantics
  ✓  24173 void
  ✓  24175 resolvetypedecl
  ✓  24177 resolvetypedecl
  ✓  24178 swift printingdiagnosticconsumer handlediagnostic
  ✓  24179 llvm bitstreamcursor read
  ✓  24182 swift constraints constraintsystem gettypeofreference
  ✓  24186 swift clangimporter implementation getwrapperformodule
  ✓  24202 swift nominaltypedecl getdeclaredtypeincontext
  ✓  24205 swift modulefile lookupvalue
  ✓  24209 swift inflightdiagnostic highlight
  ✓  24210 swift nominaltypedecl getdeclaredtypeincontext
  ✓  24216 swift functiontype get
  ✓  24217 bool
  ✓  24231 resolvetypedecl
  ✓  24233 getselftypeforcontainer
  ✓  24234 getselftypeforcontainer
  ✓  24238 llvm optional swift diagnostic operator
  ✓  24239 swift lowering silgenmodule emitobjcconstructorthunk
  ✓  24240 swift irgen emitpolymorphicarguments
  ✓  24242 argemitter emit
  ✓  24243 dce markcontrollingterminatorslive
  ✓  24244 rvalueemitter visitabstractclosureexpr
  ✓  24247 swift irgen emitcategorydata
  ✓  24249 collectfullname
  ✓  24250 exprrewriter coercetupletotuple
  ✓  24254 swift nominaltypedecl getdeclaredtypeincontext
  ✓  24255 swift iterabledeclcontext getmembers
  ✓  24258 swift nominaltypedecl getdeclaredtypeincontext
  ✓  24270 swift typechecker resolveidentifiertype
  ✓  24275 llvm stringmapimpl lookupbucketfor
  ✓  24278 swift parser parsebraceitems
  ✓  24282 swift inflightdiagnostic highlight
  ✓  24285 swift typeloc iserror
  ✓  24287 swift typechecker validatedecl
  ✓  24288 clang datarecursiveastvisitor
  ✓  24289 swift lexer lexidentifier
  ✓  24303 swift typebase isspecialized
  ✓  24319 swift declcontext lookupqualified
  ✓  24325 swift nominaltypedecl computetype
  ✓  24326 swift configureimplicitself
  ✓  24330 bool
  ✓  24335 swift lexer getlocforendoftoken
  ✓  24338 swift typechecker computeaccessibility
  ✓  24342 swift boundgenerictype get
  ✓  24349 swift lexer getlocforendoftoken
  ✓  24351 swift unqualifiedlookup unqualifiedlookup
  ✓  24356 swift nominaltypedecl getprotocols
  ✓  24364 swift sourcefile getcache
  ✓  24369 swift typechecker validatetype
  ✓  24380 swift lexer kindofidentifier
  ✓  24387 swift typebase getanyoptionalobjecttype
  ✓  24388 llvm ondiskchainedhashtable swift modulefile decltable
  ✓  24397 llvm optional swift diagnostic operator
  ✓  24398 swift inflightdiagnostic
  ✓  24405 swift typebase getanyoptionalobjecttype
  ✓  24419 std function func std function void
  ✓  24420 swift functiontype get
  ✓  24422 swift nominaltypedecl getdeclaredtypeincontext
  ✓  24424 swift typechecker validategenerictypesignature
  ✓  24429 swift astcontext setrawcomment
  ✓  24442 swift typebase getcanonicaltype
  ✓  24451 swift nominaltypedecl preparelookuptable
  ✓  24452 swift type walk
  ✓  24455 llvm foldingset swift classtype nodeequals
  ✓  24463 swift lexer getlocforendoftoken
  ✓  24468 getselftypeforcontainer
  ✓  24473 swift functiontype get
  ✓  24485 checkredeclaration
  ✓  24488 swift inflightdiagnostic
  ✓  24489 swift metatypetype get
  ✓  24493 swift inflightdiagnostic
  ✓  24494 swift archetypebuilder inferrequirementswalker walktot
  ✓  24508 swift inflightdiagnostic highlight
  ✓  24512 swift constraints constraintsystem simplifyconstraint
  ✓  24521 swift typechecker validatedecl
  ✓  24522 swift nominaltypedecl getdeclaredtypeincontext
  ✓  24532 swift genericsignature profile
  ✓  24555 swift typebase getanyoptionalobjecttype
  ✓  24567 llvm aarch targetlowering lowerbuild vector
  ✓  24568 llvm ondiskchainedhashtable swift modulefile decltable
  ✓  24579 swift iterabledeclcontext getmembers
  ✓  24584 llvm ondiskchainedhashtable swift modulefile decltable
  ✓  24589 swift archetypebuilder potentialarchetype addconforman
  ✓  24604 swift constraints constraintsystem simplifyconstraint
  ✓  24620 swift modulefile lookupvalue
  ✓  24642 swift metatypetype get
  ✓  24649 swift parser parsetoken
  ✓  24662 swift streamprinter printtext
  ✓  24669 swift removeshadoweddecls
  ✓  24671 swift constraints constraintsystem constraintsystem
  ✓  24677 swift declname printpretty
  ✓  24680 swift typechecker validategenericfuncsignature
  ✓  24703 swift archetypebuilder inferrequirementswalker walktot
  ✓  24712 swift constraints constraintsystem getconstraintlocato
  ✓  24717 swift functiontype get
  ✓  24750 llvm foldingset swift tupletype nodeequals
  ✓  24754 swift parser parseexprpostfix
  ✓  24768 cc x
  ✓  24775 llvm optional swift diagnostic operator
  ✓  24788 swift patternbindingdecl setpattern
  ✓  24796 swift irgen unpackenumpayload claim
  ✓  24801 llvm foldingset swift boundgenerictype nodeequals
  ✓  24803 swift parser diagnose
  ✓  24804 swift substitutedtype get
  ✓  24805 swift modulefile readmembers
  ✓  24809 std tree node base void
  ✓  24816 swift modulefile lookupvalue
  ✓  24818 llvm ondiskchainedhashtable swift modulefile decltable
  ✓  24820 swift typechecker checkinheritanceclause
  ✓  24821 swift nominaltypedecl getprotocols
  ✓  24825 swift boundgenerictype get
  ✓  24826 swift patternbindingdecl setpattern
  ✓  24832 swift archetypebuilder addgenericparameter
  ✓  24836 void
  ✓  24839 swift typechecker validategenericfuncsignature
  ✓  24847 swift parser parsetype
  ✓  24860 llvm optional swift diagnostic operator
  ✓  24862 void
  ✓  24865 llvm densemapbase llvm densemap swift silbasicblock
  ✓  24869 llvm foldingset swift tupletype nodeequals
  ✓  24877 swift diagnosticengine flushactivediagnostic
  ✓  24880 swift silcloner anonymous namespace specializingcloner
  ✓  24882 extension generictype typealias
  ✓  24883 broken function
  ✓  24884 swift mangle mangler mangleidentifier
  ✓  24892 swift boundgenerictype getsubstitutions
  ✓  24893 emitnominalmetadataref
** Results: 180 of 2060 tests crashed the compiler **

```

License
=======
All files in this repository are distributed under the terms of the MIT license (see LICENSE).

redpajama_set_name: RedPajamaGithub


text:
using System.Collections.Generic;

namespace Bogosoft.Collections.Async
{
    /// <summary>
    /// Extended functionality for <see cref="IEnumerable{T}"/> types.
    /// </summary>
    public static class IEnumerableExtensions
    {
        /// <summary>
        /// Convert the current <see cref="IEnumerable{T}"/> type to an <see cref="IAsyncEnumerable{T}"/> type.
        /// </summary>
        /// <typeparam name="T">The type of the items in the collection.</typeparam>
        /// <param name="source">The current <see cref="IEnumerable{T}"/> implementation.</param>
        /// <returns>An asynchronously enumerable object.</returns>
        public static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerable<T> source)
        {
            return new AsyncEnumerableSequence<T>(source);
        }
    }
}


text:
package org.wso2.carbon.mss.examples.petstore.util.model;

/**
 * The pet category; such as dog, cat, bird, reptile, fish etc.
 */
public class Category {

    private String name;

    public Category() {}

    public Category(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


text:
from datetime import datetime

from flask_admin.contrib.sqla.filters import FloatSmallerFilter, \
    FloatGreaterFilter, FloatEqualFilter
from flask_admin.model import InlineFormAdmin
from flask_babelex import lazy_gettext, gettext
from flask_login import current_user

from psi.app import const
from psi.app.models import PurchaseOrder, EnumValues
from psi.app.services.purchase_order import PurchaseOrderService
from psi.app.utils import security_util
from psi.app.views import ModelViewWithAccess
from psi.app.views.base import DeleteValidator, ModelWithLineFormatter
from psi.app.views.components import DisabledStringField
from psi.app.views.formatter import product_field, quantity_field, remark_field, \
    unit_price_field, total_amount_field

class PurchaseOrderLineInlineAdmin(InlineFormAdmin):
    form_args = dict(
        product=dict(label=lazy_gettext('Product')),
        unit_price=dict(label=lazy_gettext('Unit Price')),
        quantity=dict(label=lazy_gettext('Quantity')),
        remark=dict(label=lazy_gettext('Remark')),
    )

    def postprocess_form(self, form):
        form.total_amount = DisabledStringField(
            label=lazy_gettext('Total Amount'))
        form.remark = None
        form.pol_receiving_lines = None
        return form

class BasePurchaseOrderAdmin(ModelViewWithAccess, DeleteValidator,
                             ModelWithLineFormatter):
    from psi.app.models import PurchaseOrderLine
    from psi.app.views.formatter import supplier_formatter, expenses_formatter, \
        receivings_formatter, default_date_formatter, line_formatter

    column_labels = {
        'id': lazy_gettext('id'),
        'logistic_amount': lazy_gettext('Logistic Amount'),
        'order_date': lazy_gettext('Order Date'),
        'to_organization': lazy_gettext('Supply Organization'),
        'supplier': lazy_gettext('Supplier'),
        'remark': lazy_gettext('Remark'),
        'status': lazy_gettext('Status'),
        'all_expenses': lazy_gettext('Related Expense'),
        'all_receivings': lazy_gettext('Related Receiving'),
        'total_amount': lazy_gettext('Total Amount'),
        'goods_amount': lazy_gettext('Goods Amount'),
        'lines': lazy_gettext('Lines'),
        'supplier.name': lazy_gettext('Supplier Name'),
        'status.display': lazy_gettext('Status')
    }

    @property
    def line_fields(self):
        if not security_util.user_has_role('purchase_price_view'):
            return [product_field, quantity_field, remark_field]
        else:
            return [
                product_field, quantity_field, unit_price_field,
                total_amount_field, remark_field
            ]

    column_formatters = {
        'supplier': supplier_formatter,
        'all_expenses': expenses_formatter,
        'all_receivings': receivings_formatter,
        'order_date': default_date_formatter,
        "lines": line_formatter
    }

    form_args = dict(
        status=dict(
            query_factory=PurchaseOrder.status_option_filter,
            description=lazy_gettext(
                'Purchase order can only be created in draft status, '
                'and partially '
                'received & received status are driven by associated '
                'receiving document')),
        supplier=dict(
            description=lazy_gettext(
                'Please select a supplier and save the form, '
                'then add purchase order lines accordingly')),
        logistic_amount=dict(default=0),
        order_date=dict(default=datetime.now()),
    )

    column_filters = ('order_date', 'logistic_amount', 'status.display',
                      FloatSmallerFilter(PurchaseOrder.goods_amount,
                                         lazy_gettext('Goods Amount')),
                      FloatGreaterFilter(PurchaseOrder.goods_amount,
                                         lazy_gettext('Goods Amount')),
                      FloatEqualFilter(PurchaseOrder.goods_amount,
                                       lazy_gettext('Goods Amount')))

    form_excluded_columns = ('expenses', 'receivings')
    column_editable_list = ('remark', )
    """Type code of the purchase orders should be displayed in the subview."""
    type_code = None

    def get_list_columns(self):
        """
        This method is called instantly in list.html
        List of columns is decided runtime during render of the table
        Not decided during flask-admin blueprint startup.
        """
        columns = super(BasePurchaseOrderAdmin, self).get_list_columns()
        cols = ['goods_amount', 'total_amount', 'all_expenses']
        columns = security_util.filter_columns_by_role(columns, cols,
                                                       'purchase_price_view')
        columns = self.filter_columns_by_organization_type(columns)
        return columns

    def filter_columns_by_organization_type(self, columns):
        new_col_list = []
        local_user = current_user._get_current_object()
        if local_user is not None and local_user.is_anonymous is False:
            if local_user.organization.type.code == "FRANCHISE_STORE":
                for col in columns:
                    if col[0] != 'supplier':
                        new_col_list.append(col)
            elif local_user.organization.type.code == "DIRECT_SELLING_STORE":
                for col in columns:
                    if col[0] != 'to_organization':
                        new_col_list.append(col)
            return tuple(new_col_list)
        else:
            return columns

    def get_details_columns(self):
        cols = ['goods_amount', 'total_amount', 'all_expenses']
        columns = super(BasePurchaseOrderAdmin, self).get_details_columns()
        columns = security_util.filter_columns_by_role(columns, cols,
                                                       'purchase_price_view')
        columns = self.filter_columns_by_organization_type(columns)
        return columns

    def on_model_change(self, form, model, is_created):
        super(BasePurchaseOrderAdmin, self).on_model_change(
            form, model, is_created)
        if not security_util.user_has_role('purchase_price_view'):
            for l in model.lines:
                l.unit_price = l.product.purchase_price
        DeleteValidator.validate_status_for_change(
            model, const.PO_RECEIVED_STATUS_KEY,
            gettext(
                'Purchase order can not be update nor delete on received status'
            ))
        if is_created:
            model.type = EnumValues.get(self.type_code)
        PurchaseOrderService.create_expense_receiving(model)

    def get_query(self):
        po_type = EnumValues.get(self.type_code)
        return super(BasePurchaseOrderAdmin,
                     self).get_query().filter(self.model.type == po_type)

    def get_count_query(self):
        po_type = EnumValues.get(self.type_code)
        return super(BasePurchaseOrderAdmin,
                     self).get_count_query().filter(self.model.type == po_type)

    def on_model_delete(self, model):
        super(BasePurchaseOrderAdmin, self).on_model_delete(model)
        DeleteValidator.validate_status_for_change(
            model, const.PO_RECEIVED_STATUS_KEY,
            gettext(
                'Purchase order can not be update nor delete on received status'
            ))
        DeleteValidator.validate_status_for_change(
            model, const.PO_ISSUED_STATUS_KEY,
            gettext(
                'Purchase order can not be update nor delete on issued status')
        )

    inline_models = (PurchaseOrderLineInlineAdmin(PurchaseOrderLine), )

    def after_model_change(self, form, model, is_created):
        pass

    def get_list(self,
                 page,
                 sort_field,
                 sort_desc,
                 search,
                 filters,
                 page_size=None):
        count, query = super(BasePurchaseOrderAdmin, self).get_list(
            page, sort_field, sort_desc, search, filters, page_size)
        self.session.commit()
        return count, query


text:
package com.diffplug.gradle.spotless;

import static org.junit.jupiter.api.condition.JRE.JAVA_11;

import java.io.IOException;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledForJreRange;

import com.diffplug.common.base.StringPrinter;

class SpotlessPluginRedirectTest extends GradleIntegrationHarness {
	@Test
	void redirectPluginModernGradle() throws IOException {
		setFile("build.gradle").toLines(
				"plugins {",
				"    id 'com.diffplug.gradle.spotless'",
				"}");
		Assertions.assertThat(gradleRunner().buildAndFail().getOutput().replace("\r", ""))
				.contains(StringPrinter.buildStringFromLines(
						"   > We have moved from 'com.diffplug.gradle.spotless'",
						"                     to 'com.diffplug.spotless'",
						"     To migrate:",
						"     - Test your build with: id 'com.diffplug.gradle.spotless' version '4.5.1'"));
	}

	@Test
	@EnabledForJreRange(max = JAVA_11)
	void redirectPluginOldGradle() throws IOException {
		setFile("build.gradle").toLines(
				"plugins {",
				"    id 'com.diffplug.gradle.spotless'",
				"}");
		Assertions.assertThat(gradleRunner().withGradleVersion(GradleVersionSupport.JRE_11.version)
				.buildAndFail().getOutput().replace("\r", ""))
				.contains(StringPrinter.buildStringFromLines(
						"> Failed to apply plugin [id 'com.diffplug.gradle.spotless']",
						"   > We have moved from 'com.diffplug.gradle.spotless'",
						"                     to 'com.diffplug.spotless'",
						"     To migrate:",
						"     - Upgrade gradle to 6.1.1 or newer (you're on 5.0)",
						"     - Test your build with: id 'com.diffplug.gradle.spotless' version '4.5.1'"));
	}

	@Test
	@EnabledForJreRange(max = JAVA_11)
	void realPluginOldGradle() throws IOException {
		setFile("build.gradle").toLines(
				"plugins {",
				"    id 'com.diffplug.spotless'",
				"}");
		Assertions.assertThat(gradleRunner().withGradleVersion(GradleVersionSupport.JRE_11.version)
				.buildAndFail().getOutput().replace("\r", ""))
				.contains(StringPrinter.buildStringFromLines(
						"Spotless requires Gradle 6.1.1 or newer, this was 5.0"));
	}
}


text:
from django.conf.urls import patterns, url

from servers import views

urlpatterns = [
  url(r'^$', views.server_list, name='server_list'),
  url(r'^new$', views.server_create, name='server_new'),
  url(r'^edit/(?P<pk>\d+)$', views.server_update, name='server_edit'),
  url(r'^delete/(?P<pk>\d+)$', views.server_delete, name='server_delete'),
]


text:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class Detectx extends Migration
{
    public function up()
    {
        $capsule = new Capsule();
        $capsule::schema()->create('detectx', function (Blueprint $table) {
            $table->increments('id');
            $table->string('serial_number')->unique();
            $table->bigInteger('searchdate');
            $table->integer('numberofissues');
            $table->string('status');
            $table->integer('scantime');
            $table->boolean('spotlightindexing');
            $table->boolean('registered');
            $table->text('infections');
            $table->text('issues');

            $table->index('numberofissues');
            $table->index('searchdate');
            $table->index('status');
            $table->index('scantime');
            $table->index('spotlightindexing');
        });
    }

    public function down()
    {
        $capsule = new Capsule();
        $capsule::schema()->dropIfExists('detectx');
    }
}


text:
<!DOCTYPE html>

  <title>DriveTeX</title>
  <meta charset="UTF-8">

  <link rel="import" href="third_party/google-apis/google-client-loader.html">
  <link rel="import" href="third_party/iron-autogrow-textarea/iron-autogrow-textarea.html">
  <link rel="import" href="third_party/iron-flex-layout/classes/iron-flex-layout.html">
  <link rel="import" href="third_party/iron-icons/iron-icons.html">
  <link rel="import" href="third_party/paper-drawer-panel/paper-drawer-panel.html">
  <link rel="import" href="third_party/paper-fab/paper-fab.html">
  <link rel="import" href="third_party/paper-header-panel/paper-header-panel.html">
  <link rel="import" href="third_party/paper-icon-button/paper-icon-button.html">
  <link rel="import" href="third_party/paper-item/paper-item.html">
  <link rel="import" href="third_party/paper-material/paper-material.html">
  <link rel="import" href="third_party/paper-menu/paper-menu.html">
  <link rel="import" href="third_party/paper-progress/paper-progress.html">
  <link rel="import" href="third_party/paper-toast/paper-toast.html">
  <link rel="import" href="third_party/paper-toolbar/paper-toolbar.html">

  <link rel="stylesheet" href="index.css">

<paper-drawer-panel id="drawerPanel">

  <paper-header-panel drawer>
    <paper-toolbar id="navheader">
      Menu
    </paper-toolbar>
    <paper-menu>
      <paper-item id="loadButton">Load</paper-item>
      <paper-item id="saveButton">Save</paper-item>
    </paper-menu>
  </paper-header-panel>

  <paper-header-panel main class="flex vertical layout">
    <paper-toolbar id="mainheader">
      <paper-icon-button id="menuicon" icon="menu" paper-drawer-toggle></paper-icon-button>
      Untitled
    </paper-toolbar>

        <paper-material class="card" elevation="1">
          <iron-autogrow-textarea id="editor-text"></iron-autogrow-textarea>
        </paper-material>

        <paper-progress id="compileProgress" indeterminate></paper-progress>

    <paper-fab id="generatePreviewButton" icon="arrow-forward"></paper-fab>
    <paper-toast id="savedToast" text="Saved" duration="2000"></paper-toast>
    <paper-toast id="saveFailedToast" text="There was a problem saving" role="alert"></paper-toast>
    <paper-toast id="compileProblemToast" text="There was a problem compiling"
                 role="alert"></paper-toast>
  </paper-header-panel>
</paper-drawer-panel>
<google-client-loader id="driveApi" name="drive" version="v2"></google-client-loader>


text:
package java8professional.tests;

public class Numbers {

    public static void main(String[] args) {
        System.out.println(5 / 4);
        System.out.println(5 / 4.0);
    }

}


text:
<?php

use IvoPetkov\DataList;
use IvoPetkov\DataListContext;

/**
 * @runTestsInSeparateProcesses
 */
class DataListFilterByOptimizationsTest extends PHPUnit\Framework\TestCase
{

    /**
     *
     */
    public function testOptimizations1()
    {
        $data = [
            ['value' => 'apple'],
            ['value' => 'ant'],
            ['value' => 'bear'],
            ['value' => 'dog'],
            ['value' => 'donkey'],
        ];
        $list = new DataList($data);
        $list->filterBy('value', 'a', 'startWith');
        $this->assertEquals($list->toArray(), array(
            0 =>
            array(
                'value' => 'apple',
            ),
            1 =>
            array(
                'value' => 'ant',
            ),
        ));
    }

    /**
     *
     */
    public function testOptimizations2()
    {
        $data = [
            ['value' => 'apple'],
            ['value' => 'ant'],
            ['value' => 'bear'],
            ['value' => 'dog'],
            ['value' => 'donkey'],
        ];
        $list = new DataList($data);
        $list->filterBy('value', 'a', 'startWith');
        $list->filterBy('value', 'b', 'startWith');
        $this->assertEquals($list->toArray(), array());
    }

    /**
     *
     */
    public function testOptimizations3()
    {
        $data = [
            ['value' => 'apple'],
            ['value' => 'ant'],
            ['value' => 'bear'],
            ['value' => 'dog'],
            ['value' => 'donkey'],
        ];
        $list = new DataList($data);
        $list->filterBy('value', 'd', 'startWith');
        $list->filterBy('value', 'x1', 'notStartWith');
        $list->filterBy('value', 'x2', 'notStartWith');
        $list->filterBy('value', 'x3', 'notStartWith');
        $this->assertEquals($list->toArray(), array(
            0 =>
            array(
                'value' => 'dog',
            ),
            1 =>
            array(
                'value' => 'donkey',
            ),
        ));
    }

    /**
     *
     */
    public function testOptimizations4()
    {
        $data = [
            ['value' => 'apple'],
            ['value' => 'ant'],
            ['value' => 'bear'],
            ['value' => 'dog'],
            ['value' => 'donkey'],
        ];
        $list = new DataList($data);
        $list->filterBy('value', 'd', 'notStartWith');
        $list->filterBy('value', 'x', 'notStartWith');
        $this->assertEquals($list->toArray(), array(
            0 =>
            array(
                'value' => 'apple',
            ),
            1 =>
            array(
                'value' => 'ant',
            ),
            2 =>
            array(
                'value' => 'bear',
            ),
        ));
    }

    /**
     *
     */
    public function testOptimizations5()
    {
        $data = [
            ['value' => 'apple'],
            ['value' => 'ant'],
            ['value' => 'bear'],
            ['value' => 'dog'],
            ['value' => 'donkey'],
        ];
        $list = new DataList($data);
        $list->filterBy('value', 'do', 'startWith');
        $list->filterBy('value', 'd', 'notStartWith');
        $this->assertEquals($list->toArray(), array());
    }

    /**
     *
     */
    public function testCallbackOptimizations1()
    {
        $passedContext = null;
        $list = new DataList(function (DataListContext $context) use (&$passedContext) {
            $passedContext = $context;
            return [['value' => 'countries/bulgaria']];
        });
        $list->filterBy('value', 'countries/', 'startWith');
        $this->assertEquals($list->count(), 1);
        $this->assertEquals(sizeof($passedContext->actions), 1);
        $this->assertEquals($passedContext->actions[0]->toArray(), array(
            'name' => 'filterBy',
            'operator' => 'startWith',
            'property' => 'value',
            'value' => 'countries/',
        ));
    }

    /**
     *
     */
    public function testCallbackOptimizations2()
    {
        $passedContext = null;
        $list = new DataList(function (DataListContext $context) use (&$passedContext) {
            $passedContext = $context;
            return [];
        });
        $list->filterBy('value', 'countries/', 'startWith');
        $list->filterBy('value', 'food/', 'startWith');
        $this->assertEquals($list->count(), 0);
        $this->assertEquals($passedContext, null);
    }

    /**
     *
     */
    public function testCallbackOptimizations3()
    {
        $passedContext = null;
        $list = new DataList(function (DataListContext $context) use (&$passedContext) {
            $passedContext = $context;
            return [['value' => 'countries/bulgaria']];
        });
        $list->filterBy('value', 'countries/', 'startWith');
        $list->filterBy('value', 'food/a', 'notStartWith');
        $list->filterBy('value', 'food/b', 'notStartWith');
        $list->filterBy('value', 'food/c', 'notStartWith');
        $this->assertEquals($list->count(), 1);
        $this->assertEquals(sizeof($passedContext->actions), 1);
        $this->assertEquals($passedContext->actions[0]->toArray(), array(
            'name' => 'filterBy',
            'operator' => 'startWith',
            'property' => 'value',
            'value' => 'countries/',
        ));
    }

    /**
     *
     */
    public function testCallbackOptimizations4()
    {
        $passedContext = null;
        $list = new DataList(function (DataListContext $context) use (&$passedContext) {
            $passedContext = $context;
            return [['value' => 'countries/bulgaria']];
        });
        $list->filterBy('value', 'countries/', 'startWith');
        $list->filterBy('value', 'cou', 'notStartWith');
        $this->assertEquals($list->count(), 0);
        $this->assertEquals($passedContext, null);
    }
}


text:
using System.ComponentModel;
using System.Globalization;
using System.Text.Json;

namespace Microsoft.AspNetCore.Components;

// This is some basic coverage, it's not in depth because there are many many APIs here
// and they mostly call through to CoreFx. We don't want to test the globalization details
// of .NET in detail where we can avoid it.
//
// Instead there's a sampling of things that have somewhat unique behavior or semantics.
public class BindConverterTest
{
    [Fact]
    public void FormatValue_Bool()
    {
        // Arrange
        var value = true;
        var expected = true;

        // Act
        var actual = BindConverter.FormatValue(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_Bool_Generic()
    {
        // Arrange
        var value = true;
        var expected = true;

        // Act
        var actual = BindConverter.FormatValue<bool>(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_NullableBool()
    {
        // Arrange
        var value = (bool?)true;
        var expected = true;

        // Act
        var actual = BindConverter.FormatValue(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_NullableBool_Generic()
    {
        // Arrange
        var value = true;
        var expected = true;

        // Act
        var actual = BindConverter.FormatValue<bool?>(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_NullableBoolNull()
    {
        // Arrange
        var value = (bool?)null;
        var expected = (bool?)null;

        // Act
        var actual = BindConverter.FormatValue(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_NullableBoolNull_Generic()
    {
        // Arrange
        var value = (bool?)null;
        var expected = (bool?)null;

        // Act
        var actual = BindConverter.FormatValue<bool?>(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_Int()
    {
        // Arrange
        var value = 17;
        var expected = "17";

        // Act
        var actual = BindConverter.FormatValue(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_Int_Generic()
    {
        // Arrange
        var value = 17;
        var expected = "17";

        // Act
        var actual = BindConverter.FormatValue<int>(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_NullableInt()
    {
        // Arrange
        var value = (int?)17;
        var expected = "17";

        // Act
        var actual = BindConverter.FormatValue(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_NullableInt_Generic()
    {
        // Arrange
        var value = 17;
        var expected = "17";

        // Act
        var actual = BindConverter.FormatValue<int?>(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_DateTime()
    {
        // Arrange
        var value = DateTime.Now;
        var expected = value.ToString(CultureInfo.CurrentCulture);

        // Act
        var actual = BindConverter.FormatValue(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_DateTime_Format()
    {
        // Arrange
        var value = DateTime.Now;
        var expected = value.ToString("MM-yyyy", CultureInfo.InvariantCulture);

        // Act
        var actual = BindConverter.FormatValue(value, "MM-yyyy", CultureInfo.InvariantCulture);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_DateOnly()
    {
        // Arrange
        var value = DateOnly.FromDateTime(DateTime.Now);
        var expected = value.ToString(CultureInfo.CurrentCulture);

        // Act
        var actual = BindConverter.FormatValue(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_DateOnly_Format()
    {
        // Arrange
        var value = DateOnly.FromDateTime(DateTime.Now);
        var expected = value.ToString("MM-yyyy", CultureInfo.InvariantCulture);

        // Act
        var actual = BindConverter.FormatValue(value, "MM-yyyy", CultureInfo.InvariantCulture);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_TimeOnly()
    {
        // Arrange
        var value = TimeOnly.FromDateTime(DateTime.Now);
        var expected = value.ToString(CultureInfo.CurrentCulture);

        // Act
        var actual = BindConverter.FormatValue(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_TimeOnly_Format()
    {
        // Arrange
        var value = TimeOnly.FromDateTime(DateTime.Now);
        var expected = value.ToString("HH:mm", CultureInfo.InvariantCulture);

        // Act
        var actual = BindConverter.FormatValue(value, "HH:mm", CultureInfo.InvariantCulture);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_Enum()
    {
        // Arrange
        var value = SomeLetters.A;
        var expected = value.ToString();

        // Act
        var actual = BindConverter.FormatValue(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_Enum_OutOfRange()
    {
        // Arrange
        var value = SomeLetters.A + 3;
        var expected = value.ToString();

        // Act
        var actual = BindConverter.FormatValue(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void FormatValue_NullableEnum()
    {
        // Arrange
        var value = (SomeLetters?)null;

        // Act
        var actual = BindConverter.FormatValue(value);

        // Assert
        Assert.Null(actual);
    }

    [Fact]
    public void FormatValue_TypeConverter()
    {
        // Arrange
        var value = new Person()
        {
            Name = "Glenn",
            Age = 47,
        };

        var expected = JsonSerializer.Serialize(value);

        // Act
        var actual = BindConverter.FormatValue(value);

        // Assert
        Assert.Equal(expected, actual);
    }

    [Fact]
    public void TryConvertTo_Guid_Valid()
    {
        // Arrange
        var expected = Guid.NewGuid();
        var incomingValue = expected.ToString();

        // Act
        var successfullyConverted = BindConverter.TryConvertTo<Guid>(incomingValue, CultureInfo.CurrentCulture, out var actual);

        // Assert
        Assert.Equal(expected, actual);
        Assert.True(successfullyConverted);
    }

    [Theory]
    [InlineData("invalidguid")]
    [InlineData("")]
    [InlineData(null)]
    public void TryConvertTo_Guid_Invalid(string incomingValue)
    {
        // Act
        var successfullyConverted = BindConverter.TryConvertTo<Guid>(incomingValue, CultureInfo.CurrentCulture, out var actual);

        // Assert
        Assert.False(successfullyConverted);
        Assert.Equal(Guid.Empty, actual);
    }

    [Fact]
    public void TryConvertTo_NullableGuid_Valid()
    {
        // Arrange
        var expected = Guid.NewGuid();
        var incomingValue = expected.ToString();

        // Act
        var successfullyConverted = BindConverter.TryConvertTo<Guid?>(incomingValue, CultureInfo.CurrentCulture, out var actual);

        // Assert
        Assert.True(successfullyConverted);
        Assert.Equal(expected, actual.Value);
    }

    [Theory]
    [InlineData(null)]
    [InlineData("")]
    public void TryConvertTo_NullableGuid_ValidEmptyOrNull(string incomingValue)
    {
        // Act
        var successfullyConverted = BindConverter.TryConvertTo<Guid?>(incomingValue, CultureInfo.CurrentCulture, out var actual);

        // Assert
        Assert.True(successfullyConverted);
        Assert.Null(actual);
    }

    [Fact]
    public void TryConvertTo_NullableGuid__Invalid()
    {
        // Arrange
        var value = "invalidguid";

        // Act
        var successfullyConverted = BindConverter.TryConvertTo<Guid?>(value, CultureInfo.CurrentCulture, out var actual);

        // Assert
        Assert.False(successfullyConverted);
        Assert.Null(actual);
    }

    private enum SomeLetters
    {
        A,
        B,
        C,
        Q,
    }

    [TypeConverter(typeof(PersonConverter))]
    private class Person
    {
        public string Name { get; set; }

        public int Age { get; set; }
    }

    private class PersonConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }

            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string text)
            {
                return JsonSerializer.Deserialize<Person>(text);
            }

            return base.ConvertFrom(context, culture, value);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return true;
            }

            return base.CanConvertTo(context, destinationType);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                return JsonSerializer.Serialize((Person)value);
            }

            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}


text:
'use strict';

// eslint-disable-next-line new-cap

const bcrypt = require('bcrypt-as-promised');
const boom = require('boom');
const express = require('express');
const knex = require('../knex');
const request = require('request');
const moment = require('moment-timezone');
const jwt = require('jsonwebtoken');
const { camelizeKeys, decamelizeKeys } = require('humps');

const router = express.Router();

const authorize = function(req, res, next) {
  jwt.verify(req.cookies.token, process.env.JWT_SECRET, (err, decoded) => {
    if (err) {
      return next(boom.create(401, 'Unauthorized'));
    }

    req.token = decoded;
    next();
  });
};

router.get('/events', authorize, (_req, res, next) => {

  const date = moment.tz('America/Vancouver').format();
  console.log(date);
  request(`http://api.jambase.com/events?zipCode=98034&radius=50&startDate=${date}&page=0&api_key=uazyeq8ba3c3vxa6uewvud2b`, (err, response, body) => {

    if (err) {
      return next(boom.create(400, 'Bad Request'));
    }
    const obj = JSON.parse(body);

    res.send(obj);
  });
});

router.post('/attendeesGoing', authorize, (req, res, next) => {
  const { userId } = req.token;
  const eventId = req.body.eventId;

  knex('user_events')
    .innerJoin('users', 'users.id', 'user_events.user_id')
    .whereNot('user_id', userId)
    .andWhere('event_id', eventId)
    .andWhere('going', true)
    .then((rows) => {
      if (!rows) {
        return next(boom.create(400, 'something went wrong.'));
      }
      const camelRows = camelizeKeys(rows);

      res.send(camelRows);
    })
    .catch((err) => {
      next(err);
    });
});

router.post('/attendeesMaybe', authorize, (req, res, next) => {
  const { userId } = req.token;
  const eventId = req.body.eventId;

  knex('user_events')
    .innerJoin('users', 'users.id', 'user_events.user_id')
    .whereNot('user_id', userId)
    .andWhere('event_id', eventId)
    .andWhere('maybe', true)
    .then((rows) => {
      if (!rows) {
        return next(boom.create(400, 'something went wrong.'));
      }
      const camelRows = camelizeKeys(rows);

      res.send(camelRows);
    })
    .catch((err) => {
      next(err);
    });
});

router.get('/going', authorize, (req, res, next) => {
  const { userId } = req.token;

  knex('user_events')
    .where('user_id', userId)
    .andWhere('going', true)
    .then((rows) => {
      if (!rows) {
        return next(boom.create(400, 'something went wrong.'));
      }
      const userEvents = camelizeKeys(rows);

      res.send(userEvents);
    })
    .catch((err) => {
      next(err);
    });
});

router.get('/maybe', authorize, (req, res, next) => {
  const { userId } = req.token;

  knex('user_events')
    .where('user_id', userId)
    .andWhere('maybe', true)
    .then((rows) => {
      if (!rows) {
        return next(boom.create(400, 'something went wrong.'));
      }
      const userEvents = camelizeKeys(rows);

      res.send(userEvents);
    })
    .catch((err) => {
      next(err);
    });
});

router.post('/events', authorize, (req, res, next) => {
  const { userId } = req.token;

  let insertEvent = {
    userId: userId,
    going: req.body.going,
    maybe: req.body.maybe,
    artistName: req.body.artistName,
    venueName: req.body.venueName,
    eventDate: req.body.eventDate,
    eventId: req.body.eventId
  };

  knex('user_events')
    .where('user_id', userId)
    .andWhere('event_id', insertEvent.eventId)
    .then((rows) => {
      if (rows.length > 0) {
        return next(boom.create(400, 'Event already exists.'))
      }
      else {
        return knex('user_events')
        .insert(decamelizeKeys(insertEvent))
        .then((row) => {
          if (!row) {
            return next(boom.create(400, 'something went wrong.'));
          }

          res.send(true);
        })
      }
    })
    .catch((err) => {
      next(err);
    });
});

router.delete('/events', authorize, (req, res, next) => {
  const { userId } = req.token;
  const eventId = req.body.eventId;
  const event = {};

  knex('user_events')
    .where('user_id', userId)
    .andWhere('event_id', eventId)
    .then((row) => {
      if (!row) {
        return next(boom.create(404, 'Event not found.'));
      }

      event.userId = userId;
      event.eventId = eventId;

      return knex('user_events')
        .del()
        .where('event_id', eventId)
        .andWhere('user_id', userId)
    })
    .then(() => {
      res.send(camelizeKeys(event));
    })
    .catch((err) => {
      next(err);
    });
});

module.exports = router;


text:
1.  Create a table in SQL Server with 10 000 000 log entries (date + text).
  * Search in the table by date range. Check the speed (without caching).
1.  Add an index to speed-up the search by date.
  * Test the search speed (after cleaning the cache).
1.  Add a full text index for the text column.
  * Try to search with and without the full-text index and compare the speed.
1.  Create the same table in MySQL and partition it by date (1990, 2000, 2010).
  * Fill 1 000 000 log entries.
  * Compare the searching speed in all partitions (random dates) to certain partition (e.g. year 1995).


text:
using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;

namespace FTDISample.Converters
{
    public class InvertedExistenceToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return value == null ? Visibility.Visible : Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}


text:
NS=mycompany
VERSION ?= local
PORTS= \
	-p 3000:3000
VOLUMES= -v $PWD:/usr/src/app
WORKDIR= -w /usr/src/app
REPO=myrepo.local
NAME=web
INSTANCE=default
ENV= \
	-e RAILS_ENV=production

.PHONY: build push shell run start stop rm release up down

up:
	docker-compose up

down:
	docker-compose down

exec:
	docker exec -it ${NAME} bash

irb:
	docker exec -it ${NAME} rails console

build:
	docker build -t $(REPO)/$(NAME):$(VERSION) .

push:
	docker push $(REPO)/$(NAME):$(VERSION)

shell:
	docker run --rm --name $(NAME)-$(INSTANCE) -i -t $(PORTS) $(WORKDIR) $(ENV) $(REPO)/$(NAME):$(VERSION) /bin/bash

run:
	docker run -it --rm --name $(NAME)-$(INSTANCE) $(PORTS) $(ENV) $(REPO)/$(NAME):$(VERSION)

start:
	docker run -d --name $(NAME)-$(INSTANCE) $(PORTS) $(ENV) $(REPO)/$(NAME):$(VERSION)

stop:
	docker stop $(NAME)-$(INSTANCE)

rm:
	docker rm $(NAME)-$(INSTANCE)

release: build
	make push -e VERSION=$(VERSION)

default: build


text:
#import "EC2Filter.h"

#ifdef AWS_MULTI_FRAMEWORK
#import <AWSRuntime/AmazonServiceRequestConfig.h>
#else
#import "AmazonServiceRequestConfig.h"
#endif

/**
 * Describe Spot Price History Request
 */

@interface EC2DescribeSpotPriceHistoryRequest:AmazonServiceRequestConfig

{
    BOOL           dryRun;
    BOOL           dryRunIsSet;
    NSDate         *startTime;
    NSDate         *endTime;
    NSMutableArray *instanceTypes;
    NSMutableArray *productDescriptions;
    NSMutableArray *filters;
    NSString       *availabilityZone;
    NSNumber       *maxResults;
    NSString       *nextToken;
}

/**
 * Default constructor for a new  object.  Callers should use the
 * property methods to initialize this object after creating it.
 */
-(id)init;

/**
 * The value of the DryRun property for this object.
 */
@property (nonatomic) BOOL           dryRun;

@property (nonatomic, readonly) BOOL dryRunIsSet;

/**
 * The start date and time of the Spot Instance price history data.
 */
@property (nonatomic, retain) NSDate *startTime;

/**
 * The end date and time of the Spot Instance price history data.
 */
@property (nonatomic, retain) NSDate *endTime;

/**
 * Specifies the instance type to return.
 */
@property (nonatomic, retain) NSMutableArray *instanceTypes;

/**
 * The description of the AMI.
 */
@property (nonatomic, retain) NSMutableArray *productDescriptions;

/**
 * A list of filters used to match properties for SpotPriceHistory. For a
 * complete reference to the available filter keys for this operation,
 * see the <a
 * "http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/">Amazon
 * EC2 API reference</a>.
 */
@property (nonatomic, retain) NSMutableArray *filters;

/**
 * Filters the results by availability zone (ex: 'us-east-1a').
 */
@property (nonatomic, retain) NSString *availabilityZone;

/**
 * Specifies the number of rows to return.
 */
@property (nonatomic, retain) NSNumber *maxResults;

/**
 * Specifies the next set of rows to return.
 */
@property (nonatomic, retain) NSString *nextToken;

/**
 * Adds a single object to instanceTypes.
 * This function will alloc and init instanceTypes if not already done.
 */
-(void)addInstanceType:(NSString *)instanceTypeObject;

/**
 * Adds a single object to productDescriptions.
 * This function will alloc and init productDescriptions if not already done.
 */
-(void)addProductDescription:(NSString *)productDescriptionObject;

/**
 * Adds a single object to filters.
 * This function will alloc and init filters if not already done.
 */
-(void)addFilter:(EC2Filter *)filterObject;

/**
 * Returns a string representation of this object; useful for testing and
 * debugging.
 *
 * @return A string representation of this object.
 */
-(NSString *)description;

@end


text:
"use strict";
var router_1 = require('@angular/router');
var common_resources_1 = require('./common/common.resources');
var auth_routing_1 = require('./auth/auth.routing');
var pages_routing_1 = require('./pages/pages.routing');
var admin_routing_1 = require('./admin/admin.routing');
var routes = [
    { path: '', redirectTo: '/signin', pathMatch: 'full' }
].concat(auth_routing_1.authRoutes, pages_routing_1.pagesRoutes, admin_routing_1.adminRoutes);
exports.appRoutingProviders = [
    common_resources_1.commonProviders,
    auth_routing_1.authProviders,
    admin_routing_1.adminProviders
];
exports.routing = router_1.RouterModule.forRoot(routes, { useHash: true });
//# sourceMappingURL=app.routing.js.map


text:
import { Component, OnInit, Input } from '@angular/core';

import { User } from 'app/domain/user-model';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'app-user-login',
  templateUrl: './user-login.component.html',
  styleUrls: ['./user-login.component.css']
})
export class UserLoginComponent implements OnInit {
  public user: User = new User();
  public error: Error;

  constructor() {
  }

  ngOnInit() {
  }

  public doLogin(f: NgForm): void {
    console.log('form', f); // f是NgForm类型
    console.log('form.submitted', f.submitted);
    console.log('form.valid', f.valid);
    console.log('form.form.valid', f.form.valid);
    console.log('form.form', f.form);
  }

  public doLogout(): void {
  }

  public forgetPwd(): void {
  }
}


text:
"""Tests the Home Assistant workday binary sensor."""
from datetime import date

import pytest
import voluptuous as vol

import homeassistant.components.workday.binary_sensor as binary_sensor
from homeassistant.setup import setup_component

from tests.async_mock import patch
from tests.common import assert_setup_component, get_test_home_assistant

FUNCTION_PATH = "homeassistant.components.workday.binary_sensor.get_date"

class TestWorkdaySetup:
    """Test class for workday sensor."""

    def setup_method(self):
        """Set up things to be run when tests are started."""
        self.hass = get_test_home_assistant()

        # Set valid default config for test
        self.config_province = {
            "binary_sensor": {"platform": "workday", "country": "DE", "province": "BW"}
        }

        self.config_noprovince = {
            "binary_sensor": {"platform": "workday", "country": "DE"}
        }

        self.config_invalidprovince = {
            "binary_sensor": {
                "platform": "workday",
                "country": "DE",
                "province": "invalid",
            }
        }

        self.config_state = {
            "binary_sensor": {"platform": "workday", "country": "US", "province": "CA"}
        }

        self.config_nostate = {
            "binary_sensor": {"platform": "workday", "country": "US"}
        }

        self.config_includeholiday = {
            "binary_sensor": {
                "platform": "workday",
                "country": "DE",
                "province": "BW",
                "workdays": ["holiday"],
                "excludes": ["sat", "sun"],
            }
        }

        self.config_example1 = {
            "binary_sensor": {
                "platform": "workday",
                "country": "US",
                "workdays": ["mon", "tue", "wed", "thu", "fri"],
                "excludes": ["sat", "sun"],
            }
        }

        self.config_example2 = {
            "binary_sensor": {
                "platform": "workday",
                "country": "DE",
                "province": "BW",
                "workdays": ["mon", "wed", "fri"],
                "excludes": ["sat", "sun", "holiday"],
                "add_holidays": ["2020-02-24"],
            }
        }

        self.config_tomorrow = {
            "binary_sensor": {"platform": "workday", "country": "DE", "days_offset": 1}
        }

        self.config_day_after_tomorrow = {
            "binary_sensor": {"platform": "workday", "country": "DE", "days_offset": 2}
        }

        self.config_yesterday = {
            "binary_sensor": {"platform": "workday", "country": "DE", "days_offset": -1}
        }

    def teardown_method(self):
        """Stop everything that was started."""
        self.hass.stop()

    def test_valid_country(self):
        """Test topic name/filter validation."""
        # Invalid UTF-8, must not contain U+D800 to U+DFFF
        with pytest.raises(vol.Invalid):
            binary_sensor.valid_country("\ud800")
        with pytest.raises(vol.Invalid):
            binary_sensor.valid_country("\udfff")
        # Country MUST NOT be empty
        with pytest.raises(vol.Invalid):
            binary_sensor.valid_country("")
        # Country must be supported by holidays
        with pytest.raises(vol.Invalid):
            binary_sensor.valid_country("HomeAssistantLand")

    def test_setup_component_province(self):
        """Set up workday component."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_province)
            self.hass.block_till_done()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity is not None

    # Freeze time to a workday - Mar 15th, 2017
    @patch(FUNCTION_PATH, return_value=date(2017, 3, 15))
    def test_workday_province(self, mock_date):
        """Test if workdays are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_province)
            self.hass.block_till_done()

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "on"

    # Freeze time to a weekend - Mar 12th, 2017
    @patch(FUNCTION_PATH, return_value=date(2017, 3, 12))
    def test_weekend_province(self, mock_date):
        """Test if weekends are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_province)
            self.hass.block_till_done()

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "off"

    # Freeze time to a public holiday in province BW - Jan 6th, 2017
    @patch(FUNCTION_PATH, return_value=date(2017, 1, 6))
    def test_public_holiday_province(self, mock_date):
        """Test if public holidays are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_province)
            self.hass.block_till_done()

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "off"

    def test_setup_component_noprovince(self):
        """Set up workday component."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_noprovince)
            self.hass.block_till_done()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity is not None

    # Freeze time to a public holiday in province BW - Jan 6th, 2017
    @patch(FUNCTION_PATH, return_value=date(2017, 1, 6))
    def test_public_holiday_noprovince(self, mock_date):
        """Test if public holidays are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_noprovince)
            self.hass.block_till_done()

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "on"

    # Freeze time to a public holiday in state CA - Mar 31st, 2017
    @patch(FUNCTION_PATH, return_value=date(2017, 3, 31))
    def test_public_holiday_state(self, mock_date):
        """Test if public holidays are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_state)

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "off"

    # Freeze time to a public holiday in state CA - Mar 31st, 2017
    @patch(FUNCTION_PATH, return_value=date(2017, 3, 31))
    def test_public_holiday_nostate(self, mock_date):
        """Test if public holidays are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_nostate)

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "on"

    def test_setup_component_invalidprovince(self):
        """Set up workday component."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_invalidprovince)

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity is None

    # Freeze time to a public holiday in province BW - Jan 6th, 2017
    @patch(FUNCTION_PATH, return_value=date(2017, 1, 6))
    def test_public_holiday_includeholiday(self, mock_date):
        """Test if public holidays are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_includeholiday)

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "on"

    # Freeze time to a saturday to test offset - Aug 5th, 2017
    @patch(FUNCTION_PATH, return_value=date(2017, 8, 5))
    def test_tomorrow(self, mock_date):
        """Test if tomorrow are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_tomorrow)

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "off"

    # Freeze time to a saturday to test offset - Aug 5th, 2017
    @patch(FUNCTION_PATH, return_value=date(2017, 8, 5))
    def test_day_after_tomorrow(self, mock_date):
        """Test if the day after tomorrow are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_day_after_tomorrow)

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "on"

    # Freeze time to a saturday to test offset - Aug 5th, 2017
    @patch(FUNCTION_PATH, return_value=date(2017, 8, 5))
    def test_yesterday(self, mock_date):
        """Test if yesterday are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_yesterday)

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "on"

    # Freeze time to a Presidents day to test Holiday on a Work day - Jan 20th, 2020
    #   Presidents day Feb 17th 2020 is mon.
    @patch(FUNCTION_PATH, return_value=date(2020, 2, 17))
    def test_config_example1_holiday(self, mock_date):
        """Test if public holidays are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_example1)

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "on"

    # Freeze time to test tue - Feb 18th, 2020
    @patch(FUNCTION_PATH, return_value=date(2020, 2, 18))
    def test_config_example2_tue(self, mock_date):
        """Test if public holidays are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_example2)

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "off"

    # Freeze time to test mon, but added as holiday - Feb 24th, 2020
    @patch(FUNCTION_PATH, return_value=date(2020, 2, 24))
    def test_config_example2_add_holiday(self, mock_date):
        """Test if public holidays are reported correctly."""
        with assert_setup_component(1, "binary_sensor"):
            setup_component(self.hass, "binary_sensor", self.config_example2)

        self.hass.start()

        entity = self.hass.states.get("binary_sensor.workday_sensor")
        assert entity.state == "off"

    def test_day_to_string(self):
        """Test if day_to_string is behaving correctly."""
        assert binary_sensor.day_to_string(0) == "mon"
        assert binary_sensor.day_to_string(1) == "tue"
        assert binary_sensor.day_to_string(7) == "holiday"
        assert binary_sensor.day_to_string(8) is None


text:
class CreateRelationships < ActiveRecord::Migration
  def change
    create_table :relationships do |t|
      t.integer :follower_id, index: true
      t.integer :followed_id, index: true

      t.timestamps

    end

  end
end


text:
package us.kbase.fbatools;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

/**
 *
Original spec-file type: ExportOutput

 *
 *
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({
    "shock_id"
})
public class ExportOutput {

    @JsonProperty("shock_id")
    private String shockId;
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("shock_id")
    public String getShockId() {
        return shockId;
    }

    @JsonProperty("shock_id")
    public void setShockId(String shockId) {
        this.shockId = shockId;
    }

    public ExportOutput withShockId(String shockId) {
        this.shockId = shockId;
        return this;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperties(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

    @Override
    public String toString() {
        return ((((("ExportOutput"+" [shockId=")+ shockId)+", additionalProperties=")+ additionalProperties)+"]");
    }

}


text:
"""Unit tests for common.py."""

import unittest

from webkitpy.style.checkers.common import CarriageReturnChecker
from webkitpy.style.checkers.common import TabChecker

# FIXME: The unit tests for the cpp, text, and common checkers should
#        share supporting test code. This can include, for example, the
#        mock style error handling code and the code to check that all
#        of a checker's categories are covered by the unit tests.
#        Such shared code can be located in a shared test file, perhaps
#        even this file.

class CarriageReturnCheckerTest(unittest.TestCase):

    """Tests check_no_carriage_return()."""

    _category = 'whitespace/carriage_return'
    _confidence = 1
    _expected_message = ('One or more unexpected \\r (^M) found; '
                         'better to use only a \\n')

    def setUp(self):
        self._style_errors = []  # The list of accumulated style errors.

    def _mock_style_error_handler(self, line_number, category, confidence,
                                  message):
        """Append the error information to the list of style errors."""
        error = (line_number, category, confidence, message)
        self._style_errors.append(error)

    def assert_carriage_return(self, input_lines, expected_lines, error_lines):
        """Process the given line and assert that the result is correct."""
        handle_style_error = self._mock_style_error_handler

        checker = CarriageReturnChecker(handle_style_error)
        output_lines = checker.check(input_lines)

        # Check both the return value and error messages.
        self.assertEqual(output_lines, expected_lines)

        expected_errors = [(line_number, self._category, self._confidence,
                            self._expected_message)
                           for line_number in error_lines]
        self.assertEqual(self._style_errors, expected_errors)

    def test_ends_with_carriage(self):
        self.assert_carriage_return(['carriage return\r'],
                                    ['carriage return'],
                                    [1])

    def test_ends_with_nothing(self):
        self.assert_carriage_return(['no carriage return'],
                                    ['no carriage return'],
                                    [])

    def test_ends_with_newline(self):
        self.assert_carriage_return(['no carriage return\n'],
                                    ['no carriage return\n'],
                                    [])

    def test_carriage_in_middle(self):
        # The CarriageReturnChecker checks only the final character
        # of each line.
        self.assert_carriage_return(['carriage\r in a string'],
                                    ['carriage\r in a string'],
                                    [])

    def test_multiple_errors(self):
        self.assert_carriage_return(['line1', 'line2\r', 'line3\r'],
                                    ['line1', 'line2', 'line3'],
                                    [2, 3])

class TabCheckerTest(unittest.TestCase):

    """Tests for TabChecker."""

    def assert_tab(self, input_lines, error_lines):
        """Assert when the given lines contain tabs."""
        self._error_lines = []

        def style_error_handler(line_number, category, confidence, message):
            self.assertEqual(category, 'whitespace/tab')
            self.assertEqual(confidence, 5)
            self.assertEqual(message, 'Line contains tab character.')
            self._error_lines.append(line_number)

        checker = TabChecker('', style_error_handler)
        checker.check(input_lines)
        self.assertEqual(self._error_lines, error_lines)

    def test_notab(self):
        self.assert_tab([''], [])
        self.assert_tab(['foo', 'bar'], [])

    def test_tab(self):
        self.assert_tab(['\tfoo'], [1])
        self.assert_tab(['line1', '\tline2', 'line3\t'], [2, 3])


text:
require 'spec_helper'
include Warden::Test::Helpers

describe UserSessionsController do
  fixtures :all
  before(:each) do
    @tuser = FactoryGirl.create :tuser
  end
  after(:each) do
    Warden.test_reset!
  end

  it "should call new method" do
    mock_warden(nil)
    {:get => 'login'}.should route_to(:controller => 'user_sessions', :action => 'new')
    get :new
    response.should be_success
  end

  it "should create user session" do
    mock_warden(nil)
    post :create, :user_session => { :username => @tuser.username, :password => "secret" }
    response.should redirect_to(root_url)
  end

  it "should destroy user session" do
    mock_warden(@tuser)
    delete :destroy
    response.should redirect_to(login_path)
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <stroke android:width="0dp" android:color="#ffffff" />
    <solid android:color="@color/color_1"/>
</shape>


text:
'use strict';

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
var roles = [0, 1, 2];

/**
 * User Schema
 */
var Role = new Schema({
    role: {
        type: Number,
        enum: roles,
        required: true,
        default: 0,
    }
});

var Name = {
    first: {
        type: String,
        required: true,
        default: '',
    },
    last: {
        type: String,
        trim: true,
        required: true,
        default: ''
    }
};

var NotificationPrefs = {
    //TBD
};

var UserSchema = new Schema({
    name: Name,
    email: {
        type: String,
        trim: true,
        required: true,
        default: ''
    },
    phone: { //Used eventually for push notifications
        type: String,
        required: true,
        default: ''
    },
    notificationPrefs: NotificationPrefs,
    role: {
        type: Number,
        enum: roles,
        required: true,
        default: 0,
    },
    created: {
        type: Date,
        default: Date.now,
        required: true
    },
    updated: {
        type: Date,
        required: true,
        default: Date.now
    }
});

UserSchema.pre('save', function(next) {
    if (!this.isModified('updated')) {
        this.updated = new Date();
    }
    next();
});

UserSchema.static('returnBorrower', function(id, callback) {
    this.findOne({
        '_id': id
    }, function(err, user) {
        var borrower = {
            name: user.name,
            id: id
        };
        return callback(err, borrower);
    });
});

UserSchema.static('exists', function(email, callback) {
    this.findOne({
        'email': email
    }, {
        '_id': 1
    }, function(err, user) {
        if(!user){
            return callback(err, false);
        } else {
            return callback(err, true);
        }
    });
});

mongoose.model('User', UserSchema);