text:
'use strict';

var path     = require('path');
var fs       = require('fs');
var crypto   = require('crypto');
var expect   = require('chai').expect;
var walkSync = require('walk-sync');
var appName  = 'some-cool-app';
var EOL      = require('os').EOL;

var runCommand          = require('../helpers/run-command');
var acceptance          = require('../helpers/acceptance');
var copyFixtureFiles    = require('../helpers/copy-fixture-files');
var killCliProcess      = require('../helpers/kill-cli-process');
var assertDirEmpty      = require('../helpers/assert-dir-empty');
var ember               = require('../helpers/ember');
var createTestTargets   = acceptance.createTestTargets;
var teardownTestTargets = acceptance.teardownTestTargets;
var linkDependencies    = acceptance.linkDependencies;
var cleanupRun          = acceptance.cleanupRun;

describe('Acceptance: smoke-test', function() {
  this.timeout(500000);
  before(function() {
    return createTestTargets(appName);
  });

  after(function() {
    return teardownTestTargets();
  });

  beforeEach(function() {
    return linkDependencies(appName);
  });

  afterEach(function() {
    delete process.env._TESTEM_CONFIG_JS_RAN;

    return cleanupRun().then(function() {
      assertDirEmpty('tmp');
    });
  });

  it('ember new foo, clean from scratch', function() {
    return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'test');
  });

  it('ember test exits with non-zero when tests fail', function() {
    return copyFixtureFiles('smoke-tests/failing-test')
      .then(function() {
        return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'test')
          .then(function() {
            expect(false, 'should have rejected with a failing test');
          })
          .catch(function(result) {
            expect(result.code).to.equal(1);
          });
      });
  });

  it('ember test exits with non-zero when build fails', function() {
    return copyFixtureFiles('smoke-tests/test-with-syntax-error')
      .then(function() {
        return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'test')
          .then(function() {
            expect(false, 'should have rejected with a failing test');
          })
          .catch(function(result) {
            expect(result.code).to.equal(1);
          });
      });
  });

  it('ember test exits with non-zero when no tests are run', function() {
    return copyFixtureFiles('smoke-tests/no-testem-launchers')
      .then(function() {
        return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'test')
          .then(function() {
            expect(false, 'should have rejected with a failing test');
          })
          .catch(function(result) {
            expect(result.code).to.equal(1);
          });
      });
  });

  // TODO: re-enable, something is funky with test cleanup...
  // it('ember test exits with zero when tests pass', function() {
  //   return copyFixtureFiles('smoke-tests/passing-test')
  //     .then(function() {
  //       return ember(['test'])
  //         .then(function(result) {
  //           expect(result.code).to.equal(0);
  //         })
  //         .catch(function() {
  //           expect(false, 'should NOT have rejected with a failing test');
  //         });
  //     });
  // });

  it('ember test still runs when only a JavaScript testem config exists', function() {
    return copyFixtureFiles('smoke-tests/js-testem-config')
      .then(function() {
        // testem.json "wins" over testem.js by default so we need to delete
        // it from the default blueprint first
        fs.unlinkSync('testem.json');
        return ember(['test']);
      })
      .then(function() {
        expect(!!process.env._TESTEM_CONFIG_JS_RAN).to.equal(true);
      });
  });

  // there is a bug in here when running the entire suite on Travis
  // when run in isolation, it passes
  // here is the error:
  // test-support-80f2fe63fae0c44478fe0f8af73200a7.js contains the fingerprint (2871106928f813936fdd64f4d16005ac): expected 'test-support-80f2fe63fae0c44478fe0f8af73200a7.js' to include '2871106928f813936fdd64f4d16005ac'
  it.skip('ember new foo, build production and verify fingerprint', function() {
    return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build', '--environment=production')
      .then(function() {
        var dirPath = path.join('.', 'dist', 'assets');
        var dir = fs.readdirSync(dirPath);
        var files = [];

        dir.forEach(function (filepath) {
          if (filepath === '.gitkeep') {
            return;
          }

          files.push(filepath);

          var file = fs.readFileSync(path.join(dirPath, filepath), { encoding: null });

          var md5 = crypto.createHash('md5');
          md5.update(file);
          var hex = md5.digest('hex');

          expect(filepath).to.contain(hex, filepath + ' contains the fingerprint (' + hex + ')');
        });

        var indexHtml = fs.readFileSync(path.join('.', 'dist', 'index.html'), { encoding: 'utf8' });

        files.forEach(function (filename) {
          expect(indexHtml).to.contain(filename);
        });
      });
  });

  // TODO: restore, test harness npm appears to incorrectly dedupe broccoli-filter, causing this test to fail.
  // manually testing that case, it seems to work correctly, will restore soon.
  it.skip('ember test --environment=production', function() {
    return copyFixtureFiles('smoke-tests/passing-test')
      .then(function() {
        return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'test', '--environment=production');
      })
      .then(function(result) {
        var exitCode = result.code;
        var output = result.output.join(EOL);

        expect(exitCode).to.equal(0, 'exit code should be 0 for passing tests');
        expect(output).to.match(/JSHint/, 'JSHint should be run on production assets');
        expect(output).to.match(/fail\s+0/, 'no failures');
        expect(output).to.match(/pass\s+\d+/, 'man=y passing');
      });
  });

  it('ember test --path with previous build', function() {
    var originalWrite = process.stdout.write;
    var output = [];

    return copyFixtureFiles('smoke-tests/passing-test')
      .then(function() {
        // TODO: Change to using ember() helper once it properly saves build artifacts
        return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build');
      })
      .then(function() {
        // TODO: Figure out how to get this to write into the MockUI
        process.stdout.write = (function() {
          return function() {
            output.push(arguments[0]);
          };
        }(originalWrite));

        return ember([ 'test', '--path=dist' ]);
      }).finally(function() {
        process.stdout.write = originalWrite;
      })
      .then(function(result) {
        expect(result.exitCode).to.equal(0, 'exit code should be 0 for passing tests');

        output = output.join(EOL);

        expect(output).to.match(/JSHint/, 'JSHint should be run');
        expect(output).to.match(/fail\s+0/, 'no failures');
        expect(output).to.match(/pass\s+12/, '1 passing');
      });
  });

  it('ember new foo, build development, and verify generated files', function() {
    return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build')
      .then(function() {
        var dirPath = path.join('.', 'dist');
        var paths = walkSync(dirPath);

        expect(paths).to.have.length.below(23, 'expected fewer than 23 files in dist, found ' + paths.length);
      });
  });

  it('ember build exits with non-zero code when build fails', function () {
    var appJsPath   = path.join('.', 'app', 'app.js');
    var ouputContainsBuildFailed = false;

    return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build')
      .then(function (result) {
        expect(result.code).to.equal(0, 'expected exit code to be zero, but got ' + result.code);

        // add something broken to the project to make build fail
        fs.appendFileSync(appJsPath, '{(syntaxError>$@}{');

        return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build', {
          onOutput: function(string) {
            // discard output as there will be a lot of errors and a long stacktrace
            // just mark that the output contains expected text
            if (!ouputContainsBuildFailed && string.match(/Build failed/)) {
              ouputContainsBuildFailed = true;
            }
          }
        });

      }).then(function () {
        expect(false, 'should have rejected with a failing build');
      }).catch(function (result) {
        expect(ouputContainsBuildFailed, 'command output must contain "Build failed" text');
        expect(result.code).to.not.equal(0, 'expected exit code to be non-zero, but got ' + result.code);
      });
  });

  it('ember new foo, build --watch development, and verify rebuilt after change', function() {
    var touched     = false;
    var appJsPath   = path.join('.', 'app', 'app.js');
    var builtJsPath = path.join('.', 'dist', 'assets', 'some-cool-app.js');
    var text        = 'anotuhaonteuhanothunaothanoteh';
    var line        = 'console.log("' + text + '");';

    return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build', '--watch', {
        onOutput: function(string, child) {
          if (touched) {
            if (string.match(/Build successful/)) {
              // build after change to app.js
              var contents  = fs.readFileSync(builtJsPath).toString();
              expect(contents).to.contain(text, 'must contain changed line after rebuild');
              killCliProcess(child);
            }
          } else {
            if (string.match(/Build successful/)) {
              // first build
              touched = true;
              fs.appendFileSync(appJsPath, line);
            }
          }
        }
      })
      .catch(function() {
        // swallowing because of SIGINT
      });
  });

  it('ember new foo, build --watch development, and verify rebuilt after multiple changes', function() {
    var buildCount  = 0;
    var touched     = false;
    var appJsPath   = path.join('.', 'app', 'app.js');
    var builtJsPath = path.join('.', 'dist', 'assets', 'some-cool-app.js');
    var firstText   = 'anotuhaonteuhanothunaothanoteh';
    var firstLine   = 'console.log("' + firstText + '");';
    var secondText  = 'aahsldfjlwioruoiiononociwewqwr';
    var secondLine  = 'console.log("' + secondText + '");';

    return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build', '--watch', {
        onOutput: function(string, child) {
          if (buildCount === 0) {
            if (string.match(/Build successful/)) {
              // first build
              touched = true;
              buildCount = 1;
              fs.appendFileSync(appJsPath, firstLine);
            }
          } else if (buildCount === 1) {
            if (string.match(/Build successful/)) {
              // second build
              touched = true;
              buildCount = 2;
              fs.appendFileSync(appJsPath, secondLine);
            }
          } else if (touched && buildCount === 2) {
            if (string.match(/Build successful/)) {
              // build after change to app.js
              var contents  = fs.readFileSync(builtJsPath).toString();
              expect(contents.indexOf(secondText) > 1, 'must contain second changed line after rebuild');
              killCliProcess(child);
            }
          }
        }
      })
      .catch(function() {
        // swallowing because of SIGINT
      });
  });

  it('ember new foo, server, SIGINT clears tmp/', function() {
    return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'server', '--port=54323','--live-reload=false', {
        onOutput: function(string, child) {
          if (string.match(/Build successful/)) {
            killCliProcess(child);
          }
        }
      })
      .catch(function() {
        // just eat the rejection as we are testing what happens
      });
  });

  it('ember new foo, build production and verify css files are concatenated', function() {
    return copyFixtureFiles('with-styles')
      .then(function() {
      return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build', '--environment=production')
        .then(function() {
          var dirPath = path.join('.', 'dist', 'assets');
          var dir = fs.readdirSync(dirPath);
          var cssNameRE = new RegExp(appName + '-([a-f0-9]+)\\.css','i');
          dir.forEach(function (filepath) {
            if(cssNameRE.test(filepath)) {
              var appCss = fs.readFileSync(path.join('.', 'dist', 'assets', filepath), { encoding: 'utf8' });
              expect(appCss).to.contain('.some-weird-selector');
              expect(appCss).to.contain('.some-even-weirder-selector');
            }
          });
        });
    });
  });

  it('ember new foo, build production and verify single "use strict";', function() {
    return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'build', '--environment=production')
      .then(function() {
          var dirPath = path.join('.', 'dist', 'assets');
          var dir = fs.readdirSync(dirPath);
          var appNameRE = new RegExp(appName + '-([a-f0-9]+)\\.js','i');
          dir.forEach(function(filepath) {
            if (appNameRE.test(filepath)) {
              var contents = fs.readFileSync(path.join('.', 'dist', 'assets', filepath), { encoding: 'utf8' });
              var count = (contents.match(/(["'])use strict\1;/g) || []).length;
              expect(count).to.equal(1);
            }
          });
      });
  });

  it('ember can override and reuse the built-in blueprints', function() {
    return copyFixtureFiles('addon/with-blueprint-override')
      .then(function() {
        return runCommand(path.join('.', 'node_modules', 'ember-cli', 'bin', 'ember'), 'generate', 'component', 'foo-bar', '-p');
      })
      .then(function() {
        // because we're overriding, the fileMapTokens is default, sans 'component'
        var componentPath = path.join('app','foo-bar','component.js');
        var contents = fs.readFileSync(componentPath, { encoding: 'utf8' });

        expect(contents).to.contain('generated component successfully');
      });
  });
});


text:
import json
import pyquery
from selenium import webdriver
import sys
import time
import os

header_conv = {
   u"כתובת" : "address",
   u"מס' רשיון" : "license_number",
   u"שם החברה" : "company_name",
   u"מנכ\"ל החברה" : "company_ceo",
   u"יישוב" : "locality",
   u"בעל החברה" : "owner",
   u"גמר תוקף" : "end_date",
   u"סטאטוס רישיון" : "license_status",
   u"ח.פ/ע.מ" : "company_id",
   u"תחום פעילות" : "field_of_activity"
}

def match_int(s, i):
    try:
        return int(s) == i
    except ValueError:
        return False

# Return a list of dicts containing rows.
def ParseOnePage(x):
    l = []
    # Table header. Will use these headings as keys to the records from all trs.
    th = [e.text_content() for e in x('table#gvContractors')[0][0][0]]
    headers = [header_conv[h] for h in th]
    for tr in x('table#gvContractors')[0][0][1:-1]:
        if len(tr.getchildren()) != len(th):
            sys.stderr.write('Warning len mismatch: %d != %d\n' %
                             (len(tr.getchildren()), len(th)))
        l.append(dict(zip(headers, [e.text_content() for e in tr])))
    return l

# Starting from the main page, we will get a page at a time and try getting the
# one we want by clicking the paging links.

def is_postback_link(link):
    return link.get_attribute('href').startswith(u"javascript:__doPostBack")

def scrape(browser):
    rows = []
    next_page_index = 1
    while True:
        sys.stderr.write('Dumping page %3d\n' % next_page_index)
        rows += ParseOnePage(pyquery.PyQuery(browser.page_source))
        next_page_index += 1
        links = browser.find_elements_by_xpath("//a")

        # Skip first '...' which points back.
        if links[0].text == '...':
            links = links[1:]

        for link in links:
            #print "<%s> :%s:" % (link.get_attribute('href'),link.text)
            if is_postback_link(link):
                last_postback_link = link
                # We blindly assume that the last '...' link is ours if we did
                # not find our target in the previous ones.
                # nxt = link.get_attribute('href').split("'")[3].split('$')[1]
                # print nxt
                if (match_int(link.text, next_page_index) or
                    link.text == "..."):
                    link.click()
                    time.sleep(3)
                    break
        else:
            # We did not find the link we looked for. Either this is the last
            # page, or something went wrong.  We recognize the last page as the
            # last postback one with no "..." as last link, preferrably with
            # last link pointing to previous page, i.e. next_page_index-2.
            if match_int(last_postback_link.text, next_page_index - 2):
                return True, rows
            browser.save_screenshot('screen.png')
            return False, rows

def add_zeros(x):
    return "0"*(max(0,9-len(x))) + x

def main(output,url,field):
    dcap = dict(webdriver.DesiredCapabilities.PHANTOMJS)
    dcap["phantomjs.page.settings.userAgent"] = (
         "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
         "(KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36")
    browser = webdriver.PhantomJS(desired_capabilities = dcap, executable_path=os.environ.get('PHANTOMJS_PATH'))
    browser.set_window_size(1200, 800)
    browser.get(url)

    success, rows = scrape(browser)

    print success
    if success:
        out = file(output,'w')
        for row in rows:
            row = { 'id':add_zeros(row['company_id']), 'name':row['company_name'], field:row }
            out.write(json.dumps(row,sort_keys=True)+'\n')
        return
    raise RuntimeError("Something went wrong!")

class scrape_moital_contractors(object):

    def process(self,input,output,url,field):
        main(output,url,field)

if __name__=="__main__":
    main('moital.jsons')

redpajama_set_name: RedPajamaGithub


text:
`UserProfile` – Additional profile information about a TypePad user
===================================================================

.. autoclass:: typepad.api.UserProfile
   :members:


text:
package org.apache.hadoop.yarn.api.protocolrecords.impl.pb;

import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.yarn.api.protocolrecords.FinishApplicationMasterRequest;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.impl.pb.ProtoUtils;
import org.apache.hadoop.yarn.proto.YarnProtos.FinalApplicationStatusProto;
import org.apache.hadoop.yarn.proto.YarnServiceProtos.FinishApplicationMasterRequestProto;
import org.apache.hadoop.yarn.proto.YarnServiceProtos.FinishApplicationMasterRequestProtoOrBuilder;

import org.apache.hadoop.thirdparty.protobuf.TextFormat;

@Private
@Unstable
public class FinishApplicationMasterRequestPBImpl extends FinishApplicationMasterRequest {
  FinishApplicationMasterRequestProto proto = FinishApplicationMasterRequestProto.getDefaultInstance();
  FinishApplicationMasterRequestProto.Builder builder = null;
  boolean viaProto = false;

  public FinishApplicationMasterRequestPBImpl() {
    builder = FinishApplicationMasterRequestProto.newBuilder();
  }

  public FinishApplicationMasterRequestPBImpl(FinishApplicationMasterRequestProto proto) {
    this.proto = proto;
    viaProto = true;
  }

  public FinishApplicationMasterRequestProto getProto() {
      mergeLocalToProto();
    proto = viaProto ? proto : builder.build();
    viaProto = true;
    return proto;
  }

  @Override
  public int hashCode() {
    return getProto().hashCode();
  }

  @Override
  public boolean equals(Object other) {
    if (other == null)
      return false;
    if (other.getClass().isAssignableFrom(this.getClass())) {
      return this.getProto().equals(this.getClass().cast(other).getProto());
    }
    return false;
  }

  @Override
  public String toString() {
    return TextFormat.shortDebugString(getProto());
  }

  private void mergeLocalToBuilder() {
  }

  private void mergeLocalToProto() {
    if (viaProto)
      maybeInitBuilder();
    mergeLocalToBuilder();
    proto = builder.build();
    viaProto = true;
  }

  private void maybeInitBuilder() {
    if (viaProto || builder == null) {
      builder = FinishApplicationMasterRequestProto.newBuilder(proto);
    }
    viaProto = false;
  }

  @Override
  public String getDiagnostics() {
    FinishApplicationMasterRequestProtoOrBuilder p = viaProto ? proto : builder;
    return p.getDiagnostics();
  }

  @Override
  public void setDiagnostics(String diagnostics) {
    maybeInitBuilder();
    if (diagnostics == null) {
      builder.clearDiagnostics();
      return;
    }
    builder.setDiagnostics(diagnostics);
  }

  @Override
  public String getTrackingUrl() {
    FinishApplicationMasterRequestProtoOrBuilder p = viaProto ? proto : builder;
    return p.getTrackingUrl();
  }

  @Override
  public void setTrackingUrl(String url) {
    maybeInitBuilder();
    if (url == null) {
      builder.clearTrackingUrl();
      return;
    }
    builder.setTrackingUrl(url);
  }

  @Override
  public FinalApplicationStatus getFinalApplicationStatus() {
    FinishApplicationMasterRequestProtoOrBuilder p = viaProto ? proto : builder;
    if (!p.hasFinalApplicationStatus()) {
      return null;
    }
    return convertFromProtoFormat(p.getFinalApplicationStatus());
  }

  @Override
  public void setFinalApplicationStatus(FinalApplicationStatus finalState) {
    maybeInitBuilder();
    if (finalState == null) {
      builder.clearFinalApplicationStatus();
      return;
    }
    builder.setFinalApplicationStatus(convertToProtoFormat(finalState));
  }

  private FinalApplicationStatus convertFromProtoFormat(FinalApplicationStatusProto s) {
    return ProtoUtils.convertFromProtoFormat(s);
  }

  private FinalApplicationStatusProto convertToProtoFormat(FinalApplicationStatus s) {
    return ProtoUtils.convertToProtoFormat(s);
  }

}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.AppContainers.Models
{
    internal partial class WorkloadProfileStatesCollection
    {
        internal static WorkloadProfileStatesCollection DeserializeWorkloadProfileStatesCollection(JsonElement element)
        {
            IReadOnlyList<WorkloadProfileStates> value = default;
            Optional<string> nextLink = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("value"))
                {
                    List<WorkloadProfileStates> array = new List<WorkloadProfileStates>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(WorkloadProfileStates.DeserializeWorkloadProfileStates(item));
                    }
                    value = array;
                    continue;
                }
                if (property.NameEquals("nextLink"))
                {
                    nextLink = property.Value.GetString();
                    continue;
                }
            }
            return new WorkloadProfileStatesCollection(value, nextLink.Value);
        }
    }
}


text:
import datetime
import math
from Utc import Utc

"""Classes representing NMEA sentence types"""

class NmeaSentence:
    """A base class for all NMEA sentences"""

    def __init__(self, type):
        """Create a new NmeaSentence instance

        Arguments:
        type -- a string containing the NMEA sentence type (e.g. GPGGA)
        """
        self.__type = type

    def __str__(self):
        '''Return a string representation of the object'''
        return "NmeaSentence{type = %s}" % ( self.getType() )

    def getType(self):
        """Return the NMEA message type"""
        return self.__type

class InvalidGpggaSentence(ValueError):
    """Exception that is raised when an invalid GPGGA sentence is encountered"""

    def __init__(self, args):
        ValueError.__init__(self, args)

class GpggaSentence(NmeaSentence):
    """GPGGA NMEA sentence"""

    # The NMEA message type corresponding to GPGGA
    __Type = "GPGGA"

    # The number of expected fields in a GPGGA message
    __NumFields = 15

    def __init__(self, fields):
        """Create a new GPGGA NMEA sentence instance

        Arguments:
        fields -- a list containing the GPGGA NMEA sentence fields
        """
        if (len(fields) != GpggaSentence.__NumFields):
            raise InvalidGpggaSentence, "Incorrect number of fields"

        if (fields[0] != GpggaSentence.__Type):
            raise InvalidGpggaSentence, "Type field does not contain GPGGA"

        NmeaSentence.__init__(self, GpggaSentence.__Type)

        # UTC time the fix was taken.  Format is hhmmss.
        self.__setTime( fields[1] )

        # Latitude variables
        self.__setLatitude( fields[2], fields[3] )

        # Longitude variables
        self.__setLongitude( fields[4], fields[5] )

        # The fix quality.  Possible values are:
        #  0 - invalid
        #  1 - GPS fix
        #  2 - DGPS fix
        #  3 - PPS fix
        #  4 - Real time kinematic (RTK)
        #  5 - Float RTK
        #  6 - Estimated (dead reckoning)
        #  7 - Manual input mode
        #  8 - Simulation mode
        try:
            self.__quality = GpggaSentence.__ToInt( fields[6] )
        except ValueError:
            raise InvalidGpggaSentence("Quality field is invalid")

        # The number of satellites being tracked
        try:
            self.__numSatellites = GpggaSentence.__ToInt( fields[7] )
        except ValueError:
            raise InvalidGpggaSentence("Number of satellites field is invalid")

        # Horizontal dilution of precision
        try:
            self.__hdop = GpggaSentence.__ToFloat( fields[8] )
        except ValueError:
            raise InvalidGpggaSentence("HDOP field is invalid")

        # Altitude above mean sea level
        try:
            self.__altitude = GpggaSentence.__ToFloat( fields[9] )
        except ValueError:
            raise InvalidGpggaSentence("Altitude field is invalid")
        # Altitude units
        self.__altitudeUnits = fields[10]

        # Height of the geoid above mean sea level
        try:
            self.__geoidHeight = GpggaSentence.__ToFloat( fields[11] )
        except ValueError:
            raise InvalidGpggaSentence("Geoid height field is invalid")
        # Geoid height units
        self.__geoidHeightUnits = fields[12]

        # Time in seconds since the latest DGPS update
        try:
            self.__secondsSinceLastDgpsUpdate = \
                GpggaSentence.__ToInt( fields[13] )
        except ValueError:
            raise InvalidGpggaSentence("Seconds since last DGPS update " + \
                                       "field is invalid")
        # DGPS station ID number
        self.__dgpsStationId = fields[14]

    def __str__(self):
        '''Return a string representation of the object'''
        formatString = "GpggaSentence{time = %s, latitude = %g, " + \
                       "longitude = %g, quality = %d, numSatellites = %d, " + \
                       "hDop = %g, altitude = %g %s, geoidHeight = %g %s, " + \
                       "timeSinceLastDgpsUpdate = %s, dgpsStationId = %s}"
        formatArgs = ( self.getTime().isoformat(), self.getLatitude(),
                       self.getLongitude(), self.getQuality(),
                       self.getNumSatellites(), self.getHorizontalDop(),
                       self.getAltitude(), self.getAltitudeUnits(),
                       self.getGeoidHeight(), self.getGeoidHeightUnits(),
                       self.getSecondsSinceLastDgpsUpdate(),
                       self.getDgpsStationId() )

        return formatString % formatArgs

    def getTime(self):
        """Return the UTC time the position fix was taken"""
        return self.__time

    def getLatitude(self):
        """Return the latitude of the fix"""
        return self.__latitude

    def getLongitude(self):
        """Return the longitude of the fix"""
        return self.__longitude

    def getQuality(self):
        """Return an integer denoting the quality of the fix.  Possible values
        are:
        0 - invalid
        1 - GPS fix
        2 - DGPS fix
        3 - PPS fix
        4 - Real time kinematic (RTK)
        5 - Float RTK
        6 - Estimated (dead reckoning)
        7 - Manual input mode
        8 - Simulation mode
        """
        return self.__quality

    def getNumSatellites(self):
        """Return an integer denoting the number of satellites tracked for
        the fix.
        """
        return self.__numSatellites

    def getHorizontalDop(self):
        """Return the horizontal dilution of position (DOP)"""
        return self.__hdop

    def getAltitude(self):
        """Return the altitude above mean sea level (AMSL)"""
        return self.__altitude

    def getAltitudeUnits(self):
        """Return a string denoting the units of the altitude AMSL"""
        return self.__altitudeUnits

    def getGeoidHeight(self):
        """Return the height of the geoid above mean sea level (AMSL)"""
        return self.__geoidHeight

    def getGeoidHeightUnits(self):
        """Return a string denoting the units of the height of the geoid
        AMSL
        """
        return self.__geoidHeightUnits

    def getSecondsSinceLastDgpsUpdate(self):
        """Return an integer denoting the time in seconds since the last DGPS
        update, or None if the field is undefined
        """
        return self.__secondsSinceLastDgpsUpdate

    def getDgpsStationId(self):
        """Return a string denoting the DGPS station ID"""
        return self.__dgpsStationId

    @staticmethod
    def __ConvertLatOrLon(value):
        """Converts a latitude or longitude value in the form DDMM.MMM to a
        proper floating point format
        """
        temp = GpggaSentence.__ToFloat(value)

        degreesAndMinutes = int(temp)

        degrees = degreesAndMinutes / 100

        minutes = degreesAndMinutes - degrees * 100
        minutes += temp - degreesAndMinutes

        ans = degrees + minutes / 60.0

        return ans

    @staticmethod
    def __ToInt(field):
        """Converts a string field to an integer.  If the string is empty then
        a value of 0 is returned

        Arguments:
        field -- the field that is to be converted to an integer
        """
        if (field == ""):
            return 0

        return int(field)

    @staticmethod
    def __ToFloat(field):
        """Converts a string field to a floating point number.  If the string
        is empty then a value of 0.0 is returned

        Arguments:
        field -- the field that is to be converted to a floating point number
        """
        if (field == ""):
            return 0.0

        return float(field)

    def __setTime(self, field):
        """Set the UTC time the position fix was taken

        Arguments:
        field -- the string value of the time field in the GPGGA sentence
        """
        try:
            time = GpggaSentence.__ToFloat(field)
        except ValueError, e:
            raise InvalidGpggaSentence("Time field invalid", e)

        hours = int(time // 10000)
        time -= hours * 10000

        minutes = int(time // 100)
        time -= minutes * 100

        seconds = int(time)
        time -= seconds

        microseconds = int(time * 1000000)

        self.__time = datetime.datetime.now( tz = Utc() ).replace(hour = hours,
                        minute = minutes, second = seconds,
                        microsecond = microseconds)

    def __setLatitude(self, latField, nsField):
        """Set the latitude of the position fix

        Arguments:
        latField -- the string value of the latitude field in the GPGGA
        sentence

        nsField -- the string value of the N/S field in the GPGGA sentence
        """
        try:
            self.__latitude = GpggaSentence.__ConvertLatOrLon(latField)
        except ValueError:
            raise InvalidGpggaSentence("Latitude field is invalid")

        if (nsField.upper() == "S"):
            self.__latitude *= -1.0

    def __setLongitude(self, lonField, ewField):
        """Set the latitude of the position fix

        Arguments:
        lonField -- the string value of the longitude field in the GPGGA
        sentence

        ewField -- the string value of the E/W field in the GPGGA sentence
        """
        try:
            self.__longitude = GpggaSentence.__ConvertLatOrLon(lonField)
        except ValueError:
            raise InvalidGpggaSentence("Longitude field is invalid")

        if (ewField.upper() == "W"):
            self.__longitude *= -1.0


text:
( function( global, factory ) {

    if ( typeof module === "object" && typeof module.exports === "object" ) {
        exports[ "ChoiceFormat" ] = module.exports = factory( global );
    } else {
        factory( global );
    }

} )( this, function( global ) {

    function ChoiceFormat( newPattern ) {
        NumberFormat.call( this );
        var _choiceLimits;
        var _choiceFormats;

        this.applyPattern = function( newPattern ) {
            var segments = [ "", "" ];
            var newChoiceLimits = [];
            var newChoiceFormats = [];
            var count = 0;
            var part = 0;
            var startValue = 0;
            var oldStartValue = Number.NaN;
            var inQuote = false;
            for ( var i = 0; i < newPattern.length; ++i ) {
                var ch = newPattern.charAt( i );
                if ( ch == "'" ) {
                    // Check for "''" indicating a literal quote
                    if ( ( i + 1 ) < newPattern.length && newPattern.charAt( i + 1 ) == ch ) {
                        segments[ part ] += ch;
                        ++i;
                    } else {
                        inQuote = !inQuote;
                    }
                } else if ( inQuote ) {
                    segments[ part ] += ch;
                } else if ( ch == "<" || ch == "#" || ch == "\u2264" ) {
                    if (segments[ 0 ].length == 0) {
                        throw "";
                    }
                    try {
                        var tempBuffer = segments[ 0 ].toString();
                        if ( tempBuffer === "\u221E" ) {
                            startValue = Number.POSITIVE_INFINITY;
                        } else if ( tempBuffer === "-\u221E" ) {
                            startValue = Number.NEGATIVE_INFINITY;
                        } else {
                            startValue = parseFloat( segments[ 0 ] );
                        }
                    } catch ( e ) {
                        throw "";
                    }
                    if ( ch == "<" && startValue != Number.POSITIVE_INFINITY &&
                        startValue != Number.NEGATIVE_INFINITY ) {
                        startValue = ChoiceFormat.nextDouble( startValue );
                    }
                    if ( startValue <= oldStartValue ) {
                        throw "";
                    }
                    segments[ 0 ] = "";
                    part = 1;
                } else if ( ch == "|" ) {
                    newChoiceLimits.push( startValue );
                    newChoiceFormats.push( segments[ 1 ].toString() );
                    ++count;
                    oldStartValue = startValue;
                    segments[ 1 ] = "";
                    part = 0;
                } else {
                    segments[ part ] += ch;
                }
            }
            // clean up last one
            if ( part == 1 ) {
                newChoiceLimits.push( startValue );
                newChoiceFormats.push( segments[ 1 ].toString() );
                ++count;
            }
            _choiceLimits = newChoiceLimits.slice( 0, count );
            _choiceFormats = newChoiceFormats.slice( 0, count );
        };

        this.toPattern = function() {
            var result = "";
            for (var i = 0; i < _choiceLimits.length; ++i) {
                if ( i != 0 ) {
                    result += "|";
                }
                // choose based upon which has less precision
                // approximate that by choosing the closest one to an integer.
                // could do better, but it's not worth it.
                var less = ChoiceFormat.previousDouble( _choiceLimits[ i ] );
                var tryLessOrEqual = Math.abs( ( _choiceLimits[i] % 1.0 ) );
                var tryLess = Math.abs( ( less % 1.0 ) );

                if ( tryLessOrEqual < tryLess ) {
                    result += _choiceLimits[ i ].toString();
                    result += "#";
                } else {
                    if ( _choiceLimits[ i ] == Number.POSITIVE_INFINITY ) {
                        result += "\u221E";
                    } else if ( _choiceLimits[ i ] == Number.NEGATIVE_INFINITY ) {
                        result += "-\u221E";
                    } else {
                        result += less.toString();
                    }
                    result += "<";
                }
                // Append choiceFormats[i], using quotes if there are special characters.
                // Single quotes themselves must be escaped in either case.
                var text = _choiceFormats[ i ];
                var needQuote = text.indexOf( "<" ) >= 0
                    || text.indexOf( "#" ) >= 0
                    || text.indexOf( "\u2264" ) >= 0
                    || text.indexOf( "|" ) >= 0;
                if ( needQuote ) result += "'";
                if ( text.indexOf("'") < 0 ) result += text;
                else {
                    for ( var j = 0; j < text.length; ++j ) {
                        var c = text.charAt( j );
                        result += c;
                        if ( c == "'") result += c;
                    }
                }
                if ( needQuote ) result += "'";
            }
            return result.toString();
        };

        this.setChoices = function( limits, formats ) {
            if ( limits.length != formats.length ) {
                throw "Array and limit arrays must be of the same length.";
            }
            _choiceLimits = limits;
            _choiceFormats = formats;
        };

        this.getLimits = function() {
            return _choiceLimits;
        };

        this.getFormats = function() {
            return _choiceFormats;
        };

        this.format = function( number, toAppendTo, status ) {
            toAppendTo = typeof toAppendTo == "string" ? toAppendTo : "";
            // find the number
            var i;
            for ( i = 0; i < _choiceLimits.length; ++i ) {
                if ( !( number >= _choiceLimits[ i ] ) ) {
                    // same as number < choiceLimits, except catchs NaN
                    break;
                }
            }
            --i;
            if ( i < 0 ) i = 0;
            // return either a formatted number, or a string
            return toAppendTo + _choiceFormats[ i ];
        };

        this.parse = function( text, status ) {
            // find the best number (defined as the one with the longest parse)
            status = status || new ParsePosition( 0 );
            var start = status.index;
            var furthest = start;
            var bestNumber = Number.NaN;
            var tempNumber = 0.0;
            for ( var i = 0; i < _choiceFormats.length; ++i ) {
                var tempString = _choiceFormats[ i ];
                if ( text.substr( start, tempString.length ).search( tempString ) > -1 ) {
                    status.index = start + tempString.length;
                    tempNumber = _choiceLimits[ i ];
                    if ( status.index > furthest ) {
                        furthest = status.index;
                        bestNumber = tempNumber;
                        if ( furthest == text.length ) break;
                    }
                }
            }
            status.index = furthest;
            if ( status.index == start ) {
                status.errorIndex = furthest;
            }
            return bestNumber;
        };

        if ( arguments.length == 2 ) {
            this.setChoices.apply( this, arguments );
        } else {
            this.applyPattern( newPattern );
        }
    }

    var _SIGN                = 0x8000000000000000;
    var _EXPONENT            = 0x7FF0000000000000;
    var _POSITIVEINFINITY    = 0x7FF0000000000000;

    ChoiceFormat.previousDouble = function( d ) {
        return ChoiceFormat.nextDouble( d, false );
    };

    ChoiceFormat.nextDouble = function( d, positive ) {
        if ( typeof positive == "undefined" ) {
            return ChoiceFormat.nextDouble( d, true );
        }

        /* filter out NaN's */
        if ( isNaN( d ) ) {
            return d;
        }

        /* zero's are also a special case */
        if ( d == 0.0 ) {
            var smallestPositiveDouble = Number.MIN_VALUE;
            if ( positive ) {
                return smallestPositiveDouble;
            } else {
                return -smallestPositiveDouble;
            }
        }

        /* if entering here, d is a nonzero value */
        return d + ( ( positive ? 1 : -1 ) * 1e-15 );
    };

    ChoiceFormat.prototype = Object.create( NumberFormat.prototype );

    ChoiceFormat.prototype.constructor = ChoiceFormat;

    global.ChoiceFormat = ChoiceFormat;

    return ChoiceFormat;

} );


text:
package org.vitrivr.cineast.core.db.cottontaildb;

import static org.vitrivr.cineast.core.db.setup.AttributeDefinition.AttributeType.BITSET;
import static org.vitrivr.cineast.core.db.setup.AttributeDefinition.AttributeType.TEXT;
import static org.vitrivr.cineast.core.db.setup.AttributeDefinition.AttributeType.VECTOR;
import static org.vitrivr.cineast.core.util.CineastConstants.GENERIC_ID_COLUMN_QUALIFIER;

import org.vitrivr.cottontail.grpc.CottontailGrpc.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import org.vitrivr.cineast.core.config.DatabaseConfig;
import org.vitrivr.cineast.core.data.entities.MediaObjectDescriptor;
import org.vitrivr.cineast.core.data.entities.MediaObjectMetadataDescriptor;
import org.vitrivr.cineast.core.data.entities.MediaSegmentDescriptor;
import org.vitrivr.cineast.core.data.entities.MediaSegmentMetadataDescriptor;
import org.vitrivr.cineast.core.db.dao.reader.TagReader;
import org.vitrivr.cineast.core.db.setup.AttributeDefinition;
import org.vitrivr.cineast.core.db.setup.EntityCreator;

public class CottontailEntityCreator implements EntityCreator {

  public static final String COTTONTAIL_PREFIX = "cottontail";
  public static final String INDEX_HINT = COTTONTAIL_PREFIX+".index";

  private final CottontailWrapper cottontail;

  public CottontailEntityCreator(DatabaseConfig config) {
    this.cottontail = new CottontailWrapper(config, true);
    init();
  }

  public CottontailEntityCreator(CottontailWrapper cottontailWrapper) {
    this.cottontail = cottontailWrapper;
    init();
  }

  private void init() {
    cottontail.ensureSchemaBlocking("cineast");
  }

  @Override
  public boolean createTagEntity() {
    ArrayList<ColumnDefinition> columns = new ArrayList<>(4);
    ColumnDefinition.Builder builder = ColumnDefinition.newBuilder();

    columns.add(builder.clear().setName(TagReader.TAG_ID_COLUMNNAME).setType(Type.STRING).build());
    columns.add(builder.clear().setName(TagReader.TAG_NAME_COLUMNNAME).setType(Type.STRING).build());
    columns.add(builder.clear().setName(TagReader.TAG_DESCRIPTION_COLUMNNAME).setType(Type.STRING).build());

    EntityDefinition message = EntityDefinition.newBuilder()
        .setEntity(CottontailMessageBuilder.entity(TagReader.TAG_ENTITY_NAME))
        .addAllColumns(columns).build();

    cottontail.createEntityBlocking(message);

    this.createIndex(TagReader.TAG_ENTITY_NAME, TagReader.TAG_ID_COLUMNNAME, IndexType.HASH_UQ);
    this.createIndex(TagReader.TAG_ENTITY_NAME, TagReader.TAG_NAME_COLUMNNAME, IndexType.HASH);
    this.createIndex(TagReader.TAG_ENTITY_NAME, TagReader.TAG_NAME_COLUMNNAME, IndexType.LUCENE);

    return true;
  }

  @Override
  public boolean createMultiMediaObjectsEntity() {

    ArrayList<ColumnDefinition> columns = new ArrayList<>(4);
    ColumnDefinition.Builder builder = ColumnDefinition.newBuilder();

    columns.add(builder.clear().setName(MediaObjectDescriptor.FIELDNAMES[0]).setType(Type.STRING).build());
    columns.add(builder.clear().setName(MediaObjectDescriptor.FIELDNAMES[1]).setType(Type.INTEGER).build());
    columns.add(builder.clear().setName(MediaObjectDescriptor.FIELDNAMES[2]).setType(Type.STRING).build());
    columns.add(builder.clear().setName(MediaObjectDescriptor.FIELDNAMES[3]).setType(Type.STRING).build());

    EntityDefinition message = EntityDefinition.newBuilder()
        .setEntity(CottontailMessageBuilder.entity(MediaObjectDescriptor.ENTITY))
        .addAllColumns(columns).build();

    cottontail.createEntityBlocking(message);

    this.createIndex(MediaObjectDescriptor.ENTITY, MediaObjectDescriptor.FIELDNAMES[0], IndexType.HASH_UQ);

    return true;
  }

  @Override
  public boolean createMetadataEntity() {

    ArrayList<ColumnDefinition> columns = new ArrayList<>(4);
    ColumnDefinition.Builder builder = ColumnDefinition.newBuilder();

    columns.add(builder.clear().setName(MediaObjectMetadataDescriptor.FIELDNAMES[0]).setType(Type.STRING).build());
    columns.add(builder.clear().setName(MediaObjectMetadataDescriptor.FIELDNAMES[1]).setType(Type.STRING).build());
    columns.add(builder.clear().setName(MediaObjectMetadataDescriptor.FIELDNAMES[2]).setType(Type.STRING).build());
    columns.add(builder.clear().setName(MediaObjectMetadataDescriptor.FIELDNAMES[3]).setType(Type.STRING).build());

    EntityDefinition message = EntityDefinition.newBuilder()
        .setEntity(CottontailMessageBuilder.entity(MediaObjectMetadataDescriptor.ENTITY))
        .addAllColumns(columns).build();

    cottontail.createEntityBlocking(message);

    this.createIndex(MediaObjectMetadataDescriptor.ENTITY, MediaObjectMetadataDescriptor.FIELDNAMES[0], IndexType.HASH);

    return true;
  }

  @Override
  public boolean createSegmentMetadataEntity() {
    ArrayList<ColumnDefinition> columns = new ArrayList<>(4);
    ColumnDefinition.Builder builder = ColumnDefinition.newBuilder();

    columns.add(builder.clear().setName(MediaSegmentMetadataDescriptor.FIELDNAMES[0]).setType(Type.STRING).build());
    columns.add(builder.clear().setName(MediaSegmentMetadataDescriptor.FIELDNAMES[1]).setType(Type.STRING).build());
    columns.add(builder.clear().setName(MediaSegmentMetadataDescriptor.FIELDNAMES[2]).setType(Type.STRING).build());
    columns.add(builder.clear().setName(MediaSegmentMetadataDescriptor.FIELDNAMES[3]).setType(Type.STRING).build());

    EntityDefinition message = EntityDefinition.newBuilder()
        .setEntity(CottontailMessageBuilder.entity(MediaSegmentMetadataDescriptor.ENTITY))
        .addAllColumns(columns).build();

    cottontail.createEntityBlocking(message);
    this.createIndex(MediaSegmentMetadataDescriptor.ENTITY, MediaSegmentMetadataDescriptor.FIELDNAMES[0], IndexType.HASH);
    return true;
  }

  public boolean createIndex(String entityName, String attribute, IndexType type) {
    Entity entity = CottontailMessageBuilder.entity(entityName);
    Index index = Index.newBuilder().setEntity(entity)
            .setName("index-" + type.name().toLowerCase() + "-" + entity.getSchema().getName() + "_" + entity.getName() + "_" + attribute)
        .setType(type).build();
    IndexDefinition idxMessage = IndexDefinition.newBuilder().setIndex(index).addColumns(attribute).build();
    cottontail.createIndexBlocking(idxMessage);
    return true;
  }

  public boolean dropIndex(String entityName, String attribute, IndexType type){
    Entity entity = CottontailMessageBuilder.entity(entityName);
    Index index = Index.newBuilder().setEntity(entity)
        .setName("index-" + type.name().toLowerCase() + "-" + entity.getSchema().getName() + "_" + entity.getName() + "_" + attribute)
        .setType(type).build();
    cottontail.dropIndexBlocking(index);
    return true;
  }

  @Override
  public boolean createSegmentEntity() {
    ArrayList<ColumnDefinition> columns = new ArrayList<>(4);
    ColumnDefinition.Builder builder = ColumnDefinition.newBuilder();

    columns.add(builder.clear().setName(MediaSegmentDescriptor.FIELDNAMES[0]).setType(Type.STRING).build());
    columns.add(builder.clear().setName(MediaSegmentDescriptor.FIELDNAMES[1]).setType(Type.STRING).build());
    columns.add(builder.clear().setName(MediaSegmentDescriptor.FIELDNAMES[2]).setType(Type.INTEGER).build());
    columns.add(builder.clear().setName(MediaSegmentDescriptor.FIELDNAMES[3]).setType(Type.INTEGER).build());
    columns.add(builder.clear().setName(MediaSegmentDescriptor.FIELDNAMES[4]).setType(Type.INTEGER).build());
    columns.add(builder.clear().setName(MediaSegmentDescriptor.FIELDNAMES[5]).setType(Type.DOUBLE).build());
    columns.add(builder.clear().setName(MediaSegmentDescriptor.FIELDNAMES[6]).setType(Type.DOUBLE).build());

    EntityDefinition message = EntityDefinition.newBuilder()
        .setEntity(CottontailMessageBuilder.entity(MediaSegmentDescriptor.ENTITY))
        .addAllColumns(columns).build();

    cottontail.createEntityBlocking(message);

    this.createIndex(MediaSegmentDescriptor.ENTITY, MediaSegmentDescriptor.FIELDNAMES[0], IndexType.HASH_UQ);
    this.createIndex(MediaSegmentDescriptor.ENTITY, MediaSegmentDescriptor.FIELDNAMES[1], IndexType.HASH);

    return true;
  }

  @Override
  public boolean createFeatureEntity(String featureEntityName, boolean unique, int length,
      String... featureNames) {
    final AttributeDefinition[] attributes = Arrays.stream(featureNames)
        .map(s -> new AttributeDefinition(s, VECTOR, length))
        .toArray(AttributeDefinition[]::new);
    return this.createFeatureEntity(featureEntityName, unique, attributes);
  }

  @Override
  public boolean createFeatureEntity(String featureEntityName, boolean unique,
      AttributeDefinition... attributes) {
    final AttributeDefinition[] extended = new AttributeDefinition[attributes.length + 1];
    final HashMap<String, String> hints = new HashMap<>(1);

    extended[0] = new AttributeDefinition(GENERIC_ID_COLUMN_QUALIFIER, AttributeDefinition.AttributeType.STRING, hints);
    System.arraycopy(attributes, 0, extended, 1, attributes.length);
    return this.createEntity(featureEntityName, extended);
  }

  @Override
  public boolean createIdEntity(String entityName, AttributeDefinition... attributes) {
    final AttributeDefinition[] extended = new AttributeDefinition[attributes.length + 1];
    extended[0] = new AttributeDefinition(GENERIC_ID_COLUMN_QUALIFIER, AttributeDefinition.AttributeType.STRING);
    System.arraycopy(attributes, 0, extended, 1, attributes.length);
    return this.createEntity(entityName, extended);
  }

  @Override
  public boolean createEntity(String entityName, AttributeDefinition... attributes) {
    return this.createEntity(
            new org.vitrivr.cineast.core.db.setup.EntityDefinition.EntityDefinitionBuilder(entityName).withAttributes(attributes).build()
    );
  }

  @Override
  public boolean createEntity(org.vitrivr.cineast.core.db.setup.EntityDefinition def) {
    ArrayList<ColumnDefinition> columns = new ArrayList<>();
    ColumnDefinition.Builder builder = ColumnDefinition.newBuilder();
    for (AttributeDefinition attribute : def.getAttributes()) {
      builder.setName(attribute.getName()).setType(mapAttributeType(attribute.getType()));
      if ((attribute.getType() == VECTOR || attribute.getType() == BITSET) && attribute.getLength() > 0) {
        builder.setLength(attribute.getLength());
      }
      columns.add(builder.build());
      builder.clear();
    }
    Entity entity = CottontailMessageBuilder.entity(CottontailMessageBuilder.CINEAST_SCHEMA, def.getEntityName());
    EntityDefinition message = EntityDefinition.newBuilder()
            .setEntity(entity)
            .addAllColumns(columns).build();

    cottontail.createEntityBlocking(message);

    for (AttributeDefinition attribute : def.getAttributes()) {
      if (attribute.getType() == TEXT) {
        this.createIndex(def.getEntityName(), attribute.getName(), IndexType.LUCENE);
      }
      // TODO (LS, 18.11.2020) Shouldn't we also have abstract indices in the db abstraction layer?
      if(attribute.hasHint(INDEX_HINT)){
        IndexType idx = IndexType.valueOf(attribute.getHint(INDEX_HINT).get());
        this.createIndex(def.getEntityName(), attribute.getName(), idx);
      }
    }

    return true;
  }

  @Override
  public boolean createHashNonUniqueIndex(String entityName, String column) {
    return this.createIndex(entityName, column, IndexType.HASH);
  }

  @Override
  public boolean existsEntity(String entityName) {
    return this.cottontail.existsEntity(entityName);
  }

  @Override
  public boolean dropEntity(String entityName) {
    cottontail.dropEntityBlocking(CottontailWrapper.entityByName(entityName));
    return true;
  }

  @Override
  public void close() {
    this.cottontail.close();
  }

  public static final Type mapAttributeType(AttributeDefinition.AttributeType type) {
    switch (type) {

      case BOOLEAN:
        return Type.BOOLEAN;
      case DOUBLE:
        return Type.DOUBLE;
      case VECTOR:
        return Type.FLOAT_VEC;
      case BITSET:
        return Type.BOOL_VEC;
      case FLOAT:
        return Type.FLOAT;
      /*case GEOGRAPHY:
        return Type.GEOGRAPHY;
      case GEOMETRY:
        return Type.GEOMETRY;*/
      case INT:
        return Type.INTEGER;
      case LONG:
        return Type.LONG;
      case STRING:
      case TEXT:
        return Type.STRING;
      default:
        throw new RuntimeException("type " + type + " has no matching analogue in CottontailDB");
    }
  }

}


text:
import { webContents, shell, BrowserWindow } from 'electron'
import * as electronRemote from '@electron/remote/main'
import os from 'os'
import _ from 'lodash'

const isModernDarwin = process.platform === 'darwin' && Number(os.release().split('.')[0]) >= 17

export function stopFileNavigate(id: number) {
  webContents.fromId(id).addListener('will-navigate', (e, url) => {
    if (url.startsWith('file')) {
      e.preventDefault()
    }
  })
}

export function stopNavigateAndHandleNewWindow(id: number) {
  webContents.fromId(id).addListener('will-navigate', (e, url) => {
    e.preventDefault()
    if (url.startsWith('http')) {
      shell.openExternal(url)
    }
  })
  webContents.fromId(id).addListener('new-window', (e, url, frameName, disposition, options) => {
    e.preventDefault()
    if (url.startsWith('http')) {
      shell.openExternal(url)
    } else if (frameName.startsWith('plugin')) {
      options.resizable = true
      options.frame = false
      if (frameName.startsWith('plugin[kangame]')) {
        options.useContentSize = true
        _.set(options, ['webPreferences', 'webSecurity'], false)
      }
      if (frameName.startsWith('plugin[gpuinfo]')) {
        options = {}
        options.backgroundColor = '#FFFFFFFF'
      }
      if (url.startsWith('chrome')) {
        options.frame = true
      }

      options = {
        ...options,
        minWidth: 200,
        minHeight: 200,
        titleBarStyle: isModernDarwin ? 'hidden' : undefined,
        autoHideMenuBar: true,
        webPreferences: {
          ...options.webPreferences,
          nodeIntegration: false,
          nodeIntegrationInWorker: false,
          plugins: true,
          sandbox: false,
          webviewTag: true,
        },
      }
      const win = new BrowserWindow(options)
      if (frameName.startsWith('plugin[gpuinfo]')) {
        win.setBounds({ width: 640, height: 480 })
        win.center()
        win.loadURL('chrome://gpu')
      }
      electronRemote.enable(win.webContents)
      win.webContents.addListener('did-attach-webview', (e, webContent) => {
        electronRemote.enable(webContent)
      })
      e.newGuest = win
    }
  })
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace AudioVisualizer.test
{
    [TestClass]
    public class VisualizationDataFrameTests
    {
        AudioVisualizer.VisualizationDataFrame sut;
        TimeSpan expectedTime = TimeSpan.FromSeconds(1);
        TimeSpan expectedDuration = TimeSpan.FromMilliseconds(100);
        ScalarData expectedPeak = ScalarData.CreateEmpty(2);
        ScalarData expectedRms = ScalarData.CreateEmpty(2);
        SpectrumData expectedSpectrum = SpectrumData.CreateEmpty(2, 20, ScaleType.Linear, ScaleType.Logarithmic, 20, 20000);

        [TestInitialize]
        public void TestInit()
        {
            sut = new VisualizationDataFrame(expectedTime, expectedDuration, expectedRms, expectedPeak, expectedSpectrum);
        }

        [TestMethod]
        [TestCategory("VisualizationDataFrame")]
        public void VisualizationDataFrame_Time()
        {
            Assert.AreEqual(expectedTime, sut.Time);
        }

        [TestMethod]
        [TestCategory("VisualizationDataFrame")]
        public void VisualizationDataFrame_Duration()
        {
            Assert.AreEqual(expectedDuration, sut.Duration);
        }
        [TestMethod]
        [TestCategory("VisualizationDataFrame")]
        public void VisualizationDataFrame_Rms()
        {
            Assert.AreEqual(expectedRms, sut.RMS);
        }
        [TestMethod]
        [TestCategory("VisualizationDataFrame")]
        public void VisualizationDataFrame_Peak()
        {
            Assert.AreEqual(expectedPeak, sut.Peak);
        }
        [TestMethod]
        [TestCategory("VisualizationDataFrame")]
        public void VisualizationDataFrame_Spectrum()
        {
            Assert.AreEqual(expectedSpectrum, sut.Spectrum);
        }
        [TestMethod]
        [TestCategory("VisualizationDataFrame")]
        public void VisualizationDataFrame_PropertiesNotNull()
        {
            Assert.IsNotNull(sut.Properties);
        }
        [TestMethod]
        [TestCategory("VisualizationDataFrame")]
        public void VisualizationDataFrame_PropertiesEmpty()
        {
            Assert.IsFalse(sut.Properties.Any());
        }
    }
}


text:
<phpunit bootstrap="Bootstrap.php" colors="true">
    <testsuite name="LearnZF2Log" >
        <directory>./LearnZF2LogTest</directory>
    </testsuite>
    <filter>
        <whitelist>
            <directory suffix=".php">./../../</directory>
            <exclude>
                <directory suffix=".php">./../</directory>
            </exclude>
        </whitelist>
        <blacklist>
            <directory suffix=".php">./../../../../vendor/</directory>
        </blacklist>
    </filter>
    <logging>
        <log type="coverage-html" target="./../../../../data/test-html-report/learnzf2log/" charset="UTF-8" yui="true" />
        <log type="coverage-php" target="./../../../../build/coverage/coverage-learnzf2log.cov"/>
    </logging>
</phpunit>


text:
package net.stickycode.mockwire.bdd;

import java.util.Collection;
import java.util.List;
import java.util.Set;

import org.mockito.stubbing.Answer;
import org.mockito.stubbing.OngoingStubbing;

/**
 * See original {@link OngoingStubbing}
 */
public interface StickyMockitoMyOngoingStubbing<T> {

    /**
     * See original {@link OngoingStubbing#thenAnswer(Answer)}
     */
    StickyMockitoMyOngoingStubbing<T> willAnswer(Answer<?> answer);

    /**
     * See original {@link OngoingStubbing#thenReturn(Object)}
     */
    StickyMockitoMyOngoingStubbing<T> willReturn(T value);

    /**
     * See original {@link OngoingStubbing#thenReturn(Object, Object...)}
     */
    StickyMockitoMyOngoingStubbing<T> willReturn(T value, T... values);

    /**
     * See original {@link OngoingStubbing#thenThrow(Throwable...)}
     */
    StickyMockitoMyOngoingStubbing<T> willThrow(Throwable... throwables);

    /**
     * See original {@link OngoingStubbing#thenCallRealMethod()}
     */
    StickyMockitoMyOngoingStubbing<T> willCallRealMethod();

}


text:
# Config
API_INTERFACE = 'legendsockssr' #mudbjson, sspanelv2, sspanelv3, sspanelv3ssr, glzjinmod, legendsockssr, muapiv2(not support)
UPDATE_TIME = 15
SERVER_PUB_ADDR = '127.0.0.1' # mujson_mgr need this to generate ssr link

#mudb
MUDB_FILE = 'mudb.json'

# Mysql
MYSQL_CONFIG = 'rixcloud.json'

# API
MUAPI_CONFIG = 'usermuapi.json'


text:
/*
 * Copyright (c) 2004 - Michael Richardson <mcr@xelerance.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that: (1) source code distributions
 * retain the above copyright notice and this paragraph in its entirety, (2)
 * distributions including binary code include the above copyright notice and
 * this paragraph in its entirety in the documentation or other materials
 * provided with the distribution, and (3) all advertising materials mentioning


text:
module FactoryWoman
  VERSION = '0.1.0'
end


text:
package org.apache.commons.validator;

/**
 * Value object that contains different fields to test type conversion
 * validation.
 *
 */
public class TypeBean {

    private String sByte = null;
    private String sShort = null;
    private String sInteger = null;
    private String sLong = null;
    private String sFloat = null;
    private String sDouble = null;
    private String sDate = null;
    private String sCreditCard = null;

    public String getByte() {
        return sByte;
    }

    public void setByte(final String sByte) {
        this.sByte = sByte;
    }

    public String getShort() {
        return sShort;
    }

    public void setShort(final String sShort) {
        this.sShort = sShort;
    }

    public String getInteger() {
        return sInteger;
    }

    public void setInteger(final String sInteger) {
        this.sInteger = sInteger;
    }

    public String getLong() {
        return sLong;
    }

    public void setLong(final String sLong) {
        this.sLong = sLong;
    }

    public String getFloat() {
        return sFloat;
    }

    public void setFloat(final String sFloat) {
        this.sFloat = sFloat;
    }

    public String getDouble() {
        return sDouble;
    }

    public void setDouble(final String sDouble) {
        this.sDouble = sDouble;
    }

    public String getDate() {
        return sDate;
    }

    public void setDate(final String sDate) {
        this.sDate = sDate;
    }

    public String getCreditCard() {
        return sCreditCard;
    }

    public void setCreditCard(final String sCreditCard) {
        this.sCreditCard = sCreditCard;
    }

}


text:
<preference-headers
        xmlns:android="http://schemas.android.com/apk/res/android">

    <header android:fragment="it.openlab.studentassistant.NewActivity$GeneralFragment"
            android:title="@string/General"
            android:summary="@string/GeneralDesc" />

    <header android:fragment="it.openlab.studentassistant.NewActivity$SlidesFragment"
            android:title="@string/Slides"
            android:summary="@string/SlidesDesc" />

    <header android:fragment="it.openlab.studentassistant.NewActivity$NotesFragment"
            android:title="@string/Notes"
            android:summary="@string/NotesDesc" />

    <header android:fragment="it.openlab.studentassistant.NewActivity$TextbookFragment"
            android:title="@string/Textbook"
            android:summary="@string/TextbookDesc" />

    <header android:fragment="it.openlab.studentassistant.NewActivity$ExercisesFragment"
            android:title="@string/Exercises"
            android:summary="@string/ExercisesDesc" />

</preference-headers>


text:
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation.  All rights reserved.
//
// File: IAcceptInsertion.cs
//
//---------------------------------------------------------------------------

namespace MS.Internal.Documents
{
    /// <summary>
    /// This interface should be implemented by <see cref="System.Windows.Documents.Table"/> related types
    /// which can hold collection of other Table related objects.
    /// to provide insertion index where item will be inserted.
    /// Refer to <see cref="IIndexedChild<TParent>"/> for additional information.
    /// For an example of usage see <see cref="TableTextElementCollectionInternal"/>
    /// </summary>
    internal interface IAcceptInsertion
    {
        /// <summary>
        /// Provides value for the index where new item will be inserted.
        /// </summary>
        int InsertionIndex
        { get; set; }
    }
}


text:
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================

#ifndef SEQAN_HEADER_TEST_FIND_SWIFT_H
#define SEQAN_HEADER_TEST_FIND_SWIFT_H

#include <seqan/basic.h>
#include <seqan/index.h>
#include <seqan/seeds2.h>

#include "../../apps/stellar/stellar.h"

using namespace seqan;

// calls local swift and compares swift hits to expected swift hits
template<typename THaystack, typename TIndex>
void testLocalSwift(Finder<THaystack, Swift<SwiftLocal> > & finder,
					Pattern<TIndex, Swift<SwiftLocal> > & pattern,
					double epsilon,
					int minLength,
                    String<String<char> > & expectedPositions) {
	typedef typename Position<String<String<char> > >::Type TPosition;
	TPosition i = 0;
	while (find(finder, pattern, epsilon, minLength)) {
        // write swift hit into string and compare to expected output
        std::ostringstream pos;
		pos << "< " << positionRange(finder) << " , " << positionRange(pattern) << " >";
		SEQAN_ASSERT_EQ(pos.str().c_str(), value(expectedPositions,i));
		++i;
	}
}

void testOneLocalSwiftHit() {
	// a single pattern and a single hit
    typedef Finder<DnaString, Swift<SwiftLocal> > TFinder;
	DnaString text = "aaaaaaacgatcgatgcaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
	TFinder finder_swift(text);

    typedef Index<DnaString, IndexQGram<UngappedShape<4> > > TQGramIndexSimple;
	TQGramIndexSimple index_4gram("tttcgatcgatgctttttttttttttttttttttttttttttt");
    Pattern<TQGramIndexSimple, Swift<SwiftLocal> > pattern_swift(index_4gram);

    String<String<char> > expectedPositions;
    appendValue(expectedPositions, "< < 7 , 17 > , < 0 , 17 > >");

	testLocalSwift(finder_swift, pattern_swift, 0.1, 6, expectedPositions);
}

void testOneLocalSwiftHit2() {
    // a single pattern and a single hit 2
    typedef Finder<DnaString, Swift<SwiftLocal> > TFinder;
	DnaString text = "aaaaagagaccccccagagaaaaaa";
	TFinder finder_swift(text);

    typedef Index<DnaString, IndexQGram<UngappedShape<4> > > TQGramIndexSimple;
	TQGramIndexSimple index_4gram("tttttggccccccggtttttt");
    Pattern<TQGramIndexSimple, Swift<SwiftLocal> > pattern_swift(index_4gram);

    String<String<char> > expectedPositions;
    appendValue(expectedPositions, "< < 9 , 15 > , < 0 , 15 > >");

	testLocalSwift(finder_swift, pattern_swift, 0.1, 6, expectedPositions);
}

void testOneLocalSwiftHitStringSet() {
	// a single hit, pattern in a StringSet
    typedef Finder<DnaString, Swift<SwiftLocal> > TFinder;
	DnaString text = "aaaaaaacgatcgatgcaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
	TFinder finder_swift(text);

	typedef Index<StringSet<DnaString>, IndexQGram< UngappedShape<4> > > TQGramIndex;
	TQGramIndex index_4gram;
	appendValue(indexText(index_4gram), "tttcgatcgatgctttttttttttttttttttttttttttttt");
    Pattern<TQGramIndex, Swift<SwiftLocal> > pattern_swift(index_4gram);

    String<String<char> > expectedPositions;
    appendValue(expectedPositions, "< < 7 , 17 > , < < 0 , 0 > , < 0 , 17 > > >");

	testLocalSwift(finder_swift, pattern_swift, 0.1, 6, expectedPositions);
}

void testOneLocalSwiftHitBucketBorder() {
	// hit at bucket border
    typedef Finder<DnaString, Swift<SwiftLocal> > TFinder;
	DnaString text = "aaacgatcgatgcaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
	TFinder finder_swift(text);

	typedef Index<StringSet<DnaString>, IndexQGram< UngappedShape<4> > > TQGramIndex;
	TQGramIndex index_4gram;
	appendValue(indexText(index_4gram), "tttcgatcgatgctttttttttttttttttttttttttttttt");
    Pattern<TQGramIndex, Swift<SwiftLocal> > pattern_swift(index_4gram);

    String<String<char> > expectedPositions;
    appendValue(expectedPositions, "< < 3 , 13 > , < < 0 , 0 > , < 0 , 13 > > >");
    appendValue(expectedPositions, "< < 3 , 13 > , < < 0 , 2 > , < 0 , 29 > > >");

	testLocalSwift(finder_swift, pattern_swift, 0.1, 6, expectedPositions);
}

void testOneLocalSwiftHitNegDiag() {

	// hit at lower haystack position -> diagonal start position negative
    typedef Finder<DnaString, Swift<SwiftLocal> > TFinder;
	DnaString text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacgatcgatgc";
	TFinder finder_swift(text);

	typedef Index<StringSet<DnaString>, IndexQGram< UngappedShape<4> > > TQGramIndex;
	TQGramIndex index_4gram;
	appendValue(indexText(index_4gram), "ttttcgatcgatgctttttttttttttttttttttttttttttt");
    Pattern<TQGramIndex, Swift<SwiftLocal> > pattern_swift(index_4gram);

    String<String<char> > expectedPositions;
    appendValue(expectedPositions, "< < 36 , 46 > , < < 0 , 0 > , < 0 , 14 > > >");
    appendValue(expectedPositions, "< < 36 , 46 > , < < 0 , 3 > , < 0 , 30 > > >");

	testLocalSwift(finder_swift, pattern_swift, 0.1, 10, expectedPositions);
}

void testLocalSwiftTwoPatterns() {
	// two pattern sequences
    typedef Finder<DnaString, Swift<SwiftLocal> > TFinder;
    DnaString text = "aaaacgttccaaaaaaa";
	TFinder finder_swift(text);

	typedef Index<StringSet<DnaString>, IndexQGram< UngappedShape<4> > > TQGramIndex;
	TQGramIndex index_4gram;
	appendValue(indexText(index_4gram), "ttttcgttcctttttttttttttttttttttt"); // length = 32
    appendValue(indexText(index_4gram), "ttcgttcctt"); // length = 10
	Pattern<TQGramIndex, Swift<SwiftLocal> > pattern_swift(index_4gram);

    String<String<char> > expectedPositions;
    appendValue(expectedPositions, "< < 4 , 10 > , < < 0 , 0 > , < 0 , 10 > > >");
    appendValue(expectedPositions, "< < 4 , 10 > , < < 0 , 3 > , < 0 , 26 > > >");
    appendValue(expectedPositions, "< < 4 , 10 > , < < 1 , 0 > , < 1 , 10 > > >");

	testLocalSwift(finder_swift, pattern_swift, 0.1, 6, expectedPositions);
}

void testLocalSwiftLongPatterns() {

	// two longer pattern sequences
    typedef Finder<DnaString, Swift<SwiftLocal> > TFinder;
	DnaString text = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaacgatcagtgacaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
	TFinder finder_swift(text);

	typedef Index<StringSet<DnaString>, IndexQGram< UngappedShape<4> > > TQGramIndex;
	TQGramIndex index_4gram;
	appendValue(indexText(index_4gram), "ttttttttttttttcgatcagtgacttttttttttttttttttttttttttttttttatcagt"); // length = 63
    appendValue(indexText(index_4gram), "ttttttttttttttcgatcagtgacttttttttttttttttttttttttttttttttatcagt"); // length = 63
	Pattern<TQGramIndex, Swift<SwiftLocal> > pattern_swift(index_4gram);

    String<String<char> > expectedPositions;
    appendValue(expectedPositions, "< < 88 , 99 > , < < 0 , 7 > , < 0 , 35 > > >");
    appendValue(expectedPositions, "< < 88 , 99 > , < < 1 , 7 > , < 1 , 35 > > >");
    appendValue(expectedPositions, "< < 90 , 96 > , < < 0 , 41 > , < 0 , 63 > > >");
    appendValue(expectedPositions, "< < 90 , 96 > , < < 1 , 41 > , < 1 , 63 > > >");

	testLocalSwift(finder_swift, pattern_swift, 0.1, 6, expectedPositions);
}

SEQAN_DEFINE_TEST(test_find_swift) {
    testOneLocalSwiftHit();
    testOneLocalSwiftHit2();
    testOneLocalSwiftHitStringSet();
    testOneLocalSwiftHitBucketBorder();
    testOneLocalSwiftHitNegDiag();
    testLocalSwiftTwoPatterns();
    testLocalSwiftLongPatterns();
}

template<typename TString>
Align<TString>
testLongestEpsMatch(TString const & seq1, TString const & seq2) {
    Align<TString> alignment;
    resize(rows(alignment), 2);
    assignSource(row(alignment, 0), seq1);
    assignSource(row(alignment, 1), seq2);

    Score<int> score(1, -1, -1);
    globalAlignment(alignment, score);

    longestEpsMatch(alignment, 6, 0.125);

    return alignment;
}

SEQAN_DEFINE_TEST(test_longest_epsMatch) {
    DnaString seq1 = "ACCTTTGCCCCCCCCCCTAAAAAAAATTAAAA";
    DnaString seq2 = "ACGTTTACCCCCCCCCCGAAAAAAAAGAAAA";
    Align<DnaString> alignment = testLongestEpsMatch(seq1, seq2);
    SEQAN_ASSERT(row(alignment, 0) == "ACCTTTGCCCCCCCCCCTAAAAAAAA");
    SEQAN_ASSERT(row(alignment, 1) == "ACGTTTACCCCCCCCCCGAAAAAAAA");

    seq1 = "ACCTTTGCCCCCCCCCCTAAAAAAAATTAAAA";
    seq2 = "ACGTTTCCCCCCCCCCGAAAAAAAAGAAAA";
    alignment = testLongestEpsMatch(seq1, seq2);
    SEQAN_ASSERT(row(alignment, 0) == "ACCTTTGCCCCCCCCCCTAAAAAAAA");
    SEQAN_ASSERT(row(alignment, 1) == "ACGTTT-CCCCCCCCCCGAAAAAAAA");

    seq1 = "AAAATTAAAAAAAATCCCCCCCCCCGTTTCCA";
    seq2 = "AAAAGAAAAAAAAGCCCCCCCCCCTTTGCA";
    alignment = testLongestEpsMatch(seq1, seq2);
    SEQAN_ASSERT(row(alignment, 0) == "AAAAAAAATCCCCCCCCCCGTTTCCA");
    SEQAN_ASSERT(row(alignment, 1) == "AAAAAAAAGCCCCCCCCCC-TTTGCA");
}

template<typename TString, typename TScore, typename TAliString, typename TScoreValue>
void testXDropAlign(TString const & seq1, TString const & seq2, TScore scoring, TScoreValue scoreDropOff, TScoreValue minScore, TAliString & aliString) {
    Align<TString> align;
    resize(rows(align), 2);
    assignSource(row(align, 0), seq1);
    assignSource(row(align, 1), seq2);

    globalAlignment(align, scoring);
    //std::cout << align << std::endl;

    _splitAtXDrops(align, scoring, scoreDropOff, minScore, aliString);
}

SEQAN_DEFINE_TEST(test_split_xDrop_align) {
    Score<int> scoring(2,-1,-2);

    DnaString seq1 = "cgataagctcttggacta";
    DnaString seq2 = "cgataatatggactagg";
    String<Align<DnaString> > aliString;
    testXDropAlign(seq1, seq2, scoring, 3/*scoreDropOff*/, 10/*minScore*/, aliString);
    SEQAN_ASSERT_EQ(length(aliString), 2u);
    SEQAN_ASSERT(row(value(aliString, 0), 0) == "cgataa");
    SEQAN_ASSERT(row(value(aliString, 0), 1) == "cgataa");
    SEQAN_ASSERT(row(value(aliString, 1), 0) == "tggacta");
    SEQAN_ASSERT(row(value(aliString, 1), 1) == "tggacta");

    seq1 = "cgataagctcttggacta";
    seq2 = "cgataatatggactagggg";
    clear(aliString);
    testXDropAlign(seq1, seq2, scoring, 3/*scoreDropOff*/, 14/*minScore*/, aliString);
    SEQAN_ASSERT_EQ(length(aliString), 1u);
    SEQAN_ASSERT(row(value(aliString, 0), 0) == "tggacta");
    SEQAN_ASSERT(row(value(aliString, 0), 1) == "tggacta");

    seq1 = "cgataagctcagttggacta";
    seq2 = "cgataatcactggactagggg";
    clear(aliString);
    testXDropAlign(seq1, seq2, scoring, 2/*scoreDropOff*/, 6/*minScore*/, aliString);
    SEQAN_ASSERT_EQ(length(aliString), 3u);
    SEQAN_ASSERT(row(value(aliString, 0), 0) == "cgataa");
    SEQAN_ASSERT(row(value(aliString, 0), 1) == "cgataa");
    SEQAN_ASSERT(row(value(aliString, 1), 0) == "tca");
    SEQAN_ASSERT(row(value(aliString, 1), 1) == "tca");
    SEQAN_ASSERT(row(value(aliString, 2), 0) == "tggacta");
    SEQAN_ASSERT(row(value(aliString, 2), 1) == "tggacta");

    clear(aliString);
    testXDropAlign(seq1, seq2, scoring, 3/*scoreDropOff*/, 6/*minScore*/, aliString);
    SEQAN_ASSERT_EQ(length(aliString), 2u);
    SEQAN_ASSERT(row(value(aliString, 0), 0) == "cgataa");
    SEQAN_ASSERT(row(value(aliString, 0), 1) == "cgataa");
    SEQAN_ASSERT(row(value(aliString, 1), 0) == "tcagttggacta");
    SEQAN_ASSERT(row(value(aliString, 1), 1) == "tca-ctggacta");

    seq1 = "aaaaaa";
    seq2 = "ccaaaaaa";
    clear(aliString);
    testXDropAlign(seq1, seq2, scoring, 3/*scoreDropOff*/, 12/*minScore*/, aliString);
    SEQAN_ASSERT_EQ(length(aliString), 1u);
    SEQAN_ASSERT(row(value(aliString, 0), 0) == "aaaaaa");
    SEQAN_ASSERT(row(value(aliString, 0), 1) == "aaaaaa");

    seq1 = "aaaaaa";
    seq2 = "aaaaaa";
    clear(aliString);
    testXDropAlign(seq1, seq2, scoring, 3/*scoreDropOff*/, 12/*minScore*/, aliString);
    SEQAN_ASSERT_EQ(length(aliString), 1u);
    SEQAN_ASSERT(row(value(aliString, 0), 0) == "aaaaaa");
    SEQAN_ASSERT(row(value(aliString, 0), 1) == "aaaaaa");

    seq1 = "CCCCAGGGGGGACAAAAAAGAAACCCAGGGGGGACCCAGGG";
    seq2 = "CCCCTGGGGGGTCTTTTTGTCCCTGGGGGGTCCCTGGG";
    clear(aliString);
    testXDropAlign(seq1, seq2, Score<int>(1, -1, -1), 3/*scoreDropOff*/, 7/*minScore*/, aliString);
    SEQAN_ASSERT_EQ(length(aliString), 2u);

    seq1 = "GCTGTAGCTGGAG";
    seq2 = "GCTGTAGCTGGAG";
    clear(aliString);
    testXDropAlign(seq1, seq2, Score<int>(1, -9, -9), 5/*scoreDropOff*/, 7/*minScore*/, aliString);
    SEQAN_ASSERT_EQ(length(aliString), 1u);
}

SEQAN_BEGIN_TESTSUITE(test_find_swift) {
    SEQAN_CALL_TEST(test_find_swift);
    SEQAN_CALL_TEST(test_longest_epsMatch);
    SEQAN_CALL_TEST(test_split_xDrop_align);

    //SEQAN_VERIFY_CHECKPOINTS("core/include/seqan/index/find_swift.h");
    // SEQAN_VERIFY_CHECKPOINTS("projects/library/apps/stellar/stellar.h");
}
SEQAN_END_TESTSUITE

#endif


text:
module Spree
  class CashOnDelivery::PaymentMethod < Spree::PaymentMethod
    def payment_profiles_supported?
      true # we want to show the confirm step.
    end

    def provider_class
      self.class
    end

    def payment_source_class
      Spree::CashOnDelivery::Transaction
    end

    def method_type
      'cash_on_delivery'
    end
  end
end


text:
package rodzillaa.github.io.rodzilla.controller;

import android.os.Bundle;

import rodzillaa.github.io.rodzilla.R;
import rodzillaa.github.io.rodzilla.model.RatSightingDatabase;

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

/**
 * Activity to display recent rat sightings.
 */
public class RecentRatSightingsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recentratsightings);
        RecyclerView mRecyclerView;
        RecyclerView.Adapter mRecyclerViewAdapter;
        RecyclerView.LayoutManager mRecyclerViewLayoutManager;
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mRecyclerViewLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mRecyclerViewLayoutManager);
        mRecyclerViewAdapter = new RecyclerViewAdapter(RatSightingDatabase.getRatSightings(),
                mRecyclerView, getBaseContext());
        mRecyclerView.setAdapter(mRecyclerViewAdapter);

    }
}


text:
* Initial release

## v0.2.1
* Use a c++ function for counting lines instead of bash `wc`
* Corrects bug in `lassosum.pipeline()` when calling some functions in `data.table`

## v0.2.2
* includes some additional objects in the output of `validate.lassosum.pipeline()` and `pseudovalidate.lassosum.pipeline()`
* Allows the `validate.function` in `validate.lassosum.pipeline()` to be given as a character rather than a function.

## v0.2.3
* `best.beta` is output in `validate.lassosum.pipeline()` and `pseudovalidate.lassosum.pipeline()`
* fixes bug when grouping blocks that are too small

## v0.2.4
* fixes bug when matching variable names in `matchpos()`
* Support for parallel processing in the `pgs()` function, (and therefore `validate.lassosum.pipeline()` and `pseudovalidate.lassosum.pipeline()`)
* Allows summary statistics to be matched by SNP id as well as chromosome/position
* fixes bug when the `bfile` is too large (due to integer overflow in c++)
* adds a user-defined limit to the size of the bfile to discourage the use of large reference panels
* cpp functions are now exported (except `openPlinkBinaryFile()`)
* includes this changelog file
* fixes bug in plotting results from `validate.lassosum.pipeline()` and `pseudovalidate.lassosum.pipeline()`
* fixes bug in displaying "Running lassosum with s=1..." message.
* renames hg19 LD region files
* adds hg38 LD region files (lifted over from the hg19 ones)

## v0.2.5
* Bug fix for `lassosum.pipeline()` in parsing LDblocks when given as a vector of factors
* Bug fix for `pgs()` when `extract` is specified

## v0.3.0
* Adds function for cross-prediction [link]()
* Allows multiple bfiles in many functions

## v0.3.1
* Adds `cp.meta()` for meta-analysing external summary statistics with results from `cp.plink.linear()`
* `cp.plink.linear()` will weight correlation by sample size when averaging across folds
* A number of unrelated functions are now hidden.
* Improved documentation for `cp` functions

## v0.3.2
* fixes bug in cp.plink.linear covar option
* fixes bug when specifying keep
* adds `write.table2()`

## v0.4.0
* Removes support for cross-prediction.
* Cross-prediction moved to a separate package
* recast `validate.lassosum.pipeline()`, `pseudovalidate.lassosum.pipeline()`, and `pgs` as S3 methods
* Adds option for including covariates in `validate.lassosum.pipelin()`
* bug fix in `matchpos()`
* Introduces c++ function for `pgs()` with sparse matrix. Used as default.
* `p2cor()` will automatically code to NA those correlations with relatively small n.
* Always uses `data.table::fread()` for reading files

## v0.4.1
* Bug fix for `matchpos()`
* `pgs()` stops if keep or extract not in the same order as in .bim/.fam file

## v0.4.2
* Allows `covar` and `pheno` to take `data.frame`s or files as input.
* You no longer have to re-enter `test.bfile` if `keep` or `remove` is used in `validate.lassosum.pipeline()` or `pseudovalidate.lassosum.pipeline()`
* Adds `splitvalidate()` for split-validation.
* Adds `subset.lassosum.pipeline()` for applying validated PGS to new data.
* Allows `pheno` to be constant or NA if only one PGS is calculated in `validate.lassosum.pipeline()`.
* `plot.validate.lassosum()` will abandon if there are no finite values.
* **A standalone version of lassosum is available**

## v0.4.3
* LDblocks does not need to be specified when s < 1
* Better tracing in SD calculation
* Bug fix in `validate.lassosum.pipeline()`
* Allows multiple `test.bfile` in `validate.lassosum.pipeline()`

## v0.4.4
* Bug fix
* Better documentation for Mac users

## v0.4.5
* [Bug fix] standalone version used to ignore --nthreads option when running `validate.lassosum.pipeline`
* [Bug fix] The `pheno` and `covar` option didn't use to like `data.table` and required `data.frame`
* [Bug fix] Pull request #20
* Adds seed option in standalone version


text:
package org.switchyard.component.common.knowledge.config.model;

import java.util.List;

import org.switchyard.config.model.Model;

/**
 * A ExtraJaxbClasses Model.
 *
 * @author David Ward <dward@jboss.org> © 2014 Red Hat Inc.
 */
public interface ExtraJaxbClassesModel extends Model {

    /** The "extraJaxbClasses" name. */
    public static final String EXTRA_JAXB_CLASSES = "extraJaxbClasses";

    /**
     * Gets the child extraJaxbClass models.
     * @return the child extraJaxbClass models
     */
    public List<ExtraJaxbClassModel> getExtraJaxbClasses();

    /**
     * Adds a child extraJaxbClass model.
     * @param extraJaxbClass the child extraJaxbClass model
     * @return this ExtraJaxbClassesModel (useful for chaining)
     */
    public ExtraJaxbClassesModel addExtraJaxbClass(ExtraJaxbClassModel extraJaxbClass);

}


text:
package com.bankonet.exceptions;

public class DebitException extends CompteException {

	public DebitException() {
		// TODO Auto-generated constructor stub
	}

	public DebitException(String message) {
		super(message);
		// TODO Auto-generated constructor stub
	}

	public DebitException(Throwable cause) {
		super(cause);
		// TODO Auto-generated constructor stub
	}

	public DebitException(String message, Throwable cause) {
		super(message, cause);
		// TODO Auto-generated constructor stub
	}

	public DebitException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
		// TODO Auto-generated constructor stub
	}

}


text:
<?php

class NewProjectsButton {
	static function OnCategoryTableAddToCategory(&$buttonConfig, $output, $categoryName) {
        ## Add the Javascript module.
		$output->addModules(array(
            'ext.project-structure'
        ));

        $allProjectsPage = Title::newFromText(
            wfMsg("all-projects-page"),
            NS_CATEGORY
        )->getFullText();

        if ($categoryName == $allProjectsPage) {

            ## Change the text
            $buttonConfig["label"] = wfMsg('new-project');
        }

        return true;
    }
}

?>


text:
import Vue from 'vue'
import Vuex from 'vuex'
import components from 'views/components/module'
import vuex from 'views/vuex/module'
import events from 'views/events/module'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    message: '',
    tab: 'components'
  },
  mutations: {
    SHOW_MESSAGE (state, message) {
      state.message = message
    },
    SWITCH_TAB (state, tab) {
      state.tab = tab
    },
    RECEIVE_INSTANCE_DETAILS (state, instance) {
      state.message = 'Instance selected: ' + instance.name
    }
  },
  modules: {
    components,
    vuex,
    events
  }
})

export default store

if (module.hot) {
  module.hot.accept([
    'views/components/module',
    'views/vuex/module',
    'views/events/module'
  ], () => {
    try {
      store.hotUpdate({
        modules: {
          components: require('views/components/module').default,
          vuex: require('views/vuex/module').default,
          events: require('views/events/module').default
        }
      })
    } catch (e) {
      console.log(e.stack)
    }
  })
}


text:
"""
a plugin for sending metrics to InfluxDB
"""

import logging
import sys
from time import strftime, gmtime

try:
    from influxdb import InfluxDBClient as InfluxDBClientConnector
except ImportError, e:
    print("You need to install influxdb")
    sys.exit(1)

import libsolace
from libsolace.plugin import Plugin
from libsolace.util import get_key_from_settings

__doc__ = """
Simple influxdb client that can send metrics to influx.

.. code-block:: none

    PLUGINS:
        ...
        - libsolace.plugins.InfluxDBClient
        ...

    INFLUXDB_HOST: localhost
    INFLUXDB_PORT: 8086
    INFLUXDB_USER: user
    INFLUXDB_PASS: pass
    INFLUXDB_DB: solace

"""

def get_time():
    """ consistent time formatting

    :return: time
    """
    return strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())

def flatten_json(y):
    """
    flattens a json object combining key names to be {parent-child-leaf: value}

    :param y:
    :return:
    """
    out = {}

    def flatten(x, name=''):
        if type(x) is dict:
            for a in x:
                flatten(x[a], name + a + '_')
        else:
            try:
                out[str(name[:-1])] = long(x)
            except Exception, e:
                pass

    flatten(y)
    return out

@libsolace.plugin_registry.register
class InfluxDBClient(Plugin):
    """
    Simple influxdb client plugin for libsolace

    Example:

    .. doctest::
        :options: +SKIP

        >>> import libsolace.settingsloader as settings
        >>> import libsolace
        >>> metrics_class = libsolace.plugin_registry('InfluxDBClient', settings=settings)
        >>> metrics = metrics_class(settings=settings)

    """
    plugin_name = "InfluxDBClient"

    def __init__(self, settings=None, **kwargs):
        logging.debug("Configuring with settings: %s" % settings)
        self.settings = settings.__dict__  # type: dict
        self.influxdb_host = get_key_from_settings("INFLUXDB_HOST", self.settings, default="defiant")
        self.influxdb_port = get_key_from_settings("INFLUXDB_PORT", self.settings, default=8086)
        self.influxdb_user = get_key_from_settings("INFLUXDB_USER", self.settings, default="root")
        self.influxdb_pass = get_key_from_settings("INFLUXDB_PASS", self.settings, default="root")
        self.influxdb_db = get_key_from_settings("INFLUXDB_DB", self.settings, default="solace")

        # connect
        self.client = InfluxDBClientConnector(self.influxdb_host,
                                     self.influxdb_port,
                                     self.influxdb_user,
                                     self.influxdb_pass,
                                     self.influxdb_db)

    def send(self, measurement, data, **tags):
        """
        Sends the metrics to influxdb.

        Examples:

        .. doctest::
            :options: +SKIP

            >>> import libsolace.settingsloader as settings
            >>> import libsolace
            >>> metrics_class = libsolace.plugin_registry('InfluxDBClient', settings=settings)
            >>> metrics = metrics_class(settings=settings)
            >>> metrics.send('http-metrics', {"key": 10, "key2": 12}, environment='prod', host='foo')
            >>> metrics.send("test", {"key": 2}, host="test")

        :param data: a json object of keys and values. will be flattened!
        :param measurement:
        """

        json_body = [{
            "measurement": measurement,
            "tags": {},
            "time": get_time(),
            "fields": flatten_json(data)
        }]

        for tag in tags:
            json_body[0]['tags'][tag] = tags[tag]

        try:
            self.client.write_points(json_body)
        except Exception, e:
            logging.error(e.message)
            logging.error("Unable to write to influxdb")


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using SQMImportExport.Common;

namespace SQMReorderer.Gui.ViewModels.ArmA3
{
    public class GroupViewModel : IGroupViewModel
    {
        public GroupViewModel()
        {
            Vehicles = new ObservableCollection<VehicleViewModelBase>();
        }

        public string Name { get; set; }
        public VehicleBase ConnectedVehicle { get; set; }

        public ObservableCollection<VehicleViewModelBase> Vehicles { get; set; }

        public List<Type> ChildTypes
        {
            get
            {
                return new List<Type>
                    {
                        typeof (VehicleViewModelBase)
                    };
            }
        }
    }
}


text:
package com.insurancetelematics.team.projectl.images.gallery.cards.photos;

public class PhotoPresenter {
    private final PhotoView view;

    public PhotoPresenter(PhotoView view) {
        this.view = view;
    }

    public void fillWith(Photo photo) {
        view.showImage(photo.getImageUrl());
    }

    public void onPhotoPressed(Photo photo) {
        // TODO: 2/11/16 launch details activity with animations
    }
}


text:
namespace Stripe
{
    using Newtonsoft.Json;

    public class PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressIban : StripeEntity<PaymentIntentNextActionDisplayBankTransferInstructionsFinancialAddressIban>
    {
        ///
        /// The name of the person or business that owns the bank account.
        ///
        [JsonProperty("account_holder_name")]
        public string AccountHolderName { get; set; }

        ///
        /// The BIC/SWIFT code of the account.
        ///
        [JsonProperty("bic")]
        public string Bic { get; set; }

        ///
        /// Two-letter country code (ISO
        /// 3166-1 alpha-2).
        ///
        [JsonProperty("country")]
        public string Country { get; set; }

        ///
        /// The IBAN of the account.
        ///
        [JsonProperty("iban")]
        public string Iban { get; set; }
    }
}


text:
DataEcosystem
=============

A schema for Chicago's data ecosystem


text:
package org.opencds.cqf.ruler.behavior;

import ca.uhn.fhir.context.FhirContext;

public interface FhirContextUser {
	FhirContext getFhirContext();
}


text:
'''
Execution module to provide logging
==========================
:maintainer: Joe Julian <me@joejulian.name>
:maturity: new
:platform: Linux
.. versionadded:: 2014.7.0
'''

__virtualname__ = 'logger'

import logging as log
from pprint import pformat
import json
import yaml

def pretty(var):
    return pformat(yaml.load(json.dumps(var)))

def __virtual__():
    return __virtualname__

def debug(var, string = ""):
    '''
    Print a var to a debug output.
    '''
    ret = string + pretty(var)
    log.debug(ret)
    return ret

def info(var, string = ""):
    '''
    Print a var to a info output.
    '''
    ret = string + pretty(var)
    log.info(ret)
    return ret

def warning(var, string = ""):
    '''
    Print a var to a warning output.
    '''
    ret = string + pretty(var)
    log.warning(ret)
    return ret

def error(var, string = ""):
    '''
    Print a var to a error output.
    '''
    ret = string + pretty(var)
    log.error(ret)
    return ret

def critical(var, string = ""):
    '''
    Print a var to a critical output.
    '''
    ret = string + pretty(var)
    log.critical(ret)
    return ret


text:
clj-typesafe-config
===================

A thin clojure wrapper around the Typesafe Config library.