text:
module RTurk
  class GetHITResponse < Response
    attr_reader :hit_id, :type_id, :keywords, :status, :review_status, :title, :created_at,
                :expires_at, :assignments_duration, :reward_amount, :max_assignments,
                :auto_approval_delay, :description, :reward, :lifetime, :annotation,
                :similar_hits_count, :assignments_pending_count, :assignments_available_count,
                :assignments_completed_count, :question_external_url, :qualification_requirement_comparator,
                :qualification_requirement_value, :question

    def initialize(response)
      @raw_xml = response.body
      @xml = Nokogiri::XML(CGI.unescapeHTML(@raw_xml))
      raise_errors
      map_content(@xml.xpath('//HIT'),
        :hit_id => 'HITId',
        :type_id => 'HITTypeId',
        :keywords => 'Keywords',
        :status => 'HITStatus',
        :review_status => 'HITReviewStatus',
        :title => 'Title',
        :created_at => 'CreationTime',
        :expires_at => 'Expiration',
        :assignments_duration => 'AssignmentDurationInSeconds',
        :reward_amount => 'Reward/Amount',
        :max_assignments => 'MaxAssignments',
        :auto_approval_delay => 'AutoApprovalDelayInSeconds',
        :description => 'Description',
        :reward => 'Reward',
        :lifetime => 'LifetimeInSeconds',
        :annotation => 'RequesterAnnotation',
        :similar_hits_count => 'NumberOfSimilarHITs',
        :assignments_pending_count => 'NumberOfAssignmentsPending',
        :assignments_available_count => 'NumberOfAssignmentsAvailable',
        :assignments_completed_count => 'NumberOfAssignmentsCompleted',
        :question_external_url => 'Question/*/*[1]',
        :qualification_requirement_comparator => 'QualificationRequirement/Comparator',
        :qualification_requirement_value => 'QualificationRequirement/IntegerValue',
        :question => 'Question'
      )

      @keywords = @keywords.split(', ') if @keywords
    end
  end
end


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RemoveCaasServerDiskCmdlet.cs" company="">
//
// </copyright>
// <summary>
//   The set server state cmdlet.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace DD.CBU.Compute.Powershell
{
    using System;
    using System.Management.Automation;
    using Api.Client;
    using Api.Contracts.General;

    [Cmdlet(VerbsCommon.Remove, "CaasServerFlpFile", SupportsShouldProcess = true)]
    public class RemoveCaasServerFlpCmdlet : PSCmdletCaasWithConnectionBase
    {
        [Parameter(Mandatory = true, HelpMessage = "The Id of Device")]
        public string Id { get; set; }

        /// <summary>
        ///     The process record method.
        /// </summary>
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            try
            {
                WriteObject(Connection.ApiClient.ServerManagement.Server.RemoveFlpFile(new IdType { id = Id }).Result);
            }
            catch (AggregateException ae)
            {
                ae.Handle(
                    e =>
                    {
                        if (e is ComputeApiException)
                        {
                            WriteError(new ErrorRecord(e, "-2", ErrorCategory.InvalidOperation, Connection));
                        }
                        else
                        {
                            // if (e is HttpRequestException)
                            ThrowTerminatingError(
                                new ErrorRecord(e, "-1", ErrorCategory.ConnectionError, Connection));
                        }

                        return true;
                    });
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<template name="message">

		{{> avatar username=u.username}}
		{{u.username}}

			{{time}}
			{{#if ets}}
				({{_ "edited"}})
			{{/if}}

			{{{body}}}

</template>


text:
argbuilder - command line arguments building DSL
==========

The library provides a monadic DSL to build command line arguments. It
is especially useful for building more specific DSLs.

For example, let's define something like Hadoop Streaming command line
arguments DSL:

```haskell

data Env = Env
    { envScriptPath :: FilePath
    , envResourcePath :: FilePath
    }

data HadoopArgState = HadoopArgState
    { stOutput :: Maybe FilePath
    }

type HadoopArgM w a = ArgBuilderM Env HadoopArgState w a

-- ... defining some combinators ...

-- Example function
exampleArgs :: Bool -> HadoopArgM Argument ()
exampleArgs noFooMode = do
  "-D" =:@ do arg ("stream.num.map.output.key.fields",    "4")
              arg ("mapred.text.key.partitioner.options", "-k2,4")
              arg ("stream.num.reduce.output.key.fields", "5")

  inputs ["s3://path/to/input"]
  output "s3://path/to/output"

  mapper "Map" $ do
    when noFooMode $ flag "--no-foo"
    (Equals, "--dictionary") =:: "file.txt"

  reducer "ReducerUsesFooBarBinary.sh" $ do
    flag "--enable-foo"
    (Sticky, "-a") =:@ do arg "Date"
                          arg "Time"
                          arg "Asset"

  cacheFile $ do
    script "FooBar"
    resource $ "directory/some-file.txt" `alias` "file.txt"

  cmdenv "BEGINDATE" "2013-01-01"
  cmdenv "ENDDATE"   "2013-01-01"
```
Outputs the following list of arguments

```
-D
stream.num.map.output.key.fields=4
-D
mapred.text.key.partitioner.options=-k2,4
-D
stream.num.reduce.output.key.fields=5
-input
s3://path/to/input
-output
s3://path/to/output
-mapper
/bin/Map --no-foo --dictionary=file.txt
-reducer
/bin/ReducerUsesFooBarBinary.sh --enable-foo -aDate -aTime -aAsset
-cacheFile
/bin/FooBar#FooBar
-cacheFile
/etc/directory/some-file.txt#file.txt
-cmdenv
BEGINDATE=2013-01-01
-cmdenv
ENDDATE=2013-01-01
```


text:
package operation

import skinny.PermittedStrongParameters
import skinny.logging.LoggerProvider

/**
 * The base service for this application.
 */
abstract class OperationBase extends LoggerProvider {

  def getParameterAsString(key: String, permittedAttributes: PermittedStrongParameters): String = {
    permittedAttributes.params.get(key).map(_._1).get.toString
  }

  def getParameterAsLong(key: String, permittedAttributes: PermittedStrongParameters): Long = {
    permittedAttributes.params.get(key).map(_._1).get.toString.toLong
  }

}


text:
<?php

use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\adminUi\widget\Row;
use yii\adminUi\widget\Column;
use yii\adminUi\widget\Collapse;
use yii\adminUi\widget\Box;
use kartik\widgets\DepDrop;
use yii\helpers\Url;
use common\modules\media\widgets\MediaUpload;
use yii\adminUi\widget\DynamicField;
/* @var $this yii\web\View */

/* @var $this yii\web\View */
/* @var $model common\models\VenueSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'Id') ?>

    <?= $form->field($model, 'name') ?>

    <?php echo $form->field($model, 'venueType')->dropDownList(ArrayHelper::merge(['' => 'Select'], ArrayHelper::map(\common\models\VenueType::find()->andWhere(['status' => 1])->All(), 'Id', 'name'))); ?>

    <?php
    echo $form->field($model, 'cityId')->dropDownList(ArrayHelper::merge([0 => 'Select'], ArrayHelper::map(\common\models\City::find()->andWhere(['status' => 1])->All(), 'Id', 'name')),['id'=>'cityId']);

   echo $form->field($model, 'zoneId')->widget(DepDrop::classname(), [
                                                                            'options'=>['id'=>'zoneId'],
                                                                            'data'  => ArrayHelper::merge([0 => 'Select'], ArrayHelper::map(\common\models\Zone::find()->andWhere(['status' => 1,'cityId'=>$model->cityId])->All(), 'Id', 'name')),
                                                                            'type' => DepDrop::TYPE_SELECT2,
                                                                            'pluginOptions'=>[
                                                                            'depends'=>['cityId'],
                                                                            'placeholder'=>'Select Zone',
                                                                            'url'=>Url::to(['/zone/zone/autosuggest'])
                                                                            ]
                                                                          ]);
                       echo $form->field($model, 'localityId')->widget(DepDrop::classname(), [
                                                                            'options'=>['id'=>'localityId'],
                                                                            'data'  => ArrayHelper::merge([0 => 'Select'], ArrayHelper::map(\common\models\Locality::find()->andWhere(['status' => 1,'cityId'=>$model->cityId])->All(), 'Id', 'name')),
                                                                            'type' => DepDrop::TYPE_SELECT2,
                                                                            'pluginOptions'=>[
                                                                            'depends'=>['cityId','zoneId'],
                                                                            'placeholder'=>'Select Locality',
                                                                            'url'=>Url::to(['/locality/locality/autosuggest'])
                                                                            ]
                                                                          ]);

    ?>

    <?php // echo $form->field($model, 'localityId') ?>

    <?php // echo $form->field($model, 'address') ?>

    <?php // echo $form->field($model, 'landmark') ?>

    <?php // echo $form->field($model, 'phone') ?>

    <?php // echo $form->field($model, 'tollfree') ?>

    <?php // echo $form->field($model, 'mobile') ?>

    <?php // echo $form->field($model, 'gpsLat') ?>

    <?php // echo $form->field($model, 'gpsLong') ?>

    <?php // echo $form->field($model, 'venueType') ?>

    <?php // echo $form->field($model, 'facility') ?>

    <?php // echo $form->field($model, 'capacity') ?>

    <?php // echo $form->field($model, 'description') ?>

    <?php // echo $form->field($model, 'contactName') ?>

    <?php // echo $form->field($model, 'email') ?>

    <?php // echo $form->field($model, 'url') ?>

    <?php // echo $form->field($model, 'facebookUrl') ?>

    <?php // echo $form->field($model, 'seatType') ?>

    <?php // echo $form->field($model, 'reservationInfo') ?>

    <?php // echo $form->field($model, 'audiVsCapcity') ?>

    <?php // echo $form->field($model, 'startTime') ?>

    <?php // echo $form->field($model, 'endTime') ?>

    <?php // echo $form->field($model, 'ip') ?>

    <?php // echo $form->field($model, 'IsReccomended') ?>

    <?php // echo $form->field($model, 'status') ?>

    <?php // echo $form->field($model, 'flag') ?>

    <?php // echo $form->field($model, 'oldGuid') ?>

    <?php // echo $form->field($model, 'guid') ?>

    <?php // echo $form->field($model, 'createdOn') ?>

    <?php // echo $form->field($model, 'createdBy') ?>

    <?php // echo $form->field($model, 'updatedOn') ?>

    <?php // echo $form->field($model, 'updatedBy') ?>

    <?php // echo $form->field($model, 'csvRemarks') ?>

    <?php // echo $form->field($model, 'csvUpload') ?>

    <?php // echo $form->field($model, 'brand') ?>

    <?php // echo $form->field($model, 'mall') ?>

    <?php // echo $form->field($model, 'tags') ?>

    <?php // echo $form->field($model, 'entityType') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Services.Localization
{
    using System;
    using System.Data;
    using System.Globalization;

    using DotNetNuke.Common.Utilities;
    using DotNetNuke.Entities;
    using DotNetNuke.Entities.Modules;

    /// <summary>
    ///   <para>The Locale class is a custom business object that represents a locale, which is the language and country combination.</para>
    /// </summary>
    [Serializable]
    public class Locale : BaseEntityInfo, IHydratable
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Locale"/> class.
        /// </summary>
        public Locale()
        {
            this.PortalId = Null.NullInteger;
            this.LanguageId = Null.NullInteger;
            this.IsPublished = Null.NullBoolean;
        }

        public CultureInfo Culture
        {
            get
            {
                return CultureInfo.GetCultureInfo(this.Code);
            }
        }

        public string EnglishName
        {
            get
            {
                string name = Null.NullString;
                if (this.Culture != null)
                {
                    name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(this.Culture.EnglishName);
                }

                return name;
            }
        }

        public Locale FallBackLocale
        {
            get
            {
                Locale fallbackLocale = null;
                if (!string.IsNullOrEmpty(this.Fallback))
                {
                    fallbackLocale = LocaleController.Instance.GetLocale(this.PortalId, this.Fallback);
                }

                return fallbackLocale;
            }
        }

        public string NativeName
        {
            get
            {
                string name = Null.NullString;
                if (this.Culture != null)
                {
                    name = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(this.Culture.NativeName);
                }

                return name;
            }
        }

        public string Code { get; set; }

        public string Fallback { get; set; }

        public bool IsPublished { get; set; }

        public int LanguageId { get; set; }

        public int PortalId { get; set; }

        public string Text { get; set; }

        /// <inheritdoc/>
        public int KeyID
        {
            get
            {
                return this.LanguageId;
            }

            set
            {
                this.LanguageId = value;
            }
        }

        /// <inheritdoc/>
        public void Fill(IDataReader dr)
        {
            this.LanguageId = Null.SetNullInteger(dr["LanguageID"]);
            this.Code = Null.SetNullString(dr["CultureCode"]);
            this.Text = Null.SetNullString(dr["CultureName"]);
            this.Fallback = Null.SetNullString(dr["FallbackCulture"]);

            // These fields may not be populated (for Host level locales)
            DataTable schemaTable = dr.GetSchemaTable();
            bool hasColumns = schemaTable.Select("ColumnName = 'IsPublished' Or ColumnName = 'PortalID'").Length == 2;

            if (hasColumns)
            {
                this.IsPublished = Null.SetNullBoolean(dr["IsPublished"]);
                this.PortalId = Null.SetNullInteger(dr["PortalID"]);
            }

            // Call the base classes fill method to populate base class proeprties
            this.FillInternal(dr);
        }
    }
}


text:
[![Build Status][travis-image]][travis-url] [![Coverage Status][coveralls-image]][coveralls-url] [![Dependency Status][depstat-image]][depstat-url] [![devDependency Status][devdepstat-image]][devdepstat-url]

> [CoffeeLint][coffeelint] rule that enforces usage of [strict mode][moz-strictmode-doc].

![example-output](screenshot.png)

## Usage

First, install `coffeelint-use-strict` globally:

```shell
npm install -g coffeelint-use-strict
```

Then, add a `"use_strict"` key with value `{"module": "coffeelint-use-strict"}` to your `coffeelint.json`, e.g.

```json
{
    "use_strict": {
        "module": "coffeelint-use-strict",
        "level": "error",
        "allowGlobal": false,
        "requireGlobal": false
    }
}
```

The `coffeelint` cli will then load this rule automatically. See the [documentation][coffeelint-api-doc] for other ways to make use of custom rules.

## Options

### level
Type: `String`
Default: `'error'`

The severity level of the violated rule. `level` must be one of `'ignore'`, `'warn'`, or `'error'`.

### allowGlobal
Type: `Boolean`
Default: `true`

Allow the `'use strict'` statement to be at the top of a file.

### requireGlobal
Type: `Boolean`
Default: `false`

Require the `'use strict'` statement to be at the top of a file.

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [gulp][gulp] and [npm-test](https://npmjs.org/doc/test.html). Plus, make sure to adhere to these [commit message conventions](https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit#heading=h.uyo6cb12dt6w).

## Development
If you wanna use `gulp` and the tasks in `gulpfile.coffee`, please run `npm i gulp` manually. `gulp` is not included as a devDependency, since it cannot be installed on `node v0.8` and we want to be able to install and test this package on TravisCI on `node v0.8`.

## License

[MIT License](http://en.wikipedia.org/wiki/MIT_License) © [Jan Raasch](http://janraasch.com)

[gulp]: http://gulpjs.com/

[coffeelint]: http://www.coffeelint.org
[coffeelint-api-doc]: http://www.coffeelint.org/#api
[moz-strictmode-doc]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FFunctions_and_function_scope%2FStrict_mode

[npm-url]: https://npmjs.org/package/coffeelint-use-strict
[npm-image]: http://img.shields.io/npm/v/coffeelint-use-strict.svg

[travis-url]: http://travis-ci.org/janraasch/coffeelint-use-strict
[travis-image]: https://secure.travis-ci.org/janraasch/coffeelint-use-strict.svg?branch=master

[coveralls-url]: https://coveralls.io/r/janraasch/coffeelint-use-strict
[coveralls-image]: https://coveralls.io/repos/janraasch/coffeelint-use-strict/badge.svg

[depstat-url]: https://david-dm.org/janraasch/coffeelint-use-strict
[depstat-image]: https://david-dm.org/janraasch/coffeelint-use-strict.svg

[devdepstat-url]: https://david-dm.org/janraasch/coffeelint-use-strict#info=devDependencies
[devdepstat-image]: https://david-dm.org/janraasch/coffeelint-use-strict/dev-status.svg


text:
#ifndef GrProcessorSet_DEFINED
#define GrProcessorSet_DEFINED

#include "include/private/SkTemplates.h"
#include "src/gpu/ganesh/GrFragmentProcessor.h"
#include "src/gpu/ganesh/GrPaint.h"
#include "src/gpu/ganesh/GrProcessorAnalysis.h"
#include "src/gpu/ganesh/GrXferProcessor.h"

struct GrUserStencilSettings;
class GrAppliedClip;
class GrXPFactory;

class GrProcessorSet {
private:
    // Arbitrary constructor arg for empty set and analysis
    enum class Empty { kEmpty };

public:
    GrProcessorSet(GrPaint&&);
    GrProcessorSet(SkBlendMode);
    GrProcessorSet(std::unique_ptr<GrFragmentProcessor> colorFP);
    GrProcessorSet(GrProcessorSet&&);
    GrProcessorSet(const GrProcessorSet&) = delete;
    GrProcessorSet& operator=(const GrProcessorSet&) = delete;

    ~GrProcessorSet();

    bool hasColorFragmentProcessor() const { return fColorFragmentProcessor != nullptr; }
    bool hasCoverageFragmentProcessor() const { return fCoverageFragmentProcessor != nullptr; }

    const GrFragmentProcessor* colorFragmentProcessor() const {
        return fColorFragmentProcessor.get();
    }
    const GrFragmentProcessor* coverageFragmentProcessor() const {
        return fCoverageFragmentProcessor.get();
    }

    const GrXferProcessor* xferProcessor() const {
        SkASSERT(this->isFinalized());
        return fXP.fProcessor;
    }
    sk_sp<const GrXferProcessor> refXferProcessor() const {
        SkASSERT(this->isFinalized());
        return sk_ref_sp(fXP.fProcessor);
    }

    std::unique_ptr<GrFragmentProcessor> detachColorFragmentProcessor() {
        return std::move(fColorFragmentProcessor);
    }

    std::unique_ptr<GrFragmentProcessor> detachCoverageFragmentProcessor() {
        return std::move(fCoverageFragmentProcessor);
    }

    /** Comparisons are only legal on finalized processor sets. */
    bool operator==(const GrProcessorSet& that) const;
    bool operator!=(const GrProcessorSet& that) const { return !(*this == that); }

    /**
     * This is used to report results of processor analysis when a processor set is finalized (see
     * below).
     */
    class Analysis {
    public:
        Analysis(const Analysis&) = default;
        Analysis() { *reinterpret_cast<uint32_t*>(this) = 0; }

        Analysis& operator=(const Analysis &other) = default;

        bool isInitialized() const { return fIsInitialized; }
        bool usesLocalCoords() const { return fUsesLocalCoords; }
        bool requiresDstTexture() const { return fRequiresDstTexture; }
        bool requiresNonOverlappingDraws() const { return fRequiresNonOverlappingDraws; }
        bool isCompatibleWithCoverageAsAlpha() const { return fCompatibleWithCoverageAsAlpha; }
        // Indicates whether all color fragment processors were eliminated in the analysis.
        bool hasColorFragmentProcessor() const { return fHasColorFragmentProcessor; }

        bool inputColorIsIgnored() const { return fInputColorType == kIgnored_InputColorType; }
        bool inputColorIsOverridden() const {
            return fInputColorType == kOverridden_InputColorType;
        }
        bool usesNonCoherentHWBlending() const { return fUsesNonCoherentHWBlending; }
        bool unaffectedByDstValue() const { return fUnaffectedByDstValue; }

    private:
        constexpr Analysis(Empty)
                : fUsesLocalCoords(false)
                , fCompatibleWithCoverageAsAlpha(true)
                , fRequiresDstTexture(false)
                , fRequiresNonOverlappingDraws(false)
                , fHasColorFragmentProcessor(false)
                , fIsInitialized(true)
                , fUsesNonCoherentHWBlending(false)
                , fUnaffectedByDstValue(false)
                , fInputColorType(kOriginal_InputColorType) {}
        enum InputColorType : uint32_t {
            kOriginal_InputColorType,
            kOverridden_InputColorType,
            kIgnored_InputColorType
        };

        // MSVS 2015 won't pack different underlying types
        using PackedBool = uint32_t;
        using PackedInputColorType = uint32_t;

        PackedBool fUsesLocalCoords : 1;
        PackedBool fCompatibleWithCoverageAsAlpha : 1;
        PackedBool fRequiresDstTexture : 1;
        PackedBool fRequiresNonOverlappingDraws : 1;
        PackedBool fHasColorFragmentProcessor : 1;
        PackedBool fIsInitialized : 1;
        PackedBool fUsesNonCoherentHWBlending : 1;
        PackedBool fUnaffectedByDstValue : 1;
        PackedInputColorType fInputColorType : 2;

        friend class GrProcessorSet;
    };
    static_assert(sizeof(Analysis) <= sizeof(uint32_t));

    /**
     * This analyzes the processors given an op's input color and coverage as well as a clip. The
     * state of the processor set may change to an equivalent but more optimal set of processors.
     * This new state requires that the caller respect the returned 'inputColorOverride'. This is
     * indicated by the returned Analysis's inputColorIsOverridden(). 'inputColorOverride' will not
     * be written if the analysis does not override the input color.
     *
     * This must be called before the processor set is used to construct a GrPipeline and may only
     * be called once.
     *
     * This also puts the processors in "pending execution" state and must be called when an op
     * that owns a processor set is recorded to ensure pending and writes are propagated to
     * resources referred to by the processors. Otherwise, data hazards may occur.
     */
    Analysis finalize(const GrProcessorAnalysisColor&, const GrProcessorAnalysisCoverage,
                      const GrAppliedClip*, const GrUserStencilSettings*, const GrCaps&,
                      GrClampType, SkPMColor4f* inputColorOverride);

    bool isFinalized() const { return SkToBool(kFinalized_Flag & fFlags); }

    /** These are valid only for non-LCD coverage. */
    static const GrProcessorSet& EmptySet();
    static GrProcessorSet MakeEmptySet();
    static constexpr Analysis EmptySetAnalysis() { return Analysis(Empty::kEmpty); }

#if GR_TEST_UTILS
    SkString dumpProcessors() const;
#endif

    void visitProxies(const GrVisitProxyFunc&) const;

private:
    GrProcessorSet(Empty) : fXP((const GrXferProcessor*)nullptr), fFlags(kFinalized_Flag) {}

    int numFragmentProcessors() const {
        return (fColorFragmentProcessor ? 1 : 0) + (fCoverageFragmentProcessor ? 1 : 0);
    }

    enum Flags : uint16_t { kFinalized_Flag = 0x1 };

    union XP {
        XP(const GrXPFactory* factory) : fFactory(factory) {}
        XP(const GrXferProcessor* processor) : fProcessor(processor) {}
        explicit XP(XP&& that) : fProcessor(that.fProcessor) {
            SkASSERT(fProcessor == that.fProcessor);
            that.fProcessor = nullptr;
        }
        const GrXPFactory* fFactory;
        const GrXferProcessor* fProcessor;
    };

    const GrXPFactory* xpFactory() const {
        SkASSERT(!this->isFinalized());
        return fXP.fFactory;
    }

    std::unique_ptr<GrFragmentProcessor> fColorFragmentProcessor;
    std::unique_ptr<GrFragmentProcessor> fCoverageFragmentProcessor;
    XP fXP;
    uint8_t fFlags = 0;
};

#endif


text:
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.encoders.json;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;

import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.common.collect.Lists;
import com.google.firebase.encoders.DataEncoder;
import com.google.firebase.encoders.EncodingException;
import com.google.firebase.encoders.ObjectEncoder;
import com.google.firebase.encoders.ObjectEncoderContext;
import com.google.firebase.encoders.ValueEncoder;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.TimeZone;
import org.junit.Test;
import org.junit.runner.RunWith;

/** Tests for {@link JsonValueObjectEncoderContext} */
@RunWith(AndroidJUnit4.class)
public class JsonValueObjectEncoderContextTest {

  private static final Calendar CALENDAR = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
  // Mon Nov 04 2019 16:45:32.212
  private static long TIME_IN_MILLIS = 1572885932212L;
  private static final String FORMATTED_TIME = "2019-11-04T16:45:32.212Z";

  static {
    CALENDAR.setTimeInMillis(TIME_IN_MILLIS);
  }

  static class DummyClass {
    static final DummyClass INSTANCE = new DummyClass();
  }

  static class InnerDummyClass {
    static final InnerDummyClass INSTANCE = new InnerDummyClass();
  }

  static class InnerInnerDummyClass {
    static final InnerInnerDummyClass INSTANCE = new InnerInnerDummyClass();
  }

  @Test
  public void testRegisterOverride() throws IOException {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("Inner", InnerDummyClass.INSTANCE);
        };
    ObjectEncoder<InnerDummyClass> innerObjectEncoder =
        (o, ctx) -> {
          ctx.add("Name", "innerClass");
        };
    ValueEncoder<InnerDummyClass> innerValueEncoder =
        (o, ctx) -> {
          ctx.add(1234);
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .registerEncoder(InnerDummyClass.class, innerObjectEncoder)
            .registerEncoder(InnerDummyClass.class, innerValueEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result).isEqualTo("{\"Inner\":1234}");

    // Invert the logic
    result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .registerEncoder(InnerDummyClass.class, innerValueEncoder)
            .registerEncoder(InnerDummyClass.class, innerObjectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result).isEqualTo("{\"Inner\":{\"Name\":\"innerClass\"}}");
  }

  @Test
  public void testEncodingPrimitiveTypes() throws IOException {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("String", "string")
              .add("int", 2)
              .add("long", 42L)
              .add("double", 2.2d)
              .add("boolean", false)
              .add("null", null);
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result)
        .isEqualTo(
            "{\"String\":\"string\",\"int\":2,\"long\":42,\"double\":2.2,\"boolean\":false,\"null\":null}");
  }

  @Test
  public void testEncodingTimestamp() throws IOException {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("Timestamp", CALENDAR.getTime());
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result).isEqualTo(String.format("{\"Timestamp\":\"%s\"}", FORMATTED_TIME));
  }

  @Test
  public void testEncodingArrayPrimitives() throws IOException {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("String", new String[] {"string1", "string2"})
              .add("int", new int[] {1, 2})
              .add("long", new long[] {3L, 4L})
              .add("double", new double[] {1.1d, 2.2d})
              .add("boolean", new boolean[] {true, false})
              .add("null", new String[] {null, null});
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result)
        .isEqualTo(
            String.format(
                "{\"String\":%s,\"int\":%s,\"long\":%s,\"double\":%s,\"boolean\":%s,\"null\":%s}",
                "[\"string1\",\"string2\"]",
                "[1,2]",
                "[3,4]",
                "[1.1,2.2]",
                "[true,false]",
                "[null,null]"));
  }

  @Test
  public void testEncodingNumbers() {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> ctx.add("Number", new Number[] {1, 2473946328429347632L, 0.0d});

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result).isEqualTo(String.format("{\"Number\":%s}", "[1,2473946328429347632,0.0]"));
  }

  @Test
  public void testEncodingLongs() {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> ctx.add("long", new long[] {1L, 2473946328429347632L});

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result).isEqualTo(String.format("{\"long\":%s}", "[1,2473946328429347632]"));
  }

  enum MyEnum {
    VALUE_1,
    VALUE_2
  }

  @Test
  public void testEncodingEnum_withNoCustomEncoder() {
    String result =
        new JsonDataEncoderBuilder().build().encode(new MyEnum[] {MyEnum.VALUE_1, MyEnum.VALUE_2});
    assertThat(result).isEqualTo("[\"VALUE_1\",\"VALUE_2\"]");
  }

  @Test
  public void testEncodingEnum_withCustomEncoder() {
    ValueEncoder<MyEnum> encoder = (o, ctx) -> ctx.add(o.name().toLowerCase());
    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(MyEnum.class, encoder)
            .build()
            .encode(new MyEnum[] {MyEnum.VALUE_1, MyEnum.VALUE_2});
    assertThat(result).isEqualTo("[\"value_1\",\"value_2\"]");
  }

  @Test
  public void testEncodingCollection() throws IOException {
    ObjectEncoder<InnerDummyClass> anotherObjectEncoder =
        (o, ctx) -> {
          ctx.add("Name", "innerClass");
        };
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("String", Lists.newArrayList("string1", "string2"))
              .add(
                  "Objects",
                  Lists.newArrayList(InnerDummyClass.INSTANCE, InnerDummyClass.INSTANCE));
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .registerEncoder(InnerDummyClass.class, anotherObjectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result)
        .isEqualTo(
            String.format(
                "{\"String\":%s,\"Objects\":%s}",
                "[\"string1\",\"string2\"]",
                "[{\"Name\":\"innerClass\"},{\"Name\":\"innerClass\"}]"));
  }

  @Test
  public void testEncodingMap_withStringKey_shouldSucceed() {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("map", Collections.singletonMap("key", true));
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result).isEqualTo(String.format("{\"map\":%s}", "{\"key\":true}"));
  }

  @Test
  public void testEncodingMap_withNonStringKey_shouldFail() {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("map", Collections.singletonMap(1L, true));
        };

    DataEncoder encoder =
        new JsonDataEncoderBuilder().registerEncoder(DummyClass.class, objectEncoder).build();

    assertThrows(
        "Only String keys are currently supported in maps",
        EncodingException.class,
        () -> encoder.encode(DummyClass.INSTANCE));
  }

  @Test
  public void testEncodingBytes() throws IOException {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("Bytes", "My {custom} value.".getBytes(Charset.forName("UTF-8")));
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result).isEqualTo(String.format("{\"Bytes\":%s}", "\"TXkge2N1c3RvbX0gdmFsdWUu\""));
  }

  @Test
  public void testEncodingCollectionBoxedPrimitives() throws IOException {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("Integer", Lists.newArrayList(1, 2, 3))
              .add("Double", Lists.newArrayList(1.1, 2.2, 3.3))
              .add("Boolean", Lists.newArrayList(true, false));
          ;
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result)
        .isEqualTo(
            String.format(
                "{\"Integer\":%s,\"Double\":%s,\"Boolean\":%s}",
                "[1,2,3]", "[1.1,2.2,3.3]", "[true,false]"));
  }

  @Test
  public void testEncodingNestedCollection() throws IOException {
    ObjectEncoder<InnerDummyClass> anotherObjectEncoder =
        (o, ctx) -> {
          ctx.add("Name", "innerClass");
        };
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("String", Lists.newArrayList("string1", "string2"))
              .add(
                  "Objects",
                  Lists.newArrayList(
                      Lists.newArrayList(InnerDummyClass.INSTANCE),
                      Lists.newArrayList(InnerDummyClass.INSTANCE)));
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .registerEncoder(InnerDummyClass.class, anotherObjectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result)
        .isEqualTo(
            String.format(
                "{\"String\":%s,\"Objects\":%s}",
                "[\"string1\",\"string2\"]",
                "[[{\"Name\":\"innerClass\"}],[{\"Name\":\"innerClass\"}]]"));
  }

  @Test
  public void testEncodingComplexTypes_InnerEncoder() throws IOException {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("String", "string")
              .add("Null", null)
              .add("InnerObject", InnerDummyClass.INSTANCE);
        };
    ObjectEncoder<InnerDummyClass> anotherObjectEncoder =
        (o, ctx) -> {
          ctx.add("Name", "innerClass")
              .add("Numbers", new int[] {12, 35})
              .add("Timestamp", CALENDAR.getTime());
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .registerEncoder(InnerDummyClass.class, anotherObjectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    String innerObject =
        String.format(
            "{\"Name\":\"innerClass\",\"Numbers\":[12,35],\"Timestamp\":\"%s\"}", FORMATTED_TIME);
    String outerObject =
        String.format("{\"String\":\"string\",\"Null\":null,\"InnerObject\":%s}", innerObject);

    assertThat(result).isEqualTo(outerObject);
  }

  @Test
  public void testEncodingComplexTypes_InnerExtendedEncoder() throws IOException {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("String", "string")
              .add("Null", null)
              .add("InnerObject", InnerDummyClass.INSTANCE);
        };
    ValueEncoder<InnerDummyClass> anotherEncoder =
        (o, ctx) -> {
          ctx.add("A very complex value");
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .registerEncoder(InnerDummyClass.class, anotherEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    String innerObject = "\"A very complex value\"";
    String outerObject =
        String.format("{\"String\":\"string\",\"Null\":null,\"InnerObject\":%s}", innerObject);

    assertThat(result).isEqualTo(outerObject);
  }

  @Test
  public void testMissingEncoder() throws IOException {
    DataEncoder dataEncoder = new JsonDataEncoderBuilder().build();
    assertThrows(EncodingException.class, () -> dataEncoder.encode(DummyClass.INSTANCE));
  }

  @Test
  public void testEncoderError() throws IOException {
    ObjectEncoder<DummyClass> objectEncoder = (o, ctx) -> ctx.add("name", "value");
    Writer mockWriter = mock(Writer.class);
    doThrow(IOException.class).when(mockWriter).write(any(String.class));

    assertThrows(
        IOException.class,
        () ->
            new JsonDataEncoderBuilder()
                .registerEncoder(DummyClass.class, objectEncoder)
                .build()
                .encode(DummyClass.INSTANCE, mockWriter));
  }

  @Test
  public void testNested_whenUsedCorrectly_shouldProduceNestedJson() {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("name", "value");
          ctx.nested("nested1").add("key1", "value1");
          ctx.add("after1", true);
          ctx.nested("nested2").add("key2", "value2");
          ctx.add("after2", true);
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result)
        .isEqualTo(
            "{\"name\":\"value\",\"nested1\":{\"key1\":\"value1\"},"
                + "\"after1\":true,\"nested2\":{\"key2\":\"value2\"},\"after2\":true}");
  }

  @Test
  public void testTwiceNested_whenUsedCorrectly_shouldProduceNestedJson() {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ctx.add("name", "value");
          ctx.nested("nested1").add("key1", "value1").nested("nested2");
          ctx.add("after1", true);
        };

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result)
        .isEqualTo(
            "{\"name\":\"value\",\"nested1\":{\"key1\":\"value1\",\"nested2\":{}},\"after1\":true}");
  }

  @Test
  public void testNested_whenUsedAfterParent_shouldThrow() {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> {
          ObjectEncoderContext nested = ctx.nested("nested1");
          ctx.add("after1", true);
          nested.add("hello", "world");
        };

    DataEncoder encoder =
        new JsonDataEncoderBuilder().registerEncoder(DummyClass.class, objectEncoder).build();

    assertThrows(IllegalStateException.class, () -> encoder.encode(DummyClass.INSTANCE));
  }

  @Test
  public void testInline_shouldProduceValuesInParentObject() {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> ctx.add("name", "value").inline(InnerDummyClass.INSTANCE).add("after1", true);
    ObjectEncoder<InnerDummyClass> innerEncoder = (o, ctx) -> ctx.add("inner", "class");

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .registerEncoder(InnerDummyClass.class, innerEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result).isEqualTo("{\"name\":\"value\",\"inner\":\"class\",\"after1\":true}");
  }

  @Test
  public void testNestedInline_shouldProduceValuesInParentObject() {
    ObjectEncoder<DummyClass> objectEncoder =
        (o, ctx) -> ctx.add("name", "value").inline(InnerDummyClass.INSTANCE).add("after1", true);
    ObjectEncoder<InnerDummyClass> innerEncoder =
        (o, ctx) -> ctx.inline(InnerInnerDummyClass.INSTANCE);

    ObjectEncoder<InnerInnerDummyClass> innerInnerEncoder = (o, ctx) -> ctx.add("key", true);

    String result =
        new JsonDataEncoderBuilder()
            .registerEncoder(DummyClass.class, objectEncoder)
            .registerEncoder(InnerDummyClass.class, innerEncoder)
            .registerEncoder(InnerInnerDummyClass.class, innerInnerEncoder)
            .build()
            .encode(DummyClass.INSTANCE);

    assertThat(result).isEqualTo("{\"name\":\"value\",\"key\":true,\"after1\":true}");
  }

  @Test
  public void testInline_withNull_shouldThrow() {
    ObjectEncoder<DummyClass> objectEncoder = (o, ctx) -> ctx.inline(null);

    DataEncoder encoder =
        new JsonDataEncoderBuilder().registerEncoder(DummyClass.class, objectEncoder).build();
    assertThrows(EncodingException.class, () -> encoder.encode(DummyClass.INSTANCE));
  }

  @Test
  public void testInline_withLong_shouldThrow() {
    ObjectEncoder<DummyClass> objectEncoder = (o, ctx) -> ctx.inline(Long.valueOf(100));

    DataEncoder encoder =
        new JsonDataEncoderBuilder().registerEncoder(DummyClass.class, objectEncoder).build();
    assertThrows(EncodingException.class, () -> encoder.encode(DummyClass.INSTANCE));
  }

  @Test
  public void testInline_withArray_shouldThrow() {
    ObjectEncoder<DummyClass> objectEncoder = (o, ctx) -> ctx.inline(new int[] {1, 2, 3});

    DataEncoder encoder =
        new JsonDataEncoderBuilder().registerEncoder(DummyClass.class, objectEncoder).build();
    assertThrows(EncodingException.class, () -> encoder.encode(DummyClass.INSTANCE));
  }

  @Test
  public void testInline_withDate_shouldThrow() {
    ObjectEncoder<DummyClass> objectEncoder = (o, ctx) -> ctx.inline(new Date());

    DataEncoder encoder =
        new JsonDataEncoderBuilder().registerEncoder(DummyClass.class, objectEncoder).build();
    assertThrows(EncodingException.class, () -> encoder.encode(DummyClass.INSTANCE));
  }
}


text:
module FactoryBot
  class Linter

    def initialize(factories, linting_strategy, factory_strategy = :create)
      @factories_to_lint = factories
      @linting_method = "lint_#{linting_strategy}"
      @factory_strategy = factory_strategy
      @invalid_factories = calculate_invalid_factories
    end

    def lint!
      if invalid_factories.any?
        raise InvalidFactoryError, error_message
      end
    end

    private

    attr_reader :factories_to_lint, :invalid_factories, :factory_strategy

    def calculate_invalid_factories
      factories_to_lint.reduce(Hash.new([])) do |result, factory|
        errors = send(@linting_method, factory)
        result[factory] |= errors unless errors.empty?
        result
      end
    end

    class FactoryError
      def initialize(wrapped_error, factory)
        @wrapped_error = wrapped_error
        @factory       = factory
      end

      def message
        message = @wrapped_error.message
        "* #{location} - #{message} (#{@wrapped_error.class.name})"
      end

      def location
        @factory.name
      end
    end

    class FactoryTraitError < FactoryError
      def initialize(wrapped_error, factory, trait_name)
        super(wrapped_error, factory)
        @trait_name = trait_name
      end

      def location
        "#{@factory.name}+#{@trait_name}"
      end
    end

    def lint_factory(factory)
      result = []
      begin
        FactoryBot.public_send(factory_strategy, factory.name)
      rescue => error
        result |= [FactoryError.new(error, factory)]
      end
      result
    end

    def lint_traits(factory)
      result = []
      factory.definition.defined_traits.map(&:name).each do |trait_name|
        begin
          FactoryBot.public_send(factory_strategy, factory.name, trait_name)
        rescue => error
          result |=
              [FactoryTraitError.new(error, factory, trait_name)]
        end
      end
      result
    end

    def lint_factory_and_traits(factory)
      errors = lint_factory(factory)
      errors |= lint_traits(factory)
      errors
    end

    def error_message
      lines = invalid_factories.map do |_factory, exceptions|
        exceptions.map(&:message)
      end.flatten

      <<-ERROR_MESSAGE.strip
The following factories are invalid:

#{lines.join("\n")}
      ERROR_MESSAGE
    end
  end
end


text:
var GameState = {
  //load the game assets before the game starts
  preload: function() {
    this.load.image('background', 'assets/images/background.png');
    this.load.image('chicken', 'assets/images/chicken.png');
    this.load.image('horse', 'assets/images/horse.png');
    this.load.image('pig', 'assets/images/pig.png');
    this.load.image('sheep', 'assets/images/sheep3.png');

  },
  //executed after everything is loaded
  create: function() {

    this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;

    this.scale.pageAlignHorizontally = true;
    this.scale.pageAlignVertically = true;

    //create a sprite for the background
    this.background = this.game.add.sprite(0, 0, 'background');

    //center of the world
    this.chicken = this.game.add.sprite(this.game.world.centerX, this.game.world.centerY, 'chicken');

    //place a sprite by it's center, not the top-left corner
    this.chicken.anchor.setTo(0.5, 0.5); // or just this.chicken.anchor.setTo(0.5)

    //increate it's width by 2, keep same height
    this.chicken.scale.setTo(2, 1);

    this.horse = this.game.add.sprite(120, 10, 'horse');

    //decreate width and height to half
    this.horse.scale.setTo(0.5);

    this.pig = this.game.add.sprite(500, 300, 'pig');
    this.pig.anchor.setTo(0.5);

    //flip on x
    this.pig.scale.setTo(-1, 1);

    this.sheep = this.game.add.sprite(100, 250, 'sheep');
    this.sheep.scale.setTo(0.5);
    this.sheep.anchor.setTo(0.5);

    //rotate 90 degrees clockwise
    this.sheep.angle = 90;

  },
  //this is executed multiple times per second
  update: function() {
    this.sheep.angle += 0.5;
  },

};

//initiate the Phaser framework
var game = new Phaser.Game(640, 360, Phaser.AUTO);

game.state.add('GameState', GameState);
game.state.start('GameState');


text:
#include "buffer.hpp"
#include "error.hpp"
#include "target.hpp"
#include "util.hpp"

#include <stdio.h>

static const ArchType arch_list[] = {
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v8_3a},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v8_2a},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v8_1a},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v8},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v8r},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v8m_baseline},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v8m_mainline},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v7},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v7em},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v7m},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v7s},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v7k},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v7ve},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v6},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v6m},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v6k},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v6t2},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v5},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v5te},
    {ZigLLVM_arm, ZigLLVM_ARMSubArch_v4t},

    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v8_3a},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v8_2a},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v8_1a},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v8},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v8r},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v8m_baseline},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v8m_mainline},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v7},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v7em},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v7m},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v7s},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v7k},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v7ve},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v6},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v6m},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v6k},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v6t2},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v5},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v5te},
    {ZigLLVM_armeb, ZigLLVM_ARMSubArch_v4t},

    {ZigLLVM_aarch64, ZigLLVM_ARMSubArch_v8_3a},
    {ZigLLVM_aarch64, ZigLLVM_ARMSubArch_v8_2a},
    {ZigLLVM_aarch64, ZigLLVM_ARMSubArch_v8_1a},
    {ZigLLVM_aarch64, ZigLLVM_ARMSubArch_v8},
    {ZigLLVM_aarch64, ZigLLVM_ARMSubArch_v8r},
    {ZigLLVM_aarch64, ZigLLVM_ARMSubArch_v8m_baseline},
    {ZigLLVM_aarch64, ZigLLVM_ARMSubArch_v8m_mainline},

    {ZigLLVM_aarch64_be, ZigLLVM_ARMSubArch_v8_3a},
    {ZigLLVM_aarch64_be, ZigLLVM_ARMSubArch_v8_2a},
    {ZigLLVM_aarch64_be, ZigLLVM_ARMSubArch_v8_1a},
    {ZigLLVM_aarch64_be, ZigLLVM_ARMSubArch_v8},
    {ZigLLVM_aarch64_be, ZigLLVM_ARMSubArch_v8r},
    {ZigLLVM_aarch64_be, ZigLLVM_ARMSubArch_v8m_baseline},
    {ZigLLVM_aarch64_be, ZigLLVM_ARMSubArch_v8m_mainline},

    {ZigLLVM_arc, ZigLLVM_NoSubArch},
    {ZigLLVM_avr, ZigLLVM_NoSubArch},
    {ZigLLVM_bpfel, ZigLLVM_NoSubArch},
    {ZigLLVM_bpfeb, ZigLLVM_NoSubArch},
    {ZigLLVM_hexagon, ZigLLVM_NoSubArch},
    {ZigLLVM_mips, ZigLLVM_NoSubArch},
    {ZigLLVM_mipsel, ZigLLVM_NoSubArch},
    {ZigLLVM_mips64, ZigLLVM_NoSubArch},
    {ZigLLVM_mips64el, ZigLLVM_NoSubArch},
    {ZigLLVM_msp430, ZigLLVM_NoSubArch},
    {ZigLLVM_nios2, ZigLLVM_NoSubArch},
    {ZigLLVM_ppc, ZigLLVM_NoSubArch},
    {ZigLLVM_ppc64, ZigLLVM_NoSubArch},
    {ZigLLVM_ppc64le, ZigLLVM_NoSubArch},
    {ZigLLVM_r600, ZigLLVM_NoSubArch},
    {ZigLLVM_amdgcn, ZigLLVM_NoSubArch},
    {ZigLLVM_riscv32, ZigLLVM_NoSubArch},
    {ZigLLVM_riscv64, ZigLLVM_NoSubArch},
    {ZigLLVM_sparc, ZigLLVM_NoSubArch},
    {ZigLLVM_sparcv9, ZigLLVM_NoSubArch},
    {ZigLLVM_sparcel, ZigLLVM_NoSubArch},
    {ZigLLVM_systemz, ZigLLVM_NoSubArch},
    {ZigLLVM_tce, ZigLLVM_NoSubArch},
    {ZigLLVM_tcele, ZigLLVM_NoSubArch},
    {ZigLLVM_thumb, ZigLLVM_NoSubArch},
    {ZigLLVM_thumbeb, ZigLLVM_NoSubArch},
    {ZigLLVM_x86, ZigLLVM_NoSubArch},
    {ZigLLVM_x86_64, ZigLLVM_NoSubArch},
    {ZigLLVM_xcore, ZigLLVM_NoSubArch},
    {ZigLLVM_nvptx, ZigLLVM_NoSubArch},
    {ZigLLVM_nvptx64, ZigLLVM_NoSubArch},
    {ZigLLVM_le32, ZigLLVM_NoSubArch},
    {ZigLLVM_le64, ZigLLVM_NoSubArch},
    {ZigLLVM_amdil, ZigLLVM_NoSubArch},
    {ZigLLVM_amdil64, ZigLLVM_NoSubArch},
    {ZigLLVM_hsail, ZigLLVM_NoSubArch},
    {ZigLLVM_hsail64, ZigLLVM_NoSubArch},
    {ZigLLVM_spir, ZigLLVM_NoSubArch},
    {ZigLLVM_spir64, ZigLLVM_NoSubArch},

    {ZigLLVM_kalimba, ZigLLVM_KalimbaSubArch_v3},
    {ZigLLVM_kalimba, ZigLLVM_KalimbaSubArch_v4},
    {ZigLLVM_kalimba, ZigLLVM_KalimbaSubArch_v5},

    {ZigLLVM_shave, ZigLLVM_NoSubArch},
    {ZigLLVM_lanai, ZigLLVM_NoSubArch},
    {ZigLLVM_wasm32, ZigLLVM_NoSubArch},
    {ZigLLVM_wasm64, ZigLLVM_NoSubArch},
    {ZigLLVM_renderscript32, ZigLLVM_NoSubArch},
    {ZigLLVM_renderscript64, ZigLLVM_NoSubArch},
};

static const ZigLLVM_VendorType vendor_list[] = {
    ZigLLVM_Apple,
    ZigLLVM_PC,
    ZigLLVM_SCEI,
    ZigLLVM_BGP,
    ZigLLVM_BGQ,
    ZigLLVM_Freescale,
    ZigLLVM_IBM,
    ZigLLVM_ImaginationTechnologies,
    ZigLLVM_MipsTechnologies,
    ZigLLVM_NVIDIA,
    ZigLLVM_CSR,
    ZigLLVM_Myriad,
    ZigLLVM_AMD,
    ZigLLVM_Mesa,
    ZigLLVM_SUSE,
};

static const Os os_list[] = {
    OsFreestanding,
    OsAnanas,
    OsCloudABI,
    OsDragonFly,
    OsFreeBSD,
    OsFuchsia,
    OsIOS,
    OsKFreeBSD,
    OsLinux,
    OsLv2,        // PS3
    OsMacOSX,
    OsNetBSD,
    OsOpenBSD,
    OsSolaris,
    OsWindows,
    OsHaiku,
    OsMinix,
    OsRTEMS,
    OsNaCl,       // Native Client
    OsCNK,        // BG/P Compute-Node Kernel
    OsAIX,
    OsCUDA,       // NVIDIA CUDA
    OsNVCL,       // NVIDIA OpenCL
    OsAMDHSA,     // AMD HSA Runtime
    OsPS4,
    OsELFIAMCU,
    OsTvOS,       // Apple tvOS
    OsWatchOS,    // Apple watchOS
    OsMesa3D,
    OsContiki,
    OsAMDPAL,
    OsZen,
};

// Coordinate with zig_llvm.h
static const ZigLLVM_EnvironmentType environ_list[] = {
    ZigLLVM_UnknownEnvironment,

    ZigLLVM_GNU,
    ZigLLVM_GNUABIN32,
    ZigLLVM_GNUABI64,
    ZigLLVM_GNUEABI,
    ZigLLVM_GNUEABIHF,
    ZigLLVM_GNUX32,
    ZigLLVM_CODE16,
    ZigLLVM_EABI,
    ZigLLVM_EABIHF,
    ZigLLVM_Android,
    ZigLLVM_Musl,
    ZigLLVM_MuslEABI,
    ZigLLVM_MuslEABIHF,
    ZigLLVM_MSVC,
    ZigLLVM_Itanium,
    ZigLLVM_Cygnus,
    ZigLLVM_CoreCLR,
    ZigLLVM_Simulator,
};

static const ZigLLVM_ObjectFormatType oformat_list[] = {
    ZigLLVM_UnknownObjectFormat,
    ZigLLVM_COFF,
    ZigLLVM_ELF,
    ZigLLVM_MachO,
    ZigLLVM_Wasm,
};

size_t target_oformat_count(void) {
    return array_length(oformat_list);
}

const ZigLLVM_ObjectFormatType get_target_oformat(size_t index) {
    return oformat_list[index];
}

const char *get_target_oformat_name(ZigLLVM_ObjectFormatType oformat) {
    switch (oformat) {
        case ZigLLVM_UnknownObjectFormat: return "unknown";
        case ZigLLVM_COFF: return "coff";
        case ZigLLVM_ELF: return "elf";
        case ZigLLVM_MachO: return "macho";
        case ZigLLVM_Wasm: return "wasm";
    }
    zig_unreachable();
}

size_t target_arch_count(void) {
    return array_length(arch_list);
}

const ArchType *get_target_arch(size_t index) {
    return &arch_list[index];
}

size_t target_vendor_count(void) {
    return array_length(vendor_list);
}

ZigLLVM_VendorType get_target_vendor(size_t index) {
    return vendor_list[index];
}

size_t target_os_count(void) {
    return array_length(os_list);
}
Os get_target_os(size_t index) {
    return os_list[index];
}

ZigLLVM_OSType get_llvm_os_type(Os os_type) {
    switch (os_type) {
        case OsFreestanding:
        case OsZen:
            return ZigLLVM_UnknownOS;
        case OsAnanas:
            return ZigLLVM_Ananas;
        case OsCloudABI:
            return ZigLLVM_CloudABI;
        case OsDragonFly:
            return ZigLLVM_DragonFly;
        case OsFreeBSD:
            return ZigLLVM_FreeBSD;
        case OsFuchsia:
            return ZigLLVM_Fuchsia;
        case OsIOS:
            return ZigLLVM_IOS;
        case OsKFreeBSD:
            return ZigLLVM_KFreeBSD;
        case OsLinux:
            return ZigLLVM_Linux;
        case OsLv2:
            return ZigLLVM_Lv2;
        case OsMacOSX:
            return ZigLLVM_MacOSX;
        case OsNetBSD:
            return ZigLLVM_NetBSD;
        case OsOpenBSD:
            return ZigLLVM_OpenBSD;
        case OsSolaris:
            return ZigLLVM_Solaris;
        case OsWindows:
            return ZigLLVM_Win32;
        case OsHaiku:
            return ZigLLVM_Haiku;
        case OsMinix:
            return ZigLLVM_Minix;
        case OsRTEMS:
            return ZigLLVM_RTEMS;
        case OsNaCl:
            return ZigLLVM_NaCl;
        case OsCNK:
            return ZigLLVM_CNK;
        case OsAIX:
            return ZigLLVM_AIX;
        case OsCUDA:
            return ZigLLVM_CUDA;
        case OsNVCL:
            return ZigLLVM_NVCL;
        case OsAMDHSA:
            return ZigLLVM_AMDHSA;
        case OsPS4:
            return ZigLLVM_PS4;
        case OsELFIAMCU:
            return ZigLLVM_ELFIAMCU;
        case OsTvOS:
            return ZigLLVM_TvOS;
        case OsWatchOS:
            return ZigLLVM_WatchOS;
        case OsMesa3D:
            return ZigLLVM_Mesa3D;
        case OsContiki:
            return ZigLLVM_Contiki;
        case OsAMDPAL:
            return ZigLLVM_AMDPAL;
    }
    zig_unreachable();
}

static Os get_zig_os_type(ZigLLVM_OSType os_type) {
    switch (os_type) {
        case ZigLLVM_UnknownOS:
            return OsFreestanding;
        case ZigLLVM_Ananas:
            return OsAnanas;
        case ZigLLVM_CloudABI:
            return OsCloudABI;
        case ZigLLVM_DragonFly:
            return OsDragonFly;
        case ZigLLVM_FreeBSD:
            return OsFreeBSD;
        case ZigLLVM_Fuchsia:
            return OsFuchsia;
        case ZigLLVM_IOS:
            return OsIOS;
        case ZigLLVM_KFreeBSD:
            return OsKFreeBSD;
        case ZigLLVM_Linux:
            return OsLinux;
        case ZigLLVM_Lv2:
            return OsLv2;
        case ZigLLVM_Darwin:
        case ZigLLVM_MacOSX:
            return OsMacOSX;
        case ZigLLVM_NetBSD:
            return OsNetBSD;
        case ZigLLVM_OpenBSD:
            return OsOpenBSD;
        case ZigLLVM_Solaris:
            return OsSolaris;
        case ZigLLVM_Win32:
            return OsWindows;
        case ZigLLVM_Haiku:
            return OsHaiku;
        case ZigLLVM_Minix:
            return OsMinix;
        case ZigLLVM_RTEMS:
            return OsRTEMS;
        case ZigLLVM_NaCl:
            return OsNaCl;
        case ZigLLVM_CNK:
            return OsCNK;
        case ZigLLVM_AIX:
            return OsAIX;
        case ZigLLVM_CUDA:
            return OsCUDA;
        case ZigLLVM_NVCL:
            return OsNVCL;
        case ZigLLVM_AMDHSA:
            return OsAMDHSA;
        case ZigLLVM_PS4:
            return OsPS4;
        case ZigLLVM_ELFIAMCU:
            return OsELFIAMCU;
        case ZigLLVM_TvOS:
            return OsTvOS;
        case ZigLLVM_WatchOS:
            return OsWatchOS;
        case ZigLLVM_Mesa3D:
            return OsMesa3D;
        case ZigLLVM_Contiki:
            return OsContiki;
        case ZigLLVM_AMDPAL:
            return OsAMDPAL;
    }
    zig_unreachable();
}

const char *get_target_os_name(Os os_type) {
    switch (os_type) {
        case OsFreestanding:
            return "freestanding";
        case OsZen:
            return "zen";
        case OsAnanas:
        case OsCloudABI:
        case OsDragonFly:
        case OsFreeBSD:
        case OsFuchsia:
        case OsIOS:
        case OsKFreeBSD:
        case OsLinux:
        case OsLv2:        // PS3
        case OsMacOSX:
        case OsNetBSD:
        case OsOpenBSD:
        case OsSolaris:
        case OsWindows:
        case OsHaiku:
        case OsMinix:
        case OsRTEMS:
        case OsNaCl:       // Native Client
        case OsCNK:        // BG/P Compute-Node Kernel
        case OsAIX:
        case OsCUDA:       // NVIDIA CUDA
        case OsNVCL:       // NVIDIA OpenCL
        case OsAMDHSA:     // AMD HSA Runtime
        case OsPS4:
        case OsELFIAMCU:
        case OsTvOS:       // Apple tvOS
        case OsWatchOS:    // Apple watchOS
        case OsMesa3D:
        case OsContiki:
        case OsAMDPAL:
            return ZigLLVMGetOSTypeName(get_llvm_os_type(os_type));
    }
    zig_unreachable();
}

size_t target_environ_count(void) {
    return array_length(environ_list);
}
ZigLLVM_EnvironmentType get_target_environ(size_t index) {
    return environ_list[index];
}

void get_native_target(ZigTarget *target) {
    ZigLLVM_OSType os_type;
    ZigLLVMGetNativeTarget(
            &target->arch.arch,
            &target->arch.sub_arch,
            &target->vendor,
            &os_type,
            &target->env_type,
            &target->oformat);
    target->os = get_zig_os_type(os_type);
}

void get_unknown_target(ZigTarget *target) {
    target->arch.arch = ZigLLVM_UnknownArch;
    target->arch.sub_arch = ZigLLVM_NoSubArch;
    target->vendor = ZigLLVM_UnknownVendor;
    target->os = OsFreestanding;
    target->env_type = ZigLLVM_UnknownEnvironment;
    target->oformat = ZigLLVM_UnknownObjectFormat;
}

static void get_arch_name_raw(char *out_str, ZigLLVM_ArchType arch, ZigLLVM_SubArchType sub_arch) {
    const char *sub_str = (sub_arch == ZigLLVM_NoSubArch) ? "" : ZigLLVMGetSubArchTypeName(sub_arch);
    sprintf(out_str, "%s%s", ZigLLVMGetArchTypeName(arch), sub_str);
}

void get_arch_name(char *out_str, const ArchType *arch) {
    return get_arch_name_raw(out_str, arch->arch, arch->sub_arch);
}

int parse_target_arch(const char *str, ArchType *out_arch) {
    for (size_t i = 0; i < array_length(arch_list); i += 1) {
        const ArchType *arch = &arch_list[i];
        char arch_name[50];
        get_arch_name_raw(arch_name, arch->arch, arch->sub_arch);
        if (strcmp(arch_name, str) == 0) {
            *out_arch = *arch;
            return 0;
        }
    }
    return ErrorFileNotFound;
}

int parse_target_os(const char *str, Os *out_os) {
    for (size_t i = 0; i < array_length(os_list); i += 1) {
        Os os = os_list[i];
        const char *os_name = get_target_os_name(os);
        if (strcmp(os_name, str) == 0) {
            *out_os = os;
            return 0;
        }
    }
    return ErrorFileNotFound;
}

int parse_target_environ(const char *str, ZigLLVM_EnvironmentType *out_environ) {
    for (size_t i = 0; i < array_length(environ_list); i += 1) {
        ZigLLVM_EnvironmentType env_type = environ_list[i];
        const char *environ_name = ZigLLVMGetEnvironmentTypeName(env_type);
        if (strcmp(environ_name, str) == 0) {
            *out_environ = env_type;
            return 0;
        }
    }
    return ErrorFileNotFound;
}

void init_all_targets(void) {
    LLVMInitializeAllTargets();
    LLVMInitializeAllTargetInfos();
    LLVMInitializeAllTargetMCs();
    LLVMInitializeAllAsmPrinters();
    LLVMInitializeAllAsmParsers();
}

void get_target_triple(Buf *triple, const ZigTarget *target) {
    char arch_name[50];
    get_arch_name(arch_name, &target->arch);

    buf_resize(triple, 0);

    // LLVM WebAssembly output support requires the target to be activated at
    // build type with -DCMAKE_LLVM_EXPIERMENTAL_TARGETS_TO_BUILD=WebAssembly.
    //
    // LLVM determines the output format based on the environment suffix,
    // defaulting to an object based on the architecture. The default format in
    // LLVM 6 sets the wasm arch output incorrectly to ELF. We need to
    // explicitly set this ourself in order for it to work.
    //
    // This is fixed in LLVM 7 and you will be able to get wasm output by
    // using the target triple `wasm32-unknown-unknown-unknown`.
    if (!strncmp(arch_name, "wasm", 4)) {
        buf_appendf(triple, "%s-%s-%s-wasm", arch_name,
                ZigLLVMGetVendorTypeName(target->vendor),
                ZigLLVMGetOSTypeName(get_llvm_os_type(target->os)));
    } else {
        buf_appendf(triple, "%s-%s-%s-%s", arch_name,
                ZigLLVMGetVendorTypeName(target->vendor),
                ZigLLVMGetOSTypeName(get_llvm_os_type(target->os)),
                ZigLLVMGetEnvironmentTypeName(target->env_type));
    }
}

static bool is_os_darwin(ZigTarget *target) {
    switch (target->os) {
        case OsMacOSX:
        case OsIOS:
            return true;
        default:
            return false;
    }
}

void resolve_target_object_format(ZigTarget *target) {
    if (target->oformat != ZigLLVM_UnknownObjectFormat) {
        return;
    }

    switch (target->arch.arch) {
        case ZigLLVM_UnknownArch:
        case ZigLLVM_aarch64:
        case ZigLLVM_arm:
        case ZigLLVM_thumb:
        case ZigLLVM_x86:
        case ZigLLVM_x86_64:
            if (is_os_darwin(target)) {
                target->oformat = ZigLLVM_MachO;
            } else if (target->os == OsWindows) {
                target->oformat = ZigLLVM_COFF;
            } else {
                target->oformat = ZigLLVM_ELF;
            }
            return;

        case ZigLLVM_aarch64_be:
        case ZigLLVM_amdgcn:
        case ZigLLVM_amdil:
        case ZigLLVM_amdil64:
        case ZigLLVM_armeb:
        case ZigLLVM_arc:
        case ZigLLVM_avr:
        case ZigLLVM_bpfeb:
        case ZigLLVM_bpfel:
        case ZigLLVM_hexagon:
        case ZigLLVM_lanai:
        case ZigLLVM_hsail:
        case ZigLLVM_hsail64:
        case ZigLLVM_kalimba:
        case ZigLLVM_le32:
        case ZigLLVM_le64:
        case ZigLLVM_mips:
        case ZigLLVM_mips64:
        case ZigLLVM_mips64el:
        case ZigLLVM_mipsel:
        case ZigLLVM_msp430:
        case ZigLLVM_nios2:
        case ZigLLVM_nvptx:
        case ZigLLVM_nvptx64:
        case ZigLLVM_ppc64le:
        case ZigLLVM_r600:
        case ZigLLVM_renderscript32:
        case ZigLLVM_renderscript64:
        case ZigLLVM_riscv32:
        case ZigLLVM_riscv64:
        case ZigLLVM_shave:
        case ZigLLVM_sparc:
        case ZigLLVM_sparcel:
        case ZigLLVM_sparcv9:
        case ZigLLVM_spir:
        case ZigLLVM_spir64:
        case ZigLLVM_systemz:
        case ZigLLVM_tce:
        case ZigLLVM_tcele:
        case ZigLLVM_thumbeb:
        case ZigLLVM_xcore:
            target->oformat= ZigLLVM_ELF;
            return;

        case ZigLLVM_wasm32:
        case ZigLLVM_wasm64:
            target->oformat = ZigLLVM_Wasm;
            return;

        case ZigLLVM_ppc:
        case ZigLLVM_ppc64:
            if (is_os_darwin(target)) {
                target->oformat = ZigLLVM_MachO;
            } else {
                target->oformat= ZigLLVM_ELF;
            }
            return;
    }
}

// See lib/Support/Triple.cpp in LLVM for the source of this data.
// getArchPointerBitWidth
static int get_arch_pointer_bit_width(ZigLLVM_ArchType arch) {
    switch (arch) {
        case ZigLLVM_UnknownArch:
            return 0;

        case ZigLLVM_avr:
        case ZigLLVM_msp430:
            return 16;

        case ZigLLVM_arc:
        case ZigLLVM_arm:
        case ZigLLVM_armeb:
        case ZigLLVM_hexagon:
        case ZigLLVM_le32:
        case ZigLLVM_mips:
        case ZigLLVM_mipsel:
        case ZigLLVM_nios2:
        case ZigLLVM_nvptx:
        case ZigLLVM_ppc:
        case ZigLLVM_r600:
        case ZigLLVM_riscv32:
        case ZigLLVM_sparc:
        case ZigLLVM_sparcel:
        case ZigLLVM_tce:
        case ZigLLVM_tcele:
        case ZigLLVM_thumb:
        case ZigLLVM_thumbeb:
        case ZigLLVM_x86:
        case ZigLLVM_xcore:
        case ZigLLVM_amdil:
        case ZigLLVM_hsail:
        case ZigLLVM_spir:
        case ZigLLVM_kalimba:
        case ZigLLVM_lanai:
        case ZigLLVM_shave:
        case ZigLLVM_wasm32:
        case ZigLLVM_renderscript32:
            return 32;

        case ZigLLVM_aarch64:
        case ZigLLVM_aarch64_be:
        case ZigLLVM_amdgcn:
        case ZigLLVM_bpfel:
        case ZigLLVM_bpfeb:
        case ZigLLVM_le64:
        case ZigLLVM_mips64:
        case ZigLLVM_mips64el:
        case ZigLLVM_nvptx64:
        case ZigLLVM_ppc64:
        case ZigLLVM_ppc64le:
        case ZigLLVM_riscv64:
        case ZigLLVM_sparcv9:
        case ZigLLVM_systemz:
        case ZigLLVM_x86_64:
        case ZigLLVM_amdil64:
        case ZigLLVM_hsail64:
        case ZigLLVM_spir64:
        case ZigLLVM_wasm64:
        case ZigLLVM_renderscript64:
            return 64;
    }
    zig_unreachable();
}

uint32_t target_c_type_size_in_bits(const ZigTarget *target, CIntType id) {
    switch (target->os) {
        case OsFreestanding:
            switch (target->arch.arch) {
                case ZigLLVM_msp430:
                    switch (id) {
                        case CIntTypeShort:
                        case CIntTypeUShort:
                            return 16;
                        case CIntTypeInt:
                        case CIntTypeUInt:
                            return 16;
                        case CIntTypeLong:
                        case CIntTypeULong:
                            return 32;
                        case CIntTypeLongLong:
                        case CIntTypeULongLong:
                            return 64;
                        case CIntTypeCount:
                            zig_unreachable();
                    }
                default:
                    switch (id) {
                        case CIntTypeShort:
                        case CIntTypeUShort:
                            return 16;
                        case CIntTypeInt:
                        case CIntTypeUInt:
                            return 32;
                        case CIntTypeLong:
                        case CIntTypeULong:
                            return get_arch_pointer_bit_width(target->arch.arch);
                        case CIntTypeLongLong:
                        case CIntTypeULongLong:
                            return 64;
                        case CIntTypeCount:
                            zig_unreachable();
                    }
            }
        case OsLinux:
        case OsMacOSX:
        case OsZen:
        case OsOpenBSD:
            switch (id) {
                case CIntTypeShort:
                case CIntTypeUShort:
                    return 16;
                case CIntTypeInt:
                case CIntTypeUInt:
                    return 32;
                case CIntTypeLong:
                case CIntTypeULong:
                    return get_arch_pointer_bit_width(target->arch.arch);
                case CIntTypeLongLong:
                case CIntTypeULongLong:
                    return 64;
                case CIntTypeCount:
                    zig_unreachable();
            }
        case OsWindows:
            switch (id) {
                case CIntTypeShort:
                case CIntTypeUShort:
                    return 16;
                case CIntTypeInt:
                case CIntTypeUInt:
                case CIntTypeLong:
                case CIntTypeULong:
                    return 32;
                case CIntTypeLongLong:
                case CIntTypeULongLong:
                    return 64;
                case CIntTypeCount:
                    zig_unreachable();
            }
        case OsAnanas:
        case OsCloudABI:
        case OsDragonFly:
        case OsFreeBSD:
        case OsIOS:
        case OsKFreeBSD:
        case OsLv2:
        case OsNetBSD:
        case OsSolaris:
        case OsHaiku:
        case OsMinix:
        case OsRTEMS:
        case OsNaCl:
        case OsCNK:
        case OsAIX:
        case OsCUDA:
        case OsNVCL:
        case OsAMDHSA:
        case OsPS4:
        case OsELFIAMCU:
        case OsTvOS:
        case OsWatchOS:
        case OsMesa3D:
        case OsFuchsia:
        case OsContiki:
        case OsAMDPAL:
            zig_panic("TODO c type size in bits for this target");
    }
    zig_unreachable();
}

const char *target_o_file_ext(ZigTarget *target) {
    if (target->env_type == ZigLLVM_MSVC || target->os == OsWindows) {
        return ".obj";
    } else {
        return ".o";
    }
}

const char *target_asm_file_ext(ZigTarget *target) {
    return ".s";
}

const char *target_llvm_ir_file_ext(ZigTarget *target) {
    return ".ll";
}

const char *target_exe_file_ext(ZigTarget *target) {
    if (target->os == OsWindows) {
        return ".exe";
    } else {
        return "";
    }
}

const char *target_lib_file_ext(ZigTarget *target, bool is_static, size_t version_major, size_t version_minor, size_t version_patch) {
    if (target->os == OsWindows) {
        if (is_static) {
            return ".lib";
        } else {
            return ".dll";
        }
    } else {
        if (is_static) {
            return ".a";
        } else {
            return buf_ptr(buf_sprintf(".so.%zu", version_major));
        }
    }
}

enum FloatAbi {
    FloatAbiHard,
    FloatAbiSoft,
    FloatAbiSoftFp,
};

static FloatAbi get_float_abi(ZigTarget *target) {
    const ZigLLVM_EnvironmentType env = target->env_type;
    if (env == ZigLLVM_GNUEABIHF ||
        env == ZigLLVM_EABIHF ||
        env == ZigLLVM_MuslEABIHF)
    {
        return FloatAbiHard;
    } else {
        return FloatAbiSoft;
    }
}

static bool is_64_bit(ZigLLVM_ArchType arch) {
    return get_arch_pointer_bit_width(arch) == 64;
}

Buf *target_dynamic_linker(ZigTarget *target) {
    const ZigLLVM_ArchType arch = target->arch.arch;
    const ZigLLVM_EnvironmentType env = target->env_type;

    if (env == ZigLLVM_Android) {
        if (is_64_bit(arch)) {
            return buf_create_from_str("/system/bin/linker64");
        } else {
            return buf_create_from_str("/system/bin/linker");
        }
    } else if (arch == ZigLLVM_x86 ||
            arch == ZigLLVM_sparc ||
            arch == ZigLLVM_sparcel)
    {
        return buf_create_from_str("/lib/ld-linux.so.2");
    } else if (arch == ZigLLVM_aarch64) {
        return buf_create_from_str("/lib/ld-linux-aarch64.so.1");
    } else if (arch == ZigLLVM_aarch64_be) {
        return buf_create_from_str("/lib/ld-linux-aarch64_be.so.1");
    } else if (arch == ZigLLVM_arm || arch == ZigLLVM_thumb) {
        if (get_float_abi(target) == FloatAbiHard) {
            return buf_create_from_str("/lib/ld-linux-armhf.so.3");
        } else {
            return buf_create_from_str("/lib/ld-linux.so.3");
        }
    } else if (arch == ZigLLVM_armeb || arch == ZigLLVM_thumbeb) {
        if (get_float_abi(target) == FloatAbiHard) {
            return buf_create_from_str("/lib/ld-linux-armhf.so.3");
        } else {
            return buf_create_from_str("/lib/ld-linux.so.3");
        }
    } else if (arch == ZigLLVM_mips || arch == ZigLLVM_mipsel ||
            arch == ZigLLVM_mips64 || arch == ZigLLVM_mips64el)
    {
        // when you want to solve this TODO, grep clang codebase for
        // getLinuxDynamicLinker
        zig_panic("TODO figure out MIPS dynamic linker name");
    } else if (arch == ZigLLVM_ppc) {
        return buf_create_from_str("/lib/ld.so.1");
    } else if (arch == ZigLLVM_ppc64) {
        return buf_create_from_str("/lib64/ld64.so.2");
    } else if (arch == ZigLLVM_ppc64le) {
        return buf_create_from_str("/lib64/ld64.so.2");
    } else if (arch == ZigLLVM_systemz) {
        return buf_create_from_str("/lib64/ld64.so.1");
    } else if (arch == ZigLLVM_sparcv9) {
        return buf_create_from_str("/lib64/ld-linux.so.2");
    } else if (arch == ZigLLVM_x86_64 &&
            env == ZigLLVM_GNUX32)
    {
        return buf_create_from_str("/libx32/ld-linux-x32.so.2");
    } else if (arch == ZigLLVM_x86_64 &&
            (env == ZigLLVM_Musl || env == ZigLLVM_MuslEABI || env == ZigLLVM_MuslEABIHF))
    {
        return buf_create_from_str("/lib/ld-musl-x86_64.so.1");
    } else {
        return buf_create_from_str("/lib64/ld-linux-x86-64.so.2");
    }
}

bool target_can_exec(const ZigTarget *host_target, const ZigTarget *guest_target) {
    assert(host_target != nullptr);

    if (guest_target == nullptr) {
        // null guest target means that the guest target is native
        return true;
    }

    if (guest_target->os == host_target->os && guest_target->arch.arch == host_target->arch.arch &&
        guest_target->arch.sub_arch == host_target->arch.sub_arch)
    {
        // OS, arch, and sub-arch match
        return true;
    }

    if (guest_target->os == OsWindows && host_target->os == OsWindows &&
        host_target->arch.arch == ZigLLVM_x86_64 && guest_target->arch.arch == ZigLLVM_x86)
    {
        // 64-bit windows can run 32-bit programs
        return true;
    }

    return false;
}

const char *arch_stack_pointer_register_name(const ArchType *arch) {
    switch (arch->arch) {
        case ZigLLVM_UnknownArch:
            zig_unreachable();
        case ZigLLVM_x86:
            return "sp";
        case ZigLLVM_x86_64:
            return "rsp";
        case ZigLLVM_aarch64:
            return "sp";

        case ZigLLVM_arm:
        case ZigLLVM_thumb:
        case ZigLLVM_aarch64_be:
        case ZigLLVM_amdgcn:
        case ZigLLVM_amdil:
        case ZigLLVM_amdil64:
        case ZigLLVM_armeb:
        case ZigLLVM_arc:
        case ZigLLVM_avr:
        case ZigLLVM_bpfeb:
        case ZigLLVM_bpfel:
        case ZigLLVM_hexagon:
        case ZigLLVM_lanai:
        case ZigLLVM_hsail:
        case ZigLLVM_hsail64:
        case ZigLLVM_kalimba:
        case ZigLLVM_le32:
        case ZigLLVM_le64:
        case ZigLLVM_mips:
        case ZigLLVM_mips64:
        case ZigLLVM_mips64el:
        case ZigLLVM_mipsel:
        case ZigLLVM_msp430:
        case ZigLLVM_nios2:
        case ZigLLVM_nvptx:
        case ZigLLVM_nvptx64:
        case ZigLLVM_ppc64le:
        case ZigLLVM_r600:
        case ZigLLVM_renderscript32:
        case ZigLLVM_renderscript64:
        case ZigLLVM_riscv32:
        case ZigLLVM_riscv64:
        case ZigLLVM_shave:
        case ZigLLVM_sparc:
        case ZigLLVM_sparcel:
        case ZigLLVM_sparcv9:
        case ZigLLVM_spir:
        case ZigLLVM_spir64:
        case ZigLLVM_systemz:
        case ZigLLVM_tce:
        case ZigLLVM_tcele:
        case ZigLLVM_thumbeb:
        case ZigLLVM_wasm32:
        case ZigLLVM_wasm64:
        case ZigLLVM_xcore:
        case ZigLLVM_ppc:
        case ZigLLVM_ppc64:
            zig_panic("TODO populate this table with stack pointer register name for this CPU architecture");
    }
    zig_unreachable();
}


text:
/*
window->setWindowTitle("Enter Your Age");

QPushButton* button = new QPushButton("Quit");
QObject::connect(button, SIGNAL(clicked()), &app, SLOT(quit()));

QTableWidget* tableWidget = new QTableWidget(window);
tableWidget->setRowCount(10);
tableWidget->setColumnCount(5);

QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(button);
layout->addWidget(tableWidget);
*/

/*

int main(int argc, char** argv)
{
 QApplication app(argc, argv);
 QWidget wid;
 QPushButton *button = new QPushButton(&wid);
 button->setMinimumWidth(68);
 button->setMinimumHeight(60);
 QVBoxLayout *layout = new QVBoxLayout(&wid);
 layout->addWidget(button);
 wid.show();
 return app.exec();
}
*/

// How add widget
// http://stackoverflow.com/questions/17989231/how-to-add-buttons-to-a-main-window-in-qt
//
// Signals and slots:
// http://qt-project.org/wiki/Qt_for_beginners_Signals_and_slots_2

/*
//http://developer.nokia.com/community/wiki/How_to_use_QTableWidget_in_Qt#Header_File
#include <QtGui/QWidget>
//#include "ui_tableWidget.h"
#include<QStringList>
#include<QTableWidget>
#include<QHBoxLayout>
#include<QPushButton>
#include<QLabel>

class tableWidget : public QWidget
{
    Q_OBJECT

public:
  tableWidget(QWidget *parent = 0);
  ~tableWidget();

private:
   QTableWidget *widget;
   QHBoxLayout *layout;
   QStringList list;
   QPushButton *but1;
   QLabel *lbl;
};

tableWidget::tableWidget(QWidget *parent)
    : QWidget(parent)
{
  layout = new QHBoxLayout(this);
  list<<"No."<<"Name"<<"Adder";
  widget = new QTableWidget(this);
  but1 = new QPushButton("Press",this);
  widget->setRowCount(3);
  widget->setColumnCount(15);
  widget->setHorizontalHeaderLabels(list);
  widget->setCellWidget(0,0,but1);
  widget->setCellWidget(0,1,lbl);
  layout->addWidget(widget);
  setLayout(layout);
}

tableWidget::~tableWidget()
{
    // No need to delete any object it has got a parent which is properly deleted.

}
*/


text:
<?php

/*
 * Fichier créer par : Badr HAKKARI <b.hakkari@void.fr>
 */

namespace WBB\UserBundle\Controller\Admin;

use WBB\CoreBundle\Controller\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;

use FOS\UserBundle\Model\UserManagerInterface;

class UserAdmin extends Admin
{

    /**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('username')
            ->add('email')
            ->add('enabled', null, array('editable' => true))
            ->add('locked', null, array('editable' => true))
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureDatagridFilters(DatagridMapper $filterMapper)
    {
        $filterMapper
            ->add('username')
            ->add('enabled')
            ->add('locked')
            ->add('email')
        ;
    }

    /**
     * {@inheritdoc}
     */
    protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->with('General')
                ->add('username')
                ->add('email')
            ->end()
        ;
    }

    protected $formOptions = array(
        'validation_groups' => 'Profile'
    );

    /**
     * {@inheritdoc}
     */
    protected function configureFormFields(FormMapper $formMapper)
    {
        $generatePasswordBtn = '<input type="button" id="pwd-generator" class="pwd-generator btn" value="Generate Password" />';

        $formMapper
            ->with('General')
                ->add('title', 'choice', array(
                    'help'      => 'Mandatory',
                    'expanded'  => false,
                    'multiple'  => false,
                    'required'  => true,
                    'label'     => 'Gender',
                    'choices'  => array(
                        'F'   =>  'F',
                        'M'   =>  'M'
                    )
                ))
                ->add('username', null, array('help' => 'Mandatory'))
                ->add('email', null, array('help' => 'Mandatory'))
                ->add('firstname', null, array('help' => 'Mandatory', 'label' => 'Firstname', 'required' => false))
                ->add('lastname', null, array('help' => 'Mandatory', 'label' => 'Lastname', 'required' => false))
                ->add('birthdate', null, array('years' => range(1914, date('Y')), 'help' => 'Mandatory', 'label' => 'Birthdate'))
                ->add('website')
                ->add('country', null, array('help' => 'Mandatory', 'label' => 'Country'))
                ->add('latitude', 'hidden')
                ->add('longitude', 'hidden')
                ->add('description', 'textarea', array('required'=>false, 'attr' => array('class' => 'wysihtml5')))
                ->add('plainPassword', 'text', array(
                        'required' => false,
                        'help' => $generatePasswordBtn.'Mandatory',
                        'label' => 'Password *',
                        'attr' => array(
                            'class' => 'span5 pwd-field'
                        )
                    )
                )
            ->end()
            ->with('Preferences')
                ->add('prefCity1', null, array('read_only' => true, 'disabled'  => true))
                ->add('prefCity2', null, array('read_only' => true, 'disabled'  => true))
                ->add('prefCity3', null, array('read_only' => true, 'disabled'  => true))
                ->add('prefBar1', null, array('read_only' => true, 'disabled'  => true))
                ->add('prefBar2', null, array('read_only' => true, 'disabled'  => true))
                ->add('prefBar3', null, array('read_only' => true, 'disabled'  => true))
                ->add('prefDrinkBrand1', null, array('read_only' => true, 'disabled'  => true))
                ->add('prefDrinkBrand2', null, array('read_only' => true, 'disabled'  => true))
                ->add('prefDrinkBrand3', null, array('read_only' => true, 'disabled'  => true))
                ->add('prefCocktails1', null, array('read_only' => true, 'disabled'  => true))
                ->add('prefCocktails2', null, array('read_only' => true, 'disabled'  => true))
                ->add('prefCocktails3', null, array('read_only' => true, 'disabled'  => true))
                ->add('prefStartCity', null, array('read_only' => true, 'disabled'  => true))
                ->add('stayInformed')
                ->add('stayBrandInformed')
            ->end()
        ;

        if(!$this->getSubject()->hasRole('ROLE_SUPER_ADMIN')) {
            $formMapper
                ->with('Management')
                    ->add('roles', 'choice', array(
                        'help' => 'Mandatory',
                        'expanded' => true,
                        'multiple' => true,
                        'required' => false,
                        'choices'  => array(
                            'ROLE_SUPER_ADMIN'      =>  'Super Admin',
                            'ROLE_MODERATOR'        =>  'Moderator',
                            'ROLE_PUBLISHER'        =>  'Publisher',
                            'ROLE_EDITORIAL_EXPERT' =>  'Editorial Expert',
                            'ROLE_BAR_EXPERT'       =>  'Bar Expert',
                            'ROLE_BAR_OWNER'        =>  'Bar Owner',
                            'ROLE_USER'             =>  'User'
                        )
                    ))
                    ->add('locked', null, array('required' => false))
                    ->add('enabled', null, array('required' => false))
                ->end()
            ;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function preUpdate($user)
    {
        if($user->getPlainPassword()){
            //Get the plain password before encryption and the rest of email data
            $data = array(
                'password'  => $user->getPlainPassword(),
                'email'     => $user->getEmail(),
                'gender'    => $user->getTitle(),
                'fullName'  => $user->getFullName()
            );
            //Send Email containing the New Password
            $this->getContainer()->get('wbb_user.generate_password.mailer')->sendGeneratedPassword($data);
        }

        $this->getUserManager()->updateCanonicalFields($user);
        $this->getUserManager()->updatePassword($user);
    }

    /**
     * {@inheritdoc}
     */
    public function getExportFields()
    {
        return array(
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('firstname', 'show', 'label'))           => 'firstname',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('lastname', 'show', 'label'))            => 'lastname',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('lastname', 'show', 'label'))            => 'birthdate',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('lastname', 'show', 'label'))            => 'country.name',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('prefCity1', 'show', 'label'))           => 'prefCity1',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('prefCity2', 'show', 'label'))           => 'prefCity2',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('prefCity3', 'show', 'label'))           => 'prefCity3',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('prefBar1', 'show', 'label'))            => 'prefBar1',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('prefBar2', 'show', 'label'))            => 'prefBar2',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('prefBar3', 'show', 'label'))            => 'prefBar3',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('prefDrinkBrand1', 'show', 'label'))     => 'prefDrinkBrand1',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('prefDrinkBrand2', 'show', 'label'))     => 'prefDrinkBrand2',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('prefDrinkBrand3', 'show', 'label'))     => 'prefDrinkBrand3',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('prefCocktails1', 'show', 'label'))      => 'prefCocktails1',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('prefCocktails2', 'show', 'label'))      => 'prefCocktails2',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('prefCocktails3', 'show', 'label'))      => 'prefCocktails3',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('stayInformed', 'show', 'label'))        => 'stayInformed',
            $this->trans($this->getLabelTranslatorStrategy()->getLabel('stayBrandInformed', 'show', 'label'))   => 'stayBrandInformed',
        );
    }

    /**
     * @param UserManagerInterface $userManager
     */
    public function setUserManager(UserManagerInterface $userManager)
    {
        $this->userManager = $userManager;
    }

    /**
     * @return UserManagerInterface
     */
    public function getUserManager()
    {
        return $this->userManager;
    }
}