text:
'use strict';

angular.module('users').controller('PasswordController', ['$scope', '$filter', '$stateParams', '$http', '$location', 'Authentication', 'PasswordValidator',
  function ($scope, $filter, $stateParams, $http, $location, Authentication, PasswordValidator) {
    var $translate = $filter('translate');
    $scope.authentication = Authentication;
    $scope.popoverMsg = PasswordValidator.getPopoverMsg();

    //If user is signed in then redirect back home
    if ($scope.authentication.user) {
      $location.path('/');
    }

    // Submit forgotten password account id
    $scope.askForPasswordReset = function (isValid) {
      $scope.success = $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'forgotPasswordForm');

        return false;
      }

      $scope.credentials.username = $scope.credentials.email;
      $http.post('/api/auth/forgot', $scope.credentials).success(function (response) {
        // Show user success message and clear form
        $scope.credentials = null;
        $scope.success = response.message;

      }).error(function (response) {
        // Show user error message and clear form
        $scope.credentials = null;
        // Translate some special errors
        if (response.message.indexOf('No account with that username has been found') !== -1) {
          $scope.error = $translate('FORGOT_PASSWORD_EMAIL_NOT_FOUND');
        } else if (response.message.indexOf('Failure sending email') !== -1) {
          $scope.error = $translate('FORGOT_PASSWORD_EMAIL_SEND_FAIL');
        } else if (response.message.indexOf('An email has been sent to the provided email with further instructions.') !== -1) {
          $scope.error = $translate('FORGOT_PASSWORD_EMAIL_SEND_SUCCESS');
        } else {
          $scope.error = response.message;
        }
      });
    };

    // Change user password
    $scope.resetUserPassword = function (isValid) {
      $scope.success = $scope.error = null;

      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'resetPasswordForm');

        return false;
      }

      $http.post('/api/auth/reset/' + $stateParams.token, $scope.passwordDetails).success(function (response) {
        // If successful show success message and clear form
        $scope.passwordDetails = null;

        // Attach user profile
        Authentication.user = response;

        // And redirect to the index page
        $location.path('/password/reset/success');
      }).error(function (response) {
        $scope.error = response.message;
      });
    };
  }
]);


text:
	Licensed to the Apache Software Foundation (ASF) under one or more
	contributor license agreements. See the NOTICE file distributed with
	this work for additional information regarding copyright ownership.
	The ASF licenses this file to You under the Apache License, Version 2.0
	(the "License"); you may not use this file except in compliance with
	the License. You may obtain a copy of the License at

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

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.

----------------------------------------------------------------------------

# BigTop Bare-metal Provisioner

## Overview

This vagrant recipe is based on the vagrant recipe from `vagrant-puppet-vm` with added feature of vagrant-managed-servers plugin. The plugin allows us to deploy a Hadoop cluster on an actual baremetal servers.

The Vagrantfile creates a BigTop Bare-metal Big-Data cluster by using BigTop puppet recipes and pulling from existing bigtop repositories. Big-Data enviroment may include Hadoop, Hive, Mahout..etc.

When the configuration is correctly set up in vagrantconfig.yaml, we should be able to deploy a cluster with on single command `vagrant up`

## Set up the enviroment

1) Install vagrant from [official website](https://www.vagrantup.com/)

2) If you want to provision machines in parallel, install gnu-parallel

```
# for centos
yum install parallel
# for mac
brew install parallel
# for debian/ubuntu
apt-get install parallel
```

3) Install [vagrant-hostmanager plugin](https://github.com/smdahlen/vagrant-hostmanager) to better manage `/etc/hosts`

```
vagrant plugin install vagrant-hostmanager
```

4) Install [vagrant-managed-servers](https://github.com/tknerr/vagrant-managed-servers)

```
vagrant plugin install vagrant-managed-servers
```

5) Set up configuration

There are options in vagrantconfig.yaml that you can specify such as set number of bare-metal machines in the cluster

```
num_instance: 3
```

You can also determine what components are being installed and tested

```
components: [hadoop, yarn, hive]

```

6) Define the bare-metal servers ip addresses and hostnames.
 In Vagrantfile you should specify the bare-metal servers ip addresses and hostnames such that:

```
machines_ips = Array["111.111.11.11","222.222.22.22"]
machines_hostnames = Array["server1.bu.edu","server1.bu.edu"]
machines_aliases = Array[server1","server2"]
```

Also you should define the master node such that:
```
hadoop_master = "server1.bu.edu"
```
## GO
For sequencial Big-Data deployment run:

```
vagrant up --provider=managed
vagrant provision
```

For parallel Big-Data deployment run:

```
./para-deploy.sh
```

redpajama_set_name: RedPajamaGithub


text:
/*
 * Note: this file originally auto-generated by mib2c using
 *  $
 */

#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <net-snmp/agent/net-snmp-agent-includes.h>
#include <net-snmp/agent/table_container.h>
#include "sctpAssocLocalAddrTable.h"

/*
 * content of the sctpAssocLocalAddrTable
 */
static netsnmp_container *sctpAssocLocalAddrTable_container;

/** Initializes the sctpAssocLocalAddrTable module */
void
init_sctpAssocLocalAddrTable(void)
{
    /*
     * here we initialize all the tables we're planning on supporting
     */
    initialize_table_sctpAssocLocalAddrTable();
}

void
shutdown_sctpAssocLocalAddrTable(void)
{
    sctpAssocLocalAddrTable_container_clear
        (sctpAssocLocalAddrTable_container);
}

/** Initialize the sctpAssocLocalAddrTable table by defining its contents and how it's structured */
void
initialize_table_sctpAssocLocalAddrTable(void)
{
    static oid      sctpAssocLocalAddrTable_oid[] =
        { 1, 3, 6, 1, 2, 1, 104, 1, 4 };
    size_t          sctpAssocLocalAddrTable_oid_len =
        OID_LENGTH(sctpAssocLocalAddrTable_oid);
    netsnmp_handler_registration *reg = NULL;
    netsnmp_mib_handler *handler = NULL;
    netsnmp_container *container = NULL;
    netsnmp_table_registration_info *table_info = NULL;

    reg =
        netsnmp_create_handler_registration("sctpAssocLocalAddrTable",
                                            sctpAssocLocalAddrTable_handler,
                                            sctpAssocLocalAddrTable_oid,
                                            sctpAssocLocalAddrTable_oid_len,
                                            HANDLER_CAN_RONLY);
    if (NULL == reg) {
        snmp_log(LOG_ERR,
                 "error creating handler registration for sctpAssocLocalAddrTable\n");
        goto bail;
    }

    container =
        netsnmp_container_find("sctpAssocLocalAddrTable:table_container");
    if (NULL == container) {
        snmp_log(LOG_ERR,
                 "error creating container for sctpAssocLocalAddrTable\n");
        goto bail;
    }
    sctpAssocLocalAddrTable_container = container;

    table_info = SNMP_MALLOC_TYPEDEF(netsnmp_table_registration_info);
    if (NULL == table_info) {
        snmp_log(LOG_ERR,
                 "error allocating table registration for sctpAssocLocalAddrTable\n");
        goto bail;
    }
    netsnmp_table_helper_add_indexes(table_info, ASN_UNSIGNED,  /* index: sctpAssocId */
                                     ASN_INTEGER,       /* index: sctpAssocLocalAddrType */
                                     ASN_OCTET_STR,     /* index: sctpAssocLocalAddr */
                                     0);
    table_info->min_column = COLUMN_SCTPASSOCLOCALADDRSTARTTIME;
    table_info->max_column = COLUMN_SCTPASSOCLOCALADDRSTARTTIME;

    /*************************************************
     *
     * inject container_table helper
     */
    handler = netsnmp_container_table_handler_get(table_info, container,
                                                  TABLE_CONTAINER_KEY_NETSNMP_INDEX);
    if (NULL == handler) {
        snmp_log(LOG_ERR,
                 "error allocating table registration for sctpAssocLocalAddrTable\n");
        goto bail;
    }
    if (SNMPERR_SUCCESS != netsnmp_inject_handler(reg, handler)) {
        snmp_log(LOG_ERR,
                 "error injecting container_table handler for sctpAssocLocalAddrTable\n");
        goto bail;
    }
    handler = NULL;             /* reg has it, will reuse below */

    /*
     * register the table
     */
    if (SNMPERR_SUCCESS != netsnmp_register_table(reg, table_info)) {
        snmp_log(LOG_ERR,
                 "error registering table handler for sctpAssocLocalAddrTable\n");
        goto bail;
    }

    /*
     * Initialise the contents of the table here
     */

    return;                     /* ok */

    /*
     * Some error occurred during registration. Clean up and bail.
     */
  bail:                        /* not ok */

    if (handler)
        netsnmp_handler_free(handler);

    if (container)
        CONTAINER_FREE(container);

    if (reg)
        netsnmp_handler_registration_free(reg);
}

/** handles requests for the sctpAssocLocalAddrTable table */
int
sctpAssocLocalAddrTable_handler(netsnmp_mib_handler *handler,
                                netsnmp_handler_registration *reginfo,
                                netsnmp_agent_request_info *reqinfo,
                                netsnmp_request_info *requests)
{

    netsnmp_request_info *request;
    netsnmp_table_request_info *table_info;
    sctpAssocLocalAddrTable_entry *table_entry;

    switch (reqinfo->mode) {
        /*
         * Read-support (also covers GetNext requests)
         */
    case MODE_GET:
        for (request = requests; request; request = request->next) {
            if (request->processed)
                continue;
            table_entry = (sctpAssocLocalAddrTable_entry *)
                netsnmp_container_table_extract_context(request);
            table_info = netsnmp_extract_table_info(request);
            if ((NULL == table_entry) || (NULL == table_info)) {
                snmp_log(LOG_ERR,
                         "could not extract table entry or info for sctpAssocLocalAddrTable\n");
                snmp_set_var_typed_value(request->requestvb,
                                         SNMP_ERR_GENERR, NULL, 0);
                continue;
            }

            switch (table_info->colnum) {
            case COLUMN_SCTPASSOCLOCALADDRSTARTTIME:
                if (!table_entry) {
                    netsnmp_set_request_error(reqinfo, request,
                                              SNMP_NOSUCHINSTANCE);
                    continue;
                }
                snmp_set_var_typed_integer(request->requestvb,
                                           ASN_TIMETICKS,
                                           table_entry->sctpAssocLocalAddrStartTime);
                break;
            default:
                netsnmp_set_request_error(reqinfo, request,
                                          SNMP_NOSUCHOBJECT);
                break;
            }
        }
        break;

    }
    return SNMP_ERR_NOERROR;
}

sctpAssocLocalAddrTable_entry *
sctpAssocLocalAddrTable_entry_create(void)
{
    sctpAssocLocalAddrTable_entry *entry =
        SNMP_MALLOC_TYPEDEF(sctpAssocLocalAddrTable_entry);
    if (entry != NULL) {
        entry->oid_index.len = SCTP_ASSOC_LOCAL_ADDR_TABLE_INDEX_SIZE;
        entry->oid_index.oids = entry->oid_tmp;
    }

    return entry;
}

int
sctpAssocLocalAddrTable_entry_update_index(sctpAssocLocalAddrTable_entry *
                                           entry)
{
    int             err = 0;

    netsnmp_variable_list var_sctpAssocId;
    netsnmp_variable_list var_sctpAssocLocalAddrType;
    netsnmp_variable_list var_sctpAssocLocalAddr;

    /*
     * prepare the values to be converted
     */
    memset(&var_sctpAssocId, 0, sizeof(var_sctpAssocId));
    var_sctpAssocId.type = ASN_UNSIGNED;
    memset(&var_sctpAssocLocalAddrType, 0,
           sizeof(var_sctpAssocLocalAddrType));
    var_sctpAssocLocalAddrType.type = ASN_INTEGER;
    memset(&var_sctpAssocLocalAddr, 0, sizeof(var_sctpAssocLocalAddr));
    var_sctpAssocLocalAddr.type = ASN_OCTET_STR;

    var_sctpAssocId.next_variable = &var_sctpAssocLocalAddrType;
    var_sctpAssocLocalAddrType.next_variable = &var_sctpAssocLocalAddr;
    var_sctpAssocLocalAddr.next_variable = NULL;

    snmp_set_var_value(&var_sctpAssocId, (u_char *) & entry->sctpAssocId,
                       sizeof(entry->sctpAssocId));
    snmp_set_var_value(&var_sctpAssocLocalAddrType,
                       (u_char *) & entry->sctpAssocLocalAddrType,
                       sizeof(entry->sctpAssocLocalAddrType));
    snmp_set_var_value(&var_sctpAssocLocalAddr,
                       (u_char *) & entry->sctpAssocLocalAddr,
                       entry->sctpAssocLocalAddr_len *
                       sizeof(entry->sctpAssocLocalAddr[0]));

    /*
     * convert it
     */
    err =
        build_oid_noalloc(entry->oid_index.oids, entry->oid_index.len,
                          &entry->oid_index.len, NULL, 0,
                          &var_sctpAssocId);
    if (err)
        snmp_log(LOG_ERR, "error %d converting index to oid\n", err);

    /*
     * release any memory allocated during the conversion
     */
    snmp_reset_var_buffers(&var_sctpAssocId);

    return err;

}

void
sctpAssocLocalAddrTable_entry_copy(sctpAssocLocalAddrTable_entry * from,
                                   sctpAssocLocalAddrTable_entry * to)
{
    memcpy(to, from, sizeof(sctpAssocLocalAddrTable_entry));
    to->oid_index.oids = to->oid_tmp;
}

void
sctpAssocLocalAddrTable_entry_free(sctpAssocLocalAddrTable_entry * entry)
{
    if (entry != NULL)
        SNMP_FREE(entry);
}

netsnmp_container *
sctpAssocLocalAddrTable_get_container(void)
{
    return sctpAssocLocalAddrTable_container;
}

static void
sctpAssocLocalAddrTable_entry_clear(void *what, void *magic)
{
    sctpAssocLocalAddrTable_entry_free(what);
}

void
sctpAssocLocalAddrTable_container_clear(netsnmp_container *container)
{
    CONTAINER_CLEAR(container, sctpAssocLocalAddrTable_entry_clear, NULL);
}


text:
package com.google.cloud.teleport.templates;

import com.google.cloud.spanner.DatabaseClient;
import com.google.cloud.spanner.DatabaseId;
import com.google.cloud.spanner.Mutation;
import com.google.cloud.spanner.ResultSet;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.cloud.spanner.Statement;
import com.google.cloud.spanner.Value;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.PipelineResult;
import org.apache.beam.sdk.io.FileSystems;
import org.apache.beam.sdk.io.TextIO;
import org.apache.beam.sdk.io.gcp.spanner.SpannerIO;
import org.apache.beam.sdk.options.Default;
import org.apache.beam.sdk.options.Description;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.options.Validation;
import org.apache.beam.sdk.options.ValueProvider;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.util.StreamUtils;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This pipeline ingests CSV and other type of delimited data from GCS and writes data to a Cloud
 * Spanner database table. Each row from the input CSV file will be applied to Spanner with an
 * InsertOrUpdate mutation, so this can be used both to populate new rows or to update columns of
 * existing rows.
 *
 *
You can specify column delimiter other than comma. Also make sure to use field qualifier such
 * as double quote to escape delimiter if it is in the value.
 *
 *
Text file must NOT have a header.
 *
 *
Example Usage: Here is CSV sample data simulating an account table:
 * 1,sample_user_1,true,2018-01-01,2018-01-01T12:30:00Z
 *
 *
Schema file must have all column and type definition in one line. Schema file must use the
 * data type names of Cloud Spanner. We currently support the following Cloud Spanner data types: -
 * BOOL - DATE - FLOAT64 - INT64 - STRING - TIMESTAMP
 *
 *
Input format properties: - \\N in the source column will be considered as NULL value when
 * writing to Cloud Spanner. - If you need to escape characters, you can use the "fieldQualifier"
 * parameter to tell the pipeline. e.g. You can put all values inside double quotes like "123",
 * "john", "true" - See the implementation of parseRow() below to see what values are accepted for
 * each data type.
 *
 *
NOTE: BYTES, ARRAY, STRUCT types are not supported.
 *
 *
Example schema file for the CSV file above:
 *
 *
Id:INT64,Username:STRING,Active:BOOL,CreateDate:DATE,ModifyTime:TIMESTAMP

 *
 *
Here is the DDL for creating Cloud Spanner table:
 *
 *
CREATE TABLE example_table
 * ( Id INT64, Username STRING(MAX), Active BOOL, CreateDate DATE, ModifyTime TIMESTAMP )
 *  PRIMARY KEY(Id)
 *

 *
 *

 * {@code mvn compile exec:java \
 * -Dexec.mainClass=com.google.cloud.teleport.templates.TextToSpanner \
 * -Dexec.args=" \
 * --project=${PROJECT_ID} \
 * --stagingLocation=gs://${PROJECT_ID}/dataflow/pipelines/${PIPELINE_FOLDER}/staging \
 * --tempLocation=gs://${PROJECT_ID}/dataflow/pipelines/${PIPELINE_FOLDER}/temp \
 * --runner=DataflowRunner \
 * --inputFilePattern=gs://${INPUT_FILE_PATTERN} \
 * --schemaFilename=gs://SCHEMA_FILE_NAME \
 * --spannerInstance=SPANNER_INSTANCE_NAME \
 * --databaseName=DATABASE_NAME \
 * --tableName=TABLE_NAME \
 * --columnDelimiter=',' \
 * --fieldQualifier='\"' "
 * }
 *

 */
public class TextToSpanner {

  /** Options supported by {@link TextToSpanner}. */
  public interface Options extends PipelineOptions {
    @Description("GCP Project Id of where the Spanner table lives.")
    ValueProvider<String> getProjectId();

    void setProjectId(ValueProvider<String> value);

    @Description("Input file or filepattern to read from")
    @Validation.Required
    ValueProvider<String> getInputFilePattern();

    void setInputFilePattern(ValueProvider<String> value);

    @Description("Schema file to read from")
    @Validation.Required
    ValueProvider<String> getSchemaFilename();

    void setSchemaFilename(ValueProvider<String> value);

    @Description("Cloud Spanner instance")
    @Validation.Required
    ValueProvider<String> getSpannerInstance();

    void setSpannerInstance(ValueProvider<String> value);

    @Description("Cloud Spanner database name")
    @Validation.Required
    ValueProvider<String> getDatabaseName();

    void setDatabaseName(ValueProvider<String> value);

    @Description("Cloud Spanner table name")
    @Validation.Required
    ValueProvider<String> getTableName();

    void setTableName(ValueProvider<String> value);

    @Description("Column delimiter of the source file")
    @Validation.Required
    @Default.Character(',')
    ValueProvider<Character> getColumnDelimiter();

    void setColumnDelimiter(ValueProvider<Character> value);

    @Description(
        "Field qualifier used by the source file, default is double quote. Field "
            + "qualifier should be used when character needs to be escaped.")
    ValueProvider<Character> getFieldQualifier();

    void setFieldQualifier(ValueProvider<Character> value);
  }

  private static final Logger LOG = LoggerFactory.getLogger(TextToSpanner.class);
  private static final ImmutableSet<String> SUPPORTED_DATA_TYPES =
      ImmutableSet.of("INT64", "FLOAT64", "BOOL", "DATE", "TIMESTAMP", "STRING");

  public static Set<String> getSupportDataTypes() {
    return SUPPORTED_DATA_TYPES;
  }

  public static void main(String[] args) {
    Options options = PipelineOptionsFactory.fromArgs(args).withValidation().as(Options.class);
    run(options);
  }

  /**
   * Runs the pipeline with the supplied options.
   *
   * @param options The execution parameters to the pipeline.
   * @return The result of the pipeline execution.
   */
  public static PipelineResult run(Options options) {
    Pipeline p = Pipeline.create(options);
    Options textToSpannerOptions = options.as(Options.class);
    RowToMutationFn rowToMutationFn =
        new RowToMutationFn(
            textToSpannerOptions.getProjectId(),
            textToSpannerOptions.getSpannerInstance(),
            textToSpannerOptions.getDatabaseName(),
            textToSpannerOptions.getTableName(),
            textToSpannerOptions.getSchemaFilename(),
            textToSpannerOptions.getColumnDelimiter(),
            textToSpannerOptions.getFieldQualifier());

    p.apply(TextIO.read().from(options.getInputFilePattern()))
        .apply(ParDo.of(rowToMutationFn))
        .apply(
            SpannerIO.write()
                .withInstanceId(options.getSpannerInstance())
                .withDatabaseId(options.getDatabaseName()));

    return p.run();
  }

  /** Cloud Spanner transformation helper that convert each row to Mutation object. */
  static class RowToMutationFn extends DoFn<String, Mutation> {
    private final ValueProvider<String> projectId;
    private final ValueProvider<Character> columnDelimiter;
    private final ValueProvider<Character> fieldQualifier;
    private final ValueProvider<String> spannerTableName;
    private final ValueProvider<String> spannerDBName;
    private final ValueProvider<String> spannerInstanceName;
    private final ValueProvider<String> schemaFileName;

    private SpannerSchema spannerSchema = null;
    private List<String> spannerSchemaColumns = null;
    private Mutation.WriteBuilder writeBuilder = null;
    private CSVFormat csvFormat = null;

    public RowToMutationFn(
        ValueProvider<String> projectId,
        ValueProvider<String> spannerInstanceName,
        ValueProvider<String> spannerDBName,
        ValueProvider<String> spannerTableName,
        ValueProvider<String> schemaFileName,
        ValueProvider<Character> columnDelimiter,
        ValueProvider<Character> fieldQualifier) {
      this.columnDelimiter = columnDelimiter;
      this.spannerTableName = spannerTableName;
      this.spannerDBName = spannerDBName;
      this.spannerInstanceName = spannerInstanceName;
      this.fieldQualifier = fieldQualifier;
      this.projectId = projectId;
      this.schemaFileName = schemaFileName;
    }

    @Setup
    public void setup() {
      SpannerSchema spannerSchemaFromFile = getSpannerSchemaFromFile(schemaFileName);
      SpannerSchema spannerSchemaFromCloud =
          getSpannerSchemaFromSpanner(
              spannerInstanceName.get(), spannerDBName.get(), spannerTableName.get());
      // Validate if schema from the 2 places are compatible
      if (!spannerSchemaFromFile.compatibleWithSchema(spannerSchemaFromCloud)) {
        throw new RuntimeException(
            "Schema from file and schema from Cloud Spanner table is not compatible!");
      }
      this.spannerSchema = spannerSchemaFromFile;
      this.spannerSchemaColumns = spannerSchemaFromFile.getColumnList();

      // Initialize CSV Parser format
      csvFormat =
          CSVFormat.newFormat(columnDelimiter.get())
              .withEscape('\\')
              .withIgnoreEmptyLines(false)
              .withNullString("\\N");
      if (fieldQualifier != null) {
        csvFormat = csvFormat.withQuote(fieldQualifier.get());
      }
    }

    @ProcessElement
    public void processElement(ProcessContext c) throws IOException {
      /**
       * Input string is one line but Apache CSVParser process multiple lines, so we only take the
       * first item in the result list.
       */
      Reader in = new StringReader(c.element());
      CSVParser parser = new CSVParser(in, csvFormat);
      List<CSVRecord> list = parser.getRecords();
      if (list.isEmpty()) {
        return;
      }
      if (list.size() > 1) {
        throw new RuntimeException("Unable to parse this row: " + c.element());
      }
      CSVRecord row = list.get(0);

      writeBuilder = Mutation.newInsertOrUpdateBuilder(spannerTableName.get());
      c.output(parseRow(writeBuilder, row, spannerSchema));
    }

    /**
     * Take a String list and convert into a Mutation object base on schema provided.
     *
     * @param builder MutationBuilder to construct
     * @param row CSVRecord parsed list of data cell
     * @param spannerSchema list with column name and column data type
     * @return build Mutation object for the row
     */
    protected final Mutation parseRow(
        Mutation.WriteBuilder builder, CSVRecord row, SpannerSchema spannerSchema)
        throws IllegalArgumentException {
      if (row.size() != spannerSchemaColumns.size()) {
        throw new RuntimeException(
            "Parsed row has different number of column than schema. "
                + "Row content: "
                + row.toString());
      }

      // Extract cell by cell and construct Mutation object
      for (int i = 0; i < row.size(); i++) {
        String columnName = spannerSchemaColumns.get(i);
        SpannerDataTypes columnType = spannerSchema.getColumnType(columnName);
        String cellValue = row.get(i);

        if (cellValue == null) {
          builder.set(columnName).to(Value.string(null));
        } else {
          // TODO: make the tests below match Spanner's SQL literal rules wherever possible,
          // in terms of how input is accepted, and throw exceptions on invalid input.
          switch (columnType) {
            case BOOL:
              Boolean bCellValue;
              if (cellValue.trim().equalsIgnoreCase("true")) {
                bCellValue = Boolean.TRUE;
              } else if (cellValue.trim().equalsIgnoreCase("false")) {
                bCellValue = Boolean.FALSE;
              } else {
                throw new IllegalArgumentException(
                    cellValue.trim() + " is not recognizable value " + "for BOOL type");
              }
              builder.set(columnName).to(Boolean.valueOf(cellValue));
              break;
            case INT64:
              builder.set(columnName).to(Integer.valueOf(cellValue.trim()));
              break;
            case STRING:
              builder.set(columnName).to(cellValue.trim());
              break;
            case FLOAT64:
              builder.set(columnName).to(Float.valueOf(cellValue.trim()));
              break;
            case DATE:
              // This requires date type in format of 'YYYY-[M]M-[D]D'
              builder.set(columnName).to(com.google.cloud.Date.parseDate(cellValue.trim()));
              break;
            case TIMESTAMP:
              builder
                  .set(columnName)
                  .to(
                      com.google.cloud.Timestamp.parseTimestamp(
                          cellValue.replaceAll("\"", "").trim()));
              break;
            default:
              throw new IllegalArgumentException(
                  "Unrecognized column data type: " + spannerSchema.getColumnType(columnName));
          }
        }
      }

      return builder.build();
    }

    /*
     * Query Cloud Spanner to get the table's schema
     */
    public SpannerSchema getSpannerSchemaFromSpanner(
        String spannerInstanceName, String spannerDatabaseName, String spannerTableName) {
      String schemaQuery =
          "SELECT column_name,spanner_type FROM "
              + "information_schema.columns WHERE table_catalog = '' AND table_schema = '' "
              + "AND table_name = @tableName";

      SpannerSchema spannerSchema = new SpannerSchema();
      SpannerOptions options =
          SpannerOptions.newBuilder().setProjectId(this.projectId.get()).build();
      Spanner spanner = options.getService();

      try {
        DatabaseId db =
            DatabaseId.of(options.getProjectId(), spannerInstanceName, spannerDatabaseName);
        DatabaseClient dbClient = spanner.getDatabaseClient(db);
        ResultSet resultSet =
            dbClient
                .singleUse()
                .executeQuery(
                    Statement.newBuilder(schemaQuery)
                        .bind("tableName")
                        .to(spannerTableName)
                        .build());
        if (resultSet == null) {
          throw new RuntimeException("Could not get result of Cloud Spanner table schema!");
        }
        while (resultSet.next()) {
          String columnName = resultSet.getString(0);
          String columnType = resultSet.getString(1);

          if (Strings.isNullOrEmpty(columnName) || Strings.isNullOrEmpty(columnType)) {
            throw new RuntimeException("Could not find valid column name or type. They are null.");
          }
          spannerSchema.addEntry(columnName, SpannerSchema.parseSpannerDataType(columnType));
        }
      } finally {
        spanner.close();
      }

      LOG.info("[GetSpannerSchema] Closed Cloud Spanner DB client");
      return spannerSchema;
    }

    /**
     * Helper method to read schema file and convert content to SpannerSchema object.
     *
     * @param schemaFilename GCS location of the schema file
     * @return parsed SpannerSchema object
     */
    public SpannerSchema getSpannerSchemaFromFile(ValueProvider<String> schemaFilename) {
      if (schemaFilename == null) {
        throw new RuntimeException("No schema file provided!");
      }
      try {
        ReadableByteChannel readableByteChannel =
            FileSystems.open(FileSystems.matchNewResource(schemaFilename.get(), false));
        String schemaString =
            new String(
                StreamUtils.getBytesWithoutClosing(Channels.newInputStream(readableByteChannel)));

        SpannerSchema spannerSchema = new SpannerSchema(schemaString);

        return spannerSchema;
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  }
}

/*
 * This enum represents the Cloud Spanner data types that supported by this Dataflow pipeline.
 */
enum SpannerDataTypes {
  INT64,
  FLOAT64,
  BOOL,
  DATE,
  TIMESTAMP,
  STRING
};

/*
 * Represent a Cloud Spanner Schema. The key is the column name and the value is data type
 */
class SpannerSchema {
  private static final Logger LOG = LoggerFactory.getLogger(SpannerSchema.class);
  private static final String SCHEMA_COLUMN_DELIMITER = ",";
  private static final String SCHEMA_DELIMITER = ":";
  private static final Pattern STRING_PATTERN = Pattern.compile("STRING(?:\\((?:MAX|[0-9]+)\\))?");
  Map<String, SpannerDataTypes> spannerSchema = new LinkedHashMap<>();

  public SpannerSchema(String schemaString) {
    for (String pair : schemaString.split(SCHEMA_COLUMN_DELIMITER)) {
      String[] columnPair = pair.split(SCHEMA_DELIMITER);
      spannerSchema.put(columnPair[0].trim(), parseSpannerDataType(columnPair[1].trim()));
    }
  }

  public SpannerSchema() {}

  public static SpannerDataTypes parseSpannerDataType(String columnType) {
    if (STRING_PATTERN.matcher(columnType).matches()) {
      return SpannerDataTypes.STRING;
    } else if (columnType.equalsIgnoreCase("FLOAT64")) {
      return SpannerDataTypes.FLOAT64;
    } else if (columnType.equalsIgnoreCase("INT64")) {
      return SpannerDataTypes.INT64;
    } else if (columnType.equalsIgnoreCase("BOOL")) {
      return SpannerDataTypes.BOOL;
    } else if (columnType.equalsIgnoreCase("DATE")) {
      return SpannerDataTypes.DATE;
    } else if (columnType.equalsIgnoreCase("TIMESTAMP")) {
      return SpannerDataTypes.TIMESTAMP;
    } else {
      throw new IllegalArgumentException(
          "Unrecognized or unsupported column data type: " + columnType);
    }
  }

  public void addEntry(String columnName, SpannerDataTypes columnType) {
    spannerSchema.put(columnName, columnType);
  }

  public void addEntry(String columnName, String columnType) {
    spannerSchema.put(columnName, parseSpannerDataType(columnType));
  }

  public SpannerDataTypes getColumnType(String key) {
    return this.spannerSchema.get(key);
  }

  public List<String> getColumnList() {
    List<String> result = new ArrayList<>();
    result.addAll(spannerSchema.keySet());

    return result;
  }

  public boolean compatibleWithSchema(SpannerSchema targetSpannerSchema) {
    boolean result = true;
    for (String columnName : spannerSchema.keySet()) {
      if (!targetSpannerSchema.spannerSchema.containsKey(columnName)) {
        LOG.info("Schema does not contain column: " + columnName);
        result = false;
      }

      if (getColumnType(columnName) != targetSpannerSchema.getColumnType(columnName)) {
        LOG.info("In schema, column: " + columnName + " does not has the same data type.");
        LOG.info(
            "Source type:"
                + getColumnType(columnName).toString()
                + ", the other type:"
                + targetSpannerSchema.getColumnType(columnName).toString());
        result = false;
      }
    }
    return result;
  }
}


text:
cask 'virtualhostx' do
  version '2020.06,1012'
  sha256 '2924c88aa39aa3d920ef9ca2e6fdcabe609fc8241941c9823b6d6a7c9fef629c'

  url "https://download.clickontyler.com/virtualhostx/virtualhostxpro_#{version.after_comma}.zip"
  appcast 'https://shine.clickontyler.com/appcast.php?id=45'
  name 'VirtualHostX'
  homepage 'https://clickontyler.com/virtualhostx/'

  depends_on macos: '>= :sierra'

  app 'VirtualHostX.app'
end


text:
package main.java.utils.graph;

import java.util.HashMap;
import java.util.Map;

public class CompressedHEdge extends SimpleHEdge {

	private Map<Integer, SimpleHEdge> HSet;

	public CompressedHEdge(int id, int d) {
		super(id, d);
		HSet = new HashMap<Integer, SimpleHEdge>();
	}

	public Map<Integer, SimpleHEdge> getHESet() {
		return HSet;
	}

	public void setHESet(Map<Integer, SimpleHEdge> HSet) {
		this.HSet = HSet;
	}

	@Override
	public boolean equals(Object object) {
		if (!(object instanceof CompressedHEdge)) {
			return false;
		}

		CompressedHEdge ce = (CompressedHEdge) object;
		return (this.getId() == ce.getId());
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + this.getId();
		return result;
	}

	public int compareTo(CompressedHEdge ce) {
		return (((int)this.getId() < (int)ce.getId()) ? -1 :
			((int)this.getId() > (int)ce.getId()) ? 1 : 0);
	}

	@Override
	public String toString() {
		return ("CHE"+this.getId()+"("+this.getWeight()+") | "+this.getHESet());
	}
}


text:
Pattern: Use of `T`/`F` symbol

Issue: -

## Description

Avoid the symbols `T` and `F` (for `TRUE` and `FALSE`).

## Further Reading

* [lintr - Available linters](https://lintr.r-lib.org/reference/index.html)


text:
function [ ] = classifyimages(diskpath)

% Notes - see part1

commonpath = [diskpath,'/practical_image_registration/data/'];
basepath = [diskpath,'/practical_image_registration/'];
vocabpath = [commonpath,'/vocabulary.mat'];

postrainpath =[commonpath,'/Pos/Train/']; % positive training images
postestpath =[commonpath,'/Pos/Test/'];% positive testing images
cache_poshistograms =[commonpath,'/cache/Images_Train/']; % this is where histograms for training images will be stored
negtrainpath = [commonpath,'/Neg/Train/'];% negative training images
negtestpath = [commonpath,'/Neg/Test/'];% negative testing images
cache_neghistograms = [commonpath,'/cache/Images_Train/'];

% Specify path for where all your test images are
testimagepath = ['/Users/helenlramsden/Desktop/TempImages/'];

% This is where test image histograms will be saved
testhistograms = [commonpath,'/cache/Images_Test/'];

% add required search paths
setup;

% --------------------------------------------------------------------
% Stage A: Data Preparation
% --------------------------------------------------------------------
vocabulary = load(vocabpath) ;

fprintf('Loading Training data..\n');

% Compute positive histograms from training images
pos.names = getImageSet(postrainpath);
pos.histograms = computeHistogramsFromImageList(vocabulary, pos.names, cache_poshistograms);
neg.names = getImageSet(negtrainpath);
neg.histograms = computeHistogramsFromImageList(vocabulary, neg.names, cache_neghistograms);

names = {pos.names{:}, neg.names{:}};
histograms = [pos.histograms, neg.histograms];
labels = [ones(1,numel(pos.names)), - ones(1,numel(neg.names))];
clear pos neg;

fprintf('Loading Test data..\n');

% Compute test from own images that you have not assigned a label to
pos.names = getImageSet(testimagepath);
pos.histograms = computeHistogramsFromImageList(vocabulary, pos.names, testhistograms) ;
neg.names = {};
neg.histograms = [];

testNames = {pos.names{:}, neg.names{:}};
testHistograms = [pos.histograms, neg.histograms] ;
testLabels = [ones(1,numel(pos.names)), - ones(1,numel(neg.names))] ;
clear pos neg;

% count how many images are there
fprintf('Number of training images: %d positive, %d negative\n', ...
    sum(labels > 0), sum(labels < 0)) ;
fprintf('Number of testing images: %d positive, %d negative\n', ...
    sum(testLabels > 0), sum(testLabels < 0)) ;

% Hellinger's kernel (histograms are l1 normalized)
histograms = sqrt(histograms) ;
testHistograms = sqrt(testHistograms) ;

% --------------------------------------------------------------------
% Stage B: Training a classifier
% --------------------------------------------------------------------

fprintf('Training SVM..\n');

C = 100;  % best param value found on validation set - see part1

[w, bias] = trainLinearSVM(histograms, labels, C);

% Evaluate the scores
scores = w' * histograms + bias ;

fprintf('Testing SVM..\n');

% Test the linear SVM
testScores = w' * testHistograms + bias ;

% Print results
[drop,drop,info] = vl_pr(testLabels, testScores) ;
fprintf('Test AP: %.2f\n', info.auc) ;

[drop,perm] = sort(testScores,'descend') ;
topN = 100;
fprintf('Correctly retrieved in the top %d: %d\n',topN,sum(testLabels(perm(1:topN)) > 0)) ;

% write test scores to disk?
writeNamesScores( testNames, testScores,basepath );

end


text:
const titleSplitter = ' > ';

export default class UrlData {
  static set(data) {
    if (!data || (typeof data === 'object' && Object.keys(data).length === 0)) {
      window.history.pushState('', '/', window.location.pathname);
      return false;
    }
    window.location.hash = encodeURIComponent(JSON.stringify(data));
    return true;
  }

  static get() {
    try {
      const data = JSON.parse(decodeURIComponent(window.location.hash.substring(1)) || 'null');
      // eslint-disable-next-line no-console
      console.log(data);
      return data;
    } catch (e) {
      // eslint-disable-next-line no-console
      console.error(e);
      try {
        const data = JSON.parse(decodeURIComponent(decodeURIComponent(window.location.hash.substring(1))) || 'null');
        // eslint-disable-next-line no-console
        console.log(data);
        return data;
      } catch (e2) {
        // eslint-disable-next-line no-console
        console.error(e2);
      }
    }
    return null;
  }

  static title(newTitle) {
    const baseTitleSplit = window.document.title.split(titleSplitter);
    const baseTitle = baseTitleSplit.length > 1 ? baseTitleSplit[1] : baseTitleSplit[0];
    if (newTitle) {
      window.document.title = newTitle + titleSplitter + baseTitle;
    } else {
      window.document.title = baseTitle;
    }
  }
}


text:
//********************************************************************************************************************************
// Filename:    LoadForm.cs
// Owner:       Richard Dunkley
// Description: Partial class for the Form used to load in the XML file.
//********************************************************************************************************************************
// Copyright © Richard Dunkley 2016
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable
// law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and
// limitations under the License.
//********************************************************************************************************************************
using System;
using System.IO;
using System.Windows.Forms;

namespace XMLToDataClass.View
{
	public partial class LoadForm : Form
	{
		public bool PreserveHierarchy
		{
			get
			{
				return hierarchyCheckBox.Checked;
			}
		}

		public string FilePath
		{
			get
			{
				return filePathTextBox.Text;
			}
			set
			{
				filePathTextBox.Text = value;
			}
		}

		public LoadForm()
		{
			InitializeComponent();

			hierarchyCheckBox.Checked = true;
		}

		private void browseButton_Click(object sender, EventArgs e)
		{
			OpenFileDialog dialog = new OpenFileDialog();
			dialog.CheckFileExists = true;
			dialog.CheckPathExists = true;
			dialog.Filter = "XML files (*.xml)|*.xml|All files (*.*)|*.*";
			dialog.Multiselect = false;
			dialog.Title = "Select XML file to Generate Code For";
			if (string.IsNullOrEmpty(filePathTextBox.Text))
				dialog.InitialDirectory = Environment.CurrentDirectory;
			else
				dialog.InitialDirectory = Path.GetDirectoryName(filePathTextBox.Text);
			dialog.FileName = Path.GetFileName(filePathTextBox.Text);

			if (dialog.ShowDialog() != DialogResult.OK)
				return;

			filePathTextBox.Text = dialog.FileName;
		}
	}
}


text:
CREATE FOREIGN DATA WRAPPER sqlite3 VALIDATOR dblink.sqlite3;
CREATE SERVER server_sqlite3 FOREIGN DATA WRAPPER sqlite3 OPTIONS (location ':memory');
CREATE USER MAPPING FOR CURRENT_USER SERVER server_sqlite3;

-- dblink.connect()
SELECT name, srvname, status, keep FROM dblink.connections, pg_foreign_server WHERE server = oid;
SELECT dblink.connect('conn_sqlite3', 'server_sqlite3');
SELECT name, srvname, status, keep FROM dblink.connections, pg_foreign_server WHERE server = oid;

-- dblink.exec() with an existing connection
SELECT dblink.exec('conn_sqlite3', 'DROP TABLE IF EXISTS dblink_tbl');
SELECT dblink.exec('conn_sqlite3', 'CREATE TABLE dblink_tbl (id integer, value text)');
SELECT dblink.exec('conn_sqlite3', 'INSERT INTO dblink_tbl VALUES(1, ''X'')');
SELECT dblink.exec('conn_sqlite3', 'INSERT INTO dblink_tbl VALUES(2, ''BB'')');
SELECT dblink.exec('conn_sqlite3', 'INSERT INTO dblink_tbl VALUES(3, ''CCC'')');
SELECT dblink.exec('conn_sqlite3', 'INSERT INTO dblink_tbl VALUES(4, ''DDDD'')');
SELECT dblink.exec('conn_sqlite3', 'INSERT INTO dblink_tbl VALUES(5, NULL)');

SELECT * FROM dblink.query('server_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id') AS (id integer, value text);

BEGIN;
SELECT dblink.exec('conn_sqlite3', 'UPDATE dblink_tbl SET value = ''A'' WHERE id = 1');
SELECT name, srvname, status, keep FROM dblink.connections, pg_foreign_server WHERE server = oid;
ROLLBACK;

SELECT * FROM dblink.query('server_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id') AS (id integer, value text);

BEGIN;
SELECT dblink.exec('conn_sqlite3', 'UPDATE dblink_tbl SET value = ''A'' WHERE id = 1');
SELECT name, srvname, status, keep FROM dblink.connections, pg_foreign_server WHERE server = oid;
COMMIT;

SELECT * FROM dblink.query('server_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id') AS (id integer, value text);

-- dblink.query() with an existing connection
BEGIN;
SELECT * FROM dblink.query('conn_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id') AS t(id integer, value text) ORDER BY id;
SELECT name, srvname, status, keep FROM dblink.connections, pg_foreign_server WHERE server = oid;
COMMIT;

-- dblink.open() with an existing connection
SELECT * FROM dblink.cursor_test(dblink.open('conn_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id'), 100);
SELECT * FROM dblink.cursor_test(dblink.open('conn_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id'), 2);
SELECT * FROM dblink.cursor_test(dblink.open('conn_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id'), 1);

-- dblink.disconnect()
SELECT name, srvname, status, keep FROM dblink.connections, pg_foreign_server WHERE server = oid;
SELECT dblink.disconnect('conn_sqlite3');
SELECT name, srvname, status, keep FROM dblink.connections, pg_foreign_server WHERE server = oid;

-- dblink.query() with an anonymous connection
BEGIN;
SELECT * FROM dblink.query('server_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id') AS t(id integer, value text) ORDER BY id;
SELECT name, srvname, status, keep FROM dblink.connections, pg_foreign_server WHERE server = oid;
COMMIT;
SELECT name, srvname, status, keep FROM dblink.connections, pg_foreign_server WHERE server = oid;

-- dblink.exec() with an anonymous connection
BEGIN;
SELECT dblink.exec('server_sqlite3', 'UPDATE dblink_tbl SET value = value WHERE id < 3');
SELECT name, srvname, status, keep FROM dblink.connections, pg_foreign_server WHERE server = oid;
COMMIT;
SELECT name, srvname, status, keep FROM dblink.connections, pg_foreign_server WHERE server = oid;

-- dblink.open() with an anonymous connection
SELECT * FROM dblink.cursor_test(dblink.open('server_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id'), 100);
SELECT * FROM dblink.cursor_test(dblink.open('server_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id'), 2);
SELECT * FROM dblink.cursor_test(dblink.open('server_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id'), 1);
SELECT name, srvname, status, keep FROM dblink.connections, pg_foreign_server WHERE server = oid;

-- dblink.query() with max_value_len option
SELECT * FROM dblink.query('server_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id', 0, 1) AS (id integer, value text);

-- dblink.open() with max_value_len option
SELECT * FROM dblink.cursor_test(dblink.open('server_sqlite3', 'SELECT * FROM dblink_tbl ORDER BY id', 100, 1), 100);

-- connection without automatic transaction management
SELECT dblink.connect('conn_sqlite3', 'server_sqlite3', false);
SELECT dblink.exec('conn_sqlite3', 'VACUUM dblink_tbl');
SELECT dblink.disconnect('conn_sqlite3');

SELECT dblink.exec('server_sqlite3', 'DROP TABLE IF EXISTS dblink_tbl');


text:
define([
    "dojo/_base/declare"
], function(declare) {
    var ModelObject = declare(null, {
        constructor: function(ankorSystem, ref) {
            this.ankorSystem = ankorSystem;
            this.ref = ref;
            this._properties = {};
        },
        get: function(propertyName) {
            if (!(propertyName in this._properties)) {
                throw new Error("Model has no property " + propertyName);
            }
            return this._properties[propertyName];
        },
        set: function(propertyName, value) {
            this.apply(propertyName, value);
            //Generate message
        },
        apply: function(propertyName, value) {
            var propertyRef = this.ref.getSubPropertyRef(propertyName);
            var oldValue = this._properties[propertyName];

            if (value instanceof Array) {
                throw new Error("Array not supported yet");
            }
            else if (typeof value == "object" && value != null) {
                var modelObject = new ModelObject(this.ankorSystem, propertyRef);
                for (subPropertyName in value) {
                    modelObject.apply(subPropertyName, value[subPropertyName])
                }
                value = modelObject;
            }

            this._properties[propertyName] = value;
            this.ankorSystem.listenerRegistry.triggerChangeEvent(propertyRef, oldValue, value);
        },
        toJson: function() {
            var plainObject = {};
            for (propertyName in this._properties) {
                if (this._properties[propertyName] instanceof this.constructor) {
                    plainObject[propertyName] = this._properties[propertyName].toJson();
                }
                else {
                    plainObject[propertyName] = this._properties[propertyName];
                }
            }
        }
    });
    return ModelObject;
});


text:
:: Open from the Visual Studio Developer Console, so msbuild.exe is on PATH.
:: You also need to manually add ILMerge to PATH.
::
:: Use only for final builds.
@echo off

cd cmalcor
del build
del build_temp
mkdir build_temp
premake5 vs2019 && cd build && msbuild CmAlcor.sln /p:configuration=Release /p:platform=Win32 && cd ..
if %errorlevel% neq 0 exit /b %errorlevel%
move bin build_temp/alcor
del build
premake5 vs2019 --mizar && cd build && msbuild CmAlcor.sln /p:configuration=Release /p:platform=Win32 && cd ..
if %errorlevel% neq 0 exit /b %errorlevel%
move bin build_temp/mizar
del build
cd ..

cd cmalcor-gui
msbuild CmAlcorGUI.sln /t:Build /p:Configuration=Release /p:TargetFramework=v4.0
if %errorlevel% neq 0 exit /b %errorlevel%
cd ..

mkdir bin
mkdir bin\mizar_patch

set ILMERGE_PATH=%USERPROFILE%\.nuget\packages\ilmerge\3.0.41\tools\net452
copy /y /d "cmalcor\build_temp\alcor\cmalcor.exe" "bin\"
copy /y /d "cmalcor\build_temp\alcor\cmalcor.dll" "bin\"
copy /y /d "cmalcor\build_temp\mizar\cmalcor.exe" "bin\mizar_patch\"
copy /y /d "cmalcor\build_temp\mizar\cmalcor.dll" "bin\mizar_patch\"
%ILMERGE_PATH%\ilmerge.exe /targetplatform:v4 /out:bin/CmAlcorGUI.exe "cmalcor-gui/bin/Release/CmAlcorGUI.exe" "cmalcor-gui/bin/Release/Cyotek.Windows.Forms.ColorPicker.dll"
copy /y /d "cmalcor-gui\bin\Release\DarkUI.dll" "bin\"
copy /y /d "cmalcor-gui\bin\Release\CmAlcorGUI.exe.config" "bin\"
del bin\CmAlcorGUI.pdb

echo Better viewed on GitHub: https://github.com/thelink2012/cmalcor/blob/master/README.md > bin/readme.txt
echo. >> bin/readme.txt
type README.md >> bin/readme.txt

echo Those files allows the application to work with the CM Storm Mizar. >bin/mizar_patch/readme.txt
echo. >>bin/mizar_patch/readme.txt
echo Copy and replace the files in the directory CmAlcorGUI.exe is in. >>bin/mizar_patch/readme.txt
echo. >>bin/mizar_patch/readme.txt
echo I don't own a Mizar and did very small tests on someone that owns it, so I can't guarantee that this works great. >>bin/mizar_patch/readme.txt
echo. >>bin/mizar_patch/readme.txt
echo If it breaks something, see the 'Troubleshooting ^> CoolerMaster Warranty' section of the main readme as it explains how to erase the memory. >>bin/mizar_patch/readme.txt
echo. >>bin/mizar_patch/readme.txt

echo =================== https://github.com/thelink2012/cmalcor =================== > bin/license.txt
echo. >> bin/license.txt
type LICENSE >> bin/license.txt
echo. >> bin/license.txt
echo. >> bin/license.txt
echo =================== https://github.com/docopt/docopt.cpp =================== >> bin/license.txt
echo. >> bin/license.txt
type cmalcor\deps\docopt\LICENSE-MIT >> bin/license.txt
echo. >> bin/license.txt
echo. >> bin/license.txt
echo ========= https://github.com/cyotek/Cyotek.Windows.Forms.ColorPicker ========= >> bin/license.txt
echo. >> bin/license.txt
type cmalcor-gui\Dependencies\Cyotek.Windows.Forms.ColorPicker\license.txt >> bin/license.txt
echo. >> bin/license.txt
echo. >> bin/license.txt
echo =================== https://github.com/RobinPerris/DarkUI =================== >> bin/license.txt
echo. >> bin/license.txt
type cmalcor-gui\Dependencies\DarkUI\LICENSE >> bin/license.txt
echo. >> bin/license.txt


text:
<?php

namespace Apigee\Edge\Exception;

use Http\Message\Formatter;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * Class InvalidJsonException.
 */
class InvalidJsonException extends ApiResponseException
{
    /** @var string */
    protected $jsonErrorMessage;

    /**
     * InvalidJsonException constructor.
     *
     * @param string $jsonErrorMessage
     * @param ResponseInterface $response
     * @param RequestInterface $request
     * @param Formatter|null $formatter
     * @param \Throwable|null $previous
     */
    public function __construct(
        string $jsonErrorMessage,
        ResponseInterface $response,
        RequestInterface $request,
        Formatter $formatter = null,
        \Throwable $previous = null
    ) {
        $this->jsonErrorMessage = $jsonErrorMessage;
        parent::__construct($response, $request, $jsonErrorMessage, 0, $previous, $formatter);
    }

    /**
     * {@inheritdoc}
     */
    public function __toString()
    {
        return sprintf("%s\n%s", $this->jsonErrorMessage, parent::__toString());
    }

    /**
     * @return string
     */
    public function getJsonErrorMessage()
    {
        return $this->jsonErrorMessage;
    }
}


text:
@interface Mimp : NSObject

@end


text:
@interface IKMainViewController () <IKCameraOverlayDelegate>
@property IKCapture *captureView;
@property (strong, nonatomic) IBOutlet UILabel *noCameraLabel;
@property (strong, nonatomic) IBOutlet UIImageView *imageView;
@end

@implementation IKMainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    if ([IKCapture isCameraAvailable]) {
        IKCameraOverlay *cameraOverlay = [[IKCameraOverlay alloc] initWithFrame:self.view.frame];
        cameraOverlay.delegate = self;

        self.captureView = [[IKCapture alloc] initWithFrame:self.view.frame];
        self.captureView.overlay = cameraOverlay;
        [self.captureView startRunning];

        [self.view addSubview:self.captureView];
    }else{
        self.noCameraLabel.hidden = NO;
    }
}

#pragma mark Camera Overlay Delegates

-(void) takePicture{
    [self.captureView takeSnapshotWithCompletionHandler:^(UIImage *image) {
        [self.captureView removeFromSuperview];
        [self.captureView stopRunning];

        self.imageView.image = image;
        self.imageView.hidden = NO;
    }];
}

-(void) changeCamera{
    [self.captureView changeCamera];
}

@end


text:
import { memoize } from 'lodash';
import createGqClient, { fetchPolicies } from '~/lib/graphql';

/**
 * Returns a memoized client
 *
 * We defer creating the client so that importing this module does not cause any side-effects.
 * Creating the client immediately caused issues with miragejs where the gql client uses the
 * real fetch() instead of the shimmed one.
 */
const getClient = memoize(() =>
  createGqClient(
    {},
    {
      fetchPolicy: fetchPolicies.NO_CACHE,
    },
  ),
);

export const query = (...args) => getClient().query(...args);


text:
/*
Package backend provides the compute instance backends supported by Worker.

Other code will primarily interact with this package by creating a Provider
implementation and creating Instances. An example using the "fake" provider
(error handling omitted):

	provider := backend.NewBackendProvider(
		"fake",
		config.ProviderConfigFromMap(map[string]string{
			"STARTUP_DURATION": "1s",
			"LOG_OUTPUT": "Hello, world!",
		}),
	)

	provider.Setup(ctx)

	instance, _ := provider.Start(ctx, &backend.StartAttributes{
		Language: "go",
		OS: "linux",
	})
	defer instance.Stop(ctx)

	instance.UploadScript(ctx, []byte("#!/bin/sh\necho 'Hello, world!'))
	instance.RunScript(ctx, os.Stdout)

New providers should call Register in init() to register the alias it should be called with and the options it supports for the --help output.
*/
package backend

import (
	gocontext "context"
	"fmt"
	"io"
	"net/url"
	"regexp"
	"strings"
	"time"

	"github.com/pborman/uuid"
	"github.com/travis-ci/worker/context"
)

var (
	// ErrStaleVM is returned from one of the Instance methods if it detects
	// that the VM had already been used for a repository and was not reverted
	// afterwards.
	ErrStaleVM = fmt.Errorf("previous build artifacts found on stale vm")

	// ErrMissingEndpointConfig is returned if the provider config was missing
	// an 'ENDPOINT' configuration, but one is required.
	ErrMissingEndpointConfig = fmt.Errorf("expected config key endpoint")

	zeroDuration time.Duration

	hostnamePartsDisallowed = regexp.MustCompile("[^a-zA-Z0-9-]+")
	multiDash               = regexp.MustCompile("-+")
)

// Provider represents some kind of instance provider. It can point to an
// external HTTP API, or some process locally, or something completely
// different.
type Provider interface {
	// Setup performs whatever is necessary in order to be ready to start
	// instances.
	Setup(gocontext.Context) error

	// Start starts an instance. It shouldn't return until the instance is
	// ready to call UploadScript on (this may, for example, mean that it
	// waits for SSH connections to be possible).
	Start(gocontext.Context, *StartAttributes) (Instance, error)

	// StartWithProgress starts an instance as with Start and also reports
	// progress via an io.Writer.
	StartWithProgress(gocontext.Context, *StartAttributes, Progresser) (Instance, error)

	// SupportsProgress allows for querying of progress support, yeah!
	SupportsProgress() bool
}

// An Instance is something that can run a build script.
type Instance interface {
	// UploadScript uploads the given script to the instance. The script is
	// a bash script with a shebang (#!/bin/bash) line. Note that this
	// method should not be called multiple times.
	UploadScript(gocontext.Context, []byte) error

	// RunScript runs the build script that was uploaded with the
	// UploadScript method.
	RunScript(gocontext.Context, io.Writer) (*RunResult, error)

	// DownloadTrace attempts to download a job trace from the instance
	DownloadTrace(gocontext.Context) ([]byte, error)

	// Stop stops (and deletes) the instance
	Stop(gocontext.Context) error

	// ID is used when identifying the instance in logs and such
	ID() string

	// ImageName is the name of the image used to boot the instance
	ImageName() string

	// StartupDuration is the duration between "created" and "ready"
	StartupDuration() time.Duration

	// SupportsProgress allows for querying of progress support, yeah!
	SupportsProgress() bool

	// Check if this instance came from the warmer service
	Warmed() bool
}

// RunResult represents the result of running a script with Instance.RunScript.
type RunResult struct {
	// The exit code of the script. Only valid if Completed is true.
	ExitCode int32

	// Whether the script finished running or not. Can be false if there was a
	// connection error in the middle of the script run.
	Completed bool
}

func asBool(s string) bool {
	switch strings.ToLower(s) {
	case "0", "no", "off", "false", "":
		return false
	default:
		return true
	}
}

func str2map(s, separators string) map[string]string {
	ret := map[string]string{}

	f := func(r rune) bool {
		return strings.ContainsAny(string(r), separators)
	}

	for _, kv := range strings.FieldsFunc(s, f) {
		kvParts := strings.SplitN(kv, ":", 2)
		key := strings.TrimSpace(kvParts[0])
		if key == "" {
			continue
		}
		if len(kvParts) == 1 {
			ret[key] = ""
		} else {
			val := strings.TrimSpace(kvParts[1])
			val, _ = url.QueryUnescape(val)
			ret[key] = val
		}
	}

	return ret
}

func hostnameFromContext(ctx gocontext.Context) string {
	randName := fmt.Sprintf("travis-job-unk-unk-%s", uuid.NewRandom())
	jobID, ok := context.JobIDFromContext(ctx)
	if !ok {
		return randName
	}

	repoName, ok := context.RepositoryFromContext(ctx)
	if !ok {
		return randName
	}

	nameParts := []string{"travis-job"}
	for _, part := range strings.Split(repoName, "/") {
		cleanedPart := hostnamePartsDisallowed.ReplaceAllString(part, "-")
		// NOTE: the part limit of 14 is meant to ensure a maximum hostname of
		// 64 characters, given:
		// travis-job-{part}-{part}-{job-id}.travisci.net
		// ^---11----^^--15-^^--15-^^--11---^^---12-----^
		// therefore:
		// 11 + 15 + 15 + 11 + 12 = 64
		if len(cleanedPart) > 14 {
			cleanedPart = cleanedPart[0:14]
		}
		nameParts = append(nameParts, cleanedPart)
	}

	joined := strings.Join(append(nameParts, fmt.Sprintf("%v", jobID)), "-")
	return strings.ToLower(multiDash.ReplaceAllString(joined, "-"))
}


text:
<?php

/**
 * CSV export for crawler tables
 *
 * @package siteResearch
 * @subpackage crawler
 * @author Yves Peeters
 */

namespace Crawler\Export;

use Crawler\DB as DB;

/**
 * exports crawler table to a csv file
 */
class NetworkExport extends ExportAbstract
{
    /**
     * holds crawerlresultdb object
     * @var CrawlerResultDB
     */
    protected $db;

    /**
     * filename for csv file
     * @var string
     */
    protected $filename;

    /**
     * path to output direcotry
     * @var string
     */
    protected $output = "Output/";

    /**
     * create csvexport object
     * @param string $filename
     */
    public function __construct($filename, \Crawler\DB\DatabaseInterface $db)
    {
        $this->setFilename($filename);
        $this->setDB($db);

    }

    public function setDB($db)
    {
        $this->db = $db;
    }

    /**
     * csv file name
     * @param string $name
     */
    private function setFilename($name)
    {
        $this->filename = $name;
    }

    /**
     * write csv file
     */
    public function export()
    {
        $list = $this->generateList();
        // Actually create the file
        // The w+ parameter will wipe out and overwrite any existing file with the same name
        $handle = fopen($this->filename, 'w+') or die("can't open file");

        // Write the spreadsheet column titles / labels
        fputcsv($handle, array('url', 'origin'));

        // Write all the user records to the spreadsheet
        foreach ($list as $obj) {
            fputcsv($handle, array($obj["url"],"is a broken link, found on:",$obj["pagewitherror"]));
        }

        // Finish writing the file
        fclose($handle);
    }
}


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

namespace HLDJConverter.Tests
{
    [TestClass]
    public sealed class YoutubeDownloaderTests
    {
        [TestMethod]
        public void ShouldReturnVideoIDFromYoutubeLink()
        {
            var testCases = new[]
            {
                new {ExpectedID = "THBFWQIgWw4", Link = "https://www.youtube.com/watch?v=THBFWQIgWw4&list=PLRIWtICgwaX1gcSZ8qj8Q473tz7PsNmpR"},
                new {ExpectedID = "TQ_qwrrI8Og", Link = "https://www.youtube.com/watch?v=TQ_qwrrI8Og"},
                new {ExpectedID = "dPoMql9Ok9M", Link = "www.youtube.com/watch?v=dPoMql9Ok9M"},
                new {ExpectedID = "dPoMql9Ok9M", Link = "youtube.com/watch?v=dPoMql9Ok9M"},
                new {ExpectedID = "3q1JN_3s3gw", Link = "https://www.youtube.com/watch?v=3q1JN_3s3gw"},
                new {ExpectedID = "7wPH_Ed78VY", Link = "watch?v=7wPH_Ed78VY"},
                new {ExpectedID = "7wPH_Ed78VY", Link = "https://youtu.be/7wPH_Ed78VY"},
                new {ExpectedID = "iopENDI-Ayk", Link = "https://www.youtube.com/watch?v=iopENDI-Ayk"},
                new {ExpectedID = "6k_9QPAosTc", Link = "https://www.youtube.com/watch?v=6k_9QPAosTc"},
                new {ExpectedID = "6k_9QPAosTc", Link = "https://youtu.be/6k_9QPAosTc"},
                new {ExpectedID = "y_Rd2hByRyc", Link = "https://www.youtube.com/watch?feature=player_embedded&v=y_Rd2hByRyc"},
                new {ExpectedID = "-MPe7E1YrY4", Link = "https://www.youtube.com/watch?v=-MPe7E1YrY4&feature=player_embedded"},
                new {ExpectedID = "6xyQWw_j3fU", Link = "https://www.youtube.com/watch?v=6xyQWw_j3fU&feature=youtu.be"},
                new {ExpectedID = "0r7pnMVNvPE", Link = "https://www.youtube.com/watch?v=0r7pnMVNvPE"},
                new {ExpectedID = "3qy_kJbWfuI", Link = "https://www.youtube.com/watch?v=3qy_kJbWfuI"},
                new {ExpectedID = "n4R2p9WnzAo", Link = "https://www.youtube.com/watch?v=n4R2p9WnzAo"},
                new {ExpectedID = "BF_CI__LFSA", Link = "https://www.youtube.com/watch?v=BF_CI__LFSA"},
                new {ExpectedID = "LxO1Xqx7GqQ", Link = "https://www.youtube.com/watch?v=LxO1Xqx7GqQ"},
                new {ExpectedID = "obKI72j2iqo", Link = "https://www.youtube.com/watch?v=obKI72j2iqo&list=PL157A6EA7421FC089"},
                new {ExpectedID = "obKI72j2iqo", Link = "https://youtu.be/obKI72j2iqo?list=PL157A6EA7421FC089"},
            };

            foreach(var test in testCases)
            {
                Assert.AreEqual(test.ExpectedID, YoutubeDownloader.ExtractYoutubeID(test.Link));
            }
        }

        [TestMethod]
        public void ShouldReturnURLFromShortcut()
        {
            var testCases = new[]
            {
                new {ExpectedURL = "https://www.youtube.com/watch?v=p6j8fuvQICI", ShortcutFilepath = "TestShortcuts/Link1.url"},
                new {ExpectedURL = "https://www.youtube.com/watch?v=f9qavey27Kc", ShortcutFilepath = "TestShortcuts/Link2.url"},
                new {ExpectedURL = "https://www.youtube.com/watch?v=WpTOzX4xDUw", ShortcutFilepath = "TestShortcuts/Link3.url"},
                new {ExpectedURL = "https://www.youtube.com/watch?v=QGHlVLsbuoc", ShortcutFilepath = "TestShortcuts/Link4.url"},
            };

            foreach(var test in testCases)
            {
                Assert.AreEqual(test.ExpectedURL, YoutubeDownloader.ExtractURLFromShortcut(test.ShortcutFilepath));
            }
        }
    }
}


text:
<?php

namespace CodeEmailMKT\Application\Action\Tag\Factory;

use CodeEmailMKT\Application\Action\Tag\TagCreatePageAction;
use CodeEmailMKT\Application\Form\TagForm;
use CodeEmailMKT\Domain\Persistence\TagRepositoryInterface;
use Interop\Container\ContainerInterface;
use Zend\Expressive\Router\RouterInterface;
use Zend\Expressive\Template\TemplateRendererInterface;

class TagCreatePageFactory
{
    public function __invoke(ContainerInterface $container) : TagCreatePageAction
    {
        $template = $container->get(TemplateRendererInterface::class);
        $repository = $container->get(TagRepositoryInterface::class);
        $router = $container->get(RouterInterface::class);
        $form = $container->get(TagForm::class);
        return new TagCreatePageAction($repository, $template, $router, $form);
    }
}


text:
- Before Proceeding Further please make sure the Continuous integration is setup for you project, as CI is also used for deployment
- [Setup Continuous Integration](docs/CI.md)

#### To Deploy your Project to Heroku

1. Sign into [Heroku](https://dashboard.heroku.com/) account.

2. Click on create new button and Create new App.

    ![](images/heroku_new_app.png)

3. In the following screen. Enter unique name for your app.

    ![](images/heroku_create_app.png)

4. Setup Travis CI Environment Variables, to start deploying your application

    1. Select your project repository on Travis-CI

    2. Go to More Options and Click on Settings

        ![](images/travis_ci_settings.png)

    3. Scroll to Environment Variables section to start adding Necessary Environment Variables

        ![](images/travis_ci_env_variables.png)

    4. Add HEROKU_WEB_APP_NAME,

        Add the name of the app you created in Heroku.

        ![](images/travis_ci_heroku_web_app_name.png)

    4. Add HEROKU_API_KEY

        ![](images/travis_ci_heroku_api_key.png)

       1. To get Heroku Api Key, Sign into  [Heroku](https://dashboard.heroku.com/)

       2. Go to Account Settings

        ![](images/heroku_account_settings.png)

       3. Scroll down to API Key section, and Copy the value

        ![](images/heroku_account_api_key.png)

       4. Paste the Value in the Environment Variable being created in Travis CI

          ![](images/travis_ci_heroku_api_key.png)


text:
(function(){

	angular
		.module('presets')
		.controller('PresetCtrl', PresetCtrl);

	function PresetCtrl(preset, YoutubeSearch) {
		var vm = this;
		vm.data = {
			label: 'Preset'
		};
		vm.presets = preset.items;
		vm.updatePreset = updatePreset;
		vm.selected = preset.selected().index;
		// put selected preset

	    function updatePreset (presetValue) {
	    	YoutubeSearch.params.q = preset.update(YoutubeSearch.params.q, presetValue);
	    	YoutubeSearch.search();
	    }
	}

})();


text:
package org.flowcolab.account.service.streams.accountCreated;

import org.springframework.cloud.stream.annotation.Output;
import org.springframework.messaging.MessageChannel;

public interface AccountCreatedSource {

    String OUTPUT = "account-created-output";

    @Output(OUTPUT)
    MessageChannel output();
}


text:
'use strict';

var keystone = require('keystone');
var Types = keystone.Field.Types;
const moment = require('moment');

/**
 * Post comment model definition
 */

var PostComment = new keystone.List('PostComment', {
	label: 'Comments'
});

PostComment.add({
  post: { type: Types.Relationship, initial: true, ref: 'Post', index: true },
  replyTo: { type: Types.Relationship, ref: 'PostComment' },
	author: { type: String, required: true, initial: true },
  email: { type: Types.Email, required: true, initial: true },
	publishedDate: { type: Types.Date, default: Date.now, noedit: true, index: true },
  content: { type: Types.Html, wysiwyg: false, height: 300 }
});

PostComment.schema.virtual('format.date').get(function () {
  return moment(this.publishedDate).locale('zh-cn').format('ll');
});

PostComment.schema.virtual('formed.data').get(function () {
  return {
    id: this._id,
    author: this.author,
    formatedDate: this.format.date,
    content: this.content,
    replyTo: this.replyTo && this.replyTo.author ? {author: this.replyTo.author} : undefined
  };
});

PostComment.schema.methods.replyComment = function(comment, cb) {

  keystone.list('Post').model
    .findById(comment.post, {key: 1, title: 1, author: 1, type: 1})
    .populate('author')
    .exec((err, post) => {
      if (err) return cb(err);

      let tos = [{email: post.author.email, name: post.author.name}];

      if (comment.replyTo) tos.push({email: comment.replyTo.email, name: comment.replyTo.author});

      // send the mail to the author of current post.
      new keystone.Email('comment-reply').send({
        title: post.title,
        author: comment.author,
        content: comment.content,
        link: `/${post.type}/${post.key}`,
        to: tos,
        from: {
          name: 'HelloSleep',
          email: 'notifications@hellosleep.net'
        },
        subject: `回复:${comment.author}在[${post.title}]中的回复`
      }, cb);
  });
};

PostComment.track = true;
PostComment.defaultSort = '-publishedDate';
PostComment.defaultColumns = 'author, post, email, replyTo';
PostComment.register();


text:
from django.core.exceptions import ValidationError

from ...shipping import models as shipping_models

def validate_total_quantity(order):
    if order.get_total_quantity() == 0:
        raise ValidationError({
            'lines': 'Could not create order without any products.'})

def validate_shipping_method(order):
    method = order.shipping_method
    shipping_address = order.shipping_address
    shipping_not_valid = (
        method and shipping_address and
        shipping_address.country.code not in method.shipping_zone.countries)  # noqa
    if shipping_not_valid:
        raise ValidationError({
            'shipping':
            'Shipping method is not valid for chosen shipping address'})

def validate_order_lines(order):
    for line in order:
        if line.variant is None:
            raise ValidationError({
                'lines': 'Could not create orders with non-existing products.'})

def validate_draft_order(order):
    """Checks, if given order has a proper customer data, shipping
    address and method set up and return list of errors if not.
    Checks if product variants for order lines still exists in
    database, too.
    """
    if order.is_shipping_required():
        validate_shipping_method(order)
    validate_total_quantity(order)
    validate_order_lines(order)

# FIXME: is this function needed? QS method might be enough
def applicable_shipping_methods(obj, price):
    if not obj.is_shipping_required():
        return []
    if not obj.shipping_address:
        return []

    qs = shipping_models.ShippingMethod.objects
    return qs.applicable_shipping_methods(
        price=price, weight=obj.get_total_weight(),
        country_code=obj.shipping_address.country.code)


text:
package net.dirtydeeds.discordsoundboard.async;

import net.dirtydeeds.discordsoundboard.service.SoundboardBot;
import net.dirtydeeds.discordsoundboard.service.SoundboardDispatcher;

import java.util.Date;
import java.util.function.Consumer;

public class PeriodicLambdaJob implements SoundboardJob {

  private Consumer<SoundboardBot> lambda;
  private int numSecondsBetween;
  private Date next; // only run this after a certain time

  PeriodicLambdaJob(Consumer<SoundboardBot> lambda, int numSecondsBetween) {
    this.lambda = lambda;
    this.numSecondsBetween = numSecondsBetween;
    this.next = newTimestamp();
  }

  private Date newTimestamp() {
    return new Date(System.currentTimeMillis() + numSecondsBetween * 1000);
  }

  public boolean isApplicable(SoundboardDispatcher dispatcher) {
    if (next != null) {
      return (new Date(System.currentTimeMillis())).after(next);
    }
    return true;
  }

  public void run(SoundboardDispatcher dispatcher) {
    dispatcher.runLambda(lambda);
    next = newTimestamp();
  }

}


text:
<?php

namespace bone;

class JSONResponse {

  private $error = array();

  private $warning = array();

  private $success = array();

  private $callback = array();

  private $values = array();

  public $parent = null;

  private static $valid_message = array('error', 'warning', 'success');

  public function message($message, $type = 'error'){

//    if(!in_array($type, self::$valid_message))return;

    switch($type){
      case 'error':
          $this->error[] = $message;
        break;
      case 'warning':
        $this->warning[] = $message;
        break;
      case 'success':
        $this->success[] = $message;
        break;
    }
  }

  public function value($name, $value){
    $this->values[$name] = $value;
  }

  public function callback($function_name,Array $params = array()){
    $this->callback[$function_name][] = $params;
  }

  public function export(){

    $ret = array();

    if(count($this->values) > 0 )$ret = $this->values;

    //messages
    foreach(self::$valid_message as $type){
      if(count($this->$type) > 0)$ret['messages'][$type] = $this->$type;
    }

    //callbacks
   if(count($this->callback) > 0)$ret['callbacks'] = $this->callback;

   if(!is_null($this->parent)){
       $ret['messages']['parent'] = $this->parent;
   }

   return json_encode($ret);

  }

}


text:
'use strict'

var should = require('should')
  , qs = require('qs')
var Grant = require('../').express()
  , utils = require('../lib/utils')

describe('utils', function () {
  var grant

  before(function () {
    grant = new Grant({
      server: {protocol:'http', host:'localhost:5000', callback:'/'},
      elance:{}, facebook:{}, getpocket:{}, twitter:{}, yammer:{}
    })
  })

  it('redirect_uri', function () {
    utils.redirect_uri(grant.config.facebook)
      .should.equal('http://localhost:5000/connect/facebook/callback')
  })

  describe('toQuerystring', function () {
    it('parse json', function () {
      var str = utils.toQuerystring({}, '{"some":"data"}')
      should.deepEqual(qs.parse(str), {raw:{some:'data'}})
    })
    it('parse querystring', function () {
      var str = utils.toQuerystring({}, 'some=data')
      should.deepEqual(qs.parse(str), {raw:{some:'data'}})
    })
    it('elance', function () {
      var str = utils.toQuerystring(grant.config.elance,
        {data:{access_token:'token', refresh_token:'refresh'}})
      should.deepEqual(qs.parse(str), {access_token:'token', refresh_token:'refresh',
        raw:{data:{access_token:'token', refresh_token:'refresh'}}})
    })
    it('getpocket', function () {
      var str = utils.toQuerystring(grant.config.getpocket, {access_token:'token'})
      should.deepEqual(qs.parse(str),
        {access_token:'token', raw:{access_token:'token'}})
    })
    it('yammer', function () {
      var str = utils.toQuerystring(grant.config.yammer, {access_token:{token:'token'}})
      should.deepEqual(qs.parse(str),
        {access_token:'token', raw:{access_token:{token:'token'}}})
    })
    it('oauth1', function () {
      var str = utils.toQuerystring(grant.config.twitter,
        {oauth_token:'token', oauth_token_secret:'secret'})
      should.deepEqual(qs.parse(str),
        {access_token:'token', access_secret:'secret',
        raw:{oauth_token:'token', oauth_token_secret:'secret'}})
    })
    it('oauth2', function () {
      var str = utils.toQuerystring(grant.config.facebook,
        {access_token:'token', refresh_token:'refresh'})
      should.deepEqual(qs.parse(str),
        {access_token:'token', refresh_token:'refresh',
        raw:{access_token:'token', refresh_token:'refresh'}})
    })
  })

  describe('error', function () {
    it('http error', function () {
      var str = utils.error(new Error('HTTP error'))
      should.deepEqual(qs.parse(str), {error:{error:'HTTP error'}})
    })
    it('response error', function () {
      var str = utils.error(null, {statusCode:500}, {some:'data'})
      should.deepEqual(qs.parse(str), {error:{some:'data'}})
    })
  })
})


text:
package fr.adrienbrault.idea.symfony2plugin.action.bundle;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.jetbrains.php.lang.psi.elements.PhpClass;
import fr.adrienbrault.idea.symfony2plugin.Symfony2Icons;
import fr.adrienbrault.idea.symfony2plugin.action.AbstractProjectDumbAwareAction;
import fr.adrienbrault.idea.symfony2plugin.util.psi.PhpBundleFileFactory;
import org.jetbrains.annotations.NotNull;

/**
 * @author Daniel Espendiller <daniel@espendiller.net>
 */
public class NewBundleCompilerPass extends AbstractProjectDumbAwareAction {

    public NewBundleCompilerPass() {
        super("CompilerPass", "Create CompilerPass class", Symfony2Icons.SYMFONY);
    }

    public void update(AnActionEvent event) {
        Project project = getEventProject(event);
        if(project == null) {
            this.setStatus(event, false);
            return;
        }

        this.setStatus(event, BundleClassGeneratorUtil.getBundleDirContext(event) != null);
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {

        Project project = getEventProject(event);
        if(project == null) {
            this.setStatus(event, false);
            return;
        }

        PsiDirectory bundleDirContext = BundleClassGeneratorUtil.getBundleDirContext(event);
        if(bundleDirContext == null) {
            return;
        }

        final PhpClass phpClass = BundleClassGeneratorUtil.getBundleClassInDirectory(bundleDirContext);
        if(phpClass == null) {
            return;
        }

        new WriteCommandAction(project) {
            @Override
            protected void run(@NotNull Result result) throws Throwable {
                PsiElement psiFile = PhpBundleFileFactory.invokeCreateCompilerPass(phpClass, null);
                if(psiFile != null) {
                    new OpenFileDescriptor(getProject(), psiFile.getContainingFile().getVirtualFile(), 0).navigate(true);
                }
            }

            @Override
            public String getGroupID() {
                return "Create CompilerClass";
            }
        }.execute();

    }

}


text:
In this folder are environments, tools, resources, and the like for learning more about etcd, the distributed key-value store.

## Contents

**etcd-2.0**: Use the `Vagrantfile` and other files in this directory to turn up an etcd 2.0.9 cluster running on Ubuntu 14.04. The provisioning is handled via shell scripts.

**etcdv3-ansible-aws-tf**: This environment leverages Terraform and Ansible to create an etcd v3 cluster on Ubuntu 16.04 on AWS.


text:
/*
 * Exporst function that checks if given emails of users are shown
 * on the Teamview page. And if so how they are rendered: as text or link.
 *
 * It does not check exact emails, just count numbers.
 *
 * */

'use strict';

var
  By             = require('selenium-webdriver').By,
  expect         = require('chai').expect,
  open_page_func = require('./open_page'),
  config         = require('./config'),
  bluebird        = require("bluebird");

module.exports = bluebird.promisify( function(args, callback){

  var
    result_callback = callback,
    driver          = args.driver,
    emails          = args.emails || [],
    is_link         = args.is_link || false,
    application_host = args.application_host || config.get_application_host();

  if ( ! driver ) {
    throw "'driver' was not passed into the teamview_check_user!";
  }

  return open_page_func({
    url    : application_host + 'calendar/teamview/',
    driver : driver,
  })

  .then(function(data){
    return data.driver
      .findElements(By.css( 'tr.teamview-user-list-row > td > ' + (is_link ? 'a' : 'span') ))
      .then(function(elements){
        expect(elements.length).to.be.equal( emails.length );
        return bluebird.resolve(data);
      });
  })

  .then(function(data){
    // "export" current driver
    result_callback(
      null,
      {
        driver : data.driver,
      }
    );
  });

});


text:
#ifndef CC_RWMUTEX_H
#define CC_RWMUTEX_H

#include <Inventor/C/basic.h>  /* COIN_DLL_API */
#include <Inventor/C/threads/common.h>  /* cc_rwmutex, cc_precedence */

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

/* ********************************************************************** */

COIN_DLL_API cc_rwmutex * cc_rwmutex_construct(void);
COIN_DLL_API cc_rwmutex * cc_rwmutex_construct_etc(cc_precedence policy);
COIN_DLL_API void cc_rwmutex_destruct(cc_rwmutex * rwmutex);

COIN_DLL_API int cc_rwmutex_write_lock(cc_rwmutex * rwmutex);
COIN_DLL_API int cc_rwmutex_write_try_lock(cc_rwmutex * rwmutex);
COIN_DLL_API int cc_rwmutex_write_unlock(cc_rwmutex * rwmutex);

COIN_DLL_API int cc_rwmutex_read_lock(cc_rwmutex * rwmutex);
COIN_DLL_API int cc_rwmutex_read_try_lock(cc_rwmutex * rwmutex);
COIN_DLL_API int cc_rwmutex_read_unlock(cc_rwmutex * rwmutex);

/* ********************************************************************** */

#ifdef __cplusplus
} /* extern "C" */
#endif /* __cplusplus */

#endif /* ! CC_RWMUTEX_H */


text: © {{$ctrl.data.years}} {{$ctrl.data.name}}. {{$ctrl.data.copyright}}


text:
/**
 * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
 * @version v6.3.0
 * @link http://www.ag-grid.com/
 * @license MIT
 */
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var component_1 = require("../widgets/component");
var rowNode_1 = require("../entities/rowNode");
var utils_1 = require('../utils');
var context_1 = require("../context/context");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var svgFactory_1 = require("../svgFactory");
var svgFactory = svgFactory_1.SvgFactory.getInstance();
var CheckboxSelectionComponent = (function (_super) {
    __extends(CheckboxSelectionComponent, _super);
    function CheckboxSelectionComponent() {
        _super.call(this, "<span class=\"ag-selection-checkbox\"/>");
    }
    CheckboxSelectionComponent.prototype.createAndAddIcons = function () {
        this.eCheckedIcon = utils_1.Utils.createIconNoSpan('checkboxChecked', this.gridOptionsWrapper, null, svgFactory.createCheckboxCheckedIcon);
        this.eUncheckedIcon = utils_1.Utils.createIconNoSpan('checkboxUnchecked', this.gridOptionsWrapper, null, svgFactory.createCheckboxUncheckedIcon);
        this.eIndeterminateIcon = utils_1.Utils.createIconNoSpan('checkboxIndeterminate', this.gridOptionsWrapper, null, svgFactory.createCheckboxIndeterminateIcon);
        var eGui = this.getGui();
        eGui.appendChild(this.eCheckedIcon);
        eGui.appendChild(this.eUncheckedIcon);
        eGui.appendChild(this.eIndeterminateIcon);
    };
    CheckboxSelectionComponent.prototype.onSelectionChanged = function () {
        var state = this.rowNode.isSelected();
        utils_1.Utils.setVisible(this.eCheckedIcon, state === true);
        utils_1.Utils.setVisible(this.eUncheckedIcon, state === false);
        utils_1.Utils.setVisible(this.eIndeterminateIcon, typeof state !== 'boolean');
    };
    CheckboxSelectionComponent.prototype.onCheckedClicked = function () {
        this.rowNode.setSelected(false);
    };
    CheckboxSelectionComponent.prototype.onUncheckedClicked = function (event) {
        this.rowNode.setSelectedParams({ newValue: true, rangeSelect: event.shiftKey });
    };
    CheckboxSelectionComponent.prototype.onIndeterminateClicked = function (event) {
        this.rowNode.setSelectedParams({ newValue: true, rangeSelect: event.shiftKey });
    };
    CheckboxSelectionComponent.prototype.init = function (params) {
        this.createAndAddIcons();
        this.rowNode = params.rowNode;
        this.onSelectionChanged();
        // we don't want the row clicked event to fire when selecting the checkbox, otherwise the row
        // would possibly get selected twice
        this.addGuiEventListener('click', function (event) { return event.stopPropagation(); });
        // likewise we don't want double click on this icon to open a group
        this.addGuiEventListener('dblclick', function (event) { return event.stopPropagation(); });
        this.addDestroyableEventListener(this.eCheckedIcon, 'click', this.onCheckedClicked.bind(this));
        this.addDestroyableEventListener(this.eUncheckedIcon, 'click', this.onUncheckedClicked.bind(this));
        this.addDestroyableEventListener(this.eIndeterminateIcon, 'click', this.onIndeterminateClicked.bind(this));
        this.addDestroyableEventListener(this.rowNode, rowNode_1.RowNode.EVENT_ROW_SELECTED, this.onSelectionChanged.bind(this));
    };
    __decorate([
        context_1.Autowired('gridOptionsWrapper'),
        __metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper)
    ], CheckboxSelectionComponent.prototype, "gridOptionsWrapper", void 0);
    return CheckboxSelectionComponent;
})(component_1.Component);
exports.CheckboxSelectionComponent = CheckboxSelectionComponent;


text:
TOPDIR=../..

TARGETS:=extlibexample

# ----------------------------------------------------------------------

extlibexample_TYPE=shlib

extlibexample_SRC_EXTENSION=c

# only cygwin needs this
#extlibexample_LIBS=rtlib cutils butils nutils

ifeq "$(OS_TYPE)" ""
OS_TYPE:=$(shell uname -o | sed -e 's\#/\#-\#g' -e 's\#(\#-\#g' -e 's\#)\#-\#g' )
export OS_TYPE
endif

extlibexample_LIBS-Cygwin=rtlib cutils butils nutils pthread
extlibexample_LIBS-GNU-Linux=

extlibexample_LIBS=$(extlibexample_LIBS-$(OS_TYPE))

# ----------------------------------------------------------------------

include $(TOPDIR)/rules.make


text:
layout: post
title:  "Final"
date:   2017-02-28
preview: "/assets/final1 3.jpg"
---

The final project of the Brandeis Art Science Initiative was on view the
week of April 27th 2017. It consisted of two mechanical sculptures, and an
interactive display that challenged the viewer to think about science and art
critically.

![picture1]({{ site.baseurl }}//assets/final1.jpg)
![picture1]({{ site.baseurl }}//assets/final2.jpg)
![picture1]({{ site.baseurl }}//assets/final3.jpg)
![picture1]({{ site.baseurl }}//assets/final4.jpg)
![picture1]({{ site.baseurl }}//assets/final5.jpg)
![picture1]({{ site.baseurl }}//assets/final6.jpg)
![picture1]({{ site.baseurl }}//assets/final7.jpg)


text:
/**
 */
package CIM15.IEC61970.LoadModel;

import CIM15.IEC61970.Core.RegularIntervalSchedule;

import org.eclipse.emf.common.notify.NotificationChain;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;

/**
 *
 * A representation of the model object 'Season Day Type Schedule'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link CIM15.IEC61970.LoadModel.SeasonDayTypeSchedule#getSeason Season}

 *
{@link CIM15.IEC61970.LoadModel.SeasonDayTypeSchedule#getDayType Day Type}

 *

 *

 *
 * @generated
 */
public class SeasonDayTypeSchedule extends RegularIntervalSchedule {
	/**
	 * The cached value of the '{@link #getSeason() Season}' reference.
	 *
	 *
	 * @see #getSeason()
	 * @generated
	 * @ordered
	 */
	protected Season season;

	/**
	 * The cached value of the '{@link #getDayType() Day Type}' reference.
	 *
	 *
	 * @see #getDayType()
	 * @generated
	 * @ordered
	 */
	protected DayType dayType;

	/**
	 *
	 *
	 * @generated
	 */
	protected SeasonDayTypeSchedule() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return LoadModelPackage.Literals.SEASON_DAY_TYPE_SCHEDULE;
	}

	/**
	 * Returns the value of the 'Season' reference.
	 * It is bidirectional and its opposite is '{@link CIM15.IEC61970.LoadModel.Season#getSeasonDayTypeSchedules Season Day Type Schedules}'.
	 *
	 *

	 * If the meaning of the 'Season' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Season' reference.
	 * @see #setSeason(Season)
	 * @see CIM15.IEC61970.LoadModel.Season#getSeasonDayTypeSchedules
	 * @generated
	 */
	public Season getSeason() {
		if (season != null && season.eIsProxy()) {
			InternalEObject oldSeason = (InternalEObject)season;
			season = (Season)eResolveProxy(oldSeason);
			if (season != oldSeason) {
			}
		}
		return season;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public Season basicGetSeason() {
		return season;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetSeason(Season newSeason, NotificationChain msgs) {
		Season oldSeason = season;
		season = newSeason;
		return msgs;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.LoadModel.SeasonDayTypeSchedule#getSeason Season}' reference.
	 *
	 *
	 * @param value the new value of the 'Season' reference.
	 * @see #getSeason()
	 * @generated
	 */
	public void setSeason(Season newSeason) {
		if (newSeason != season) {
			NotificationChain msgs = null;
			if (season != null)
				msgs = ((InternalEObject)season).eInverseRemove(this, LoadModelPackage.SEASON__SEASON_DAY_TYPE_SCHEDULES, Season.class, msgs);
			if (newSeason != null)
				msgs = ((InternalEObject)newSeason).eInverseAdd(this, LoadModelPackage.SEASON__SEASON_DAY_TYPE_SCHEDULES, Season.class, msgs);
			msgs = basicSetSeason(newSeason, msgs);
			if (msgs != null) msgs.dispatch();
		}
	}

	/**
	 * Returns the value of the 'Day Type' reference.
	 * It is bidirectional and its opposite is '{@link CIM15.IEC61970.LoadModel.DayType#getSeasonDayTypeSchedules Season Day Type Schedules}'.
	 *
	 *

	 * If the meaning of the 'Day Type' reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Day Type' reference.
	 * @see #setDayType(DayType)
	 * @see CIM15.IEC61970.LoadModel.DayType#getSeasonDayTypeSchedules
	 * @generated
	 */
	public DayType getDayType() {
		if (dayType != null && dayType.eIsProxy()) {
			InternalEObject oldDayType = (InternalEObject)dayType;
			dayType = (DayType)eResolveProxy(oldDayType);
			if (dayType != oldDayType) {
			}
		}
		return dayType;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public DayType basicGetDayType() {
		return dayType;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetDayType(DayType newDayType, NotificationChain msgs) {
		DayType oldDayType = dayType;
		dayType = newDayType;
		return msgs;
	}

	/**
	 * Sets the value of the '{@link CIM15.IEC61970.LoadModel.SeasonDayTypeSchedule#getDayType Day Type}' reference.
	 *
	 *
	 * @param value the new value of the 'Day Type' reference.
	 * @see #getDayType()
	 * @generated
	 */
	public void setDayType(DayType newDayType) {
		if (newDayType != dayType) {
			NotificationChain msgs = null;
			if (dayType != null)
				msgs = ((InternalEObject)dayType).eInverseRemove(this, LoadModelPackage.DAY_TYPE__SEASON_DAY_TYPE_SCHEDULES, DayType.class, msgs);
			if (newDayType != null)
				msgs = ((InternalEObject)newDayType).eInverseAdd(this, LoadModelPackage.DAY_TYPE__SEASON_DAY_TYPE_SCHEDULES, DayType.class, msgs);
			msgs = basicSetDayType(newDayType, msgs);
			if (msgs != null) msgs.dispatch();
		}
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case LoadModelPackage.SEASON_DAY_TYPE_SCHEDULE__SEASON:
				if (season != null)
					msgs = ((InternalEObject)season).eInverseRemove(this, LoadModelPackage.SEASON__SEASON_DAY_TYPE_SCHEDULES, Season.class, msgs);
				return basicSetSeason((Season)otherEnd, msgs);
			case LoadModelPackage.SEASON_DAY_TYPE_SCHEDULE__DAY_TYPE:
				if (dayType != null)
					msgs = ((InternalEObject)dayType).eInverseRemove(this, LoadModelPackage.DAY_TYPE__SEASON_DAY_TYPE_SCHEDULES, DayType.class, msgs);
				return basicSetDayType((DayType)otherEnd, msgs);
		}
		return super.eInverseAdd(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case LoadModelPackage.SEASON_DAY_TYPE_SCHEDULE__SEASON:
				return basicSetSeason(null, msgs);
			case LoadModelPackage.SEASON_DAY_TYPE_SCHEDULE__DAY_TYPE:
				return basicSetDayType(null, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case LoadModelPackage.SEASON_DAY_TYPE_SCHEDULE__SEASON:
				if (resolve) return getSeason();
				return basicGetSeason();
			case LoadModelPackage.SEASON_DAY_TYPE_SCHEDULE__DAY_TYPE:
				if (resolve) return getDayType();
				return basicGetDayType();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case LoadModelPackage.SEASON_DAY_TYPE_SCHEDULE__SEASON:
				setSeason((Season)newValue);
				return;
			case LoadModelPackage.SEASON_DAY_TYPE_SCHEDULE__DAY_TYPE:
				setDayType((DayType)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case LoadModelPackage.SEASON_DAY_TYPE_SCHEDULE__SEASON:
				setSeason((Season)null);
				return;
			case LoadModelPackage.SEASON_DAY_TYPE_SCHEDULE__DAY_TYPE:
				setDayType((DayType)null);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case LoadModelPackage.SEASON_DAY_TYPE_SCHEDULE__SEASON:
				return season != null;
			case LoadModelPackage.SEASON_DAY_TYPE_SCHEDULE__DAY_TYPE:
				return dayType != null;
		}
		return super.eIsSet(featureID);
	}

} // SeasonDayTypeSchedule


text:
require 'gitlab/utils'

module ProjectFeaturesCompatibility
  extend ActiveSupport::Concern

  # TODO: remove in API v5, replaced by *_access_level
  def wiki_enabled=(value)
    write_feature_attribute_boolean(:wiki_access_level, value)
  end

  # TODO: remove in API v5, replaced by *_access_level
  def builds_enabled=(value)
    write_feature_attribute_boolean(:builds_access_level, value)
  end

  # TODO: remove in API v5, replaced by *_access_level
  def merge_requests_enabled=(value)
    write_feature_attribute_boolean(:merge_requests_access_level, value)
  end

  # TODO: remove in API v5, replaced by *_access_level
  def issues_enabled=(value)
    write_feature_attribute_boolean(:issues_access_level, value)
  end

  # TODO: remove in API v5, replaced by *_access_level
  def snippets_enabled=(value)
    write_feature_attribute_boolean(:snippets_access_level, value)
  end

  def repository_access_level=(value)
    write_feature_attribute_string(:repository_access_level, value)
  end

  def wiki_access_level=(value)
    write_feature_attribute_string(:wiki_access_level, value)
  end

  def builds_access_level=(value)
    write_feature_attribute_string(:builds_access_level, value)
  end

  def merge_requests_access_level=(value)
    write_feature_attribute_string(:merge_requests_access_level, value)
  end

  def forking_access_level=(value)
    write_feature_attribute_string(:forking_access_level, value)
  end

  def issues_access_level=(value)
    write_feature_attribute_string(:issues_access_level, value)
  end

  def snippets_access_level=(value)
    write_feature_attribute_string(:snippets_access_level, value)
  end

  def pages_access_level=(value)
    write_feature_attribute_string(:pages_access_level, value)
  end

  def metrics_dashboard_access_level=(value)
    write_feature_attribute_string(:metrics_dashboard_access_level, value)
  end

  private

  def write_feature_attribute_boolean(field, value)
    access_level = Gitlab::Utils.to_boolean(value) ? ProjectFeature::ENABLED : ProjectFeature::DISABLED
    write_feature_attribute_raw(field, access_level)
  end

  def write_feature_attribute_string(field, value)
    access_level = ProjectFeature.access_level_from_str(value)
    write_feature_attribute_raw(field, access_level)
  end

  def write_feature_attribute_raw(field, value)
    build_project_feature unless project_feature

    project_feature.__send__(:write_attribute, field, value) # rubocop:disable GitlabSecurity/PublicSend
  end
end