text:
package org.apache.hadoop.tools.posum.scheduler.portfolio.srtf;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.tools.posum.client.data.Database;
import org.apache.hadoop.tools.posum.common.records.call.JobForAppCall;
import org.apache.hadoop.tools.posum.common.records.dataentity.JobProfile;
import org.apache.hadoop.tools.posum.common.util.communication.DatabaseProvider;
import org.apache.hadoop.tools.posum.simulation.core.SimulationContext;

import java.text.MessageFormat;

import static org.apache.hadoop.tools.posum.common.util.GeneralUtils.orZero;

public class AppWorkCalculator {
  private Log logger = LogFactory.getLog(AppWorkCalculator.class);

  private DatabaseProvider dbProvider;

  protected AppWorkCalculator(DatabaseProvider dbProvider) {
    this.dbProvider = dbProvider;
    if (dbProvider instanceof SimulationContext) {
      logger = LogFactory.getLog("org.apache.hadoop.tools.posum.scheduler.simulation.AppWorkCalculator");
    }
  }

  public void updateRemainingTime(SRTFAppAttempt app) {
    String appId = app.getApplicationId().toString();
    JobProfile job = fetchJobProfile(appId);
    if (job == null) {
      logger.debug("Could not update app priority for : " + app.getApplicationId() + " because job cannot be found");
      return;
    }
    if (app.getJobId() == null) {
      app.setJobId(job.getId());
      app.setSubmitTime(job.getSubmitTime());
    }
    Long avgMapDuration = job.getAvgMapDuration();
    int totalMaps = job.getTotalMapTasks();
    int completedMaps = job.getCompletedMaps();
    if (avgMapDuration == null) {
      logger.debug(MessageFormat.format("Not enough information to calculate remaining time for {0}", app.getJobId()));
      return;
    }

    long totalWork = avgMapDuration * totalMaps;
    long remainingWork = totalWork - avgMapDuration * completedMaps;

    int totalReduceTasks = job.getTotalReduceTasks();
    if (totalReduceTasks > 0) {
      Long avgReduceDuration = orZero(job.getAvgReduceDuration());
      if (avgReduceDuration == 0 && job.getTotalSplitSize() != null && job.getMapOutputBytes() != null) {
        // estimate avg reduce time
        double avgMapSize = job.getTotalSplitSize() / completedMaps;
        double avgMapRate = avgMapDuration / avgMapSize;
        long totalReduceInputSize = orZero(job.getMapOutputBytes()) / completedMaps * totalMaps;
        long reducerInputSize = totalReduceInputSize / totalReduceTasks;
        avgReduceDuration = Double.valueOf(reducerInputSize * avgMapRate).longValue();
      }
      remainingWork += avgReduceDuration * (totalReduceTasks - job.getCompletedReduces());
      totalWork += avgReduceDuration * totalReduceTasks;
    }
    app.setRemainingWork(remainingWork);
    app.setTotalWork(totalWork);
    logger.debug(MessageFormat.format("Work for {0}: remaining={1}, total={2}", app.getJobId(), remainingWork, totalWork));
  }

  private JobProfile fetchJobProfile(String appId) {
    Database db = dbProvider.getDatabase();
    if (db == null)
      // DataMaster is not connected; do nothing
      return null;
    JobForAppCall getJobProfileForApp = JobForAppCall.newInstance(appId);
    JobProfile job = db.execute(getJobProfileForApp).getEntity();
    if (job == null) {
      logger.debug("Could not retrieve job info for " + appId);
      return null;
    }
    return job;
  }
}


text:
def extractWatermelons(item):
	"""
	# World of Watermelons

	"""
	vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
	if not (chp or vol) or 'preview' in item['title'].lower():
		return None
	matches = re.search('\\bB(\\d+)C(\\d+)\\b', item['title'])
	if 'The Desolate Era' in item['tags'] and matches:
		vol, chp = matches.groups()
		postfix = ''
		if '–' in item['title']:
			postfix = item['title'].split('–', 1)[-1]
		return buildReleaseMessageWithType(item, 'Mang Huang Ji', vol, chp, frag=frag, postfix=postfix)
	return False

redpajama_set_name: RedPajamaGithub


text:
#import "NSObject.h"

// Not exported
@interface ML3MigrationDirectives : NSObject
{
    _Bool _needsToRecreateIndexes;
    _Bool _needsToRecreateTriggers;
    _Bool _needsToRemoveLocationsForItemsMissingAssets;
    _Bool _needsToReloadStoreBookmarkMetadataIdentifiers;
    _Bool _needsAnalyze;
    int _userVersion;
}

@property(nonatomic) int userVersion; // @synthesize userVersion=_userVersion;
@property(nonatomic) _Bool needsAnalyze; // @synthesize needsAnalyze=_needsAnalyze;
@property(nonatomic) _Bool needsToReloadStoreBookmarkMetadataIdentifiers; // @synthesize needsToReloadStoreBookmarkMetadataIdentifiers=_needsToReloadStoreBookmarkMetadataIdentifiers;
@property(nonatomic) _Bool needsToRemoveLocationsForItemsMissingAssets; // @synthesize needsToRemoveLocationsForItemsMissingAssets=_needsToRemoveLocationsForItemsMissingAssets;
@property(nonatomic) _Bool needsToRecreateTriggers; // @synthesize needsToRecreateTriggers=_needsToRecreateTriggers;
@property(nonatomic) _Bool needsToRecreateIndexes; // @synthesize needsToRecreateIndexes=_needsToRecreateIndexes;

@end


text:
/**
 * @file
 **/

#include "modules/planning/tasks/optimizers/open_space_trajectory_generation/open_space_trajectory_optimizer.h"

#include "gtest/gtest.h"
#include "modules/planning/proto/open_space_task_config.pb.h"

namespace apollo {
namespace planning {
class OpenSpaceTrajectoryOptimizerTest : public ::testing::Test {
 public:
  virtual void SetUp() {
    OpenSpaceTrajectoryOptimizer open_space_trajectory_optimizer(config);
  }

 protected:
  OpenSpaceTrajectoryOptimizerConfig config;
};

}  // namespace planning
}  // namespace apollo


text:
package com.microsoft.azure.management.labservices.v2018_10_15;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Represents a VM and the setting Id it was created for.
 */
public class ResourceSet {
    /**
     * VM resource Id for the environment.
     */
    @JsonProperty(value = "vmResourceId")
    private String vmResourceId;

    /**
     * resourceSettingId for the environment.
     */
    @JsonProperty(value = "resourceSettingId")
    private String resourceSettingId;

    /**
     * Get vM resource Id for the environment.
     *
     * @return the vmResourceId value
     */
    public String vmResourceId() {
        return this.vmResourceId;
    }

    /**
     * Set vM resource Id for the environment.
     *
     * @param vmResourceId the vmResourceId value to set
     * @return the ResourceSet object itself.
     */
    public ResourceSet withVmResourceId(String vmResourceId) {
        this.vmResourceId = vmResourceId;
        return this;
    }

    /**
     * Get resourceSettingId for the environment.
     *
     * @return the resourceSettingId value
     */
    public String resourceSettingId() {
        return this.resourceSettingId;
    }

    /**
     * Set resourceSettingId for the environment.
     *
     * @param resourceSettingId the resourceSettingId value to set
     * @return the ResourceSet object itself.
     */
    public ResourceSet withResourceSettingId(String resourceSettingId) {
        this.resourceSettingId = resourceSettingId;
        return this;
    }

}


text:
So this is going to be the official MGKNeT.com website. It has a lot of work to be done, soon i will add a TODO, a good readme file and at least a good config file.

##To-Do List
- [x] Contact Form
- [ ] Automaticly generated sitemap
- [ ] Database for the team
- [ ] Database for the portfolio
- [ ] Making the website multy-lang. Starting with (EN/BG)
- [ ] Blog

## Quick install
 1. Download the latest revision of MGKNeT
 2. Copy (or upload) all the files contained in this archive into the directory where you want to run your forums. (e.g. /home/user/www/mgknet/)
 3. Done.

 ## Requirements
 - A webserver
 - PHP 5 and up

## Browser Support

![IE](https://mgknet.com/images/browsers/internet-explorer_48x48.png) | ![Chrome](https://mgknet.com/images/browsers/chrome_48x48.png) | ![Firefox](https://mgknet.com/images/browsers/firefox_48x48.png) | ![Opera](https://mgknet.com/images/browsers/opera_48x48.png) |
![Safari](https://mgknet.com/images/browsers/safari_48x48.png)
--- | --- | --- | --- | --- |
IE 9+ ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ |

## Links
 - [Documentation](http://punbb.informer.com/wiki/)
 - [Twitter](https://twitter.com/mgknetwork)
 - [Development](https://github.com/MGKNeT/MGKNeT.com)


text:
FIND_PATH(LOG4CXX_INCLUDE_DIR logger.h PATHS /include/log4cxx /usr/include/log4cxx /usr/local/include/log4cxx /opt/local/include/log4cxx )
FIND_LIBRARY(LOG4CXX_LIBRARIES NAMES log4cxx log4cxxd PATHS /lib /usr/lib /usr/local/lib /opt/local/lib )

IF(LOG4CXX_INCLUDE_DIR AND LOG4CXX_LIBRARIES)
  SET(LOG4CXX_FOUND 1)
  #remove last /log4cxx string
  STRING(REGEX REPLACE "/log4cxx" "" LOG4CXX_INCLUDE_DIR_SUP_LEVEL ${LOG4CXX_INCLUDE_DIR})
  SET (LOG4CXX_INCLUDE_DIR ${LOG4CXX_INCLUDE_DIR_SUP_LEVEL} ${LOG4CXX_INCLUDE_DIR} )
  if(NOT LOG4CXX_FIND_QUIETLY)
   message(STATUS "Found log4cxx: ${LOG4CXX_LIBRARIES}")
  endif(NOT LOG4CXX_FIND_QUIETLY)
ELSE(LOG4CXX_INCLUDE_DIR AND LOG4CXX_LIBRARIES)
  SET(LOG4CXX_FOUND 0 CACHE BOOL "Not found log4cxx library")
  message(STATUS "NOT Found log4cxx, disabling it")
ENDIF(LOG4CXX_INCLUDE_DIR AND LOG4CXX_LIBRARIES)

MARK_AS_ADVANCED(LOG4CXX_INCLUDE_DIR LOG4CXX_LIBRARIES)


text:
<resources>

  <string name="app_name">Speech engine demo</string>

  <string name="api_key_message">Enter API key</string>

  <string name="api_key_doc_link">See here for more details.</string>

  <string name="select_language_message">Select language. See  here for more details.</string>
</resources>


text:
<tool id="obi_tab" name="obitab" version="@TOOL_VERSION@">
    <description>converts sequence file to a tabular file that can be open by a spreadsheet program or R</description>
    <macros>
        <import>macros.xml</import>
    </macros>
    <expand macro="requirements"/>
    <expand macro="stdio"/>

    <command>

        <![CDATA[
        obitab
        #if $additional_file
            --omit-attribute='$additional_file'
        #end if
        ${output_seq_option}
        ${no_definition_option}
        ${options_inputtype}
        ${options_seqtype}

        '$input' > '$output'
        ]]>

    </command>

    <inputs>
        <param name="input" type="data" format="fastq,fasta,txt,tabular" label="Input sequences file" />
        <param name="output_seq_option" type="boolean" checked="false" truevalue="-o" falsevalue="" label="Do you want to add an extra column?" help="Use this option if you want to add an extra column at the end of the table for the sequence itself"/>
        <param name="no_definition_option" type="boolean" checked="false" truevalue="-d" falsevalue="" label="Do you want to remove column containing the sequence definition?" help="Use this option if you want to remove column containing the sequence definition in the output tab file"/>
        <param name="additional_file" type="data" optional="true" format="tabular" label="filter attributes from tabular file" />
        <param name="options_inputtype" type="select" label="Specify the input datatype">
            <expand macro="inputtype"/>
        </param>
        <param name="options_seqtype" type="select" label="Specify the sequence datatype" >
            <option value="--nuc" selected="true">nucleic</option>
            <option value="--prot">protein</option>
        </param>
    </inputs>
    <outputs>
        <data format="tabular" name="output" label="output.tabular with ${tool.name} on ${on_string}" />
    </outputs>
    <tests>
        <test>
            <param name="input" value="output_obisort.fastq" />
            <param name="output_seq_option" value="False"/>
            <param name="no_definition_option" value="True"/>
            <param name="options_inputtype" value="fasta"/>
            <param name="options_seqtype" value="--prot"/>
            <output name="output" file="output_obitab.txt" ftype="tabular"/>
        </test>
    </tests>
    <help><![CDATA[

.. class:: infomark

**What it does**

obitab command converts sequence file to a tabular file that can be open by a spreadsheet program or R

@OBITOOLS_LINK@

    ]]>
    </help>
    <expand macro="citation" />
    </tool>


text:
#include "vector.h"
#include <assert.h>
#include "safe_memory_operations.h"

struct Vector {
  size_t size;
  size_t capacity;
  size_t elementSize;
  enum VectorMemoryMode memoryMode;
  void* elements;
};

static size_t CalculateCapacity(size_t current_capacity, size_t desired_capacity, enum VectorMemoryMode memoryMode) {
  if (current_capacity >= desired_capacity) {
    return current_capacity;
  }
  else if (memoryMode == VECTOR_GREEDY) {
    return desired_capacity;
  }
  else {
    size_t result = 1;
    while (result < desired_capacity)
      result *= 2;
    return result;
  }
}

Vector_pointer Vector_create(size_t elementSize, enum VectorMemoryMode memoryMode) {
  Vector_pointer this = new(struct Vector);
  this->size = 0;
  this->capacity = 0;
  this->elements = NULL;
  this->elementSize = elementSize;
  this->memoryMode = memoryMode;
  return this;
}

void Vector_destroy(Vector_pointer this) {
  if (this == NULL)
    return;
  free(this->elements);
  this->elements = NULL;
  this->size = 0;
  this->capacity = 0;
  free(this);
}

void Vector_reserve(Vector_pointer this, size_t target_capacity) {
  assert(this != NULL);
  size_t new_capacity = CalculateCapacity(this->capacity, target_capacity, this->memoryMode);
  if (this->capacity != new_capacity) {
    void* new_elements = safe_raw_allocate(new_capacity, this->elementSize);
    safe_raw_copy(new_elements, this->elements, this->size, this->elementSize);
    free(this->elements);
    this->elements = new_elements;
    this->capacity = new_capacity;
  }
}

void Vector_pushBack(Vector_pointer this, const void* pointer) {
  assert(this != NULL);
  Vector_reserve(this, this->size + 1);
  void* new_element_position = safe_raw_offset(this->elements, this->size, this->elementSize);
  safe_raw_copy(new_element_position, pointer, 1, this->elementSize);
  this->size++;
}

void Vector_append(Vector_pointer this, const void* pointer, size_t count) {
  Vector_insertN(this, pointer, Vector_size(this), count);
}

void Vector_popBack(Vector_pointer this) {
  assert(this != NULL);
  assert(this->size > 0);
  this->size--;
}

void Vector_insert(Vector_pointer this, const void* pointer, size_t index) {
  Vector_insertN(this, pointer, index, 1);
}

void Vector_insertN(Vector_pointer this, const void* pointer, size_t index, size_t count) {
  assert(this != NULL);
  assert(0 <= index && index <= this->size);
  Vector_reserve(this, this->size + count);

  void* new_elements_position = safe_raw_offset(this->elements, index, this->elementSize);
  safe_raw_move(new_elements_position, this->size - index, count, this->elementSize);
  safe_raw_copy(new_elements_position, pointer, count, this->elementSize);

  this->size += count;
}

void Vector_remove(Vector_pointer this, size_t index) {
  Vector_removeN(this, index, 1);
}

void Vector_removeN(Vector_pointer this, size_t index, size_t count) {
  assert(this != NULL);
  assert(0 <= index && index + count <= this->size);
  void* next_elements_position = safe_raw_offset(this->elements, index + count, this->elementSize);
  ptrdiff_t offset = -((ptrdiff_t)count);
  safe_raw_move(next_elements_position, this->size - (index + count), offset, this->elementSize);
  this->size -= count;
}

void* Vector_at(Vector_pointer this, size_t index) {
  assert(this != NULL);
  assert(0 <= index);
  assert(index < this->size);
  return safe_raw_offset(this->elements, index, this->elementSize);
}

size_t Vector_size(Vector_pointer this) {
  assert(this != NULL);
  return this->size;
}

bool Vector_empty(Vector_pointer this) {
  assert(this != NULL);
  return this->size == 0;
}

size_t Vector_capacity(Vector_pointer this) {
  assert(this != NULL);
  return this->capacity;
}

void Vector_clear(Vector_pointer this) {
  assert(this != NULL);
  this->size = 0;
}

void* Vector_data(Vector_pointer this) {
  assert(this != NULL);
  return this->elements;
}

void Vector_shrinkToFit(Vector_pointer this) {
  assert(this != NULL);
  if (this->size < this->capacity) {
    void* new_elements = safe_raw_allocate(this->size, this->elementSize);
    safe_raw_copy(new_elements, this->elements, this->size, this->elementSize);
    free(this->elements);
    this->elements = new_elements;
    this->capacity = this->size;
  }
}

void* Vector_back(Vector_pointer this) {
  assert(this != NULL);
  assert(this->size > 0);
  return Vector_at(this, this->size - 1);
}

void* Vector_front(Vector_pointer this) {
  assert(this != NULL);
  assert(this->size > 0);
  return Vector_at(this, 0);
}


text:
# C Hash Table

## Source code for a hash table data structure in C

This code is made available under the terms of the new BSD license.

If you use this code, drop me an email. It's nice to feel useful occasionally.
I promise not to sell your email address to Nigerian spam bandits. Thanks.
Christopher Clark (firstname.lastname @ cl.cam.ac.uk), January 2005.

## Defined functions

  * create_hashtable
  * hashtable_insert
  * hashtable_search
  * hashtable_remove
  * hashtable_count
  * hashtable_destroy

## Example of use

          struct hashtable  *h;
          struct some_key   *k;
          struct some_value *v;

          static unsigned int         hash_from_key_fn( void *k );
          static int                  keys_equal_fn ( void *key1, void *key2 );

          h = create_hashtable(16, hash_from_key_fn, keys_equal_fn);

          insert_key   = (struct some_key *) malloc(sizeof(struct some_key));
          retrieve_key = (struct some_key *) malloc(sizeof(struct some_key));

          v = (struct some_value *) malloc(sizeof(struct some_value));

          (You should initialise insert_key, retrieve_key and v here)

          if (! hashtable_insert(h,insert_key,v) )
          {     exit(-1);               }

          if (NULL == (found = hashtable_search(h,retrieve_key) ))
          {    printf("not found!");                  }

          if (NULL == (found = hashtable_remove(h,retrieve_key) ))
          {    printf("Not found\n");                 }

          hashtable_destroy(h,1); /* second arg indicates "free(value)" */

## Description

The table will increase in size as elements are added, to keep the ratio of elements to table size below a threshold. The table is sized by selecting a prime number of appropriate magnitude, to ensure best distribution of the contents.

For improved type safety, macros have been defined and may be used to define type-safe(r) hashtable access functions, with methods specialized to take known key and value types as parameters. Example: Insert this at the start of your file:

     DEFINE_HASHTABLE_INSERT(insert_some, struct some_key, struct some_value);
     DEFINE_HASHTABLE_SEARCH(search_some, struct some_key, struct some_value);
     DEFINE_HASHTABLE_REMOVE(remove_some, struct some_key, struct some_value);

This defines the functions `insert_some`, `search_some` and `remove_some`. These operate just like hashtable_insert etc., with the same parameters, but their function signatures have `struct some_key *` rather than `void *`, and hence can generate compile time errors if your program is supplying incorrect data as a key (and similarly for value).

Note that the hash and key equality functions passed to create_hashtable still take `void *` parameters instead of `some key *`. This shouldn't be a serious issue as they're only defined and passed once, and the other functions will ensure that only valid keys are supplied to them.

The cost for this checking is increased code size and runtime overhead - if performance is important, it may be worth switching back to the unsafe methods once your program has been debugged with the safe methods.

## Iterator

The iterator is a simple one-way iterator over the hashtable contents, providing accessors for the the key and value at the current element.

        /* Iterator constructor only returns a valid iterator if
         * the hashtable is not empty */

        if (hashtable_count(h) > 0)
        {
            itr = hashtable_iterator(h);
            do {
                k = hashtable_iterator_key(itr);
                v = hashtable_iterator_value(itr);

                /* here (k,v) are a valid (key, value) pair */
                /* We could call 'hashtable_remove(h,k)' - and this operation
                 * 'free's k and returns v.
                 * However, after the operation, the iterator is broken.
                 */

            } while (hashtable_iterator_advance(itr));
        }
        free(itr);

## Notes

You may find this (external) page of [hash functions for strings][1] helpful. Note that the hashtable includes a small section of code to protect against poor hash functions - it may be worthwhile removing this if you are sure you are using a good hash function.

If hashing strings, remember that `strcmp` is not a boolean comparison function directly suitable for `keys_equal_fn`.

Archived copy of the original hashtable implementation, where table size is a power of two, rather than prime. [ hashtable_powers.c ]

[Christopher Clark][2]
Updated 11th January, 2005.

   [1]: http://www.cs.yorku.ca/~oz/hash.html
   [2]: http://www.cl.cam.ac.uk/~cwc22/


text:
title: Automated E2E testing using protractor
date: 2015-09-15T06:00:20+00:00
author: adam.bourg@gmail.com
layout: post
permalink: /2015/09/15/automated-e2e-testing-using-protractor/
categories:
  - javascript
tags:
  - automated
  - e2e tests
  - javascript
  - tdd
  - unit tests
---
At UHG we use Protractor to test our Backbone app for automated E2E dev only regression tests. We do this as apart of an automated CI process to ensure every branch we ingrate doesn't break existing functionaility. Today, I'm going to walk you through our setup and how you can use Protractor (an Angular tool) to test your non-Angular app.

**Get the test runner**

I like running protractor by the CLI as much as the next guy, but you’ll want to get the grunt task runner first. This is available at: https://github.com/teerapap/grunt-protractor-runner

Add the following to your grunt tasks file:

> webdriver: {

> command: ‘./node_modules/webdriver-manager/bin/webdriver-manager start’

> }

This will allow you to now run the protractor instance by:

  1. grunt webdriver // starts the selnium interface
  2. grunt test // runs the tests

**Configure your instance**

To our tasks file we add the following options for protractor:

> protractor: {

> options: {

> configFile: ‘./config/test/protractor-config.js’, // Default config file

> keepAlive: false, // If false, the grunt process stops when the test fails.

> args: {}

> },

> runner: {}

> }

Within the config file we provide a few common global helper methods. Within the config, we supply it a few options.

First, we tell it where the selenium sever is running:

> seleniumAddress: ‘http://127.0.0.1:4444/wd/hub’,

This is the default address location for the default instance.

Next we tell it what testing framework we want to use. Jasmine is default but we have all of our other tests written in Mocha. Mocha bundled with Chai with a Chai As Promised plugin helps us do Async tests.

> framework: ‘mocha’,
>
> mochaOpts: {

> timeout: 10000

> },

Then we have the following onPrepare function that loads a config file and a reusable functions file into the protractor global scope

> onPrepare: function() {

> ‘use strict’;
>
> // Merge in default config options for the global scope

> _.extend(global, globalConfig);
>
> // Merge the object containing all our reusable stuff into the global scope

> _.extend(global, reusableFunctions);

> }

Having things in the global scope that protractor uses; allows us to provide some easy to use default functions that make our testing efforts much easier.

A couple helpers we’ve written are:

  1. Checking for the presence of an element:

    > isPresent: function(element){

    > return browser.isElementPresent(element);

    > },

  2. We abstract the browser sleep function

    > // Allows us to pause to allow the browser to render stuff to the ui browserSleep: function(callback,time){

    > var sleepTime = time ? time : 1000;

    > if(callback){ return browser.sleep(sleepTime).then(callback()); }

    > },

  3. Inject javascript helper:

    > runScript: function(script){ return browser.executeScript(script); },

  4. Inject sinon:

    > injectSinon: function(){ browser.executeScript(“server = sinon.fakeServer.create();”); },

  5. Lastly we need to force the browser to not wait for Angular since this isn’t an Angular app:

    > disableAngularWait: function(){ browser.ignoreSynchronization = true; },

In the image above we use the standard describe / it syntax. We use a before to load the page, setup generic elements and then we fire “done():” which allows us to tell Mocha that the tests are finished.

A line like the one below allows us to check for an element to eventually be present, once the page is done loading, then notify done.

> expect(emailElement.isPresent()).to.eventually.be.true.notify(done);

We can take an element then send it new values, such as an email address field, we provide it an email address to test with:

> emailElement.sendKeys(email)

## Running the code

To run the code we trigger the grunt web driver runner:

> grunt webdriver;

To run the tests:

> grunt test;

Hopefully now you have a better understanding on how to use protractor to do automated UI testing.


text:
'use strict';

import React from 'react';
import _ from 'underscore';
import DropdownButton from 'react-bootstrap/esm/DropdownButton';
import DropdownItem from 'react-bootstrap/esm/DropdownItem';
import Dropdown from 'react-bootstrap/esm/Dropdown';

import { JWT, console, object, layout, ajax, navigate, logger } from '@hms-dbmi-bgm/shared-portal-components/es/components/util';
import { Alerts } from '@hms-dbmi-bgm/shared-portal-components/es/components/ui/Alerts';

import { MicroMetaPlainContainer } from './components/MicroMeta/MicroMetaPlainContainer';
import { Wrapper as ItemHeaderWrapper, TopRow, MiddleRow, BottomRow } from './components/ItemHeader';
import DefaultItemView from './DefaultItemView';
import { CollapsibleItemViewButtonToolbar } from './components/CollapsibleItemViewButtonToolbar';
import { ConfirmModal } from './HiGlassViewConfigView';
import { onLoginNavItemClick } from './../navigation/components/LoginNavItem';

export default class MicroscopeConfigurationView extends DefaultItemView {

    itemHeader() {
        const itemActionsDescriptions = {
            'edit': 'Edit the properties of this Item.',
        };

        return (
            <ItemHeaderWrapper {..._.pick(this.props, 'context', 'href', 'schemas', 'windowWidth')}>
                <TopRow itemActionsDescriptions={itemActionsDescriptions} typeInfoVisible={false} />
                <MiddleRow isInlineEditable={false} className="micro-meta-item-page-heading" />
                <BottomRow />
            </ItemHeaderWrapper>
        );
    }

    getTabViewContents(){
        const initTabs = [];
        const width = this.getTabViewWidth();
        initTabs.push(MicroMetaTabView.getTabObject(this.props, width));
        return initTabs.concat(this.getCommonTabs()); // Add remainder of common tabs (Details, Attribution)
    }

}

export class MicroMetaTabView extends React.PureComponent {

    static getTabObject(props, width) {
        return {
            'tab' :  MicroMeta,
            'key' : 'micrometa',
            'content' : <MicroMetaTabView {...props} width={width} />
        };
    }

    constructor(props){
        super(props);
        this.fullscreenButton = this.fullscreenButton.bind(this);
        this.saveButton = this.saveButton.bind(this);
        this.cloneButton = this.cloneButton.bind(this);
        this.havePermissionToEdit = this.havePermissionToEdit.bind(this);
        this.handleFullscreenToggle = this.handleFullscreenToggle.bind(this);
        this.handleSave = _.throttle(this.handleSave.bind(this), 3000);
        this.handleClone = _.throttle(this.handleClone.bind(this), 3000);
        this.handleModalCancel = _.throttle(this.handleModalCancel.bind(this), 3000);
        this.handleStatusChange = this.handleStatusChange.bind(this);
        this.handleLoginModalConfirm = this.handleLoginModalConfirm.bind(this);
        this.onSaveMicroscope = this.onSaveMicroscope.bind(this);
        this.getMicroscopyMetadataToolComponent = this.getMicroscopyMetadataToolComponent.bind(this);
        this.generateNewTitle = this.generateNewTitle.bind(this);

        this.state = {
            'saveLoading'           : false,
            'cloneLoading'          : false,
            'releaseLoading'        : false,
            'modal'                 : null
        };

        this.microMetaToolRef = React.createRef();

        //force the page display in full screen
        // const { toggleFullScreen } = props;
        // setTimeout(toggleFullScreen, 0, true);
    }

    getMicroscopyMetadataToolComponent(){
        return (this.microMetaToolRef && this.microMetaToolRef.current && this.microMetaToolRef.current.getMicroMetaAppComponent()) || null;
    }

    havePermissionToEdit(){
        const { session, context : { actions = [] } } = this.props;
        return !!(session && _.findWhere(actions, { 'name' : 'edit' }));
    }

    /**
     * Update the current microscope configuration for the user, based on the current data.
     * Note that this function is throttled in constructor() to prevent someone clicking it like, 100 times within 3 seconds.
     * @returns {void}
     */
    handleSave(evt) {
        evt.preventDefault();

        const mtc = this.getMicroscopyMetadataToolComponent();
        if (!mtc || !mtc.api){
            logger.error('Could not get API.');
            throw new Error('Could not get API.');
        }
        const microscopeStr = mtc.api.exportMicroscopeConfString();
        const microscope = microscopeStr && JSON.parse(microscopeStr);

        if (!microscope){
            logger.error('Could not get current configuration.');
            throw new Error('Could not get current configuration.');
        }

        this.onSaveMicroscope(microscope);
    }

    /**
     * Create a new microscope configuration for the user, based on the current data.
     * @returns {void}
     */
    handleClone(evt) {
        const { context } = this.props;
        evt.preventDefault();

        const mtc = this.getMicroscopyMetadataToolComponent();
        if (!mtc || !mtc.api){
            logger.error('Could not get API.');
            throw new Error('Could not get API.');
        }
        const microscopeStr = mtc.api.exportMicroscopeConfString();
        const microscope = microscopeStr && JSON.parse(microscopeStr);

        if (!microscope) {
            logger.error('Could not get current configuration.');
            throw new Error('Could not get current configuration.');
        }

        const microConfTitle = this.generateNewTitle();
        const microConfDesc = context.description;

        microscope.Name = microConfTitle;
        microscope.ID = ''; //remove old microscope's ID to be re-set in backend

        const payload = {
            'title': microConfTitle,
            'description': microConfDesc,
            'microscope': microscope,
            // We don't include other properties and let them come from schema default values.
            // For example, default status is 'draft', which will be used.
            // Lab and award do not carry over as current user might be from different lab.
        };

        // Try to POST/PUT a new viewconf.
        this.setState(
            { 'cloneLoading': true },
            () => {
                ajax.load(
                    '/microscope-configurations/',
                    (resp) => { // We're likely to get a status code of 201 - Created.
                        this.setState({ 'cloneLoading': false }, () => {
                            const newItemHref = object.itemUtil.atId(resp['@graph'][0]);

                            // Redirect the user to the new Microscope display.
                            navigate(newItemHref, {}, (resp) => {
                                // Show alert on new Item page
                                Alerts.queue({
                                    'title': "Saved " + microConfTitle,
                                    'message': "Saved new display.",
                                    'style': 'success'
                                });
                            });
                        });
                    },
                    'POST',
                    () => {
                        // Error callback
                        Alerts.queue({
                            'title': "Failed to save configuration.",
                            'message': "Sorry, can you try to save again?",
                            'style': 'danger'
                        });
                        this.setState({ 'cloneLoading': false });
                    },
                    JSON.stringify(payload)
                );
            }
        );
    }
    /**
     * Generate a new title and description based on the current display.
     */
    generateNewTitle(){
        const { context } = this.props;

        const userDetails = JWT.getUserDetails();
        let userFirstName = "Unknown";

        if (userDetails && typeof userDetails.first_name === 'string' && userDetails.first_name.length > 0) userFirstName = userDetails.first_name;

        const microConfTitleAppendStr = " - " + userFirstName + "'s copy";
        let microConfTitle = context.display_title + microConfTitleAppendStr; // Default, used if title does not already have " - [this user]'s copy" substring.

        // Check if our title already has " - user's copy" substring and if so,
        // increment an appended counter instead of re-adding the substring.
        if (context.display_title.indexOf(microConfTitleAppendStr) > -1) {
            const regexCheck = new RegExp('(' + microConfTitleAppendStr + ')\\s\\(\\d+\\)');
            const regexMatches = context.display_title.match(regexCheck);

            if (regexMatches && regexMatches.length === 2) {
                // regexMatches[0] ==> " - user's copy (int)"
                // regexMatches[1] ==> " - user's copy"
                let copyCount = parseInt(
                    regexMatches[0].replace(regexMatches[1], '')
                        .trim()
                        .replace('(', '')
                        .replace(')', '')
                );

                copyCount++;
                microConfTitle = (
                    context.display_title.replace(regexMatches[0], '') // Remove old " - user's copy (int)" substr
                    + microConfTitleAppendStr + ' (' + copyCount + ')'  // Add new count
                );
            } else {
                // Our title already has " - user's copy" substring, but not an " (int)"
                microConfTitle = context.display_title + ' (2)';
            }
        }

        return microConfTitle;
    }

    /**
      * Cancel/hide modal popup
      * @returns {void}
    */
    handleModalCancel() {
        this.setState({ 'modal': null });
    }

    /**
        * Copies current URL to clipbard.
        * Sets the microscope display status to released if it isn't already.
        *
        * @returns {void}
    */
    handleStatusChange(statusToSet = 'released', evt) {
        evt.preventDefault();

        const { context, href } = this.props;
        const confTitle = context.title || context.display_title;

        // If the view config has already been released, just copy the URL to the clipboard and return.
        if (context.status === statusToSet) {
            return;
        }

        if (!this.havePermissionToEdit()) {
            logger.error('No edit permissions.');
            throw new Error('No edit permissions.');
        }

        // PATCH `status: released` to current href, then in a callback, copy the URL to the clipboard.
        this.setState(
            { 'releaseLoading': true },
            () => {
                ajax.load(
                    href,
                    (resp) => {
                        // Success! Generate an alert telling the user it's successful
                        this.setState({ 'releaseLoading': false });
                        Alerts.queue({
                            'title': "Updated Status for " + confTitle,
                            'message': (

                                    Changed Display status to {statusToSet}.
                                    It may take some time for this edit to take effect.

                            ),
                            'style': 'info'
                        });
                    },
                    'PATCH',
                    (resp) => {
                        // Error callback
                        this.setState({ 'releaseLoading': false });
                        Alerts.queue({
                            'title': "Failed to release display.",
                            'message': "Sorry, can you try to share again?",
                            'style': 'danger'
                        });
                    },
                    JSON.stringify({
                        'status': statusToSet
                    })
                );
            }
        );
    }

    /** @todo make into functional component */
    statusChangeButton(){
        const { session, context } = this.props;
        const { saveLoading, cloneLoading, releaseLoading } = this.state;
        const editPermission = this.havePermissionToEdit();

        if (!session || !editPermission) return null; // TODO: Remove and implement for anon users. Eventually.

        const btnProps = {
            'onSelect'      : this.handleStatusChange,
            //'onClick'       : context.status === 'released' ? null : this.handleStatusChangeToRelease,
            'variant'       : context.status === 'released' ? 'outline-dark' : 'info',
            'disabled'      : releaseLoading,
            'key'           : 'statuschangebtn',
            'data-tip'      : "Change the visibility/permissions of this Microscope Configuration",
            'title'         : (
                <React.Fragment>
                      Manage
                </React.Fragment>
            ),
            'pullRight'     : true
        };

        return (
            <DropdownButton {...btnProps}>
                <StatusMenuItem eventKey="released" context={context}>Visible by Everyone</StatusMenuItem>
                <StatusMenuItem eventKey="released to project" context={context}>Visible by Network</StatusMenuItem>
                {/* <StatusMenuItem eventKey="released to lab" context={context}>Visible by Lab</StatusMenuItem> */}
                <StatusMenuItem eventKey="draft" context={context}>Private</StatusMenuItem>
                <Dropdown.Divider />
                <StatusMenuItem eventKey="deleted" context={context}>Delete</StatusMenuItem>
            </DropdownButton>
        );
    }

    /** @todo make into functional component or move to this components render method */
    saveButton(){
        const { saveLoading } = this.state;
        const tooltip = "Save the current view shown below to this display";

        const editPermission = this.havePermissionToEdit();

        return (
            <button type="button" onClick={this.handleSave} disabled={!editPermission || saveLoading} className="btn btn-success" key="savebtn" data-tip={tooltip}>
                  Save
            </button>
        );
    }

    /** @todo make into functional component or move to this components render method */
    cloneButton(){
        const { session } = this.props;
        const { cloneLoading } = this.state;
        const tooltip = "Create your own new Microscope Configuration based off of this one";

        return (
            <button type="button" onClick={this.handleClone} disabled={!session || cloneLoading} className="btn btn-success" key="clonebtn" data-tip={tooltip}>
                  Clone
            </button>
        );
    }

    /**
     * Is used to call {function} `props.toggleFullScreen` which is passed down from app.js BodyElement.
     */
    handleFullscreenToggle(){
        const { isFullscreen, toggleFullScreen } = this.props;
        setTimeout(toggleFullScreen, 0, !isFullscreen);
    }

    handleLoginModalConfirm() {
        this.setState(function () {
            return { 'modal': null };
        }, onLoginNavItemClick);
    }

    /** @todo make into functional component or move to this components render method */
    fullscreenButton(){
        const { isFullscreen, toggleFullScreen } = this.props;
        if(typeof isFullscreen === 'boolean' && typeof toggleFullScreen === 'function'){
            return (
                <button type="button" className="btn btn-outline-dark" onClick={this.handleFullscreenToggle} data-tip={!isFullscreen ? 'Expand to full screen' : null}>
                    {!isFullscreen ? ' Full Screen' : ' Exit Full Screen'}
                </button>
            );
        }
        return null;
    }

    onSaveMicroscope(microscope, complete) {
        const { href, context, session } = this.props;
        const { modal } = this.state;

        if (!this.havePermissionToEdit()) {
            logger.error('No edit permissions.');
            // I guess would also get caught in ajax error callback.
            // throw new Error('No edit permissions.');
            if (!session) {
                this.setState({
                    'modal': (
                        <ConfirmModal handleConfirm={this.handleLoginModalConfirm} handleCancel={this.handleModalCancel}
                            confirmButtonText="Login" modalTitle="Login Required">
                            Log in or create an account to save this configuration.
                        </ConfirmModal>
                    )
                });
            } else {
                this.setState({
                    'modal': (
                        <ConfirmModal handleCancel={this.handleModalCancel}
                            cancelButtonText="Close" confirmButtonVisible={false} modalTitle="Permission Denied">
                            Access was denied to save this configuration.
                        </ConfirmModal>
                    )
                });
            }

            return;
        }

        //determine save or save as clicked
        //todo: It would be better if this information provided from micrometa api
        const mtc = this.getMicroscopyMetadataToolComponent();
        if (!mtc || !mtc.api) {
            throw new Error('Could not get API.');
        }
        const microscopeStr = mtc.api.exportMicroscopeConfString();
        const microscopeOrig = microscopeStr && JSON.parse(microscopeStr);

        //save as
        if (microscopeOrig.ID !== microscope.ID) {
            const microConfTitle = this.generateNewTitle();
            const microConfDesc = context.description;

            microscope.Name = microConfTitle;

            const payload = {
                'title': microConfTitle,
                'description': microConfDesc,
                'microscope': microscope,
                // We don't include other properties and let them come from schema default values.
                // For example, default status is 'draft', which will be used.
                // Lab and award do not carry over as current user might be from different lab.
            };

            // Try to POST/PUT a new viewconf.
            this.setState(
                { 'cloneLoading': true },
                () => {
                    ajax.load(
                        '/microscope-configurations/',
                        (resp) => { // We're likely to get a status code of 201 - Created.
                            this.setState({ 'cloneLoading': false }, () => {
                                const newItemHref = object.itemUtil.atId(resp['@graph'][0]);

                                // Redirect the user to the new Microscope display.
                                navigate(newItemHref, {}, (resp) => {
                                    // Show alert on new Item page
                                    Alerts.queue({
                                        'title': "Saved " + microConfTitle,
                                        'message': "Saved new display.",
                                        'style': 'success'
                                    });
                                });
                            });
                        },
                        'POST',
                        () => {
                            // Error callback
                            Alerts.queue({
                                'title': "Failed to save configuration.",
                                'message': "Sorry, can you try to save again?",
                                'style': 'danger'
                            });
                            this.setState({ 'cloneLoading': false });
                        },
                        JSON.stringify(payload)
                    );
                }
            );
            if (complete) {
                complete(microscope.Name);
            }

            console.log('SAVE AS CLICKED: microscope.ID:', microscope.ID, ', microscopeOrig.ID:', microscopeOrig.ID);

            return;
        }

        if (modal == null && context.status && typeof context.status === 'string' &&
            (context.status === 'released' || context.status === 'released to project')) {
            this.setState({
                'modal': (
                    <ConfirmModal handleConfirm={this.handleSave} handleCancel={this.handleModalCancel}
                        confirmButtonText="Save" cancelButtonText="Cancel" modalTitle="Confirm Save">
                        You are overwriting a Microscope Configuration Item that was previously shared with public. Are you sure?

Note that you can also clone this display and share the new copy.
                    </ConfirmModal>
                )
            });
            return;
        }

        // We're updating this object's microscope.
        const payload = {
            'title': microscope.Name,
            'description': microscope.Description || '',
            'microscope': microscope
        };

        this.setState({ 'saveLoading': true, 'modal': null }, () => {
            ajax.load(
                href,
                (resp) => {
                    // Success callback... maybe update state.originalViewConfigString or something...
                    // At this point we're saved maybe just notify user somehow if UI update re: state.saveLoading not enough.
                    Alerts.queue({
                        'title': "Saved " + microscope.Name,
                        'message': "This Microscope Configuration Item has been updated with the current viewport. This may take a few minutes to take effect.",
                        'style': 'success'
                    });
                    this.setState({ 'saveLoading': false });
                },
                'PATCH',
                () => {
                    // Error callback
                    Alerts.queue({
                        'title': "Failed to save display.",
                        'message': "Sorry, can you try to save again?",
                        'style': 'danger'
                    });
                    this.setState({ 'saveLoading': false });
                },
                JSON.stringify(payload)
            );
        });

        if (complete) {
            complete(microscope.Name);
        }
    }

    render(){
        const { isFullscreen, context, windowWidth, windowHeight } = this.props;
        const { modal } = this.state;

        const width = isFullscreen ? windowWidth - 40 : layout.gridContainerWidth(windowWidth);
        const height = isFullscreen ? Math.max(800, windowHeight - 120) : Math.max(800, windowHeight / 2);

        return (

                    4DN MicroMeta
                    <CollapsibleItemViewButtonToolbar windowWidth={windowWidth}
                        constantButtons={this.fullscreenButton()} collapseButtonTitle={this.collapseButtonTitle}>
                        {/* {this.saveButton()}
                        {this.cloneButton()}
                        {this.statusChangeButton()} */}
                    </CollapsibleItemViewButtonToolbar>

                {/*
 */}

                        <MicroMetaPlainContainer {..._.omit(this.props, 'context', 'microscope')}
                            {...{ width, height, onSaveMicroscope: this.onSaveMicroscope, microscopeConfig: context.microscope }}
                            ref={this.microMetaToolRef} zoomVisible={false} />

                {modal}

        );
    }

}

function StatusMenuItem(props){
    const { eventKey, context, children } = props;
    const active = context.status === eventKey;
    return (
        <DropdownItem {..._.omit(props, 'context')} active={active}>

                   { children }

        </DropdownItem>
    );
}


text:
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/line_width_dialog"
    android:columnCount="1"
    android:orientation="vertical"
    android:useDefaultMargins="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin">

    <ImageView
        android:id="@+id/width_image_view"
        android:layout_width="wrap_content"
        android:layout_height="@dimen/line_imageview_height"
        android:layout_gravity="fill_horizontal"
        android:contentDescription="@string/line_imageview_description" />

    <SeekBar
        android:id="@+id/width_seekbar"
        android:max="50"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="fill_horizontal" />

</GridLayout>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<wicket:head>

</wicket:head>

<wicket:extend>

		Title

		Instructions here

	<form wicket:id="form">

<wicket:message key="searchSites"/>

					<wicket:message key="siteIdTitleField"/>

					<input type="text" wicket:id="search" />

					<input type="text" wicket:id="instructorField" />

					<wicket:container wicket:id="instructorOptionsGroup">
					    <input wicket:id="instructorOption" type="radio" name="ticker"/><wicket:message key="instructor"/>
					    <input wicket:id="memberOption" type="radio" name="ticker"/><wicket:message key="member"/>
				  </wicket:container>

			<wicket:enclosure child="termField">

						<wicket:message key="termField"/>

						<select wicket:id="termField">
						</select>

			</wicket:enclosure>

				<wicket:component wicket:id="hierarchyDropdowns">

							Dept:

							<select wicket:id="hierarchyLevel" onchange=" this.form.submit();"/>

				</wicket:component>

					<input type="submit" onclick="loadSemaphore = true; showLoading();"/>

	</form>

	<wicket:enclosure child="tree">

	</wicket:enclosure>

</wicket:extend>


text:
#pragma once
#include <aws/greengrassv2/GreengrassV2_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace GreengrassV2
{
namespace Model
{

  /**
   *
Contains information about a component version in a list.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_GREENGRASSV2_API ComponentVersionListItem
  {
  public:
    ComponentVersionListItem();
    ComponentVersionListItem(Aws::Utils::Json::JsonView jsonValue);
    ComponentVersionListItem& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The name of the component.

     */
    inline const Aws::String& GetComponentName() const{ return m_componentName; }

    /**
     *
The name of the component.

     */
    inline bool ComponentNameHasBeenSet() const { return m_componentNameHasBeenSet; }

    /**
     *
The name of the component.

     */
    inline void SetComponentName(const Aws::String& value) { m_componentNameHasBeenSet = true; m_componentName = value; }

    /**
     *
The name of the component.

     */
    inline void SetComponentName(Aws::String&& value) { m_componentNameHasBeenSet = true; m_componentName = std::move(value); }

    /**
     *
The name of the component.

     */
    inline void SetComponentName(const char* value) { m_componentNameHasBeenSet = true; m_componentName.assign(value); }

    /**
     *
The name of the component.

     */
    inline ComponentVersionListItem& WithComponentName(const Aws::String& value) { SetComponentName(value); return *this;}

    /**
     *
The name of the component.

     */
    inline ComponentVersionListItem& WithComponentName(Aws::String&& value) { SetComponentName(std::move(value)); return *this;}

    /**
     *
The name of the component.

     */
    inline ComponentVersionListItem& WithComponentName(const char* value) { SetComponentName(value); return *this;}

    /**
     *
The version of the component.

     */
    inline const Aws::String& GetComponentVersion() const{ return m_componentVersion; }

    /**
     *
The version of the component.

     */
    inline bool ComponentVersionHasBeenSet() const { return m_componentVersionHasBeenSet; }

    /**
     *
The version of the component.

     */
    inline void SetComponentVersion(const Aws::String& value) { m_componentVersionHasBeenSet = true; m_componentVersion = value; }

    /**
     *
The version of the component.

     */
    inline void SetComponentVersion(Aws::String&& value) { m_componentVersionHasBeenSet = true; m_componentVersion = std::move(value); }

    /**
     *
The version of the component.

     */
    inline void SetComponentVersion(const char* value) { m_componentVersionHasBeenSet = true; m_componentVersion.assign(value); }

    /**
     *
The version of the component.

     */
    inline ComponentVersionListItem& WithComponentVersion(const Aws::String& value) { SetComponentVersion(value); return *this;}

    /**
     *
The version of the component.

     */
    inline ComponentVersionListItem& WithComponentVersion(Aws::String&& value) { SetComponentVersion(std::move(value)); return *this;}

    /**
     *
The version of the component.

     */
    inline ComponentVersionListItem& WithComponentVersion(const char* value) { SetComponentVersion(value); return *this;}

    /**
     *
The ARN
     * of the component version.

     */
    inline const Aws::String& GetArn() const{ return m_arn; }

    /**
     *
The ARN
     * of the component version.

     */
    inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; }

    /**
     *
The ARN
     * of the component version.

     */
    inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; }

    /**
     *
The ARN
     * of the component version.

     */
    inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); }

    /**
     *
The ARN
     * of the component version.

     */
    inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); }

    /**
     *
The ARN
     * of the component version.

     */
    inline ComponentVersionListItem& WithArn(const Aws::String& value) { SetArn(value); return *this;}

    /**
     *
The ARN
     * of the component version.

     */
    inline ComponentVersionListItem& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;}

    /**
     *
The ARN
     * of the component version.

     */
    inline ComponentVersionListItem& WithArn(const char* value) { SetArn(value); return *this;}

  private:

    Aws::String m_componentName;
    bool m_componentNameHasBeenSet = false;

    Aws::String m_componentVersion;
    bool m_componentVersionHasBeenSet = false;

    Aws::String m_arn;
    bool m_arnHasBeenSet = false;
  };

} // namespace Model
} // namespace GreengrassV2
} // namespace Aws


text:
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
from django.core.urlresolvers import reverse_lazy
from clientes.models import Cliente
from profesores.models import Profesor
import datetime

class Curso(models.Model):
    nombre = models.CharField(max_length=25,default="")
    precio = models.FloatField(default=100)
    ##No obligatorios
    examen = models.CharField(max_length=25,default="",blank=True,null=True)
    nivel = models.CharField(max_length=25,default="",blank=True,null=True)
    libros = models.ManyToManyField('Libro')
    nota_aprobado = models.FloatField(default=50)
    solo_examen_final = models.BooleanField(default=False)

#~ class CursoIntensivo(models.Model):
    #~ cliente = models.ForeignKey(Cliente)
    #~ nombre = models.CharField(max_length=100)
    #~ inicio = models.DateField(default=datetime.date.today())
    #~ fin = models.DateField(default=datetime.date.today())
    #~ def __unicode__(self):
        #~ return "%s - %s"%(self.cliente.nombre,self.nombre)
    #~ def get_absolute_url(self):
        #~ return reverse_lazy("curso_detalle",args=[self.id])

class Libro(models.Model):
    titulo = models.CharField(max_length=25,default="")
    autor = models.CharField(max_length=25,default="")
    isbn = models.CharField(max_length=25,default="")
    editorial = models.CharField(max_length=25,default="")

class Festivo(models.Model):
    ano = models.DecimalField(max_digits=4,decimal_places=0)
    mes = models.DecimalField(max_digits=2,decimal_places=0)
    dia = models.DecimalField(max_digits=2,decimal_places=0)
    inicio = models.BooleanField(default=False)
    fin = models.BooleanField(default=False)
    observaciones = models.CharField(max_length=250,default="",blank=True,null=True)


text: exec python -m pydo "$@"


text:
package com.tesshu.subsonic.client.fx.view;

import javafx.beans.property.BooleanProperty;

public interface IOwnerFocusListenable {

  BooleanProperty ownerFocusedProperty();

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.wildfly.swarm</groupId>
    <artifactId>build-parent</artifactId>
    <version>2018.2.0-SNAPSHOT</version>
    <relativePath>../../../build-parent/pom.xml</relativePath>
  </parent>

  <groupId>org.wildfly.swarm</groupId>
  <artifactId>jsonp</artifactId>

  <name>JSON-P</name>
  <description>JSON-P</description>

  <packaging>jar</packaging>

  <properties>
    <swarm.fraction.bootstrap>true</swarm.fraction.bootstrap>
    <swarm.fraction.stability>stable</swarm.fraction.stability>
    <swarm.fraction.tags>JavaEE,JSON</swarm.fraction.tags>
  </properties>

  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
  </build>

  <dependencies>
    <!-- Fraction Dependencies -->
    <dependency>
      <groupId>org.wildfly.swarm</groupId>
      <artifactId>logging</artifactId>
    </dependency>

    <!-- Provided APIs -->
    <dependency>
      <groupId>org.glassfish</groupId>
      <artifactId>javax.json</artifactId>
    </dependency>

    <!-- Meta SPI -->
    <dependency>
      <groupId>org.wildfly.swarm</groupId>
      <artifactId>meta-spi</artifactId>
    </dependency>

    <dependency>
      <groupId>org.wildfly.core</groupId>
      <artifactId>wildfly-core-feature-pack</artifactId>
      <type>zip</type>
      <scope>provided</scope>
      <exclusions>
        <exclusion>
          <groupId>*</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.wildfly</groupId>
      <artifactId>wildfly-servlet-feature-pack</artifactId>
      <type>zip</type>
      <scope>provided</scope>
      <exclusions>
        <exclusion>
          <groupId>*</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.wildfly</groupId>
      <artifactId>wildfly-feature-pack</artifactId>
      <type>zip</type>
      <scope>provided</scope>
      <exclusions>
        <exclusion>
          <groupId>*</groupId>
          <artifactId>*</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
  </dependencies>

</project>


text:
from pygame import *
from Game.const import *

class Sound(object):
	""" Play sound effects """

	def __init__(self):
		# All sound effects

		if not mac:
			self.coinCollected = mixer.Sound("resources/sound/coinCollected.wav")

			# I was going to use dictionaries but it was too slow...

			self.themes = {
				"mainWorldFight" : "resources/sound/mainWorldFight.ogg",
				"mainWorldTheme" : "resources/sound/mainWorldTheme.ogg",
				"waterWorldTheme" : "resources/sound/waterWorld.ogg",
				"shopTheme" : "resources/sound/shop.ogg",
				"fireWorldTheme" : "resources/sound/fireWorld.ogg",
				"conclusion" : "resources/sound/conclusion.ogg",
				"introTheme" : "resources/sound/introTheme.ogg",
				"churchTheme" : "resources/sound/church.ogg",
				"castleTheme" : "resources/sound/castle.ogg",
				"finalTempleTheme" : "resources/sound/temple.ogg"
			}

			# # Key -> scenename | value -> theme name
			# self.sceneData = {
			# 	"mainWorld" : "mainWorldTheme",
			# 	"mainWorldShop" : "shopTheme",
			# 	"waterWorldEnter" : "waterWorldTheme",
			# 	"waterWorld" : "waterWorldTheme",
			# 	"waterWorldRoom1" : "waterWorldTheme",
			# 	"waterWorldRoom2" : "waterWorldTheme",
			# 	"waterWorldRoom3" : "waterWorldTheme",
			# 	"waterWorldRoom4" : "waterWorldTheme",
			# 	"fireWorldEnter" : "fireWorldTheme",
			# 	"fireWorld" : "fireWorldTheme",
			# 	"fireWorldRoom1" : "fireWorldTheme",
			# 	"fireWorldRoom2" : "fireWorldTheme",
			# 	"church" : "churchTheme",
			# 	"ultimateShop" : "shopTheme",
			# 	"surpriseTemple" : "castleTheme",
			# 	"finalTemple" : "finalTempleTheme"
			# }

			# Set sound and theme volumes
			self.coinCollected.set_volume(.8)
			mixer.music.set_volume(.6)

	def getMusic(self, sound):
		""" Return music themes """
		return self.themes[sound]

	def stopSound(self, sound):
		""" Stops specific sound """
		self.sounds[sound].fadeout(500)

	def stopMusic(self):
		""" Stop mixer """
		mixer.music.fadeout(500)

	# def setVolume(self, amount):
	# 	""" Set volume """
	# 	mixer.music.set_volume(amount)


text:
namespace views {

// static
bool UnhandledKeyboardEventHandler::HandleNativeKeyboardEvent(
    gfx::NativeEvent event,
    FocusManager* focus_manager) {
  return !focus_manager->OnKeyEvent(*(event->AsKeyEvent()));
}

}  // namespace views


text:
"""Utility module that contains APIs usable in the generated code."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.contrib.py2tf.utils.context_managers import control_dependency_on_returns
from tensorflow.contrib.py2tf.utils.misc import alias_tensors


text:
package cn.momia.jobs.notify.impl;

import cn.momia.common.service.AbstractService;
import cn.momia.jobs.notify.Notifier;

public class PackageExpiredNotifier extends AbstractService implements Notifier {
    @Override
    public void notifyUser() {

    }
}


text:
class Groovysdk < Formula
  desc "SDK for Groovy: a Java-based scripting language"
  homepage "http://www.groovy-lang.org"
  url "https://dl.bintray.com/groovy/maven/apache-groovy-sdk-2.5.4.zip"
  sha256 "f8e32382ff0b4079e70d47f776363b86ce5ec0ffe56d73608c3ec1dca8d01fc0"

  bottle :unneeded

  # Groovy 2.5 requires JDK8+ to build and JDK7 is the minimum version of the JRE that we support.
  depends_on :java => "1.7+"

  conflicts_with "groovy", :because => "both install the same binaries"

  def install
    ENV["GROOVY_HOME"] = libexec

    # We don't need Windows' files.
    rm_f Dir["bin/*.bat"]

    prefix.install_metafiles
    bin.install Dir["bin/*"]
    libexec.install "conf", "lib", "src", "doc"
    bin.env_script_all_files(libexec+"bin", :GROOVY_HOME => ENV["GROOVY_HOME"])
  end

  test do
    system "#{bin}/grape", "install", "org.activiti", "activiti-engine", "5.16.4"
  end
end


text:
var angular = require('angular');

# content #

module.exports = $module;


text:
using System.Runtime.InteropServices;
public class Leader
{

    private void Leader_Load(object sender, System.EventArgs e)
    {
        SolidEdgeFramework.Application objApplication = null;
        SolidEdgeDraft.DraftDocument objDraftDocument = null;
        SolidEdgeDraft.Sheet objSheet = null;

        SolidEdgeFrameworkSupport.Leaders objLeaders = null;
        SolidEdgeFrameworkSupport.Leader objLeader = null;
        SolidEdgeFrameworkSupport.TextBoxes objTextBoxes = null;
        SolidEdgeFrameworkSupport.TextBox objTextBox = null;

        try
        {
            objApplication = Microsoft.VisualBasic.Interaction.GetObject(null, "SolidEdge.Application");
            objApplication.Visible = true;
            objDraftDocument = objApplication.ActiveDocument;
            objSheet = objDraftDocument.ActiveSheet;

            //Following Code will add Text in the sheet
            objTextBoxes = objSheet.TextBoxes;
            objTextBox = objTextBoxes.Add(0.25, 0.25, 0);
            objTextBox.TextScale = 1;
            objTextBox.VerticalAlignment = SolidEdgeFrameworkSupport.TextVerticalAlignmentConstants.igTextHzAlignVCenter;
            objTextBox.Text = "Leader";

            //Following Code will add Leader in the sheet
            objLeaders = objSheet.Leaders;
            objLeader = objLeaders.Add(0.225, 0.225, 0, 0.25, 0.25, 0);
            objLeader.Style.FreeSpaceTerminatorType = SolidEdgeFrameworkSupport.DimTermTypeConstants.igDimStyleTermFilled; // Change Terminator type if Required.

            Marshal.ReleaseComObject(objSheet);
            objSheet = null;
            Marshal.ReleaseComObject(objDraftDocument);
            objDraftDocument = null;
            Marshal.ReleaseComObject(objTextBox);
            objTextBox = null;

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

    public Leader()
    {
    	SubscribeToEvents();
    }

	private bool EventsSubscribed = false;
	private void SubscribeToEvents()
	{
		if (EventsSubscribed)
			return;
		else
			EventsSubscribed = true;

		base.Load += Leader_Load;
	}

}


text:
package apns

import (
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"net"
	"testing"
	"time"
)

func writeToken(b []byte, token string) {
	tokenBytes, _ := hex.DecodeString(token)
	for i := 0; i < 32; i++ {
		b[i] = tokenBytes[i]
	}
}

type MockConnTokens struct {
	WriteHeaderState *bool
	CurrentResponse  **FeedbackResponse
	ResponseChannel  chan *FeedbackResponse
	CloseChannel     chan bool
}

func (conn MockConnTokens) Read(b []byte) (n int, err error) {
	if !(*conn.WriteHeaderState) {
		//write token
		writeToken(b, (*conn.CurrentResponse).Token)

		(*conn.WriteHeaderState) = true

		return 32, nil
	} else {
		select {
		case r := <-conn.ResponseChannel:
			(*conn.CurrentResponse) = r

			//write time in big endian
			b[0] = uint8(r.Timestamp >> 24)
			b[1] = uint8(r.Timestamp >> 16)
			b[2] = uint8(r.Timestamp >> 8)
			b[3] = uint8(r.Timestamp)

			//write token size
			b[4] = uint8(0)
			b[5] = uint8(32)

			(*conn.WriteHeaderState) = false

			return 6, nil
		case <-conn.CloseChannel:
			return 0, io.EOF
		}
	}
}
func (conn MockConnTokens) Write(b []byte) (n int, err error) {
	return 0, nil
}
func (conn MockConnTokens) Close() error {
	return nil
}
func (conn MockConnTokens) LocalAddr() net.Addr {
	return nil
}
func (conn MockConnTokens) RemoteAddr() net.Addr {
	return nil
}
func (conn MockConnTokens) SetDeadline(t time.Time) error {
	return nil
}
func (conn MockConnTokens) SetReadDeadline(t time.Time) error {
	return nil
}
func (conn MockConnTokens) SetWriteDeadline(t time.Time) error {
	return nil
}

func TestFeedbackServiceReadShouldReturnTokens(t *testing.T) {
	var writeHeaderState = true
	var feedbackResponse = &FeedbackResponse{}
	socket := MockConnTokens{
		CurrentResponse:  &feedbackResponse,
		WriteHeaderState: &writeHeaderState,
		ResponseChannel:  make(chan *FeedbackResponse),
		CloseChannel:     make(chan bool),
	}

	token := "4ec500020d8350072d2417ba566feda10b2b266558371a65ba67fede21393c8f"
	token2 := "4ec500020d8350072d2417ba566feda10b2b266558371a65ba67fede21393c8e"
	token3 := "4ec500020d8350072d2417ba566feda10b2b266558371a65ba67fede21393c8d"
	token4 := "4ec500020d8350072d2417ba566feda10b2b266558371a65ba67fede21393c8c"

	timestamp := uint32(837431)

	go func() {
		r1 := &FeedbackResponse{
			Timestamp: timestamp,
			Token:     token,
		}
		r2 := &FeedbackResponse{
			Timestamp: uint32(837432),
			Token:     token2,
		}
		r3 := &FeedbackResponse{
			Timestamp: uint32(837433),
			Token:     token3,
		}
		r4 := &FeedbackResponse{
			Timestamp: uint32(837434),
			Token:     token4,
		}

		socket.ResponseChannel <- r1
		socket.ResponseChannel <- r2
		socket.ResponseChannel <- r3
		socket.ResponseChannel <- r4
		socket.CloseChannel <- true
	}()

	responses, err := readFromFeedbackService(socket)
	if err != nil {
		fmt.Printf("Shouldn't have received an error but got %v\n", err)
		t.FailNow()
	}

	if responses.Len() != 4 {
		fmt.Printf("Should've received 4 tokens\n")
		t.FailNow()
	}

	var res = responses.Front()
	recToken := res.Value.(*FeedbackResponse).Token
	recTime := res.Value.(*FeedbackResponse).Timestamp
	res = res.Next()
	recToken2 := res.Value.(*FeedbackResponse).Token
	res = res.Next()
	recToken3 := res.Value.(*FeedbackResponse).Token
	res = res.Next()
	recToken4 := res.Value.(*FeedbackResponse).Token

	if recToken != token {
		fmt.Printf("Should've received token %v but got %v\n", token, recToken)
		t.FailNow()
	}

	if recToken2 != token2 {
		fmt.Printf("Should've received token2 %v but got %v\n", token2, recToken2)
		t.FailNow()
	}

	if recToken3 != token3 {
		fmt.Printf("Should've received token3 %v but got %v\n", token3, recToken3)
		t.FailNow()
	}

	if recToken4 != token4 {
		fmt.Printf("Should've received token4 %v but got %v\n", token4, recToken4)
		t.FailNow()
	}

	if recTime != timestamp {
		fmt.Printf("Should've received timestamp %v but got %v\n", timestamp, recTime)
		t.FailNow()
	}
}

type MockConnTokensAndErr struct {
	WriteHeaderState *bool
	CurrentResponse  **FeedbackResponse
	ResponseChannel  chan *FeedbackResponse
	CloseChannel     chan bool
}

func (conn MockConnTokensAndErr) Read(b []byte) (n int, err error) {
	if !(*conn.WriteHeaderState) {
		//write token
		writeToken(b, (*conn.CurrentResponse).Token)

		(*conn.WriteHeaderState) = true

		return 32, nil
	} else {
		select {
		case r := <-conn.ResponseChannel:
			(*conn.CurrentResponse) = r

			//write time in big endian
			b[0] = uint8(r.Timestamp >> 24)
			b[1] = uint8(r.Timestamp >> 16)
			b[2] = uint8(r.Timestamp >> 8)
			b[3] = uint8(r.Timestamp)

			//write token size
			b[4] = uint8(0)
			b[5] = uint8(32)

			(*conn.WriteHeaderState) = false

			return 6, nil
		case <-conn.CloseChannel:
			return 0, errors.New("Some random error")
		}
	}
}
func (conn MockConnTokensAndErr) Write(b []byte) (n int, err error) {
	return 0, nil
}
func (conn MockConnTokensAndErr) Close() error {
	return nil
}
func (conn MockConnTokensAndErr) LocalAddr() net.Addr {
	return nil
}
func (conn MockConnTokensAndErr) RemoteAddr() net.Addr {
	return nil
}
func (conn MockConnTokensAndErr) SetDeadline(t time.Time) error {
	return nil
}
func (conn MockConnTokensAndErr) SetReadDeadline(t time.Time) error {
	return nil
}
func (conn MockConnTokensAndErr) SetWriteDeadline(t time.Time) error {
	return nil
}

func TestFeedbackServiceReadShouldReturnTokensAndError(t *testing.T) {
	var writeHeaderState = true
	var feedbackResponse = &FeedbackResponse{}
	socket := MockConnTokensAndErr{
		CurrentResponse:  &feedbackResponse,
		WriteHeaderState: &writeHeaderState,
		ResponseChannel:  make(chan *FeedbackResponse),
		CloseChannel:     make(chan bool),
	}

	token := "4ec500020d8350072d2417ba566feda10b2b266558371a65ba67fede21393c8f"
	token2 := "4ec500020d8350072d2417ba566feda10b2b266558371a65ba67fede21393c8e"
	token3 := "4ec500020d8350072d2417ba566feda10b2b266558371a65ba67fede21393c8d"
	token4 := "4ec500020d8350072d2417ba566feda10b2b266558371a65ba67fede21393c8c"

	go func() {
		r1 := &FeedbackResponse{
			Timestamp: uint32(837431),
			Token:     token,
		}
		r2 := &FeedbackResponse{
			Timestamp: uint32(837432),
			Token:     token2,
		}
		r3 := &FeedbackResponse{
			Timestamp: uint32(837433),
			Token:     token3,
		}
		r4 := &FeedbackResponse{
			Timestamp: uint32(837434),
			Token:     token4,
		}

		socket.ResponseChannel <- r1
		socket.ResponseChannel <- r2
		socket.ResponseChannel <- r3
		socket.ResponseChannel <- r4
		socket.CloseChannel <- true
	}()

	responses, err := readFromFeedbackService(socket)
	if err == nil {
		fmt.Printf("Should have received an error\n")
		t.FailNow()
	}

	if responses.Len() != 4 {
		fmt.Printf("Should've received 4 tokens\n")
		t.FailNow()
	}

	var res = responses.Front()
	recToken := res.Value.(*FeedbackResponse).Token
	res = res.Next()
	recToken2 := res.Value.(*FeedbackResponse).Token
	res = res.Next()
	recToken3 := res.Value.(*FeedbackResponse).Token
	res = res.Next()
	recToken4 := res.Value.(*FeedbackResponse).Token

	if recToken != token {
		fmt.Printf("Should've received token %v but got %v\n", token, recToken)
		t.FailNow()
	}

	if recToken2 != token2 {
		fmt.Printf("Should've received token2 %v but got %v\n", token2, recToken2)
		t.FailNow()
	}

	if recToken3 != token3 {
		fmt.Printf("Should've received token3 %v but got %v\n", token3, recToken3)
		t.FailNow()
	}

	if recToken4 != token4 {
		fmt.Printf("Should've received token4 %v but got %v\n", token4, recToken4)
		t.FailNow()
	}
}


text:
import ApolloClient, {
  createNetworkInterface,
  addTypeName,
} from 'apollo-client';
import { BASE_URL } from './config';
const url = `${BASE_URL}graphql`;

const client = new ApolloClient({
  networkInterface: createNetworkInterface(url),
  initialState: typeof window !== 'undefined' ? window.__APOLLO_STATE__ : null,
  queryTransformer: addTypeName,
});

export default client;


text:
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
env = ENV['RAILS_ENV'] || "development"
require 'bundler/setup' # Set up gems listed in the Gemfile.
require 'bootsnap/setup' if (env == "development") || (env == "test") # Speed up boot time by caching expensive operations.

if ENV['DOCKER']
  require 'rails/commands/server'

  module Rails
    class Server
      alias :default_options_bk :default_options
      def default_options
        default_options_bk.merge!(Host: '0.0.0.0')
      end
    end
  end
end


text:
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';

export default class Input extends PureComponent {
  static propTypes = {
    onChange: PropTypes.func.isRequired
  };

  state = { value: '' };

  clear = () => this.setState(
    () => ({ value: '' }),
    () => this.props.onChange({ target: { value: '' } })
  );

  handleChange = (e) => {
    e.persist();
    this.setState(
      () => ({ value: e.target.value }),
      () => this.props.onChange(e)
    );
  }

  render() {
    return (
      <input
        type="text"
        value={ this.state.value }
        onChange={ this.handleChange }
      />
    );
  }
}


text:
require 'zip'
class Complaint < ApplicationRecord
  mount_uploaders :media, MediaUploader
  validates :content, presence: true
  validates_integrity_of :media
  validate :file_size
  after_initialize :create_key
  after_initialize :create_pin

  belongs_to :user, dependent: :destroy
  # has_many :allegations
  # has_many :allegation_types, through: :allegations
  has_many :messages, dependent: :destroy
  has_many :video_links, dependent: :destroy

  def self.possible_statuses
    ["New", "Non-Actionable", "Pending", "Initiated-Investigation"]
  end

  def possible_other_statuses #returns non-current status options
    return Complaint.possible_statuses.reject {|st| st == self.status}
  end

  def content_shortened
    if self.content.split(" ").length>10
      return self.content.split(" ")[0..10].join(" ") + "..."
    end
    return self.content
  end

  def video_links_array
    array = self.video_links.map{|link| link.url}
    array
  end

  def create_key
    rand_key = SecureRandom.hex(5)
    until Complaint.find_by(key: rand_key) == nil
      rand_key = SecureRandom.hex(5)
    end
    self.key = rand_key if !self.key
  end

  def create_pin
    tipster_pin = Devise.friendly_token.first(4)
      until Complaint.find_by(pin: tipster_pin) == nil
        tipster_pin = Devise.friendly_token.first(4)
      end
      self.pin = tipster_pin if !self.pin
  end

  def allegation_types_as_nice_string
    return_string = ""
    self.allegation_types.each do |a|
      return_string += "#{a.allegation_nature}, \n"
    end
    return return_string[0..-4]
  end

  def allegation_types_as_string
    return_string = self.allegation_types.map{|a| a.allegation_nature.split(" ").join("-")}.join(" ")
    return_string
  end

  def pretty_created_at
    self.created_at.to_formatted_s(:long)
  end

  def zip_media
    image_names = []
    Zip::File.open("tmp/key-#{self.key}.zip", Zip::File::CREATE) do |z|
      self.media.each do |media|
        url = media.url
        image_name = "tmp/#{media.file.filename}"
        image_names << image_name
        open(image_name, 'wb') do |file|
          file << open(url).read
          z.add(media.file.filename, "tmp/#{media.file.filename}")
        end
      end
    end
    image_names.each{ |name| FileUtils.rm(name) }
    return "tmp/key-#{self.key}.zip"
  end

  def podio_setup
    Podio.setup(:api_key => ENV['PODIO_CLIENT_ID'], :api_secret => ENV['PODIO_CLIENT_SECRET'])
    Podio.client.authenticate_with_app(ENV['PODIO_APP_ID'],ENV['PODIO_APP_TOKEN'])
  end

  def export_to_podio
    podio_setup
    Podio::Item.create(ENV['PODIO_APP_ID'], {
      :fields =>
        {'project-title' => "New Compliant #{Time.now.to_s}" ,
          'project-description' => podio_description
        },
          :external_id => self.key
      }
    )
  end

  def podio_description
    link = "http://whistlblowr.herokuapp.com/complaints/find?complaint_key=#{self.key}"

    "#{self.content}

 Contact Info (if provided):
 #{self.user.to_s}

 Link to tip site
"
  end

  def exists_in_podio?
    podio_setup
    Podio::Item.find_all_by_external_id(ENV['PODIO_APP_ID'], self.key).count > 0
  end

  def has_unviewed_messages
    self.messages.each do |m|
      return true if m.viewed == false
    end
    false
  end

  def self.run_cleanup
    complaints = Complaint.where("created_at < ?", 30.days.ago)
    # comment this in if you want to clear records older than 30 days on all loads
    # complaints.delete_all
  end

  private

  def file_size
    upload_limit = 15
    media_total = media.reduce(0) { |total, medium| total + medium.file.size.to_f }
    if media_total > upload_limit.megabytes.to_f
      errors.add(:media, "You cannot upload more than #{upload_limit.to_f}MB")
    end
  end

end


text:
module Krane
  class RoleBinding < KubernetesResource
    TIMEOUT = 30.seconds

    def status
      exists? ? "Created" : "Not Found"
    end

    def deploy_succeeded?
      exists?
    end

    def deploy_failed?
      false
    end

    def timeout_message
      UNUSUAL_FAILURE_MESSAGE
    end
  end
end


text:
import { State } from "../../../../types/index";

export type Props = {
    className?: string;
    mixId: string;
}

export const Model = (state: State) => state;


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="tab_divider_vertical_padding">2dp</dimen>
</resources>