text:
/**
 * Infrastructure for producing logs of individual compiler phases.
 *
 * @author sliva
 */
package compiler.common.logger;

redpajama_set_name: RedPajamaGithub


text:
package org.apache.oodt.pcs.opsui;

//OODT imports
import org.apache.oodt.cas.webcomponents.filemgr.browser.types.Types;

//Wicket imports
import org.apache.wicket.PageParameters;

/**
 *
 * The types page that shows type names and bucket counts
 * (that are clickable).
 *
 * @author mattmann
 * @version $Revision$
 *
 */
public class TypesPage extends BasePage {

  public TypesPage(PageParameters parameters) {
    super(parameters);
    add(new Types("types_component",
       app.getFmUrlStr(), TypeBrowserPage.class));
  }
}


text:
module Sable

  # The base class to use for notifiables
  mattr_accessor :notifiable_class_name
  @@notifiable_class_name = 'Notification'

  # The foreign_key to use for notifiables
  mattr_accessor :notifiable_recipient_class_name
  @@notifiable_recipient_class_name = 'User'

  # The foreign_key to use for notifiables
  mattr_accessor :subscriber_class_name
  @@subscriber_class_name = 'User'

  # Compatibility: name of subscriber relation in subscription
  mattr_accessor :subscriber_relation_name
  @@subscriber_relation_name = 'subscriber'

  # Enable initializer
  def self.setup
    yield self
  end

  %w(acceptable notifiable notifiable_recipient subscriber subscribable).each do |m|
    require "concerns/#{m}"
  end

end


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Simple Harmonic</title>
    <script src="../base.js"></script>
    <script src="../vector.js"></script>
    <script src="../oscillator.js"></script>
  </head>
  <body>
    <canvas id="canvas" style="position: fixed; top: 0; left: 0;"></canvas>
    <script>
      var
        angle, vel, amp,
        oscillators = [],
        space = document.getElementById("canvas"),
        context = space.getContext("2d");

      space.width = window.innerWidth;
      space.height = window.innerHeight;

      for (var i = 0; i < 20; i++) {
        angle = new Vector(0, 0);
        vel = new Vector(randomRange(-0.05, 0.05), randomRange(-0.05, 0.05));
        amp = new Vector(Math.random() * space.width/2, Math.random() * space.height/2);
        oscillators[i] = new Oscillator(angle, vel, amp);
      }

      function draw() {
        context.clearRect(0, 0, space.width, space.height);

        for (var i = 0; i < 20; i++) {
          oscillators[i].oscillate();
          oscillators[i].display(space);
        }
      }

      (function animationLoop() {
        requestAnimationFrame(animationLoop);
        draw();
      })();
    </script>
  </body>
</html>


text:
package amu.zhcet.core.admin.dean.datatables;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import lombok.Data;
import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;

@Data
class UserView {
    @JsonView(DataTablesOutput.View.class)
    @JsonProperty("user_name")
    private String userName;
    @JsonView(DataTablesOutput.View.class)
    @JsonProperty("user_gender")
    private String userGender;
    @JsonView(DataTablesOutput.View.class)
    @JsonProperty("user_email")
    private String userEmail;
    @JsonView(DataTablesOutput.View.class)
    @JsonProperty("avatar-url")
    private String userDetailsAvatarUrl;
    @JsonView(DataTablesOutput.View.class)
    @JsonProperty("original-avatar-url")
    private String userDetailsOriginalAvatarUrl;
    @JsonView(DataTablesOutput.View.class)
    @JsonProperty("user_department_name")
    private String userDepartmentName;
    @JsonView(DataTablesOutput.View.class)
    @JsonProperty("is-verified")
    private boolean userEmailVerified;
    @JsonView(DataTablesOutput.View.class)
    @JsonProperty("user_enabled")
    private String userEnabled;
}


text:
'use strict';

/* Services */

angular.module('learny.services.home', ['ngResource'])

	.factory('Posts', function($resource){
		return $resource("http://localhost:3010/post");
	})


text:
package org.sirix.axis.concurrent;

import static com.google.common.base.Preconditions.checkNotNull;
import java.util.concurrent.BlockingQueue;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.sirix.api.Axis;
import org.sirix.settings.Fixed;
import org.sirix.utils.LogWrapper;
import org.slf4j.LoggerFactory;

/**
 *

 * Is the helper for the ConcurrentAxis and realizes the concurrent evaluation of pipeline steps by
 * decoupling the given axis from the main thread and storing its results in a blocking queue so
 * establish a producer-consumer-relationship between the ConcurrentAxis and this one.
 *

 *

 * This axis should only be used and instantiated by the ConcurrentAxis. Find more information on
 * how to use this framework in the ConcurrentAxis documentation.
 *

 */
public class ConcurrentAxisHelper implements Runnable {

  /** Logger. */
  public static final LogWrapper LOGWRAPPER =
      new LogWrapper(LoggerFactory.getLogger(ConcurrentAxisHelper.class));

  /** {@link Axis} that computes the results. */
  private final Axis axis;

  /**
   * Queue that stores result keys already computed by this axis. End of the result sequence is
   * marked by the NULL_NODE_KEY. This is used for communication with the consumer.
   */
  private BlockingQueue<Long> results;

  /**
   * Bind axis step to transaction. Make sure to create a new ReadTransaction instead of using the
   * parameter rtx. Because of concurrency every axis has to have it's own transaction.
   *
   * @param axis Axis to bind with
   * @param results queue which has results related to the axis
   */
  public ConcurrentAxisHelper(final Axis axis, @NonNull final BlockingQueue<Long> results) {
    this.axis = checkNotNull(axis);
    this.results = checkNotNull(results);
  }

  @Override
  public void run() {
    // Compute all results of the given axis and store the results in the queue.
    while (axis.hasNext()) {
      final long nodeKey = axis.next();
      try {
        // Store result in queue as soon as there is space left.
        results.put(nodeKey);
        // Wait until next thread arrives and exchange blocking queue.
      } catch (final InterruptedException e) {
        LOGWRAPPER.error(e.getMessage(), e);
      }
    }

    try {
      // Mark end of result sequence by the NULL_NODE_KEY.
      results.put(Fixed.NULL_NODE_KEY.getStandardProperty());
    } catch (final InterruptedException e) {
      LOGWRAPPER.error(e.getMessage(), e);
    }
  }
}


text:
const gulp      = require('gulp');
const concat    = require('gulp-concat');
const uglify    = require('gulp-uglify');
const gulpDocs  = require('gulp-ngdocs');
const clean     = require('gulp-clean');
const rename    = require('gulp-rename');
const through = require('through2');
const File = require('vinyl');

var fs = require('fs');

var env = {};

// See if there is an enviromental file with options to override
try {
    env = JSON.parse(fs.readFileSync('.env.json').toString());
} catch (e) {}

var target = {
    docs: env.docs || './docs'
};

function processScripts () {
    return gulp.src('./src/**/*.js')
        .pipe(concat('angular-screenfull.js'))
        .pipe(gulp.dest('./dist/'))
        .pipe(uglify())
        .pipe(rename({suffix: '.min'}))
        .pipe(gulp.dest('./dist/'));
};

const watch = function() {
    gulp.watch('./src/**/*.js', gulp.series(processScripts, ngdocs));
};

exports.watch = watch;

const ngdocs = gulp.series(cleanNgdocs, function ngdocs () {
    var options = {
        html5Mode: false,
        analytics: {
            account: 'UA-44454147-3',
            domainName: 'http://hrajchert.github.io/angular-screenfull/'
        },
        scripts: [
            'dist/angular-screenfull.js',
            'https://cdnjs.cloudflare.com/ajax/libs/screenfull.js/4.0.0/screenfull.js'
        ]
    };
    return gulp.src(['./src/**/*.js', './src/**/*.ngdoc'])
        .pipe(gulpDocs.process(options))
        .pipe(upgradeVynil())
        .pipe(gulp.dest(target.docs));
});

/**
 * gulp-watch/vinyl-source-stream uses an outdated vinyl, which doesn't have some functions which vinyl-fs expects.
 * Can be removed when gulp-watch updates it to vinyl 2.x.
 * @returns {NodeJS.ReadWriteStream}
 */
function upgradeVynil() {
    return through.obj(function(file, encoding, cb) {
      const upgradedFile = new File(file);
      cb(null, upgradedFile);
    });
  }

exports.ngdocs = ngdocs;
function cleanNgdocs() {
    return gulp.src(target.docs + '/*', {read:false})
        .pipe(clean({force: true}));
}

exports.release = gulp.series(processScripts, ngdocs);
exports.default = gulp.series(processScripts, ngdocs, watch);


text:
package com.dpz.learn.archetype.manager;

import com.dpz.learn.archetype.model.Log;

public interface ILogManager extends IBaseManager<Log>{

}


text:
var ss = require("../../../lib/html-snapshots");
var result = ss.run({
  input: "array",
  source: ["http://localhost:9001/", "http://localhost:9001/sample-page", "http://localhost:9001/page-two"],
  port: 9001,
  outputDirClean: true,
  outputDir: "./tmp/snapshots",
  selector: {
    "http://localhost:9001/": "#content .multiple-posts",
    "__default": "#content .grid-row"
  },
  timeout: 10000
}, function(err, results) {
  console.log("err = "+err);
  console.log("snapshots = "+results);
  console.log("result = "+result);
});
console.log("first result = "+result);


text:
layout: post
date: 2017-09-17
title: "Watters-Seahorse Girls Seahorse Dress 43312 Sleeveless Tea-Length Ballgown"
category: Watters-Seahorse Girls
tags: [Watters-Seahorse Girls,Seahorse Girls,Ballgown,Straps,Tea-Length,Sleeveless]
---
### Watters-Seahorse Girls Seahorse Dress 43312
Just **$219.99**
###   Sleeveless Tea-Length Ballgown

BRANDS	Seahorse Girls

Silhouette	Ballgown

Neckline	Straps

Hemline/Train	Tea-Length

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/watters-seahorse-girls/14344-watters-dress-43312.html](https://www.readybrides.com/en/watters-seahorse-girls/14344-watters-dress-43312.html)


text:
[ ![Download](https://api.bintray.com/packages/xsolla/maven/xsollasdk/images/download.svg) ](https://bintray.com/xsolla/maven/xsollasdk/_latestVersion)

Xsolla Android SDK
===============
## Overview

Xsolla created Android Client SDK for accepting credit card payments from your application.

Before start, please choose one of the modules listed
[here](https://developers.xsolla.com/), implement the IPN handling, create an [access token](https://developers.xsolla.com/api/v2/pay-station/#api_payment_ui).

## System Requirements

1. Minimum required Android OS version: 4.0
2. Internet Connection is essential for the Xsolla Android SDK

## Download

Download via Maven:
```xml
<dependency>
  <groupId>com.xsolla.android</groupId>
  <artifactId>xsollasdk</artifactId>
  <version>2.3.4</version>
</dependency>
```
or Gradle:
```groovy
implementation 'com.xsolla.android:xsollasdk:2.3.4'
```

## Installing
* Add to your `build.gradle` in android section the following:
```javascript
packagingOptions {
   exclude 'META-INF/LICENSE'
   exclude 'META-INF/NOTICE'
}
```

## Make a Payment

For the proper work of the SDK, please make sure that you have an access token. More information about getting token is available [here](https://developers.xsolla.com/api/v2/getting-started/#api_token_ui).

##### Xsolla UI

Let's take as an example the simple application that has a payment button, when clicked our Shop is opened.

```java

public class MainActivity extends Activity {

   public void openShop(String token, boolean isTestPayment) {
        XsollaSDK.createPaymentForm(this, token, isTestPayment);
   }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case XsollaActivity.REQUEST_CODE:
                if(data != null) {
                    long objectId = data.getExtras().getLong(XsollaActivity.EXTRA_OBJECT_ID);
                    if (resultCode == RESULT_OK) {
                        XStatus statusData = (XStatus) XsollaObject.getRegisteredObject(objectId);
                        Toast.makeText(this, statusData.toString(), Toast.LENGTH_LONG).show();
                    } else {
                        XError error = (XError) XsollaObject.getRegisteredObject(objectId);
                        Toast.makeText(this, error.toString(), Toast.LENGTH_LONG).show();
                    }
                }
        }
    }

}
```

## Objects to work with
Below you can find useful methods

### XStatus
Contains info about payment

```
public long getInvoice();// transaction id
public String getGroup();// payment status
```

### XError
Contains error info

```
public int getSupportCode();
public String getMessage();
```


text:
package com.google.api.ads.dfp.jaxws.v201505;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             A premium feature applied to geography targeting.
 *
 *
 *
Java class for GeographyPremiumFeature complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="GeographyPremiumFeature">
 *   <complexContent>
 *     <extension base="{https://www.google.com/apis/ads/publisher/v201505}PremiumFeature">
 *       <sequence>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "GeographyPremiumFeature")
public class GeographyPremiumFeature
    extends PremiumFeature
{

}


text:
/**
 * Created by david on 24/03/2017.
 */
import {Script} from "vm";
import {resolve, parse} from "url";

import {FilteredResults, MangaFilter} from "../../../filter";
import {gin, Site, ImageCollection, GinImage} from "./../../interface";
import {MangaSite} from "./../../mangasite";
import {config} from "./config";

import {processFilter} from "./filter";
import {Helper} from "./names";
import {Parser} from "./parser";
import MangaSource = gin.MangaSource;
import SiteConfig = gin.SiteConfig;
import {Lazy} from "./../../util";

export class KissManga extends MangaSite<SiteConfig, Parser, Helper> implements Site {
  sitename: string = "kissmanga";

  public constructor() {
    super(config, new Parser(), new Helper());
  }

  private async getVM(secret: string): Promise<Script> {
    let vm = this.parser.VM;
    if (vm && this.parser.secretAlgorithm === secret) {
      return vm;
    }

    let tkCa = this.getHtml(resolve(this.config.site, "/Scripts/ca.js"));
    let tkLo = this.getHtml(resolve(this.config.site, "/Scripts/lo.js"));
    let tkLst = [tkCa
      , tkLo];

    let lst = await Promise.all(tkLst);

    return this.parser.buildVM(lst[0], lst[1], secret);
  }

  mangas(filter?: MangaFilter): Promise<MangaSource[]> {
    return this.filter().then(x => x.results);
  }

  async filter(filter?: MangaFilter): Promise<FilteredResults> {
    this.debug("filter mangas with: %o", filter);

    let search = processFilter(filter);
    let opts = this.buildMangasRequest(search.src);
    let headers = opts.headers || {};
    headers["Content-Type"] = headers["Content-Type"] || "application/x-www-form-urlencoded; charset=UTF-8";
    headers["Content-Length"] = headers["Content-Length"] || search.params.length;
    opts.body = search.params.toString();

    let doc = await this.postDoc(opts);
    let mangas = await this.parser.filter(doc);

    this.debug(`mangas: ${mangas.results.length}`);

    return mangas;
  }

  async images(name: string, chapNumber: string): Promise<ImageCollection> {
    const chapSrc = await this.resolveChapterSource(name, chapNumber);

    const html = await this.getHtml(chapSrc);
    const secret = this.parser.getSecret(html);
    const vm = await this.getVM(secret);

    const imgs = this.parser.imagesList(html, secret, vm);

    const srcs: GinImage[] = imgs.map(x => ({
      name: parse(x).pathname.split("/").reverse()[0],
      src: x
    }));

    return srcs.map(x => new Lazy(() => Promise.resolve(x)));
  }
}

export const manga: Site = new KissManga();
export default manga;


text:
<?php

namespace Worldskills\CareBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class WorldskillsCareBundle extends Bundle
{
}


text:
1. Install VS Code.
2. Install the Code Spell Checker by Street Side Software.
This will allow testing of the changes locally with minimal effort. Literally, you'll just need to load a file and anything it flags will be underlined in blue. The configuration definition can be found at <https://cspell.org/configuration/>
3. The main spellcheck document can be found [here](https://github.com/Azure/azure-sdk-tools/blob/main/doc/common/spellcheck.md) in the [azure-sdk-tools](https://github.com/Azure/azure-sdk-tools) repository.

## Words and word boundaries

"-" and "." are word boundaries. For example: An artifactId, azure-core-amqp, will verify azure, core and amqp.AMQP, not being in the dictionary would get flagged and that's the only word that would be required to add to the list.

## Case insensitivity

The ignored words are case insensitive. AMQP, amqp, Amqp etc would all be picked up from "amqp"

## Regular expressions

There are times when a single word really isn't enough. For example: Instead of adding each unique word from each and every groupId and artifactId from every Azure SDK library and external dependency, it's cleaner to regex away the line that contains the artifactId. Always match

### Multi-line regular expression

Multi-line regular expressions should be used with extreme caution as it's far too easy to accidentally regex away too much. Any multi-line regular expression should have hard tags that delineate a clear beginning and a clear ending with the multi-line regular expression in between these tags. These tags should be as close to what you want to regex away as possible. For example: A `<properties>` tag may contain a number other tags that you with to regex away but they can also contain things, like a `<legal>`, which contains a string that needs to get checked. For any set of tags that may contain sub-tags, only the sub-tags should be regex'd unless you can guarantee that the all of possible sub-tags will never need to be scanned. `<compilerArguments>` would be an example where all of the sub-tags would be skipped.

**If a multi-line regular expression is needed then a member of the Azure SDK Engineering System Team should be added to the code review.**

### What type of things should regular expressions be used for?

1. Anything that would contain a groupId
2. Anything that would contain an artifactId
3. Anything that would contain a version. There are two reasons for this. The first reason because of version tags in pom files. Each version tag should have a version update tag which contains the group and artifact. The second reason is that while our Azure SDK for Java versions will successfully pass spelling checks, it's not a guarantee that external dependency version will. For ex. 2.0-groovy-3.0. Maven accepts these type of version strings.
4. Anything that contains class names. Classes often contain abbreviations or words that won't pass spellcheck. For example: AMQP.
5. Anything that contain lists 1-4. For example `<excludePackageNames>` is a multi-line regular expression because it contains a list of packages to exclude.

## Do nots

1. Do not add a name, initials or aliases to the skip list. Individual names, initials or aliases does not belong in anything that ships.
2. Do not exclude a filetype or directory that contains artifacts that ship.
3. Do not write a multi-line regular expression for a tag that contains other tags. Unless you can guarantee each sub-tag won't contain items that need to be scanned.


text:
@interface Animal : NSObject

@end


text:
// Version: 0.13.1-13-gd5fad5d
// Last commit: d5fad5d (2013-09-15 20:29:23 -0500)

(function() {
var define, requireModule;

(function() {
  var registry = {}, seen = {};

  define = function(name, deps, callback) {
    registry[name] = { deps: deps, callback: callback };
  };

  requireModule = function(name) {
    if (seen[name]) { return seen[name]; }
    seen[name] = {};

    var mod, deps, callback, reified , exports;

    mod = registry[name];

    if (!mod) {
      throw new Error("Module '" + name + "' not found.");
    }

    deps = mod.deps;
    callback = mod.callback;
    reified = [];
    exports;

    for (var i=0, l=deps.length; i<l; i++) {
      if (deps[i] === 'exports') {
        reified.push(exports = {});
      } else {
        reified.push(requireModule(deps[i]));
      }
    }

    var value = callback.apply(this, reified);
    return seen[name] = exports || value;
  };
})();
(function() {
var get = Ember.get, set = Ember.set, isNone = Ember.isNone;

DS.DjangoRESTSerializer = DS.JSONSerializer.extend({

    init: function() {
        this._super.apply(this, arguments);
    },

    extractDjangoPayload: function(store, type, payload) {
        for (var item in payload) {
            if (typeof(payload[item][0]) !== 'number') {
                if (payload[item].constructor.name === 'Array') {
                    var singular_type = Ember.String.singularize(item);
                    /*jshint loopfunc:true*/
                    var ids = payload[item].map(function(related) {
                        store.push(singular_type, related);
                        return related.id; //todo find pk (not always id)
                    });
                    payload[item] = ids;
                }
            }
        }
    },

    extractSingle: function(store, type, payload) {
        this.extractDjangoPayload(store, type, payload);
        return payload;
    },

    extractArray: function(store, type, payload) {
        var self = this;
        for (var j = 0; j < payload.length; j++) {
            self.extractDjangoPayload(store, type, payload[j]);
        }
        return payload;
    }

});

})();

(function() {
var get = Ember.get, set = Ember.set, isNone = Ember.isNone;

DS.DjangoRESTAdapter = DS.RESTAdapter.extend({
    defaultSerializer: "DS/djangoREST",

    createRecord: function(store, type, record) {
        var url = this.getCorrectPostUrl(record, this.buildURL(type.typeKey));
        var data = store.serializerFor(type.typeKey).serialize(record);
        return this.ajax(url, "POST", { data: data });
    },

    updateRecord: function(store, type, record) {
        var data = store.serializerFor(type.typeKey).serialize(record);
        var id = get(record, 'id'); //todo find pk (not always id)
        return this.ajax(this.buildURL(type.typeKey, id), "PUT", { data: data });
    },

    findMany: function(store, type, ids, parent) {
        var adapter, root, url;
        adapter = this;

        if (parent) {
            url = this.buildFindManyUrlWithParent(type, parent);
        } else {
            Ember.assert("You need to add belongsTo for type (" + type.typeKey + "). No Parent for this record was found");
        }

        return this.ajax(url, "GET");
    },

    ajax: function(url, type, hash) {
        hash = hash || {};
        hash.cache = false;

        return this._super(url, type, hash);
    },

    buildURL: function(type, id) {
        var url = this._super(type, id);

        if (url.charAt(url.length -1) !== '/') {
            url += '/';
        }

        return url;
    },

    getBelongsTo: function(record) {
        var totalParents = [];
        record.eachRelationship(function(name, relationship) {
            if (relationship.kind === 'belongsTo') {
                totalParents.push(name);
            }
        }, this);
        return totalParents;
    },

    getNonEmptyRelationships: function(record, totalParents) {
        var totalHydrated = [];
        totalParents.forEach(function(item) {
            if (record.get(item) !== null) {
                totalHydrated.push(item);
            }
        }, this);
        return totalHydrated;
    },

    getCorrectPostUrl: function(record, url) {
        var totalParents = this.getBelongsTo(record);
        var totalHydrated = this.getNonEmptyRelationships(record, totalParents);
        if (totalParents.length > 1 && totalHydrated.length <= 1) {
            return this.buildUrlWithParentWhenAvailable(record, url, totalHydrated);
        }

        if (totalParents.length === 1 && totalHydrated.length === 1) {
            var parent_value = record.get(totalParents[0]).get('id'); //todo find pk (not always id)
            var parent_plural = Ember.String.pluralize(totalParents[0]);
            var endpoint = url.split('/').reverse()[1];
            return url.replace(endpoint, parent_plural + "/" + parent_value + "/" + endpoint);
        }

        return url;
    },

    buildUrlWithParentWhenAvailable: function(record, url, totalHydrated) {
        if (record && url && totalHydrated) {
            var parent_type = totalHydrated[0];
            var parent_pk = record.get(parent_type).get('id'); //todo find pk (not always id)
            var parent_plural = Ember.String.pluralize(parent_type);
            var endpoint = url.split('/').reverse()[1];
            url = url.replace(endpoint, parent_plural + "/" + parent_pk + "/" + endpoint);
        }
        return url;
    },

    buildFindManyUrlWithParent: function(type, parent) {
        var root, url, endpoint, parentValue;

        endpoint = Ember.String.pluralize(type.typeKey);
        parentValue = parent.get('id'); //todo find pk (not always id)
        root = parent.constructor.typeKey;
        url = this.buildURL(root, parentValue);

        return url + endpoint + '/';
    }

});

})();

(function() {

})();

})();


text:
#include <string>
#include <fstream>
#include <iostream>
#include <vector>

#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sstream>
#include "t_generator.h"
#include "platform.h"

using namespace std;

/**
 * Erlang code generator.
 *
 */
class t_erl_generator : public t_generator {
 public:
  t_erl_generator(
      t_program* program,
      const std::map<std::string, std::string>& parsed_options,
      const std::string& option_string)
    : t_generator(program)
  {
    program_name_[0] = tolower(program_name_[0]);
    service_name_[0] = tolower(service_name_[0]);
    out_dir_base_ = "gen-erl";
  }

  /**
   * Init and close methods
   */

  void init_generator();
  void close_generator();

  /**
   * Program-level generation functions
   */

  void generate_typedef  (t_typedef*  ttypedef);
  void generate_enum     (t_enum*     tenum);
  void generate_const    (t_const*    tconst);
  void generate_struct   (t_struct*   tstruct);
  void generate_xception (t_struct*   txception);
  void generate_service  (t_service*  tservice);

  std::string render_const_value(t_type* type, t_const_value* value);

  /**
   * Struct generation code
   */

  void generate_erl_struct(t_struct* tstruct, bool is_exception);
  void generate_erl_struct_definition(std::ostream& out, std::ostream& hrl_out, t_struct* tstruct, bool is_xception=false, bool is_result=false);
  void generate_erl_struct_info(std::ostream& out, t_struct* tstruct);
  void generate_erl_function_helpers(t_function* tfunction);

  /**
   * Service-level generation functions
   */

  void generate_service_helpers   (t_service*  tservice);
  void generate_service_interface (t_service* tservice);
  void generate_function_info     (t_service* tservice, t_function* tfunction);

  /**
   * Helper rendering functions
   */

  std::string erl_autogen_comment();
  std::string erl_imports();
  std::string render_includes();
  std::string declare_field(t_field* tfield);
  std::string type_name(t_type* ttype);

  std::string function_signature(t_function* tfunction, std::string prefix="");

  std::string argument_list(t_struct* tstruct);
  std::string type_to_enum(t_type* ttype);
  std::string generate_type_term(t_type* ttype, bool expand_structs);
  std::string type_module(t_type* ttype);

  std::string capitalize(std::string in) {
    in[0] = toupper(in[0]);
    return in;
  }

  std::string uncapitalize(std::string in) {
    in[0] = tolower(in[0]);
    return in;
  }

 private:

  /**
   * add function to export list
   */

  void export_function(t_function* tfunction, std::string prefix="");
  void export_string(std::string name, int num);

  void export_types_function(t_function* tfunction, std::string prefix="");
  void export_types_string(std::string name, int num);

  /**
   * write out headers and footers for hrl files
   */

  void hrl_header(std::ostream& out, std::string name);
  void hrl_footer(std::ostream& out, std::string name);

  /**
   * stuff to spit out at the top of generated files
   */

  bool export_lines_first_;
  std::ostringstream export_lines_;

  bool export_types_lines_first_;
  std::ostringstream export_types_lines_;

  /**
   * File streams
   */

  std::ostringstream f_types_;
  std::ofstream f_types_file_;
  std::ofstream f_types_hrl_file_;

  std::ofstream f_consts_;
  std::ostringstream f_service_;
  std::ofstream f_service_file_;
  std::ofstream f_service_hrl_;

};

/**
 * UI for file generation by opening up the necessary file output
 * streams.
 *
 * @param tprogram The program to generate
 */
void t_erl_generator::init_generator() {
  // Make output directory
  MKDIR(get_out_dir().c_str());

  // setup export lines
  export_lines_first_ = true;
  export_types_lines_first_ = true;

  // types files
  string f_types_name = get_out_dir()+program_name_+"_types.erl";
  string f_types_hrl_name = get_out_dir()+program_name_+"_types.hrl";

  f_types_file_.open(f_types_name.c_str());
  f_types_hrl_file_.open(f_types_hrl_name.c_str());

  hrl_header(f_types_hrl_file_, program_name_ + "_types");

  f_types_file_ <<
    erl_autogen_comment() << endl <<
    "-module(" << program_name_ << "_types)." << endl <<
    erl_imports() << endl;

  f_types_file_ <<
    "-include(\"" << program_name_ << "_types.hrl\")." << endl <<
    endl;

  f_types_hrl_file_ << render_includes() << endl;

  // consts file
  string f_consts_name = get_out_dir()+program_name_+"_constants.hrl";
  f_consts_.open(f_consts_name.c_str());

  f_consts_ <<
    erl_autogen_comment() << endl <<
    erl_imports() << endl <<
    "-include(\"" << program_name_ << "_types.hrl\")." << endl <<
    endl;
}

/**
 * Boilerplate at beginning and end of header files
 */
void t_erl_generator::hrl_header(ostream& out, string name) {
  out << "-ifndef(_" << name << "_included)." << endl <<
    "-define(_" << name << "_included, yeah)." << endl;
}

void t_erl_generator::hrl_footer(ostream& out, string name) {
  out << "-endif." << endl;
}

/**
 * Renders all the imports necessary for including another Thrift program
 */
string t_erl_generator::render_includes() {
  const vector<t_program*>& includes = program_->get_includes();
  string result = "";
  for (size_t i = 0; i < includes.size(); ++i) {
    result += "-include(\"" + includes[i]->get_name() + "_types.hrl\").\n";
  }
  if (includes.size() > 0) {
    result += "\n";
  }
  return result;
}

/**
 * Autogen'd comment
 */
string t_erl_generator::erl_autogen_comment() {
  return
    std::string("%%\n") +
    "%% Autogenerated by Thrift\n" +
    "%%\n" +
    "%% DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING\n" +
    "%%\n";
}

/**
 * Prints standard thrift imports
 */
string t_erl_generator::erl_imports() {
  return "";
}

/**
 * Closes the type files
 */
void t_erl_generator::close_generator() {
  // Close types file
  export_types_string("struct_info", 1);

  f_types_file_ << "-export([" << export_types_lines_.str() << "])." << endl;
  f_types_file_ << f_types_.str();
  f_types_file_ << "struct_info('i am a dummy struct') -> undefined." << endl;

  hrl_footer(f_types_hrl_file_, string("BOGUS"));

  f_types_file_.close();
  f_types_hrl_file_.close();
  f_consts_.close();
}

/**
 * Generates a typedef. no op
 *
 * @param ttypedef The type definition
 */
void t_erl_generator::generate_typedef(t_typedef* ttypedef) {
}

/**
 * Generates code for an enumerated type. Done using a class to scope
 * the values.
 *
 * @param tenum The enumeration
 */
void t_erl_generator::generate_enum(t_enum* tenum) {
  vector<t_enum_value*> constants = tenum->get_constants();
  vector<t_enum_value*>::iterator c_iter;

  int value = -1;

  for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
    if ((*c_iter)->has_value()) {
      value = (*c_iter)->get_value();
    } else {
      ++value;
    }

    string name = capitalize((*c_iter)->get_name());

    f_types_hrl_file_ <<
      indent() << "-define(" << program_name_ << "_" << name << ", " << value << ")."<< endl;
  }

  f_types_hrl_file_ << endl;
}

/**
 * Generate a constant value
 */
void t_erl_generator::generate_const(t_const* tconst) {
  t_type* type = tconst->get_type();
  string name = capitalize(tconst->get_name());
  t_const_value* value = tconst->get_value();

  f_consts_ << "-define(" << program_name_ << "_" << name << ", " << render_const_value(type, value) << ")." << endl << endl;
}

/**
 * Prints the value of a constant with the given type. Note that type checking
 * is NOT performed in this function as it is always run beforehand using the
 * validate_types method in main.cc
 */
string t_erl_generator::render_const_value(t_type* type, t_const_value* value) {
  type = get_true_type(type);
  std::ostringstream out;

  if (type->is_base_type()) {
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
    switch (tbase) {
    case t_base_type::TYPE_STRING:
      out << '"' << get_escaped_string(value) << '"';
      break;
    case t_base_type::TYPE_BOOL:
      out << (value->get_integer() > 0 ? "true" : "false");
      break;
    case t_base_type::TYPE_BYTE:
    case t_base_type::TYPE_I16:
    case t_base_type::TYPE_I32:
    case t_base_type::TYPE_I64:
      out << value->get_integer();
      break;
    case t_base_type::TYPE_DOUBLE:
      if (value->get_type() == t_const_value::CV_INTEGER) {
        out << value->get_integer();
      } else {
        out << value->get_double();
      }
      break;
    default:
      throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
    }
  } else if (type->is_enum()) {
    indent(out) << value->get_integer();

  } else if (type->is_struct() || type->is_xception()) {
    out << "#" << type->get_name() << "{";
    const vector<t_field*>& fields = ((t_struct*)type)->get_members();
    vector<t_field*>::const_iterator f_iter;
    const map<t_const_value*, t_const_value*>& val = value->get_map();
    map<t_const_value*, t_const_value*>::const_iterator v_iter;

    bool first = true;
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
      t_type* field_type = NULL;
      for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
        if ((*f_iter)->get_name() == v_iter->first->get_string()) {
          field_type = (*f_iter)->get_type();
        }
      }
      if (field_type == NULL) {
        throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
      }

      if (first) {
        first = false;
      } else {
        out << ",";
      }
      out << v_iter->first->get_string();
      out << " = ";
      out << render_const_value(field_type, v_iter->second);
    }
    indent_down();
    indent(out) << "}";

  } else if (type->is_map()) {
    t_type* ktype = ((t_map*)type)->get_key_type();
    t_type* vtype = ((t_map*)type)->get_val_type();
    const map<t_const_value*, t_const_value*>& val = value->get_map();
    map<t_const_value*, t_const_value*>::const_iterator v_iter;

    bool first = true;
    out << "dict:from_list([";
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
      if (first) {
        first=false;
      } else {
        out << ",";
      }
      out << "("
          << render_const_value(ktype, v_iter->first)  << ","
          << render_const_value(vtype, v_iter->second) << ")";
    }
    out << "])";

  } else if (type->is_set()) {
    t_type* etype;
    etype = ((t_set*)type)->get_elem_type();

    bool first = true;
    const vector<t_const_value*>& val = value->get_list();
    vector<t_const_value*>::const_iterator v_iter;
    out << "sets:from_list([";
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
      if (first) {
        first=false;
      } else {
        out << ",";
      }
      out << "(" << render_const_value(etype, *v_iter) << ",true)";
    }
    out << "])";

  } else if (type->is_list()) {
    t_type* etype;
    etype = ((t_list*)type)->get_elem_type();
    out << "[";

    bool first = true;
    const vector<t_const_value*>& val = value->get_list();
    vector<t_const_value*>::const_iterator v_iter;
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
      if (first) {
        first=false;
      } else {
        out << ",";
      }
      out << render_const_value(etype, *v_iter);
    }
    out << "]";
  } else {
    throw "CANNOT GENERATE CONSTANT FOR TYPE: " + type->get_name();
  }
  return out.str();
}

/**
 * Generates a struct
 */
void t_erl_generator::generate_struct(t_struct* tstruct) {
  generate_erl_struct(tstruct, false);
}

/**
 * Generates a struct definition for a thrift exception. Basically the same
 * as a struct but extends the Exception class.
 *
 * @param txception The struct definition
 */
void t_erl_generator::generate_xception(t_struct* txception) {
  generate_erl_struct(txception, true);
}

/**
 * Generates a struct
 */
void t_erl_generator::generate_erl_struct(t_struct* tstruct,
                                          bool is_exception) {
  generate_erl_struct_definition(f_types_, f_types_hrl_file_, tstruct, is_exception);
}

/**
 * Generates a struct definition for a thrift data type.
 *
 * @param tstruct The struct definition
 */
void t_erl_generator::generate_erl_struct_definition(ostream& out,
                                                     ostream& hrl_out,
                                                     t_struct* tstruct,
                                                     bool is_exception,
                                                     bool is_result)
{
  const vector<t_field*>& members = tstruct->get_members();
  vector<t_field*>::const_iterator m_iter;

  indent(out) << "%% struct " << type_name(tstruct) << endl;

  if (is_exception) {
  }

  out << endl;

  if (members.size() > 0) {
    indent(out)     << "% -record(" << type_name(tstruct) << ", {";
    indent(hrl_out) <<   "-record(" << type_name(tstruct) << ", {";

    bool first = true;
    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
      if (first) {
        first = false;
      } else {
        out     << ", ";
        hrl_out << ", ";
      }
      std::string name = uncapitalize((*m_iter)->get_name());
      out     << name;
      hrl_out << name;
    }
    out     << "})." << endl;
    hrl_out << "})." << endl;
  } else { // no members; explicit comment
    indent(out)     << "% -record(" << type_name(tstruct) << ", {})." << endl;
    indent(hrl_out) <<   "-record(" << type_name(tstruct) << ", {})." << endl;
  }

  out << endl;
  hrl_out << endl;

  generate_erl_struct_info(out, tstruct);
}

/**
 * Generates the read method for a struct
 */
void t_erl_generator::generate_erl_struct_info(ostream& out,
                                                  t_struct* tstruct) {
  string name = type_name(tstruct);

  indent(out) << "struct_info('" << name << "') ->" << endl;
  indent_up();

  out << indent() << generate_type_term(tstruct, true) << ";" << endl;

  indent_down();
  out << endl;
}

/**
 * Generates a thrift service.
 *
 * @param tservice The service definition
 */
void t_erl_generator::generate_service(t_service* tservice) {
  // somehow this point is reached before the constructor and it's not downcased yet
  // ...awesome
  service_name_[0] = tolower(service_name_[0]);

  string f_service_hrl_name = get_out_dir()+service_name_+"_thrift.hrl";
  string f_service_name = get_out_dir()+service_name_+"_thrift.erl";
  f_service_file_.open(f_service_name.c_str());
  f_service_hrl_.open(f_service_hrl_name.c_str());

  // Reset service text aggregating stream streams
  f_service_.str("");
  export_lines_.str("");
  export_lines_first_ = true;

  hrl_header(f_service_hrl_, service_name_);

  if (tservice->get_extends() != NULL) {
    f_service_hrl_ << "-include(\"" <<
      uncapitalize(tservice->get_extends()->get_name()) << "_thrift.hrl\"). % inherit " << endl;
  }

  f_service_hrl_ <<
    "-include(\"" << program_name_ << "_types.hrl\")." << endl <<
    endl;

  // Generate the three main parts of the service (well, two for now in PHP)
  generate_service_helpers(tservice); // cpiro: New Erlang Order

  generate_service_interface(tservice);

  // indent_down();

  f_service_file_ <<
    erl_autogen_comment() << endl <<
    "-module(" << service_name_ << "_thrift)." << endl <<
    "-behaviour(thrift_service)." << endl << endl <<
    erl_imports() << endl;

  f_service_file_ << "-include(\"" << uncapitalize(tservice->get_name()) << "_thrift.hrl\")." << endl << endl;

  f_service_file_ << "-export([" << export_lines_.str() << "])." << endl << endl;

  f_service_file_ << f_service_.str();

  hrl_footer(f_service_hrl_, f_service_name);

  // Close service file
  f_service_file_.close();
  f_service_hrl_.close();
}

/**
 * Generates helper functions for a service.
 *
 * @param tservice The service to generate a header definition for
 */
void t_erl_generator::generate_service_helpers(t_service* tservice) {
  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::iterator f_iter;

  //  indent(f_service_) <<
  //  "% HELPER FUNCTIONS AND STRUCTURES" << endl << endl;

  export_string("struct_info", 1);

  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    generate_erl_function_helpers(*f_iter);
  }
  f_service_    << "struct_info('i am a dummy struct') -> undefined." << endl;
}

/**
 * Generates a struct and helpers for a function.
 *
 * @param tfunction The function
 */
void t_erl_generator::generate_erl_function_helpers(t_function* tfunction) {
}

/**
 * Generates a service interface definition.
 *
 * @param tservice The service to generate a header definition for
 */
void t_erl_generator::generate_service_interface(t_service* tservice) {

  export_string("function_info", 2);

  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::iterator f_iter;
  f_service_ << "%%% interface" << endl;
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    f_service_ <<
      indent() << "% " << function_signature(*f_iter) << endl;

    generate_function_info(tservice, *f_iter);
  }

  // Inheritance - pass unknown functions to base class
  if (tservice->get_extends() != NULL) {
      indent(f_service_) << "function_info(Function, InfoType) ->" << endl;
      indent_up();
      indent(f_service_) << uncapitalize(tservice->get_extends()->get_name())
                         << "_thrift:function_info(Function, InfoType)." << endl;
      indent_down();
  } else {
      // Dummy function_info so we don't worry about the ;s
      indent(f_service_) << "function_info(xxx, dummy) -> dummy." << endl;
  }

  indent(f_service_) << endl;
}

/**
 * Generates a function_info(FunctionName, params_type) and
 * function_info(FunctionName, reply_type)
 */
void t_erl_generator::generate_function_info(t_service* tservice,
                                                t_function* tfunction) {

  string name_atom = "'" + tfunction->get_name() + "'";

  t_struct* xs = tfunction->get_xceptions();
  t_struct* arg_struct = tfunction->get_arglist();

  // function_info(Function, params_type):
  indent(f_service_) <<
    "function_info(" << name_atom << ", params_type) ->" << endl;
  indent_up();

  indent(f_service_) << generate_type_term(arg_struct, true) << ";" << endl;

  indent_down();

  // function_info(Function, reply_type):
  indent(f_service_) <<
    "function_info(" << name_atom << ", reply_type) ->" << endl;
  indent_up();

  if (!tfunction->get_returntype()->is_void())
    indent(f_service_) <<
        generate_type_term(tfunction->get_returntype(), false) << ";" << endl;
  else if (tfunction->is_oneway())
    indent(f_service_) << "oneway_void;" << endl;
  else
    indent(f_service_) << "{struct, []}" << ";" << endl;
  indent_down();

  // function_info(Function, exceptions):
  indent(f_service_) <<
    "function_info(" << name_atom << ", exceptions) ->" << endl;
  indent_up();
  indent(f_service_) << generate_type_term(xs, true) << ";" << endl;
  indent_down();
}

/**
 * Declares a field, which may include initialization as necessary.
 *
 * @param ttype The type
 */
string t_erl_generator::declare_field(t_field* tfield) {  // TODO
  string result = "@" + tfield->get_name();
  t_type* type = get_true_type(tfield->get_type());
  if (tfield->get_value() != NULL) {
    result += " = " + render_const_value(type, tfield->get_value());
  } else {
    result += " = nil";
  }
  return result;
}

/**
 * Renders a function signature of the form 'type name(args)'
 *
 * @param tfunction Function definition
 * @return String of rendered function definition
 */
string t_erl_generator::function_signature(t_function* tfunction,
                                           string prefix) {
  return
    prefix + tfunction->get_name() +
    "(This" +  capitalize(argument_list(tfunction->get_arglist())) + ")";
}

/**
 * Add a function to the exports list
 */
void t_erl_generator::export_string(string name, int num) {
  if (export_lines_first_) {
    export_lines_first_ = false;
  } else {
    export_lines_ << ", ";
  }
  export_lines_ << name << "/" << num;
}

void t_erl_generator::export_types_function(t_function* tfunction,
                                               string prefix) {

  export_types_string(prefix + tfunction->get_name(),
                      1 // This
                      + ((tfunction->get_arglist())->get_members()).size()
                      );
}

void t_erl_generator::export_types_string(string name, int num) {
  if (export_types_lines_first_) {
    export_types_lines_first_ = false;
  } else {
    export_types_lines_ << ", ";
  }
  export_types_lines_ << name << "/" << num;
}

void t_erl_generator::export_function(t_function* tfunction,
                                      string prefix) {

  export_string(prefix + tfunction->get_name(),
                1 // This
                + ((tfunction->get_arglist())->get_members()).size()
                );
}

/**
 * Renders a field list
 */
string t_erl_generator::argument_list(t_struct* tstruct) {
  string result = "";

  const vector<t_field*>& fields = tstruct->get_members();
  vector<t_field*>::const_iterator f_iter;
  bool first = true;
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    if (first) {
      first = false;
      result += ", "; // initial comma to compensate for initial This
    } else {
      result += ", ";
    }
    result += capitalize((*f_iter)->get_name());
  }
  return result;
}

string t_erl_generator::type_name(t_type* ttype) {
  string prefix = "";
  string name = ttype->get_name();

  if (ttype->is_struct() || ttype->is_xception() || ttype->is_service()) {
    name = uncapitalize(ttype->get_name());
  }

  return prefix + name;
}

/**
 * Converts the parse type to a Erlang "type" (macro for int constants)
 */
string t_erl_generator::type_to_enum(t_type* type) {
  type = get_true_type(type);

  if (type->is_base_type()) {
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
    switch (tbase) {
    case t_base_type::TYPE_VOID:
      throw "NO T_VOID CONSTRUCT";
    case t_base_type::TYPE_STRING:
      return "?tType_STRING";
    case t_base_type::TYPE_BOOL:
      return "?tType_BOOL";
    case t_base_type::TYPE_BYTE:
      return "?tType_BYTE";
    case t_base_type::TYPE_I16:
      return "?tType_I16";
    case t_base_type::TYPE_I32:
      return "?tType_I32";
    case t_base_type::TYPE_I64:
      return "?tType_I64";
    case t_base_type::TYPE_DOUBLE:
      return "?tType_DOUBLE";
    }
  } else if (type->is_enum()) {
    return "?tType_I32";
  } else if (type->is_struct() || type->is_xception()) {
    return "?tType_STRUCT";
  } else if (type->is_map()) {
    return "?tType_MAP";
  } else if (type->is_set()) {
    return "?tType_SET";
  } else if (type->is_list()) {
    return "?tType_LIST";
  }

  throw "INVALID TYPE IN type_to_enum: " + type->get_name();
}

/**
 * Generate an Erlang term which represents a thrift type
 */
std::string t_erl_generator::generate_type_term(t_type* type,
                                                   bool expand_structs) {
    type = get_true_type(type);

  if (type->is_base_type()) {
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
    switch (tbase) {
    case t_base_type::TYPE_VOID:
      throw "NO T_VOID CONSTRUCT";
    case t_base_type::TYPE_STRING:
      return "string";
    case t_base_type::TYPE_BOOL:
      return "bool";
    case t_base_type::TYPE_BYTE:
      return "byte";
    case t_base_type::TYPE_I16:
      return "i16";
    case t_base_type::TYPE_I32:
      return "i32";
    case t_base_type::TYPE_I64:
      return "i64";
    case t_base_type::TYPE_DOUBLE:
      return "double";
    }
  } else if (type->is_enum()) {
    return "i32";
  } else if (type->is_struct() || type->is_xception()) {
    if (expand_structs) {
      // Convert to format: {struct, [{Fid, TypeTerm}, {Fid, TypeTerm}...]}
      std::stringstream ret;

      ret << "{struct, [";

      int first = true;
      const vector<t_field*>& fields = ((t_struct*)type)->get_members();
      vector<t_field*>::const_iterator f_iter;

      for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
        // Comma separate the tuples
        if (!first) ret << "," << endl << indent();
        first = false;

        ret << "{" << (*f_iter)->get_key() << ", " <<
          generate_type_term((*f_iter)->get_type(), false) << "}";
      }

      ret << "]}" << endl;

      return ret.str();
    } else {
      return "{struct, {'" + type_module(type) + "', '" + type_name(type) + "'}}";
    }
  } else if (type->is_map()) {
    // {map, KeyType, ValType}
    t_type *key_type = ((t_map*)type)->get_key_type();
    t_type *val_type = ((t_map*)type)->get_val_type();

    return "{map, " + generate_type_term(key_type, false) + ", " +
      generate_type_term(val_type, false) + "}";

  } else if (type->is_set()) {
    t_type *elem_type = ((t_set*)type)->get_elem_type();

    return "{set, " + generate_type_term(elem_type, false) + "}";

  } else if (type->is_list()) {
    t_type *elem_type = ((t_list*)type)->get_elem_type();

    return "{list, " + generate_type_term(elem_type, false) + "}";
  }

  throw "INVALID TYPE IN type_to_enum: " + type->get_name();
}

std::string t_erl_generator::type_module(t_type* ttype) {
  return uncapitalize(ttype->get_program()->get_name()) + "_types";
}

THRIFT_REGISTER_GENERATOR(erl, "Erlang", "");


text:
@import url(http://fonts.googleapis.com/css?family=Open+Sans:300);

body {
    position: relative;
    font-family: "Open Sans", sans-serif;
    color: #333333;
    width: 700px;
    margin: 1em auto;
}

.button {
    display: inline-block;
    font: 500 13px "Open Sans";
    text-align: center;
    text-transform: uppercase;
    padding: 0.5em 1em;
    margin: 0 1em 0 0;
    color: #333333;
    border-radius: 4px;
    cursor: pointer;
    border: none;
    background-color: #e6e6e6;
}

.button:hover {
    background-color: #9ca7af;
    color: white;
}

#domain-list {
    margin-top: 1em;
    width: 100%;
    min-height: 33em;
}

.keys-table-wrapper {
    border: solid 1px #cccccc;
    border-radius: 4px;
    background-image: url("table-background.png");
    font: 300 17px "Open Sans";
}

.keys-table {
    width: 100%;
    border-spacing: 0;
    border-collapse: collapse;
}

.keys-table .domain-name {
    width: 250px;
}

.keys-table tr {
    height: 40px;
}

.keys-table tr:hover {
    background-color: #9ca7af;
    color: white;
}

.keys-table td {
    padding: 0 0.5em;
}

.uc-key {
    width: 40px;
    height: 25px;
    background: url("../Spritesheet-01.png");
}

.keys-table .key-holder, .keys-table .delete-button {
    position: relative;
    display: inline-block;
    cursor: pointer;
    border: 0;
    background: none;
}

.keys-table .key-holder {
    top: 7px;
}

.keys-table .delete-button {
    visibility: hidden;
    float: right;
    background: -40px 0 url("../Spritesheet-01.png");
    width: 40px;
    height: 40px;
    transition: transform ease-in-out 0.2s 0s;
}

.keys-table tr:hover .delete-button {
    visibility: visible;
}

.keys-table .delete-button:hover {
    transform: scale(1.2);
}

.keys-table .uc-key {
    position: relative;
    display: inline-block;
    transition: transform ease-in-out 0.2s,  opacity ease-in-out 0.2s;
    transform: scale(0.9) rotate(-20deg);
    opacity: 0.5;
}

.keys-table .key-holder.default-key .uc-key {
    transform: rotate(-20deg) scale(1);
    opacity: 1;
}

.keys-table .key-holder:hover .uc-key {
    transform: translate(0, -2px) rotate(-25deg) scale(1.2);
    opacity: 1;

}

.keys-table .key-name-wrapper {
    position: absolute;
    left: 50%;
    z-index: 1;
    visibility: hidden;
    opacity: 0;
    transition: all ease-in-out 0.2s 0s;
}

.keys-table .key-holder:hover .key-name-wrapper {
    visibility: visible;
    opacity: 1;
    transition: all ease-in-out 0.2s 1s;
}

.keys-table.tooltip-active .key-holder:hover .key-name-wrapper {
    transition: all ease-in-out 0.2s 0;
}

.keys-table .key-holder.default-key .uc-key-name:after  {
    content: " [default]";
    font-variant: small-caps;
    font-weight: 500;
}

.keys-table .key-holder.default-key:only-child .uc-key-name:after  {
    content: "";
}

.keys-table .uc-key-name {
    position: relative;
    left: -50%;
    top: -1px;
    background-color: white;
    border: solid 1px #cccccc;
    white-space: nowrap;
    font: 10px "Open Sans";
    padding: 3px;

}

/* MODAL DIALOGS */

.modal, .modal-fade {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
}

.modal {
    z-index: 1000;
    transition: visibility 0s linear 0.3s, opacity 0.3s;
    visibility: hidden;
    opacity: 0;
    overflow: hidden;
}

.modal.displayed {
    opacity: 1;
    visibility: visible;
    transition-delay:0s;
}

.modal .modal-element {
    visibility: hidden;
    transition: visibility 0s linear 0.3s;
}

.modal.displayed .displayed.modal-element {
    visibility: visible;
    transition-delay:0s;
}

.modal-fade {
    background-color: white;
    opacity: 0;
}

.modal.fade-out .modal-fade {
    opacity: 0.3;
}

.dialog {
    position: absolute;
    display: table;
    margin: auto;
    top: 0; left: 0; bottom: 0; right: 0;
    width: 476px;
    padding: 15px 12px 20px;
    border-radius: 4px;
    font-size: 14px;

    border: solid 1px #ccc;
    box-shadow: 0px 5px 10px rgba(0,0,0,0.3);
    background-color: white;
}

#dialog-box .dialog {
    width: 376px;
}

.dialog h2 {
    font-size: 24px;
    font-weight: 300;
    margin-bottom: 1em;
    margin-top: 0;
    text-align: center;
}

.dialog h2#edit-key-title {
    text-align: left;
}

.dialog h2#edit-key-title .uc-key {
    display: inline-block;
    transform: translate(0,4px) rotate(-20deg) ;
    margin-right: 0.5em;
}

.dialog .dialog-content {
    font-size: 16px;
    text-align: center;
    font-weight: 300;
}

.dialog p {
    margin: 0;
}

.dialog .dialog-content p {
    margin-bottom: 1em;
}

.dialog .hint {
    float: right;
    font-weight: 300;
    color: #999;
}

.dialog label, .dialog .label {
    text-transform: uppercase;
}

.dialog input, .dialog .input, .dialog textarea {
    width: 450px;
    background: #f2f2f2;
    border: 1px solid #cccccc;
    padding: 8px 12px;
    margin: 7px 0 22px;
    font: 300 18px "Open Sans";
}

.dialog .key-color-selection input[type=radio] {
    display: none;
}

.dialog textarea {
    min-height: 4em;
}

.dialog .export-string, #key-dialog-import, .dialog textarea {
    font-size: 14px;
}

.dialog .key-color-selection label {
    display: inline-block;
    width: 40px;
    height: 40px;
    border-radius: 3px;
    cursor: pointer;
}

.dialog .key-color-selection .uc-key {
    display: inline-block;
    transform: translate(1px,8px) rotate(-20deg) ;
}

.dialog .key-color-selection input[type=radio]:checked + label {
    background-color: #cccccc;
}

.dialog .button {
    display: inline-block;
}

.dialog .dialog-buttons {
    position: relative;
    text-align: center;
}

.dialog .delete-button {
    position: absolute;
    right: 0;
    bottom: -1px;
    background: -79px -4px url("../Spritesheet-01.png");
    width: 40px;
    height: 33px;
    cursor: pointer;
    border-radius: 4px;
}

.dialog .delete-button:hover {
    background-color: #9ca7af;
    background-position: -79px -44px;
}

/* Specific dialogs */

#key-dialog .dialog-area {
    display: none;
}

#key-dialog.new-key .new-key.dialog-area {
    display: block;
}

#key-dialog.edit-key .edit-key.dialog-area {
    display: block;
}

#key-dialog.import-key .import-key.dialog-area {
    display: block;
}


text:
import { Component, Output, OnInit, HostListener, ViewEncapsulation, ElementRef, EventEmitter } from '@angular/core';

@Component({
    moduleId: module.id,
    encapsulation: ViewEncapsulation.None,
    selector: 'item',
    templateUrl: 'item.component.html',
    styleUrls: ['item.component.scss']
})
export class ItemComponent implements OnInit {
    @Output('clickme') clickme = new EventEmitter();
    _active = false;
    constructor(private ref: ElementRef) { }

    @HostListener('click', ["$event"]) onClick(event: Event) {
        this._active = true;
        this.clickme.emit(this);
    }

    ngOnInit() {

    }
}


text:
function Client_PresentSettingsUI(rootParent)
	local vert = UI.CreateVerticalLayoutGroup(rootParent);

	UI.CreateLabel(vert).SetText('Pestilence Strength:' .. Mod.Settings.PestilenceStrength);
end


text:
A webgl shader example library.

Note: coordinates: -1<=x<=1; -1<=y<=1

Initializing a webgl context:
```javascript
  // returns the webgl context or null
  // canvas must be a DOM canvas element with widh>0 and height>0
  var ctx = createWebglContext(canvas, {
  // types to try - may exclude experimental types
    types: ['webgl', 'experimental-webgl'],
    attrs: { // attributes
      antialias: true
    }
  });
```
Attaching a shader to the webgl context:
```javascript
  // for polygons, lines and points
  var lineRenderer = attachPloygonShader(ctx);
  // for heatmap surfaces
  var hmRenderer = attachHeatmapShader(ctx, {
    x: 200, // points in x direction
    y: 100  // points in y direction
    // 200*100=20000 points for heatmap
  });
  // for waterfall surfaces
  var wfRenderer = attachWaterfallShader(ctx, {
    x: 200, // points in x direction
    y: 100 // points in y direction
    // 200*100=20000 points for waterfall
  });
  // for textures (like text)
  var teRenderer = attachTextureShader(ctx);
```

Using polygon shaders:
```javascript
  var p = [0,0,0.5,0.5,0.5,0.7];
  var c = [1,0,0,0,1,0,0,0,1];
  // draws a line (0,0)->(0.5,0.5)->(0.5,0.7)
  // color gradients between points red->green->blue
  // POINTS, LINES, TRIANGLES, TRIANGLE_STRIP, TRIANGLE_FAN also possible
  lineRenderer.draw(p, c, 'LINE_STRIP');
```

Using texture shaders:
```javascript
  // size of texture for auto text rendering
  teRenderer.setTextureSize(256, 256);
  // maximal number of textures buffered
  // note: creation is expensive
  teRenderer.setTextureBufferSize(50);
  // style and position of the text
  var textStyle = {
    font: '18px/30px Arial, serif',
    fill: '#000000',
    stroke: '#000000',
    plane: 'n', //n:2D, x,y,z:plane in 3D
    pos: [0.0, 0.0, 0.0]
  };
  // write to canvas
  teRenderer.writeText('hello', textStyle);
  // style attributes for precomputed texture
  var textureStyle = {
    redraw: true, // texture changed -> redraw buffer
    plane: 'n', //n:2D, x,y,z:plane in 3D
    pos: [0.0, 0.0, 0.0]
  };
  // draw predefined texture from any2dCanvas
  // create a canvas, put something in it and convert it
  // to a webgl texture
  teRenderer.drawTexture(any2dCanvas, textureStyle);
```
Using waterfall shaders:
```javascript
  // reinit buffer
  wfRenderer.reinitBuffer(200,100);
  // change size of points drawn
  wfRenderer.setPointSize(3);
  var d = [];
  for (var i = 0; i < 100; i++) {
    d[i] = i/100;
  }
  // add a nuew column
  // all older columns are shifted one pixel left
  wfRenderer.setColumn(d);
  // draw a colored waterfall
  // POINTS, LINES, TRIANGLES, TRIANGLE_STRIP, TRIANGLE_FAN also possible
  wfRenderer.drawC('POINTS');
  // draw a black/white waterfall
  // POINTS, LINES, TRIANGLES, TRIANGLE_STRIP, TRIANGLE_FAN also possible
  wfRenderer.drawBw('POINTS');
```
Using heatmap shaders:
```javascript
  // reinit buffer
  hmRenderer.reinitBuffer(200,100);
  // change size of points drawn
  hmRenderer.setPointSize(3);
  // imcrease pixel (45, 17) by 0.3
  // pixel color range from 0 to 1
  hmRenderer.setPixel(45, 17, 0.3);
  // draw a colored heatmap
  // POINTS, LINES, TRIANGLES, TRIANGLE_STRIP, TRIANGLE_FAN also possible
  hmRenderer.drawC('POINTS');
  // draw a black/white heatmap
  // POINTS, LINES, TRIANGLES, TRIANGLE_STRIP, TRIANGLE_FAN also possible
  hmRenderer.drawBw('POINTS');
  // decrease all pixels by 0.002
  hmRenderer.age(0.002);
```
Setting transformation:
```javascript
  // works for every renderer
  // rotates, translates, scales scene
  renderer.transform({
    translate: {
      x: 0,
      y: 0,
      z: 0
    },
    rotate: {
      x: 0.0,
      y: 0.0,
      z: 0.0
    },
    aspectRatio: 1,
    scaling: 1.0,
    distance: 1.0,
    plane: {
      far: 1,
      near: -1
    }
  });
```


text:
#ifndef __CONFIG_H
#define __CONFIG_H

#include <configs/rk3288_common.h>

#define CONFIG_SPL_MMC_SUPPORT

#endif


text:
package org.accela.minesweeper.view;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.accela.minesweeper.util.Common;

public class HighScoreDialog extends BasicDialog
{
	private static final long serialVersionUID = 1L;

	private Panel panel = new Panel();

	public HighScoreDialog()
	{
		initHighScoreDialog();
	}

	public HighScoreDialog(Frame owner)
	{
		super(owner);
		initHighScoreDialog();
	}

	private void initHighScoreDialog()
	{
		panel.setOpaque(true);
		this.setContentPane(panel);
		this.pack();

		this.addExitDialogActionListenerFor(panel.getOkButton());
	}

	public Panel getPanel()
	{
		return panel;
	}

	@Override
	protected void onEscStroke()
	{
		this.panel.getOkButton().doClick();
	}

	@Override
	protected void onEnterStroke()
	{
		this.panel.getOkButton().doClick();
	}

	public static class PanelValue
	{
		public int lowScore;
		public int middleScore;
		public int highScore;

		public PanelValue()
		{
			// do nothing
		}

		public PanelValue(int lowScore, int middleScore, int highScore)
		{
			this.lowScore = lowScore;
			this.middleScore = middleScore;
			this.highScore = highScore;
		}

	}

	public static class Panel extends JPanel
	{
		private static final long serialVersionUID = 1L;

		private JLabel lowLevelLabel = new JLabel();
		private JLabel middleLevelLabel = new JLabel();
		private JLabel highLevelLabel = new JLabel();

		private JLabel lowScoreLabel = new JLabel();
		private JLabel middleScoreLabel = new JLabel();
		private JLabel highScoreLabel = new JLabel();

		private JLabel lowScoreUnitLabel = new JLabel();
		private JLabel middleScoreUnitLabel = new JLabel();
		private JLabel highScoreUnitLabel = new JLabel();

		private JLabel lowScoreNameLabel = new JLabel();
		private JLabel middleScoreNameLabel = new JLabel();
		private JLabel highScoreNameLabel = new JLabel();

		private JButton resetButton = new JButton();
		private JButton okButton = new JButton();

		private final JLabel[][] labels = new JLabel[][] {
				{
						lowLevelLabel,
						lowScoreLabel,
						lowScoreUnitLabel,
						lowScoreNameLabel },
				{
						middleLevelLabel,
						middleScoreLabel,
						middleScoreUnitLabel,
						middleScoreNameLabel },
				{
						highLevelLabel,
						highScoreLabel,
						highScoreUnitLabel,
						highScoreNameLabel }, };

		public Panel()
		{
			this.setLayout(new BorderLayout(0, Common.GUI_STANDARD_INTERVAL * 2));

			this.add(createTopPanel(), BorderLayout.CENTER);
			this.add(createBottomPanel(), BorderLayout.SOUTH);
		}

		private JPanel createTopPanel()
		{
			// JPanel p = new JPanel(new GridLayout(3, 1, 0,
			// Common.GUI_STANDARD_INTERVAL));
			// for (int i = 0; i < labels.length; i++)
			// {
			// JLabel[] group = labels[i];
			//
			// JLabel level = group[0];
			// JLabel score = group[1];
			// JLabel unit = group[2];
			// JLabel name = group[3];
			//
			// JPanel outer = new JPanel(new BorderLayout(
			// Common.GUI_STANDARD_INTERVAL, 0));
			// outer.add(level, BorderLayout.WEST);
			//
			// JPanel inner = new JPanel(new BorderLayout(
			// Common.GUI_STANDARD_INTERVAL, 0));
			// inner.add(score, BorderLayout.CENTER);
			// inner.add(unit, BorderLayout.EAST);
			// outer.add(inner, BorderLayout.CENTER);
			//
			// outer.add(name, BorderLayout.EAST);
			//
			// p.add(outer);
			// }

			JPanel p = new JPanel(new GridBagLayout());
			for (int i = 0; i < labels.length; i++)
			{
				JLabel[] group = labels[i];

				JLabel level = group[0];
				JLabel score = group[1];
				JLabel unit = group[2];
				JLabel name = group[3];

				GridBagConstraints c = new GridBagConstraints();
				c.gridx = 0;
				c.gridy = i;
				c.fill = GridBagConstraints.NONE;
				c.weightx = 0;
				c.insets = new Insets(Common.GUI_STANDARD_INTERVAL / 2,
						Common.GUI_STANDARD_INTERVAL / 2,
						Common.GUI_STANDARD_INTERVAL / 2,
						Common.GUI_STANDARD_INTERVAL / 2);
				p.add(level, c);

				c.gridx = 1;
				c.fill = GridBagConstraints.HORIZONTAL;
				c.weightx = 0.8;
				p.add(score, c);

				c.gridx = 2;
				c.fill = GridBagConstraints.NONE;
				c.weightx = 0;
				p.add(unit, c);

				c.gridx = 3;
				c.fill = GridBagConstraints.HORIZONTAL;
				c.weightx = 0.4;
				p.add(name, c);

			}

			return p;
		}

		public PanelValue getValue()
		{
			PanelValue v = new PanelValue();
			try
			{
				v.lowScore = Integer.parseInt(this.lowScoreLabel.getText());
				v.middleScore = Integer.parseInt(this.middleScoreLabel
						.getText());
				v.highScore = Integer.parseInt(this.highScoreLabel.getText());
			}
			catch (NumberFormatException ex)
			{
				v.lowScore = 0;
				v.middleScore = 0;
				v.highScore = 0;
			}

			return v;
		}

		public void setValue(PanelValue v)
		{
			this.lowScoreLabel.setText(v.lowScore + "");
			this.middleScoreLabel.setText(v.middleScore + "");
			this.highScoreLabel.setText(v.highScore + "");
		}

		private JPanel createBottomPanel()
		{
			JPanel p = new JPanel(new FlowLayout(FlowLayout.CENTER,
					Common.GUI_STANDARD_INTERVAL * 4, 0));
			p.add(resetButton);
			p.add(okButton);

			return p;
		}

		public JLabel getLowLevelLabel()
		{
			return lowLevelLabel;
		}

		public JLabel getMiddleLevelLabel()
		{
			return middleLevelLabel;
		}

		public JLabel getHighLevelLabel()
		{
			return highLevelLabel;
		}

		public JLabel getLowScoreLabel()
		{
			return lowScoreLabel;
		}

		public JLabel getMiddleScoreLabel()
		{
			return middleScoreLabel;
		}

		public JLabel getHighScoreLabel()
		{
			return highScoreLabel;
		}

		public JLabel getLowScoreUnitLabel()
		{
			return lowScoreUnitLabel;
		}

		public JLabel getMiddleScoreUnitLabel()
		{
			return middleScoreUnitLabel;
		}

		public JLabel getHighScoreUnitLabel()
		{
			return highScoreUnitLabel;
		}

		public JLabel getLowScoreNameLabel()
		{
			return lowScoreNameLabel;
		}

		public JLabel getMiddleScoreNameLabel()
		{
			return middleScoreNameLabel;
		}

		public JLabel getHighScoreNameLabel()
		{
			return highScoreNameLabel;
		}

		public JButton getResetButton()
		{
			return resetButton;
		}

		public JButton getOkButton()
		{
			return okButton;
		}

		public JLabel[][] getLabels()
		{
			return labels;
		}
	}
}


text:
import Ember from 'ember';
var Bundle = Ember.Object.extend({

});
export {Bundle};


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#ifndef JSONDECODER_H
#define JSONDECODER_H

#include "multitree.h"

#ifdef __cplusplus
#include <cstddef>
extern "C" {
#else
#include <stddef.h>
#endif

typedef enum JSON_DECODER_RESULT_TAG
{
    JSON_DECODER_OK,
    JSON_DECODER_INVALID_ARG,
    JSON_DECODER_PARSE_ERROR,
    JSON_DECODER_MULTITREE_FAILED,
    JSON_DECODER_ERROR
} JSON_DECODER_RESULT;

#include "azure_c_shared_utility/umock_c_prod.h"
MOCKABLE_FUNCTION(, JSON_DECODER_RESULT, JSONDecoder_JSON_To_MultiTree, char*, json, MULTITREE_HANDLE*, multiTreeHandle);

#ifdef __cplusplus
}
#endif

#endif /* JSONDECODER_H */


text:
from unittest import mock

from celery.bin.base import Command
from tornado.options import options

from wscelery.tests import AsyncHTTPTestCase
from wscelery.command import WsCeleryCommand

class OptionsTestCase(AsyncHTTPTestCase):
    def mock_option(self, name, value):
        return mock.patch.object(options.mockable(), name, value)

class TestWsCeleryCommand(OptionsTestCase):
    def test_port(self):
        with self.mock_option('port', 1337):
            command = WsCeleryCommand()
            command.apply_options('wscelery', argv=['--port=4321'])
            self.assertEqual(options.port, 4321)

    def test_address(self):
        with self.mock_option('address', '127.0.0.1'):
            command = WsCeleryCommand()
            command.apply_options('wscelery', argv=['--address=foobar'])
            self.assertEqual(options.address, 'foobar')

    def test_allow_origin_regex(self):
        with self.mock_option('allow_origin', None):
            command = WsCeleryCommand()
            command.apply_options('wscelery', argv=['--allow-origin=.*'])
            self.assertEqual(options.allow_origin, '.*')

    def test_invalid_allow_origin_regex(self):
        with self.mock_option('allow_origin', None):
            command = WsCeleryCommand()
            command.apply_options('wscelery', argv=['--allow-origin=*'])
            try:
                command.execute_from_commandline()
            except Command.UsageError:
                pass
            else:
                self.fail('Expected invalid regex to fail')


text:
package com.loginbox.dropwizard.mybatis;

import com.codahale.metrics.health.HealthCheckRegistry;
import com.loginbox.dropwizard.mybatis.healthchecks.SqlSessionFactoryHealthCheck;
import com.loginbox.dropwizard.mybatis.mappers.Ping;
import com.loginbox.dropwizard.mybatis.providers.SqlSessionProvider;
import com.loginbox.dropwizard.mybatis.testMappers.ExampleMapper;
import io.dropwizard.db.DataSourceFactory;
import io.dropwizard.db.ManagedDataSource;
import io.dropwizard.jersey.setup.JerseyEnvironment;
import io.dropwizard.lifecycle.setup.LifecycleEnvironment;
import io.dropwizard.setup.Bootstrap;
import org.apache.ibatis.session.Configuration;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Matchers;

import java.net.URI;
import java.net.URL;
import java.util.UUID;

import static com.loginbox.dropwizard.mybatis.matchers.ConfigurationMapperMatcher.hasMapper;
import static com.loginbox.dropwizard.mybatis.matchers.ConfigurationTypeHandlerMatcher.hasTypeHandler;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class MybatisBundleTest {
    private final DataSourceFactory dataSourceFactory = mock(DataSourceFactory.class);
    private final Bootstrap<io.dropwizard.Configuration> bootstrap = mock(Bootstrap.class);
    private final io.dropwizard.Configuration configuration = mock(io.dropwizard.Configuration.class);
    private final io.dropwizard.setup.Environment environment = mock(io.dropwizard.setup.Environment.class);
    private final ManagedDataSource dataSource = mock(ManagedDataSource.class);
    private final LifecycleEnvironment lifecycle = mock(LifecycleEnvironment.class);
    private final HealthCheckRegistry healthChecks = mock(HealthCheckRegistry.class);
    private final JerseyEnvironment jersey = mock(JerseyEnvironment.class);

    private class TestMybatisBundle<T extends io.dropwizard.Configuration>
            extends MybatisBundle<T> {
        public TestMybatisBundle() {
            super();
        }

        public TestMybatisBundle(Class<?> mapper, Class<?>... mappers) {
            super(mapper, mappers);
        }

        public TestMybatisBundle(String packageName, String... packageNames) {
            super(packageName, packageNames);
        }

        @Override
        public DataSourceFactory getDataSourceFactory(io.dropwizard.Configuration configuration) {
            return dataSourceFactory;
        }
    }

    @Before
    public void wireMocks() {
        when(environment.lifecycle()).thenReturn(lifecycle);
        when(environment.healthChecks()).thenReturn(healthChecks);
        when(environment.jersey()).thenReturn(jersey);

        when(dataSourceFactory.build(Matchers.any(), Matchers.any())).thenReturn(dataSource);
    }

    @Test
    public void managesDataSource() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle
                = new TestMybatisBundle<io.dropwizard.Configuration>();
        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        verify(lifecycle).manage(dataSource);
    }

    @Test
    public void usesDataSource() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle
                = new TestMybatisBundle<io.dropwizard.Configuration>();
        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        assertThat(bundle.getSqlSessionFactory().getConfiguration().getEnvironment().getDataSource(), is(dataSource));
    }

    @Test
    public void registersHealthChecks() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle
                = new TestMybatisBundle<io.dropwizard.Configuration>();
        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        verify(healthChecks).register(anyString(), isA(SqlSessionFactoryHealthCheck.class));
    }

    @Test
    public void registersProviders() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle
                = new TestMybatisBundle<io.dropwizard.Configuration>();
        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        verify(jersey).register(isA(SqlSessionProvider.Binder.class));
    }

    @Test
    public void registersInterfaces() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle
                = new TestMybatisBundle<io.dropwizard.Configuration>(ExampleMapper.class);
        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        Configuration configuration = bundle.getSqlSessionFactory().getConfiguration();

        assertThat(configuration, hasMapper(ExampleMapper.class));
    }

    @Test
    public void registersPackages() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle
                = new TestMybatisBundle<io.dropwizard.Configuration>("com.loginbox.dropwizard.mybatis.testMappers");
        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        Configuration configuration = bundle.getSqlSessionFactory().getConfiguration();

        assertThat(configuration, hasMapper(ExampleMapper.class));
    }

    @Test
    public void registersPingMapper() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle
                = new TestMybatisBundle<io.dropwizard.Configuration>();
        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        Configuration configuration = bundle.getSqlSessionFactory().getConfiguration();

        assertThat(configuration, hasMapper(Ping.class));
    }

    @Test
    public void registersUuidType() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle
                = new TestMybatisBundle<io.dropwizard.Configuration>();
        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        Configuration configuration = bundle.getSqlSessionFactory().getConfiguration();

        assertThat(configuration, hasTypeHandler(UUID.class));
    }

    @Test
    public void registersUriType() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle
                = new TestMybatisBundle<io.dropwizard.Configuration>();
        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        Configuration configuration = bundle.getSqlSessionFactory().getConfiguration();

        assertThat(configuration, hasTypeHandler(URI.class));
    }

    @Test
    public void registersUrlType() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle
                = new TestMybatisBundle<io.dropwizard.Configuration>();
        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        Configuration configuration = bundle.getSqlSessionFactory().getConfiguration();

        assertThat(configuration, hasTypeHandler(URL.class));
    }

    @Test
    public void registersJava8OptionalType() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle
                = new TestMybatisBundle<io.dropwizard.Configuration>();
        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        Configuration configuration = bundle.getSqlSessionFactory().getConfiguration();

        assertThat(configuration, hasTypeHandler(java.util.Optional.class));
    }

    @Test
    public void registersGuavaOptionalType() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle
                = new TestMybatisBundle<io.dropwizard.Configuration>();
        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        Configuration configuration = bundle.getSqlSessionFactory().getConfiguration();

        assertThat(configuration, hasTypeHandler(com.google.common.base.Optional.class));
    }

    @Test
    public void appliesCustomConfiguration() throws Exception {
        MybatisBundle<io.dropwizard.Configuration> bundle = new TestMybatisBundle<io.dropwizard.Configuration>(ExampleMapper.class) {
            @Override
            protected void configureMybatis(Configuration configuration) {
                configuration.setDatabaseId("--test-value--");
            }
        };

        bundle.initialize(bootstrap);
        bundle.run(configuration, environment);

        Configuration configuration = bundle.getSqlSessionFactory().getConfiguration();
        assertThat(configuration.getDatabaseId(), is("--test-value--"));
    }
}


text:
#ifndef JABBERWERX_UTIL_WORKQ_H
#define JABBERWERX_UTIL_WORKQ_H

#include "htable.h"

/**
 * The work queue configuration hash table key for event_base selector.
 * The value for this option MUST be a (struct event_base*)(uintptr_t).
 *
 * NOTE:
 * this key is identical to the stream's selector key.
 */
#define JW_WORKQ_CONFIG_SELECTOR "selector"

/** A work queue reference */
typedef struct jw_workq_t jw_workq;

/** A work queue item reference */
typedef struct jw_workq_item_t jw_workq_item;

/**
 * Signature of the function executed when a jw_workq_item is processed
 * in a jw_workq.
 *
 * \param[in] item The item being executed
 * \param[in] data Data associated with executing item.
 */
typedef void (*jw_workq_func)(jw_workq_item *item, void *data);

/**
 * Signature for a jw_workq_item cleaner.
 *
 * This function is called when the jw_workq_item's data is ready to be
 * released, either because new data has been applied or because the
 * jw_workq_item is being destroyed.
 *
 * \param[in] item The item being cleaned
 * \param[in] data The data to free
 */
typedef void (*jw_workq_item_cleaner)(jw_workq_item *item, void *data);

#ifdef __cplusplus
extern "C"
{
#endif

/**
 * This function calls jw_data_free on the data argument, and ignores item.
 * It is a convenience for cleaning memory allocated via
 * jw_data_malloc/jw_data_realloc.
 *
 * \param[in] item Ignored
 * \param[in] data The reference to be freed
 */
JABBERWERX_API void jw_workq_item_free_data_cleaner(jw_workq_item *item,
                                                    void          *data);

/**
 * A convenience function for destroying jw_pool when working with jw_workq.
 * This function calls jw_pool_destroy on the data argument, and ignores the
 * item.
 *
 * \see jw_workq_item_set_data for more information.
 *
 * \param[in] item Ignored
 * \param[in] data The jw_pool to be destroyed
 */
JABBERWERX_API void jw_workq_item_pool_cleaner(jw_workq_item *item, void *data);

/**
 * This function creates a workq item against a given workq.
 *
 * Item will be destroyed when the given jw_workq is destroyed (unless
 * explicitly destroyed by the creator)
 *
 * NOTE:
 * This function can generate the following errors (set when returning false):
 * \li \c JW_ERR_NO_MEMORY if jw_workq_item instance could not be allocated.
 *
 * \invariant (q != NULL)
 * \invariant (fn != NULL)
 * \invariant (item != NULL)
 * \param[in] q The item's jw_workq
 * \param[in] fn The function to be executed when a scheduled item is dequeued.
 * \param[out] item The newly created item.
 * \param[out] err The error information (provide NULL to ignore)
 * \retval bool Returns true if the item was created, false otherwise.
*/
JABBERWERX_API bool jw_workq_item_create(jw_workq       *q,
                                         jw_workq_func   fn,
                                         jw_workq_item **item,
                                         jw_err         *err);

/**
 * Destroy a jw_workq_item.
 *
 * The item is canceled if it is in its workq but not yet executed.
 * The jw_workq_item_cleaner is called if registered.
 *
 *\invariant (item != NULL)
 *\param[in] item The item to destroy
 */
JABBERWERX_API void jw_workq_item_destroy(jw_workq_item *item);

/**
 * Cancels this workq item.
 *
 * If the workq item has already executed or was never scheduled, this function
 * does nothing. Otherwise, it marks the workq item as canceled, and removes it
 * from the workq. Canceled workq items can be rescheduled.
 *
 * NOTE:
 * This function does NOT destroy the workq_item.
 *
 * \invariant (item != NULL)
 * \param[in] item The item to cancel
 */
JABBERWERX_API void jw_workq_item_cancel(jw_workq_item *item);

/**
 * Add the given workq item to the end of its owning workq, behind
 * any items already queued. The given workq item will be executed after
 * all others currently in the queue.
 *
 * If the workq item has a delay, it will be considered scheduled, but will
 * actually be added to the end of the queue when the delay is reached.
 *
 * NOTE:
 * This function can generate the following errors (set when returning false):
 * \li \c JW_ERR_INVALID_STATE - the workq item is already scheduled
 *
 * \invariant (item != NULL)
 * \param[in] item The item to append to its owning jw_workq
 * \param[out] err The error information (provide NULL to ignore)
 * \retval bool Returns true if successfully enqueued, false otherwise.
 */
JABBERWERX_API bool jw_workq_item_append(jw_workq_item *item, jw_err *err);

/**
 * Add the given workq item to the front of its owning workq. The given
 * workq item will be the next item executed.
 *
 * If the workq item has a delay, it will be considered scheduled, but will
 * actually be added to the front of the queue when the delay is reached.
 *
 * NOTE:
 * This function can generate the following errors (set when returning false):
 * \li \c JW_ERR_INVALID_STATE - the workq item is already scheduled
 *
 * \invariant (item != NULL)
 * \param[in] item The item to prepend to its owning jw_workq
 * \param[out] err The error information (provide NULL to ignore)
 * \retval bool Returns true if successfully enqueued, false otherwise.
 */
JABBERWERX_API bool jw_workq_item_prepend(jw_workq_item *item, jw_err *err);

/**
 * Sets the data and its associated cleaner for the workq item.
 *
 * If there is already data applied, this function will call the cleaner
 * associated with the original data (if any).
 *
 * \invariant (item != NULL)
 * \param[in] item The item to associate with the given data.
 * \param[in] data Optional item specific data.
 * \param[in] cleaner Optional cleaner function
*/
JABBERWERX_API void jw_workq_item_set_data(jw_workq_item        *item,
                                           void                 *data,
                                           jw_workq_item_cleaner cleaner);

/**
 * Get the data associated with this item.
 *
 * \invariant (item != NULL)
 * \param[in] item The item used to get the data reference
 * \retval void* May be NULL if item has no associated data
 */
JABBERWERX_API void *jw_workq_item_get_data(jw_workq_item *item);

/**
 * Sets the execution delay for the workq item.  If msecs is 0, then the workq
 * item will execute as soon as possible after it is scheduled.
 *
 * NOTE:
 * The delay takes effect only at the moment when the workq item is scheduled.
 * Calling this function after the delay is scheduled has no effect.
 *
 * NOTE:
 * This function can generate the following errors (set when returning false):
 * \li \c JW_ERR_NO_MEMORY - memory need to track the delay could not be
 *     allocated
 *
 * \invariant (item != NULL)
 * \param[in] item The item to set the delay on
 * \param[in] msecs The delay (in milliseconds) before this workq item
 *            executes
 * \param[out] err The error information (provide NULL to ignore)
 * \retval bool Returns true if delay is set successfully, false otherwise.
 */
JABBERWERX_API bool jw_workq_item_set_delay(jw_workq_item *item,
                                            uint64_t       msecs,
                                            jw_err        *err);

/**
 * Get the execution delay for the workq item.
 *
 * \invariant (item != NULL)
 * \param[in] item The item to retrieve the delay for
 * \retval uint64_t The delay (in milliseconds) associated with the
 *         workq_item, or 0 if a delay was not set.
 */
JABBERWERX_API uint64_t jw_workq_item_get_delay(jw_workq_item *item);

/**
 * Get the jw_workq associated with this item.
 *
 * \invariant (item != NULL)
 * \param[in] item The item used to get the jw_workq reference
 * \retval jw_workq All items have a jw_workq, result will never be NULL.
 */
JABBERWERX_API jw_workq *jw_workq_item_get_workq(jw_workq_item *item);

/**
 * Is the given item enqueued in its associated workq?
 *
 * Scheduled items are items in the workq. Executing and canceled items are
 * *not* scheduled.
 *
 * \invariant (item != NULL)
 * \param[in] item The item to check
 * \retval bool True if the given item is in its associated jw_workq
 */
JABBERWERX_API bool jw_workq_item_is_scheduled(jw_workq_item *item);

/**
 * Create a work queue
 *
 * This function is passed a jw_htable configuration containing the following:
 *      JW_WORKQ_CONFIG_SELECTOR - The event_base the work queue should use
 *          for eventing.
 *
 * The work queue does not reference the configuration htable after its
 * construction is completed and will not attempt any cleanup of the table.
 *
 * NOTE:
 * Users of the work queue must call event_base_dispatch (or another event
 * loop function) for queued tasks to be executed.
 *
 * NOTE:
 * This function can generate the following errors (set when returning false):
 * \li \c JW_ERR_NO_MEMORY if queue heap references could not be allocated.
 * \li \c JW_ERR_INVALID_ARG if config does not contain JW_WORKQ_CONFIG_SELECTOR
 *
 * \invariant q != NULL
 * \invariant config != NULL
 * \param[in] config A hashtable with queue options
 * \param[out] q The newly created work item queue
 * \param[out] err The error information (provide NULL to ignore)
 * \retval bool Returns true if queue was successfully created, false otherwise.
 */
JABBERWERX_API bool jw_workq_create(jw_htable *config,
                                    jw_workq **q,
                                    jw_err    *err);

/**
 * Destroy the given queue.
 *
 * Task processing is stopped immediately. No queued items will be executed
 * after the queue is destroyed.
 *
 * All jw_workq_items created with this queue are destroyed and their
 * associated data cleaners called as needed.
 *
 * \invariant q != NULL
 * \param[in] q The queue to destroy
 */
JABBERWERX_API void jw_workq_destroy(jw_workq *q);

/**
 * Pause the given queue
 *
 * No currently queued tasks will be executed until a paired
 * jw_workq_resume is called.
 *
 * NOTE:
 * pause and resume are reference counted to avoid nested call problems
 *
 * \invariant q != NULL
 * \param[in] q The queue to pause
 */
JABBERWERX_API void jw_workq_pause(jw_workq *q);

/**
 * Resume processing items on the given queue
 *
 * Queue processing will begin again as soon as possible.
 *
 * NOTE:
 * pause and resume are reference counted to avoid nested call problems
 *
 * \invariant q != NULL
 * \param[in] q The queue to resume
 */
JABBERWERX_API void jw_workq_resume(jw_workq *q);

/**
 * Get the number of scheduled tasks in the given queue
 *
 * \invariant q != NULL
 * \param[in] q The queue to count entries from
 * \retval size_t The number of jw_work_item(s) in the given queue
 */
JABBERWERX_API size_t jw_workq_get_length(jw_workq *q);

/**
 * Check if the given queue is empty, no scheduled items
 *
 * \invariant q != NULL
 * \param[in] q The specified queue
 * \retval bool
 */
JABBERWERX_API bool jw_workq_is_empty(jw_workq *q);

/**
 * Get the event base selector used by the given queue
 *
 * \invariant q != NULL
 * \param[in] q The specified queue
 * \retval struct event_base* The libevent event_base selector this queue
 *                            is using for eventing.
 */
JABBERWERX_API struct event_base *jw_workq_get_selector(jw_workq *q);

#ifdef __cplusplus
}
#endif

#endif  /* JABBERWERX_UTIL_WORKQ_H */


text:
NAMESPACE_BEGIN(CryptoPP)

//! \brief Randomness Pool
//! \details RandomPool can be used to generate cryptographic quality pseudorandom bytes
//!   after seeding the pool with IncorporateEntropy(). Internally, the generator uses
//!   AES-256 to produce the stream. Entropy is stirred in using SHA-256.
//! \details RandomPool used to follow the design of randpool in PGP 2.6.x,
//!   but as of version 5.5 it has been redesigned to reduce the risk
//!   of reusing random numbers after state rollback (which may occur
//!   when running in a virtual machine like VMware).
class CRYPTOPP_DLL RandomPool : public RandomNumberGenerator, public NotCopyable
{
public:
	//! \brief Construct a RandomPool
	RandomPool();

	bool CanIncorporateEntropy() const {return true;}
	void IncorporateEntropy(const byte *input, size_t length);
	void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword size);

	// for backwards compatibility. use RandomNumberSource, RandomNumberStore, and RandomNumberSink for other BufferTransformation functionality
	void Put(const byte *input, size_t length) {IncorporateEntropy(input, length);}

private:
	FixedSizeAlignedSecBlock<byte, 16, true> m_seed;
	FixedSizeAlignedSecBlock<byte, 32> m_key;
	member_ptr<BlockCipher> m_pCipher;
	bool m_keySet;
};

NAMESPACE_END

#endif


text:
<?php
namespace Drakojn\Io\Driver\Descriptor;

use Drakojn\Io\Mapper\Map;

class Ini extends AbstractDescriptor
{
    /**
     * Serializes Object
     *
     * @param Map   $map    the object structure map
     * @param mixed $object candidate to serialize
     *
     * @return mixed
     */
    public function serialize(Map $map, $object)
    {
        $properties = $map->getProperties();
        $data = $this->prepareData($map, $object);
        $content = [];
        foreach ($data as $localProperty => $value) {
            $value     = serialize($value);
            $content[] = "{$properties[$localProperty]}='{$value}'";
        }
        return implode(PHP_EOL, $content);
    }

    /**
     * Unserializes data into an object
     *
     * @param Map    $map   the object structure map
     * @param string $data  serialized data
     *
     * @return mixed
     */
    public function unserialize(Map $map, $data)
    {
        $parsed          = parse_ini_string($data);
        $object = $this->injectDataIntoObject($map, $parsed);
        return $object;
    }
}


text:
#include <aws/sagemaker/model/TransformOutput.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SageMaker
{
namespace Model
{

TransformOutput::TransformOutput() :
    m_s3OutputPathHasBeenSet(false),
    m_acceptHasBeenSet(false),
    m_assembleWith(AssemblyType::NOT_SET),
    m_assembleWithHasBeenSet(false),
    m_kmsKeyIdHasBeenSet(false)
{
}

TransformOutput::TransformOutput(JsonView jsonValue) :
    m_s3OutputPathHasBeenSet(false),
    m_acceptHasBeenSet(false),
    m_assembleWith(AssemblyType::NOT_SET),
    m_assembleWithHasBeenSet(false),
    m_kmsKeyIdHasBeenSet(false)
{
  *this = jsonValue;
}

TransformOutput& TransformOutput::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("S3OutputPath"))
  {
    m_s3OutputPath = jsonValue.GetString("S3OutputPath");

    m_s3OutputPathHasBeenSet = true;
  }

  if(jsonValue.ValueExists("Accept"))
  {
    m_accept = jsonValue.GetString("Accept");

    m_acceptHasBeenSet = true;
  }

  if(jsonValue.ValueExists("AssembleWith"))
  {
    m_assembleWith = AssemblyTypeMapper::GetAssemblyTypeForName(jsonValue.GetString("AssembleWith"));

    m_assembleWithHasBeenSet = true;
  }

  if(jsonValue.ValueExists("KmsKeyId"))
  {
    m_kmsKeyId = jsonValue.GetString("KmsKeyId");

    m_kmsKeyIdHasBeenSet = true;
  }

  return *this;
}

JsonValue TransformOutput::Jsonize() const
{
  JsonValue payload;

  if(m_s3OutputPathHasBeenSet)
  {
   payload.WithString("S3OutputPath", m_s3OutputPath);

  }

  if(m_acceptHasBeenSet)
  {
   payload.WithString("Accept", m_accept);

  }

  if(m_assembleWithHasBeenSet)
  {
   payload.WithString("AssembleWith", AssemblyTypeMapper::GetNameForAssemblyType(m_assembleWith));
  }

  if(m_kmsKeyIdHasBeenSet)
  {
   payload.WithString("KmsKeyId", m_kmsKeyId);

  }

  return payload;
}

} // namespace Model
} // namespace SageMaker
} // namespace Aws


text:
using System;
using Azure.Core;
using Azure.Storage.Queues;

namespace Microsoft.Azure.WebJobs.Extensions.Storage.Queues
{
    internal class FakeQueueServiceClientProvider : QueueServiceClientProvider
    {
        private readonly QueueServiceClient _queueServiceClient;

        public FakeQueueServiceClientProvider(QueueServiceClient queueServiceClient)
            : base(null, null, null, null, null, null, null, null)
        {
            _queueServiceClient = queueServiceClient;
        }

        public override QueueServiceClient Get(string name)
        {
            return _queueServiceClient;
        }
    }
}


text:
package com.google.cloud.spanner.pgadapter.parsers;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;

import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.SpannerException;
import com.google.cloud.spanner.pgadapter.error.PGException;
import com.google.cloud.spanner.pgadapter.parsers.Parser.FormatCode;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.postgresql.util.ByteConverter;

@RunWith(JUnit4.class)
public class LongParserTest {

  @Test
  public void testToLong() {
    long l = new Random().nextLong();
    byte[] data = new byte[8];
    ByteConverter.int8(data, 0, l);
    assertEquals(l, LongParser.toLong(data));

    // We allow 4 byte values to be parsed as a long as well, as Cloud Spanner allows int4 as a
    // valid data type for a column in a DDL statement, but it is converted to an int8 on the
    // backend.
    int i = new Random().nextInt();
    data = new byte[4];
    ByteConverter.int4(data, 0, i);
    assertEquals(i, LongParser.toLong(data));

    SpannerException spannerException =
        assertThrows(SpannerException.class, () -> LongParser.toLong(new byte[2]));
    assertEquals(ErrorCode.INVALID_ARGUMENT, spannerException.getErrorCode());
  }

  @Test
  public void testStringParse() {
    assertEquals("100", new LongParser(100L).stringParse());
    assertNull(new LongParser(null).stringParse());
    assertThrows(
        PGException.class,
        () -> new LongParser("foo".getBytes(StandardCharsets.UTF_8), FormatCode.TEXT));
  }
}


text:
from .base import SQLAdapter
from . import adapters

@adapters.register_for('teradata')
class Teradata(SQLAdapter):
    dbengine = ''
    drivers = ('pyodbc',)

    def _initialize_(self, do_connect):
        super(Teradata, self)._initialize_(do_connect)
        self.ruri = self.uri.split('://', 1)[1]

    def connector(self):
        return self.driver.connect(self.ruri, **self.driver_args)

    def close(self):
        # Teradata does not implicitly close off the cursor
        # leading to SQL_ACTIVE_STATEMENTS limit errors
        self.cursor.close()
        super(Teradata, self).close()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Class org.apache.poi.xssf.usermodel.TextAutofit (POI API Documentation)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.poi.xssf.usermodel.TextAutofit

Packages that use TextAutofit

org.apache.poi.xssf.usermodel

Uses of TextAutofit in org.apache.poi.xssf.usermodel

Methods in org.apache.poi.xssf.usermodel that return TextAutofit

 TextAutofit
XSSFSimpleShape.getTextAutofit()

static TextAutofit
TextAutofit.valueOf(java.lang.String name)

          Returns the enum constant of this type with the specified name.

static TextAutofit[]
TextAutofit.values()

          Returns an array containing the constants of this enum type, in
the order they are declared.

Methods in org.apache.poi.xssf.usermodel with parameters of type TextAutofit

 void
XSSFSimpleShape.setTextAutofit(TextAutofit value)

          Specifies that a shape should be auto-fit to fully contain the text described within it.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

                Copyright 2015 The Apache Software Foundation or
        its licensors, as applicable.