text:
package org.apache.druid.indexing.kinesis;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import org.apache.druid.indexing.seekablestream.SeekableStreamEndSequenceNumbers;
import org.apache.druid.indexing.seekablestream.SeekableStreamIndexTaskIOConfig;
import org.apache.druid.indexing.seekablestream.SeekableStreamStartSequenceNumbers;
import org.joda.time.DateTime;

import javax.annotation.Nullable;
import java.util.Set;

public class KinesisIndexTaskIOConfig extends SeekableStreamIndexTaskIOConfig<String, String>
{
  public static final int DEFAULT_RECORDS_PER_FETCH = 4000;
  public static final int DEFAULT_FETCH_DELAY_MILLIS = 0;

  private final String endpoint;
  private final Integer recordsPerFetch;
  private final Integer fetchDelayMillis;

  private final String awsAssumedRoleArn;
  private final String awsExternalId;
  private final boolean deaggregate;

  @JsonCreator
  public KinesisIndexTaskIOConfig(
      @JsonProperty("taskGroupId") @Nullable Integer taskGroupId,
      @JsonProperty("baseSequenceName") String baseSequenceName,
      // below three deprecated variables exist to be able to read old ioConfigs in metadata store
      @JsonProperty("startPartitions")
      @Nullable
      @Deprecated SeekableStreamEndSequenceNumbers<String, String> startPartitions,
      @JsonProperty("endPartitions")
      @Nullable
      @Deprecated SeekableStreamEndSequenceNumbers<String, String> endPartitions,
      @JsonProperty("exclusiveStartSequenceNumberPartitions")
      @Nullable
      @Deprecated Set<String> exclusiveStartSequenceNumberPartitions,
      // startSequenceNumbers and endSequenceNumbers must be set for new versions
      @JsonProperty("startSequenceNumbers") SeekableStreamStartSequenceNumbers<String, String> startSequenceNumbers,
      @JsonProperty("endSequenceNumbers") SeekableStreamEndSequenceNumbers<String, String> endSequenceNumbers,
      @JsonProperty("useTransaction") Boolean useTransaction,
      @JsonProperty("minimumMessageTime") DateTime minimumMessageTime,
      @JsonProperty("maximumMessageTime") DateTime maximumMessageTime,
      @JsonProperty("endpoint") String endpoint,
      @JsonProperty("recordsPerFetch") Integer recordsPerFetch,
      @JsonProperty("fetchDelayMillis") Integer fetchDelayMillis,
      @JsonProperty("awsAssumedRoleArn") String awsAssumedRoleArn,
      @JsonProperty("awsExternalId") String awsExternalId,
      @JsonProperty("deaggregate") boolean deaggregate
  )
  {
    super(
        taskGroupId,
        baseSequenceName,
        getStartSequenceNumbers(startSequenceNumbers, startPartitions, exclusiveStartSequenceNumberPartitions),
        endSequenceNumbers == null ? endPartitions : endSequenceNumbers,
        useTransaction,
        minimumMessageTime,
        maximumMessageTime
    );
    Preconditions.checkArgument(
        getEndSequenceNumbers().getPartitionSequenceNumberMap()
                               .values()
                               .stream()
                               .noneMatch(x -> x.equals(KinesisSequenceNumber.END_OF_SHARD_MARKER)),
        "End sequenceNumbers must not have the end of shard marker (EOS)"
    );

    this.endpoint = Preconditions.checkNotNull(endpoint, "endpoint");
    this.recordsPerFetch = recordsPerFetch != null ? recordsPerFetch : DEFAULT_RECORDS_PER_FETCH;
    this.fetchDelayMillis = fetchDelayMillis != null ? fetchDelayMillis : DEFAULT_FETCH_DELAY_MILLIS;
    this.awsAssumedRoleArn = awsAssumedRoleArn;
    this.awsExternalId = awsExternalId;
    this.deaggregate = deaggregate;
  }

  public KinesisIndexTaskIOConfig(
      int taskGroupId,
      String baseSequenceName,
      SeekableStreamStartSequenceNumbers<String, String> startSequenceNumbers,
      SeekableStreamEndSequenceNumbers<String, String> endSequenceNumbers,
      Boolean useTransaction,
      DateTime minimumMessageTime,
      DateTime maximumMessageTime,
      String endpoint,
      Integer recordsPerFetch,
      Integer fetchDelayMillis,
      String awsAssumedRoleArn,
      String awsExternalId,
      boolean deaggregate
  )
  {
    this(
        taskGroupId,
        baseSequenceName,
        null,
        null,
        null,
        startSequenceNumbers,
        endSequenceNumbers,
        useTransaction,
        minimumMessageTime,
        maximumMessageTime,
        endpoint,
        recordsPerFetch,
        fetchDelayMillis,
        awsAssumedRoleArn,
        awsExternalId,
        deaggregate
    );
  }

  private static SeekableStreamStartSequenceNumbers<String, String> getStartSequenceNumbers(
      @Nullable SeekableStreamStartSequenceNumbers<String, String> newStartSequenceNumbers,
      @Nullable SeekableStreamEndSequenceNumbers<String, String> oldStartSequenceNumbers,
      @Nullable Set<String> exclusiveStartSequenceNumberPartitions
  )
  {
    if (newStartSequenceNumbers == null) {
      Preconditions.checkNotNull(
          oldStartSequenceNumbers,
          "Either startSequenceNumbers or startPartitions shoulnd't be null"
      );

      return new SeekableStreamStartSequenceNumbers<>(
          oldStartSequenceNumbers.getStream(),
          oldStartSequenceNumbers.getPartitionSequenceNumberMap(),
          exclusiveStartSequenceNumberPartitions
      );
    } else {
      return newStartSequenceNumbers;
    }
  }

  /**
   * This method is for compatibilty so that newer version of KinesisIndexTaskIOConfig can be read by
   * old version of Druid. Note that this method returns end sequence numbers instead of start. This is because
   * {@link SeekableStreamStartSequenceNumbers} didn't exist before.
   *
   * A SeekableStreamEndSequenceNumbers (has no exclusivity info) is returned here because the Kinesis extension
   * previously stored exclusivity info separately in exclusiveStartSequenceNumberPartitions.
   */
  @JsonProperty
  @Deprecated
  public SeekableStreamEndSequenceNumbers<String, String> getStartPartitions()
  {
    final SeekableStreamStartSequenceNumbers<String, String> startSequenceNumbers = getStartSequenceNumbers();
    return new SeekableStreamEndSequenceNumbers<>(
        startSequenceNumbers.getStream(),
        startSequenceNumbers.getPartitionSequenceNumberMap()
    );
  }

  /**
   * This method is for compatibilty so that newer version of KinesisIndexTaskIOConfig can be read by
   * old version of Druid.
   */
  @JsonProperty
  @Deprecated
  public SeekableStreamEndSequenceNumbers<String, String> getEndPartitions()
  {
    return getEndSequenceNumbers();
  }

  @JsonProperty
  @Deprecated
  public Set<String> getExclusiveStartSequenceNumberPartitions()
  {
    return getStartSequenceNumbers().getExclusivePartitions();
  }

  @JsonProperty
  public String getEndpoint()
  {
    return endpoint;
  }

  @JsonProperty
  public int getRecordsPerFetch()
  {
    return recordsPerFetch;
  }

  @JsonProperty
  public int getFetchDelayMillis()
  {
    return fetchDelayMillis;
  }

  @JsonProperty
  public String getAwsAssumedRoleArn()
  {
    return awsAssumedRoleArn;
  }

  @JsonProperty
  public String getAwsExternalId()
  {
    return awsExternalId;
  }

  @JsonProperty
  public boolean isDeaggregate()
  {
    return deaggregate;
  }

  @Override
  public String toString()
  {
    return "KinesisIndexTaskIOConfig{" +
           "baseSequenceName='" + getBaseSequenceName() + '\'' +
           ", startPartitions=" + getStartSequenceNumbers() +
           ", endPartitions=" + getEndSequenceNumbers() +
           ", useTransaction=" + isUseTransaction() +
           ", minimumMessageTime=" + getMinimumMessageTime() +
           ", maximumMessageTime=" + getMaximumMessageTime() +
           ", endpoint='" + endpoint + '\'' +
           ", recordsPerFetch=" + recordsPerFetch +
           ", fetchDelayMillis=" + fetchDelayMillis +
           ", awsAssumedRoleArn='" + awsAssumedRoleArn + '\'' +
           ", awsExternalId='" + awsExternalId + '\'' +
           ", deaggregate=" + deaggregate +
           '}';
  }
}


text:
class OfficeRecipient
  def initialize(benefit_application:)
    @benefit_application = benefit_application
  end

  def phone_number
    office["phone_number"]
  end

  def name
    office["name"]
  end

  def email
    office["email"]
  end

  def office
    if office_location.present?
      self.class.offices[office_location]
    else
      self.class.find_by(zip: residential_or_mailing_zip)
    end
  end

  def residential_or_mailing_zip
    residential_address&.zip || mailing_address&.zip
  end

  def self.find_by(zip:)
    name = covered_zip_codes[zip.to_s] || configuration["fallback_office"]
    Rails.logger.debug("Mapped zip #{zip} to office #{name}")
    offices[name]
  end

  def self.covered_zip_codes
    configuration["covered_zip_codes"]
  end

  def self.offices
    configuration["offices"]
  end

  def self.configuration
    full_configuration[GateKeeper.application_routing_environment]
  end

  def self.full_configuration
    return @full_configuration if @full_configuration.present?
    @full_configuration = YAML.safe_load(configuration_file, [Symbol], [],
                                           true)
    add_names_to_offices(@full_configuration)
    @full_configuration
  end

  def self.add_names_to_offices(configuration)
    configuration.each_key do |stage|
      next unless configuration[stage].key?("offices")
      configuration[stage]["offices"].each_key do |office|
        configuration[stage]["offices"][office]["name"] = office.to_s.titleize
      end
    end
  end

  def self.configuration_file
    File.read(Rails.root.join("config", "offices.yml"))
  end

  private

  attr_reader :benefit_application

  def residential_address
    benefit_application.residential_address
  end

  def mailing_address
    benefit_application.mailing_address
  end

  def office_location
    benefit_application.office_location
  end
end

redpajama_set_name: RedPajamaGithub


text:
package ru.otus.kirillov.service.myorm;

import ru.otus.kirillov.dao.Dao;
import ru.otus.kirillov.myorm.MyOrmService;
import ru.otus.kirillov.service.AbstractDBService;
import ru.otus.kirillov.utils.CommonUtils;

import java.io.Closeable;

import static ru.otus.kirillov.utils.ReflectionUtils.instantiateWithInjections;

/**
 * Created by Александр on 28.01.2018.
 */
public class DBServiceMyOrmImpl extends AbstractDBService {

    private final MyOrmService service;

    public DBServiceMyOrmImpl(MyOrmService service) {
        this.service = CommonUtils.retunIfNotNull(service);
    }

    /**
     *  И так. Задача создать DAO. И тут 2 варианта (в самом распространенном случае):
     *  1. У него есть конструктор с одним параметров Supplier<Connection>
     *  2. У него есть дефолтный конструктор и поле Supplier<Connection>
     *  3. Он должен иметь модификатор public
     * @param daoClass - класс DAO-шки
     * @return
     */
    @Override
    protected Dao<?> createDao(Class<?> daoClass) {
        Dao<?> dao = instantiateWithInjections(daoClass, service);
        if(dao == null) {
            throw new RuntimeException(
                    String.format("Unable to create DAO %s: try to check contract " +
                            "for DBServiceMyOrmImpl", daoClass));
        }
        return dao;
    }

    public void destroy() {
        service.destroy();
    }

}


text:
@implementation CLJAbstractTransientSet

- (id)initWithImplementation:(id<CLJITransientMap>)impl {
	self = [super init];

	_impl = impl;

	return self;
}

- (NSUInteger)count {
	return _impl.count;
}

- (id<CLJITransientCollection>)conj:(id)val {
	id<CLJITransientMap> m = [_impl associateKey:val value:val];
	if (m != _impl) _impl = m;
	return self;
}

- (BOOL)containsObject:(id)key  {
	return self != [_impl objectForKey:key default:self];
}

- (id<CLJITransientSet>)disjoin:(id)key {
	id<CLJITransientMap> m = [_impl without:key];;
	if (m != _impl) {
		_impl = m;
	}
	return self;
}

- (id)objectForKey:(id)key {
	return [_impl objectForKey:key];
}

#pragma mark - Abtract

- (id<CLJIPersistentCollection>)persistent {
	return nil;
}

@end


text:
/**
 * @class Ext.ux.upload.Basic
 * @extends Ext.util.Observable
 *
 * @author Harald Hanek (c) 2011-2012
 * @license http://harrydeluxe.mit-license.org
 */
Ext.define('Ext.ux.upload.Basic', {
    extend: 'Ext.util.Observable',
    autoStart: true,
    autoRemoveUploaded: true,

    statusQueuedText: 'Ready to upload',
    statusUploadingText: 'Uploading ({0}%)',
    statusFailedText: 'Error',
    statusDoneText: 'Complete',
    statusInvalidSizeText: 'File too large',
    statusInvalidExtensionText: 'Invalid file type',

    configs: {
        uploader: {
            runtimes: '',
            url: '',
            browse_button: null,
            container: null,
            max_file_size: '128mb',
            resize: '',
            flash_swf_url: '',
            silverlight_xap_url: '',
            filters: [],
            //chunk_size: '1mb', // @see http://www.plupload.com/punbb/viewtopic.php?id=1259
            chunk_size: null,
            unique_names: true,
            multipart: true,
            multipart_params: {},
            multi_selection: true,
            drop_element: null,
            required_features: null
        }
    },

    constructor: function(owner, config)
    {
        var me = this;
        me.owner = owner;
        me.success = [];
        me.failed = [];
        Ext.apply(me, config.listeners);
        me.uploaderConfig = Ext.apply(me, config.uploader, me.configs.uploader);

        me.addEvents('beforestart',
                'uploadready',
                'uploadstarted',
                'uploadcomplete',
                'uploaderror',
                'filesadded',
                'beforeupload',
                'fileuploaded',
                'updateprogress',
                'uploadprogress',
                'storeempty');

        Ext.define('Ext.ux.upload.Model', {
            extend: 'Ext.data.Model',
            fields: ['id',
                    'loaded',
                    'name',
                    'size',
                    'percent',
                    'status',
                    'msg']
        });

        me.store = Ext.create('Ext.data.JsonStore', {
            model: 'Ext.ux.upload.Model',
            listeners: {
                load: me.onStoreLoad,
                remove: me.onStoreRemove,
                update: me.onStoreUpdate,
                scope: me
            }
        });

        me.actions = {

            textStatus: Ext.create('Ext.Action', {
                text: 'uploader not initialized'
            }),
            add: Ext.create('Ext.Action', {
                text: config.addButtonText || 'Add files',
                iconCls: config.addButtonCls,
                disabled: false
            }),
            start: Ext.create('Ext.Action', {
                text: config.uploadButtonText || 'Start',
                disabled: true,
                iconCls: config.uploadButtonCls,
                handler: me.start,
                scope: me
            }),
            cancel: Ext.create('Ext.Action', {
                text: config.cancelButtonText || 'Cancel',
                disabled: true,
                iconCls: config.cancelButtonCls,
                handler: me.cancel,
                scope: me
            }),
            removeUploaded: Ext.create('Ext.Action', {
                text: config.deleteUploadedText || 'Remove uploaded',
                disabled: true,
                handler: me.removeUploaded,
                scope: me
            }),
            removeAll: Ext.create('Ext.Action', {
                text: config.deleteAllText || 'Remove all',
                disabled: true,
                handler: me.removeAll,
                scope: me
            })
        };

        me.callParent();
    },

    /**
     * @private
     */
    initialize: function()
    {
        var me = this;
        if(!me.initialized)
        {
            me.initialized = true;
            me.initializeUploader();
        }
    },

    /**
     * Destroys this object.
     */
    destroy: function()
    {
        this.clearListeners();
    },

    setUploadPath: function(path)
    {
        this.uploadpath = path;
    },

    removeAll: function()
    {
        this.store.data.each(function(record)
        {
            this.removeFile(record.get('id'));
        }, this);
    },

    removeUploaded: function()
    {
        //console.log(this.store);
        this.store.each(function(record)
        {
            //console.log(record);
            if(record && record.get('status') == 5)
            {
                this.removeFile(record.get('id'));
            }
        }, this);
    },

    removeFile: function(id)
    {
        var me = this,
            file = me.uploader.getFile(id);

        if(file)
            me.uploader.removeFile(file);
        else
            me.store.remove(me.store.getById(id));
    },

    cancel: function()
    {
        var me = this;
        me.uploader.stop();
        me.actions.start.setDisabled(me.store.data.length == 0);
    },

    start: function()
    {
        var me = this;
        me.fireEvent('beforestart', me);
        if(me.multipart_params)
        {
            me.uploader.settings.multipart_params = me.multipart_params;
        }
        me.uploader.start();
        //console.log(me.uploader);
    },

    initializeUploader: function()
    {
        var me = this;

        if (!me.uploaderConfig.runtimes) {
            var runtimes = ['html5'];

            me.uploaderConfig.flash_swf_url && runtimes.push('flash');
            me.uploaderConfig.silverlight_xap_url && runtimes.push('silverlight');

            runtimes.push('html4');

            me.uploaderConfig.runtimes = runtimes.join(',');
        }

        me.uploader = Ext.create('plupload.Uploader', me.uploaderConfig);

        Ext.each(['Init',
                'ChunkUploaded',
                'FilesAdded',
                'FilesRemoved',
                'FileUploaded',
                'PostInit',
                'QueueChanged',
                'Refresh',
                'StateChanged',
                'BeforeUpload',
                'UploadFile',
                'UploadProgress',
                'Error'], function(v){
                    me.uploader.bind(v, eval("me._" + v), me);
                }, me);

        me.uploader.init();
    },

    updateProgress: function()
    {
        var me = this,
            t = me.uploader.total,
            speed = Ext.util.Format.fileSize(t.bytesPerSec),
            total = me.store.data.length,
            failed = me.failed.length,
            success = me.success.length,
            sent = failed + success,
            queued = total - success - failed,
            percent = t.percent;

        me.fireEvent('updateprogress', me, total, percent, sent, success, failed, queued, speed);
    },

    updateStore: function(v)
    {
        var me = this,
            data = me.store.getById(v.id);

        if(!v.msg)
        {
            v.msg = '';
        }
        if(data)
        {
            data.data = v;
            data.commit();
        }
        else
        {
            me.store.loadData([v], true);
        }
    },

    onStoreLoad: function(store, record, operation)
    {
        this.updateProgress();
    },

    onStoreRemove: function(store, record, operation)
    {
        var me = this;
        if(!store.data.length)
        {
            me.actions.start.setDisabled(true);
            me.actions.removeUploaded.setDisabled(true);
            me.actions.removeAll.setDisabled(true);
            me.uploader.total.reset();
            me.fireEvent('storeempty', me);
        }

        var id = record.get('id');
        Ext.each(me.success, function(v)
        {
            if(v && v.id == id)
                Ext.Array.remove(me.success, v);
        }, me);

        Ext.each(me.failed, function(v)
        {
            if(v && v.id == id)
                Ext.Array.remove(me.failed, v);
        }, me);

        me.updateProgress();
    },

    onStoreUpdate: function(store, record, operation)
    {
        record.data = this.fileMsg(record.data);
        this.updateProgress();
    },

    fileMsg: function(file)
    {
        var me = this;
        if(file.status && file.server_error != 1)
        {
            switch(file.status)
            {
                case 1:
                    file.msg = me.statusQueuedText;
                    break;
                case 2:
                    file.msg = Ext.String.format(me.statusUploadingText, file.percent);
                    break;
                case 4:
                    file.msg = file.msg || me.statusFailedText;
                    break;
                case 5:
                    file.msg = me.statusDoneText;
                    break;
            }
        }
        return file;
    },

    /**
     * Plupload EVENTS
     */
    _Init: function(uploader, data)
    {
        this.runtime = data.runtime;
        this.owner.enable(true); // button aktiv schalten
        this.fireEvent('uploadready', this);
    },

    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    _BeforeUpload: function(uploader, file)
    {
        this.fireEvent('beforeupload', this, uploader, file);
    },

    _ChunkUploaded: function()
    {
    },

    _FilesAdded: function(uploader, files)
    {
        var me = this;

        if(me.uploaderConfig.multi_selection != true)
        {
            if(me.store.data.length == 1)
            //if(uploader.files.length == 1)
                return false;

            files = [files[0]];
            uploader.files = [files[0]];
        }

        me.actions.removeUploaded.setDisabled(false);
        me.actions.removeAll.setDisabled(false);
        me.actions.start.setDisabled(uploader.state == 2);
        Ext.each(files, function(v)
        {
            me.updateStore(v);

        }, me);

        if(me.fireEvent('filesadded', me, files) !== false)
        {
            if(me.autoStart && uploader.state != 2)
                Ext.defer(function()
                {
                    me.start();
                }, 300);
        }
    },

    _FilesRemoved: function(uploader, files)
    {
        Ext.each(files, function(file)
        {
            this.store.remove(this.store.getById(file.id));
        }, this);
    },

    _FileUploaded: function(uploader, file, status)
    {
        var me = this,
            response = Ext.JSON.decode(status.response);

        if(response.success == true)
        {
            file.server_error = 0;
            me.success.push(file);
            me.fireEvent('fileuploaded', me, file, response);
        }
        else
        {
            if(response.message)
            {
                file.msg = '' + response.message + '';
            }
            file.server_error = 1;
            me.failed.push(file);
            me.fireEvent('uploaderror', me, Ext.apply(status, {
                file: file
            }));
        }
        this.updateStore(file);
    },

    _PostInit: function(uploader)
    {
    },

    _QueueChanged: function(uploader)
    {
    },

    _Refresh: function(uploader)
    {
        Ext.each(uploader.files, function(v)
        {
            this.updateStore(v);
        }, this);
    },

    _StateChanged: function(uploader)
    {
        if(uploader.state == 2)
        {
            this.fireEvent('uploadstarted', this);
            this.actions.cancel.setDisabled(false);
            this.actions.start.setDisabled(true);
        }
        else
        {
            this.fireEvent('uploadcomplete', this, this.success, this.failed);
            if(this.autoRemoveUploaded)
                this.removeUploaded();
            this.actions.cancel.setDisabled(true);
            this.actions.start.setDisabled(this.store.data.length == 0);
        }
    },

    _UploadFile: function(uploader, file)
    {
    },

    _UploadProgress: function(uploader, file)
    {
        var me = this,
            name = file.name,
            size = file.size,
            percent = file.percent;

        me.fireEvent('uploadprogress', me, file, name, size, percent);

        if(file.server_error)
            file.status = 4;

        me.updateStore(file);
    },

    _Error: function(uploader, data)
    {
        if(data.file)
        {
            data.file.status = 4;
            if(data.code == -600)
            {
                data.file.msg = Ext.String.format('{0}', this.statusInvalidSizeText);
            }
            else if(data.code == -700)
            {
                data.file.msg = Ext.String.format('{0}', this.statusInvalidExtensionText);
            }
            else
            {
                data.file.msg = Ext.String.format('{2} ({0}: {1})', data.code, data.details,
                        data.message);
            }
            this.failed.push(data.file);
            this.updateStore(data.file);
        }
        this.fireEvent('uploaderror', this, data);
    }
});


text:
START_ATF_NAMESPACE
    namespace Detail
    {
        extern ::std::array<hook_record, 1> BASE_HACKSHEILD_PARAM_functions;
    }; // end namespace Detail
END_ATF_NAMESPACE


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

<title>CURLOPT_DNS_SERVERS man page</title>
<meta name="generator" content="roffit">

NAME

CURLOPT_DNS_SERVERS - set preferred DNS servers
SYNOPSIS

#include <curl/curl.h>

CURLcode curl_easy_setopt(CURL *handle, CURLOPT_DNS_SERVERS, char *servers);
DESCRIPTION

Pass a char * that is the list of DNS servers to be used instead of the system default.  The format of the dns servers option is:

host[:port][,host[:port]]...

For example:

192.168.1.100,192.168.1.101,3.4.5.6
DEFAULT

NULL - use system default
PROTOCOLS

All
EXAMPLE

TODO
AVAILABILITY

This option requires that libcurl was built with a resolver backend that supports this operation. The c-ares backend is the only such one.

Added in 7.24.0
RETURN VALUE

Returns CURLE_OK if the option is supported, CURLE_UNKNOWN_OPTION if not, CURLE_NOT_BUILT_IN if support was disabled at compile-time, CURLE_BAD_FUNCTION_ARGUMENT when given an invalid server list, or CURLE_OUT_OF_MEMORY if there was insufficient heap space.
SEE ALSO

CURLOPT_DNS_LOCAL_IP4, CURLOPT_DNS_CACHE_TIMEOUT

 This HTML page was made with roffit.


text:
class IdsPlease
  module Grabbers
    class Twitter < IdsPlease::Grabbers::Base

      def grab_link
        @network_id   = find_network_id
        @avatar       = find_avatar
        @display_name = find_display_name
        @username     = find_username

        @counts = {
          tweets: find_tweets,
          following: find_following,
          followers: find_followers,
          favorites: find_favorites,
          lists: find_listed
        }.delete_if { |_k, v| v.nil? }

        @data = {
          description: find_description,
          location: find_location,
          join_date: find_join_date
        }.delete_if { |_k, v| v.nil? }

        self
      rescue => e
        record_error __method__, e.message
        return self
      end

      def find_network_id
        find_by_regex(/data-user-id="(\d+)"/)
      rescue => e
        record_error __method__, e.message
        return nil
      end

      def find_avatar
        find_by_regex(/ProfileAvatar-image " src="([^"]+)"/)
      rescue => e
        record_error __method__, e.message
        return nil
      end

      def find_display_name
        find_by_regex(/ProfileHeaderCard-nameLink[^>]+>([^<]+)</)
      rescue => e
        record_error __method__, e.message
        return nil
      end

      def find_username
        find_by_regex(/<title>[^\(]+\(@([^\)]+)\)/)
      rescue => e
        record_error __method__, e.message
        return nil
      end

      def find_description
        _desc = find_by_regex(/ProfileHeaderCard-bio[^>]+>([^<]+)</)
        CGI.unescapeHTML(_desc.encode('utf-8')).strip
      rescue => e
        record_error __method__, e.message
        return nil
      end

      def find_location
        _loc = find_by_regex(/ProfileHeaderCard-locationText[^>]+>([^<]+)</)
        CGI.unescapeHTML(_loc.encode('utf-8')).strip
      rescue => e
        record_error __method__, e.message
        return nil
      end

      def find_join_date
        _date = find_by_regex(/ProfileHeaderCard-joinDateText[^>]+>([^<]+)</)
        CGI.unescapeHTML(_date.encode('utf-8')).strip
      rescue => e
        record_error __method__, e.message
        return nil
      end

      def find_tweets
        find_by_regex(/statuses_count":(\d+),"/).to_i
      rescue => e
        record_error __method__, e.message
        return nil
      end

      def find_followers
        find_by_regex(/followers_count":(\d+),"/).to_i
      rescue => e
        record_error __method__, e.message
        return nil
      end

      def find_following
        find_by_regex(/friends_count":(\d+),"/).to_i
      rescue => e
        record_error __method__, e.message
        return nil
      end

      def find_favorites
        find_by_regex(/favourites_count":(\d+),"/).to_i
      rescue => e
        record_error __method__, e.message
        return nil
      end

      def find_listed
        find_by_regex(/listed_count":(\d+),"/).to_i
      rescue => e
        record_error __method__, e.message
        return nil
      end

    end
  end
end


text:
<!DOCTYPE html>

  	  <meta charset="UTF-8">
  	  <meta name="viewport" content="width=device-width, initial-scale=1">
 			<title>Jennifer Cross | CV</title>

 			<link rel="icon" type="image/png" href="images/favicon.png">

			<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

			<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,600' rel='stylesheet' type='text/css'>

			<link rel="stylesheet" type="text/css" href="css/style.css">
			<link rel="stylesheet" type="text/css" href="css/JimmyScript-Regular.css">
			<link rel="stylesheet" type="text/css" href="css/JimmyScript-Bold.css">
			<link rel="stylesheet" type="text/css" href="css/JimmySans-Regular.css">
			<link rel="stylesheet" type="text/css" href="css/JimmySans-Bold.css">
			<link rel="stylesheet" type="text/css" href="css/portfolio.jquery.css">

Jennifer Cross

Nice to meet you.

Profile

I'm a Web Developer and Librarian

ABOUT ME

I'm the Web Services Manager for RUSA and ASCLA, two divisions of the American Library Association. In this role I have a variety of responsibilities, including: developing and maintaining multiple websites, digital content and database management, and shaping digital marketing strategy. I'm also the Online Learning Coordinator.

Before joining the ALA, I worked in private and public education as a librarian, web developer, and programming/technology teacher. I was also lucky enough to spend four years co-organizing an annually sold-out TEDx conference.

I believe in serving my community, that details are vitally important, and that Firefly was the best television show ever created. When I'm not working, you'll probably find me in my garden where I grow both flowers and vegetables, admittedly with mixed results. I may be talking to the chickens, as well.

Portfolio

Things I've worked on.

Eventually...

this list will be full-up with amazing apps and websites. Really! For now, here are just a few of the things I've worked on (besides this site) which have served to make me want to learn more and get better.

You can also browse some of my flailing on GitHub.

				        A new-tab Chrome extension

				        Puget Sound Independent Schools Website

	              TEDxEastsidePrep Website

	              Eastside Preparatory School Website

Scout

Scout is a new-tab Chrome extension aimed at keeping travel dreams in the forefront of day-to-day online activities. This was a created as a group final project while attending DevBootcamp, 2016.

                GitHub  Chrome Store

PSIS

At the request of PSIS, I designed and built this WordPress site as a low-maintenance source of information for parents looking at independent schools in the greater Seattle area.

TEDxEastsidePrep

As the long-time co-organizer of this conference, I also designed, developed, and maintained our conference website and TED.com pages.

EastsidePrep

The main EastsidePrep website was just one of dozens that I designed, created, and maintained for the school between 2011 and 2015.

Experience

People I've worked with over the last decade.

American Library Association

2016 - present

Web Services Manager, ASCLA / RUSA

Chicago , IL

Developed and maintained WordPress and Drupal websites

Digital content and database management

Online learning coordination

Escuela Campo Alegre

2015 - 2016

Technology Teacher

Caracas,Venezuela

Taught middle and high school web design and technology courses

Provided on-demand tech support to the school community

Supported and educated faculty in technology use and integration

Eastside Preparatory School

2011 - 2015

Web Developer, Technology Teacher

Kirkland, WA

Designed, built, and managed the school WordPress multi-site ecosystem

Taught middle and high school web design and technology courses

Provided on-demand tech support to the school community

Led summer trips and taught camps in Programming and the Makerspace

TEDx
EastsidePrep

2011 - 2015

Event Co-Organizer, Web Developer

Seattle, WA

TED Profile

Planned, organized, and delivered an annually "sold-out" professional development conference for educators

Created and managed web and social media presence

The French American School of Puget Sound

2008 - 2010

School Librarian, Technology Support

Mercer Island, WA

Standardized the physical and database organization of a large bilingual library collection

Supported and educated faculty in technology use and integration

New Orleans Public Schools

2006 - 2008

School Librarian, Technology Teacher

New Orleans, LA

Taught 650+ students in weekly library and technology classes

Rebuilt library database after Katrina-caused total loss of data

Education

I liked school. So I kept on going.

Dev Bootcamp

Full-Stack Web Development

Dev Bootcamp is a 19-week immersive curriculum focusing on Ruby, JavaScript, Ruby on Rails, common JavaScript libraries, SQL, HTML and CSS, as well as pair programming, agile and test-driven development. The program also integrates team skills like communication, empathy and effective feedback.

Texas Woman's University

Master's Degree in Library & Information Science

Studied information architecture and information seeking behaviors in both digital and traditional service arenas.

Beta Phi Mu International Honor Society

Golden Key International Honor Society

ITI - Information Technology Institute

Post-Graduate Diploma In Applied Information Technology

ITI is what Bootcamps looked like 15 years ago. Full-time. 9 month, post graduate program in software and database development, and project management.

University of Colorado Law School

J.D. (incomplete)

I got halfway through law school and decided being a whitewater guide was more what I was looking for. I mention it because it was one of the best decisions I ever made! Sometimes, you need to quit.

University of Illinois

B.A. in Creative Writing

Phi Kappa Phi National Honor Society

Golden Key International Honor Society

Contact Me

I can make anything happen through sheer force of will and resourcefulness.
And I can do it in style.

									 https://www.linkedin.com/in/nearlyjen

									 https://github.com/NearlyJen

									 2016 Jennifer Cross

						<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-jen-collapse">
							Toggle navigation

						</button>

About Me

Portfolio

Experience

Education

Contact


text:
package com.ansorgit.plugins.bash.lang.psi.fileInclude;

import com.ansorgit.plugins.bash.lang.psi.FileInclusionManager;
import com.ansorgit.plugins.bash.lang.psi.api.BashFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiReference;
import org.junit.Assert;
import org.junit.Test;

import java.util.Set;

/**
 * @author jansorg
 */
public class InvalidIncludesTestCase extends AbstractFileIncludeTest {
    @Override
    protected String getTestDataPath() {
        return super.getTestDataPath() + "invalidIncludes/";
    }

    @Test
    public void testTextIncluded() throws Exception {
        Set<PsiFile> includedFiles = findIncludedFiles(false);

        Assert.assertEquals("Included text file was not found!", 1, includedFiles.size());
        Assert.assertFalse("Included file shouldn't be a Bash file", includedFiles.iterator().next() instanceof BashFile);
    }

    @Test
    public void testTextIncludedJustBash() throws Exception {
        Set<PsiFile> includedFiles = findIncludedFiles(true);
        Assert.assertEquals("Included text file was not found!", 0, includedFiles.size());
    }

    private Set<PsiFile> findIncludedFiles(boolean justBashFiles) throws Exception {
        PsiReference ref = configure();
        addFile("included.txt");

        Assert.assertNotNull("Reference was not found", ref);

        PsiFile file = ref.getElement().getContainingFile();
        Assert.assertTrue(file instanceof BashFile);

        return FileInclusionManager.findIncludedFiles(file, true, justBashFiles);
    }
}


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

    <TITLE>
        org.apache.jmeter.examples.testbeans.example2 (Apache JMeter API)
    </TITLE>

    <META NAME="keywords" CONTENT="org.apache.jmeter.examples.testbeans.example2 package">

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

    org.apache.jmeter.examples.testbeans.example2

            Classes

                Example2

                Example2BeanInfo


text:
namespace ngraph
{
    namespace op
    {
        namespace v0
        {
            // clang-format off
        /// \brief Tensor reshape operation.
        ///
        /// "Converts" an input tensor into a new shape with the same number of elements.
        ///
        /// Given that the input tensor has shape \f$[d_1,\dots,d_n]\f$, the output may have any
        /// shape \f$[d'_1,\dots,d'_m]\f$ such that
        /// \f$\Pi_{0 \leq i \lt n}(d_i) = \Pi_{0 \leq i \lt m}(d'_i)\f$. For example, a
        /// \f$3\times{}4\f$ matrix can be reshaped into a 3-tensor of shape
        /// \f$3\times{}2\times{}2\f$, a matrix of shape \f$6\times{}2\f$, or a vector of size
        /// \f$12\f$, but not, for example, a matrix of size \f$4\times{}4\f$.
        ///
        /// The parameter `input_order` indicates the order in which to "walk" over the input axes.
        /// Given a tensor of shape \f$(d_1,\dots,d_n)\f$, an input order of
        /// \f$(a_0, a_1, \dots, a_{n-1})\f$ results in the coordinate for axis \f$a_{n-1}\f$ being
        /// varied most frequently, followed by axis \f$a-2\f$, and so on down to \f$a_0\f$.
        ///
        /// (TODO: example.)
        ///
        /// ## Parameters
        ///
        /// |                | Description                                                |
        /// | -------------- | ---------------------------------------------------------- |
        /// | `input_order`  | The order in which to walk over the input axes.            |
        /// | `output_shape` | The shape \f$[d'_1,\dots,d'_m]\f$ for the reshaped tensor. |
        ///
        /// ## Inputs
        ///
        /// |       | Type                              | Description                                                                                |
        /// | ----- | --------------------------------- | ------------------------------------------------------------------------------------------------------------ |
        /// | `arg` | \f$E[d_1,\dots,d_n]~(n \geq 0)\f$ | An input tensor of any type and shape, as long as the product of \f$d_i\f$ equals the product of \f$d'_i\f$. |
        ///
        /// ## Output
        ///
        /// | Type                     | Description                                                                                |
        /// | ------------------------ | ------------------------------------------------------------------------------------------------------ |
        /// | \f$E[d'_1,\dots,d'_m]\f$ | The tensor \f$T\f$, where \f$T\f$ is the input tensor with its elements rearranged as described above. |
            // clang-format on
            class NGRAPH_API Reshape : public Op
            {
            public:
                static constexpr NodeTypeInfo type_info{"Reshape", 0};
                const NodeTypeInfo& get_type_info() const override { return type_info; }
                /// \brief Constructs a reshape operation.
                Reshape() = default;
                /// \brief Constructs a reshape operation.
                ///
                /// \param arg The tensor to be reshaped.
                /// \param input_order The order in which to iterate over input axes. This must be a
                ///                    permutation of the sequence \f$(0,\dots,n-1)\f$ where \f$n\f$
                ///                    is
                ///                    the rank of the input tensor.
                /// \param output_shape The output shape. If the input shape is
                ///                     \f$(a_0,\dots,a_{k-1})\f$ then the output shape must
                ///                     be of the form \f$(b_0,\dots,b_{j-1})\f$ where
                ///                     \f$\Pi(a_i) = \Pi(b_i)\f$.
                Reshape(const Output<Node>& arg,
                        const AxisVector& input_order,
                        const Shape& output_shape);

                void validate_and_infer_types() override;

                virtual std::shared_ptr<Node>
                    clone_with_new_inputs(const OutputVector& new_args) const override;
                bool visit_attributes(AttributeVisitor& visitor) override;

                /// \return The order in which to iterate over input axes.
                const AxisVector& get_input_order() const { return m_input_order; }
                void set_input_order(const AxisVector& input_order) { m_input_order = input_order; }
                /// \return The shape of the output tensor.
                const Shape& get_reshape_output_shape() const { return m_output_shape; }
                void set_output_shape(const Shape& output_shape) { m_output_shape = output_shape; }
                bool get_is_transpose() const { return m_is_transpose; }
                void set_is_transpose(bool is_transpose) { m_is_transpose = is_transpose; }
                bool evaluate(const HostTensorVector& outputs,
                              const HostTensorVector& inputs) const override;

            protected:
                virtual void generate_adjoints(autodiff::Adjoints& adjoints,
                                               const OutputVector& deltas) override;

                AxisVector m_input_order;
                Shape m_output_shape;
                bool m_is_transpose{false};
            };
        }

        namespace v1
        {
            /// \brief Tensor dynamic reshape operation.
            ///
            /// "Converts" an input tensor into a new shape with the same number of elements.
            /// This op does not touch the actual data. If needed, use Transpose for that purpose.
            ///
            class NGRAPH_API Reshape : public Op
            {
            public:
                static constexpr NodeTypeInfo type_info{"Reshape", 1};
                const NodeTypeInfo& get_type_info() const override { return type_info; }
                Reshape() = default;
                /// \brief Constructs a dynamic reshape operation. This operation does not perform
                ///        transpose.
                ///
                /// \param arg The tensor to be reshaped.
                /// \param pattern The node that defines output shape pattern.
                ///        If the input shape is \f$(a_0,\dots,a_{k-1})\f$ then the output shape
                ///        must
                ///        be of the form \f$(b_0,\dots,b_{j-1})\f$ where \f$\Pi(a_i) = \Pi(b_i)\f$.
                ///        A value of -1 is allowed for at most one dimension, in which case the
                ///        dimension size is inferred based on element count of input tensor.
                /// \param special_zero Treats zeros in `pattern` as wildcard flags indicating a
                ///        copy from input shape at the same index.
                ///
                Reshape(const Output<Node>& arg, const Output<Node>& pattern, bool special_zero);

                bool visit_attributes(AttributeVisitor& visitor) override;
                void validate_and_infer_types() override;

                virtual std::shared_ptr<Node>
                    clone_with_new_inputs(const OutputVector& new_args) const override;

                bool get_special_zero() const { return m_special_zero; }
                void set_special_zero(bool special_zero) { m_special_zero = special_zero; }
                bool evaluate(const HostTensorVector& outputs,
                              const HostTensorVector& inputs) const override;

            protected:
                virtual void generate_adjoints(autodiff::Adjoints& adjoints,
                                               const OutputVector& deltas) override;

            private:
                bool m_special_zero;
            };
        }
    }
}


text:
var User = require('../models/user'),
  Note = require('../models/note'),
  _ = require('underscore'),
  passport = require('passport');

// use for routes that require authentication; user is automatically
// added to handlebars vars.
function requireAuth(req, res, next) {
  if (!req.isAuthenticated()) {
    req.flash('error', 'Please log in or register.');
    return res.redirect('/');
  }
  res.locals.user = req.user;
  return next();
}

// populates handlebars local vars with user, if logged in.
function optionalAuth(req, res, next) {
  if (req.isAuthenticated()) {
    res.locals.user = req.user;
  }
  return next();
}

module.exports = function(app) {
  app.get('/', optionalAuth, function(req, res) {
    var texts = [
      "Pretty notes for fun and profit.",
      "Your mom wishes you were this good.",
      "This is what freedom sounds like.",
      "Better than bitcoin.",
      "We collect all your data and then give it back to you. And you'll like it.",
      "Now with 200% more kittens.",
      "5 out of 5 dentists recommend it.",
      "sudo rm -rf /",
      "It's like drinking all night and not waking up with a hangover.",
      "Well, what are you waiting for?",
      "1110111110010111011001100011110111111011011100101100001",
      "pinterest++;",
      "evernote++;"
    ];
    var text = texts[Math.floor(Math.random() * texts.length)];
    res.render('home', {text: text, errors: req.flash('error')});
  });
  app.get('/register', optionalAuth, function(req, res) {
    res.render('register', {title: 'Register'});
  });
  app.post('/register', function(req, res) {
    req.body.email = req.body.email.toLowerCase();
    req.sanitize('name').trim();
    req.sanitize('email').trim();
    req.checkBody('name', 'A name is required.').notEmpty();
    req.checkBody('email', 'Your email address is invalid.').isEmail();
    req.checkBody('password', 'A password is required.').notNull();
    var errors = req.validationErrors(true);

    User.count({ email: req.body.email }, function(err, count) {
      if (count === 0) {
        if (_.size(errors)) {
          // there are validator errors, rerender to register page.
          res.render('register', {
            title: 'Register',
            errors: errors,
            values: req.body
          });
        } else {
          // no errors; populate db, login, and redirect
          var user = new User({
            name: req.body.name,
            email: req.body.email
          });
          user.setPassword(req.body.password, function(err) {
            if (err) {
              console.log("[ERROR] could not set user's password: " + err);
              req.flash('error', err);
              return res.redirect('/');
            } else {
              user.save(function(err) {
                if (err) {
                  console.log("[ERROR] cannot save user to MongoDB: " + err);
                  req.flash('error', err);
                  return res.redirect('/');
                } else {
                  req.login(user, function(err) {
                    if (err) {
                      console.log("[ERROR] cannot log user in: " + err);
                      req.flash('error', err);
                      return res.redirect('/');
                    } else {
                      return res.redirect('/notes');
                    }
                  });
                }
              });
            }
          });
        }
      } else {
        errors = errors || {};
        errors.email = {
          param: 'email',
          msg: 'This email address is already registered.',
          value: req.body.email
        };
        // there is at least one error, rerender register page.
        res.render('register', {
          title: 'Register',
          errors: errors,
          values: req.body
        });
      }
    });

  });
  app.get('/login', optionalAuth, function(req, res) {
    var errors = req.flash('error');
    res.render('login', {
      title: 'Log in',
      errors: errors
    });
  });
  app.post('/login',
    passport.authenticate('local', {
      successRedirect: '/notes',
      failureRedirect: '/login',
      failureFlash: 'Invalid username or password.'
    }));
  app.get('/notes', requireAuth, function(req, res) {
    Note.lookupByUserId(req.user._id, function(err,userNotes) {
      if (err) {
        console.log("[ERROR] could not find note: " + err);
        req.flash('error', err);
        return res.redirect('/');
      } else {
        res.render('notes', {
          layout: 'notes_ui',
          title: 'Notes',
          errors: req.flash('error'),
          notes: userNotes
        });
      }
    });
  });
  app.post('/logout', function(req, res) {
    req.logout();
    res.redirect('/');
  });
  app.get('/terms', optionalAuth, function(req, res) {
    res.render('terms', {title: 'Terms of Service'});
  });
  app.post('/upload', requireAuth, function(req, res){
    console.log(req.files);
    res.redirect('/notes');
  });
  app.get('/images/:id', optionalAuth, function(req,res){
    Note.lookupImageById(req.params.id, function(err, data){
      if (err) {
        console.log("[ERROR] could not lookup image: " + err);
        req.flash('error', err);
        return res.redirect('/');
      }
      else {
        res.set('Content-Type', data.data.mimetype);
        res.send(data.data.binary);
      }
    });
  });

  /*
   * TODO: write an error page (403,404,500,etc) and
   * change errors to redirect to that instead of "/"
   */

};


text:
ompl::geometric::SLPRM::SLPRMEdge::SLPRMEdge():
  towards_(0),
  weight_(0.0),
  exactInvalid_(false),
  exactValid_(false)
{
}
ompl::geometric::SLPRM::SLPRMEdge::SLPRMEdge(double weight, ompl::geometric::SLPRM::tIndex towards):
  towards_(towards),
  weight_(weight),
  exactInvalid_(false),
  exactValid_(false)
{
}
ompl::geometric::SLPRM::SLPRMEdge::SLPRMEdge(ompl::geometric::SLPRM::SLPRMEdge const &orig):
  towards_(orig.towards_),
  weight_(orig.weight_),
  exactInvalid_(orig.exactInvalid_),
  exactValid_(orig.exactValid_)
{
}
ompl::geometric::SLPRM::SLPRMEdge::SLPRMEdge(ompl::geometric::SLPRM::SLPRMEdge const *orig):
  towards_(orig->towards_),
  weight_(orig->weight_),
  exactInvalid_(orig->exactInvalid_),
  exactValid_(orig->exactValid_)
{
}
ompl::geometric::SLPRM::SLPRMEdge::~SLPRMEdge()
{
}

void ompl::geometric::SLPRM::SLPRMEdge::initialize(double weight, ompl::geometric::SLPRM::tIndex towards)
{
  weight_ = weight;
  towards_ = towards;
  exactInvalid_ = false;
  exactValid_ = false;
}
void ompl::geometric::SLPRM::SLPRMEdge::getEdgeData(double &weight, ompl::geometric::SLPRM::tIndex &towards) const
{
  weight = weight_;
  towards = towards_;
}

bool ompl::geometric::SLPRM::SLPRMEdge::isInteresting(void) const
{
  return (false == exactInvalid_);
}
void ompl::geometric::SLPRM::SLPRMEdge::setExactInvalid(bool isFlagged)
{
  exactInvalid_ = isFlagged;
  if(exactInvalid_)
  {
    exactValid_ = false;
  }
}
void ompl::geometric::SLPRM::SLPRMEdge::clearExactInvalid()
{
  exactInvalid_ = false;
}
void ompl::geometric::SLPRM::SLPRMEdge::setExactValid(bool isValid)
{
  exactValid_ = isValid;
  if(exactValid_)
  {
    exactInvalid_ = false;
  }
}
void ompl::geometric::SLPRM::SLPRMEdge::clearExactValid()
{
  exactValid_ = false;
}
bool ompl::geometric::SLPRM::SLPRMEdge::isExactValid() const
{
  return exactValid_;
}
bool ompl::geometric::SLPRM::SLPRMEdge::isExactInvalid() const
{
  return exactInvalid_;
}


text:
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.contenttypes.models import ContentType
from django.core.paginator import Paginator
from django.core.urlresolvers import reverse, reverse_lazy
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect

from django.views.generic import (
	View,
	ListView,
	DetailView,
	UpdateView,
	CreateView
	)

from django.views.generic.edit import FormView, FormMixin

from .forms import ItemForm
from comments.forms import CommentForm
from comments.models import Comment

from .models import Item
from restaurants.models import RestaurantLocations

# Create your views here.

class HomeView(ListView):
	# template_name='home-feed.html'
	paginate_by = 10

	# def get_queryset(self):
	# 	query = self.request.GET.get('q')
	# 	querset = RestaurantLocations.objects.search(query)
	# 	return querset

	def get(self, request, *args, **kwargs):
		if request.user.is_authenticated():
			user = request.user
			is_following_user_id = [x.user.id for x in user.is_following.all()]
			qs = Item.objects.filter(user__id__in=is_following_user_id, public=True).order_by("-updated")
			return render(request, 'menus/home-feed.html', {'object_list': qs})
		else:
			context = {}
			# if 'q' in self.request.GET:
			#     query = self.request.GET.get('q')
			#     qs = RestaurantLocations.objects.search(query)
			#     if qs.exists():
			#         context['locations'] = qs
			#         return render(request, 'search_results.html', context)
			return render(request, 'home.html', context)

class ItemListView(ListView):
	template_name = 'menus/item_list_all.html'
	paginate_by = 10

	def get_queryset(self):
		query = self.request.GET.get('q')
		querset = Item.objects.filter(public=True).search(query)
		return querset

class MyItemListView(LoginRequiredMixin, ListView):
	template_name = 'menus/item_list.html'
	paginate_by = 10

	def get_queryset(self):
		return Item.objects.filter(user=self.request.user)

class ItemDetailView(DetailView, FormView):
	def get_queryset(self):
		return Item.objects.filter(public=True)

	def get_context_data(self, **kwargs):
		comments = Comment.objects.filter(object_id=objects.id)
		context = super(ItemDetailView, self).get_context_data(**kwargs)
		return context

	def render(self, request):
		objects = get_object_or_404(Item, pk=self.kwargs.get('pk'))
		comments = Comment.objects.filter(object_id=objects.id)
		return render(request, 'menus/item_detail.html', {'comment_form': self.form, 'comments':comments, 'object':objects})

	def get(self, request, *args, **kwargs):
		self.object = self.get_object()
		# initial_data = {
		# 	"content_type": self.object.get_content_type,
		# 	"object_id": self.object.id
		# 	}
		self.form = CommentForm(initial={"content_type": self.object.get_content_type,"object_id": self.object.id})
		return self.render(request)
		#return super(ItemDetailView, self).get(request, *args, **kwargs)

	def post(self, request, *args, **kwargs):
		if not request.user.is_authenticated:
			return HttpResponseForbidden()
		self.object = self.get_object()

		self.form = CommentForm(request.POST or None)
		form = self.form
		if form.is_valid() and request.user.is_authenticated:

			c_type = form.cleaned_data["content_type"]
			#content_qs = ContentType.objects.filter(app_label ='restaurants')
			content_type = ContentType.objects.get(app_label="menus", model="item")
			obj_id = form.cleaned_data['object_id']
			content_data = form.cleaned_data["content"]
			parent_obj = None

			try:
				parent_id = int(request.POST.get("parent_id"))
			except:
				parent_id = None

			if parent_id:
				parent_qs = Comment.objects.filter(id=parent_id)
				if parent_qs.exists() and parent_qs.count() == 1:
					parent_obj = parent_qs.first()

			new_comment, created = Comment.objects.get_or_create(
								user = request.user,
								content_type= content_type,
								object_id = obj_id,
								content = content_data,
								parent = parent_obj,
							)

			return HttpResponseRedirect(new_comment.get_absolute_url())
		else:
			return self.render(request)

		#return super(RetaurantComment, self).post(request, *args, **kwargs)

class ItemCreateView(LoginRequiredMixin, CreateView):
	form_class = ItemForm
	template_name = 'form.html'

	def get_queryset(self):
		return Item.objects.filter(user=self.request.user)

	def get_context_data(self, *args, **kwargs):
		context = super(ItemCreateView, self).get_context_data(*args, **kwargs)
		context['title'] = 'Create Item'
		return context

	def form_valid(self, form):
		obj = form.save(commit=False)
		obj.user = self.request.user
		return super(ItemCreateView, self).form_valid(form)

	def get_form_kwargs(self):
		kwargs = super(ItemCreateView, self).get_form_kwargs()
		kwargs['user'] = self.request.user
		return kwargs

class ItemUpdateView(LoginRequiredMixin, UpdateView):
	form_class = ItemForm
	template_name = 'menus/detail-update.html'

	def get_queryset(self):
		return Item.objects.filter(user=self.request.user)

	def get_context_data(self, *args, **kwargs):
		context = super(ItemUpdateView, self).get_context_data(*args, **kwargs)
		context['title'] = 'Update Item'
		return context

	def get_form_kwargs(self):
		kwargs = super(ItemUpdateView, self).get_form_kwargs()
		kwargs['user'] = self.request.user
		return kwargs


text:
__author__ = 'wreichardt'
import time
import signal, os
import rpyc

conn = rpyc.connect('k9mk5',12345)
rpyc.BgServingThread(conn)
def event_handler(*args):
    print(args[0])
    event_type=args[0][0]
    event_parameter=args[0][1]

    if(event_type=='key_down'):
        key_number=event_parameter
        if key_number == 1:
            conn.root.animation_blinking_left_arrow()
            conn.root.lcd_write_line14("Blinking Arrow")
        if key_number == 2:
            conn.root.cancel_animation()
            conn.root.lcd_write_line4("              ")
        if key_number == 3:
            conn.root.animation_horizontal_sweep_up()
            conn.root.lcd_write_line4("Horizontal Sweep Up")
        if key_number == 4:
            conn.root.animation_diagonal_rl_bottom()
            conn.root.lcd_write_line4("Diagonal Sweep RL Bottom")
        # if key_number == 6:
        #     conn.root.animation(self.animation_strobe())
        #     conn.root.lcd_write_line4("Strobe")
        # if key_number ==7:
        #     conn.root.animation(self.animation_random())
        #     conn.root.lcd_write_line4("Random")
        # if key_number == 9:
        #     self.set_animation(self.animation_diagonal_lr_top())
        #     self.lcd_write_line4("Diagonal Sweep LR Top")
        if key_number == 11:
            conn.root.restart()
        if key_number == 12:
            #self.set_animation(self.animation_horizontal_sweep_down())
            conn.root.shutdown()

def handler(signum,stuff):
    print 'Signal handler called with signal', signum
    conn.root.release_handler(False);
    rpyc.BgServingThread.stop()
    conn.close()
    running=False

try:

    conn.root.remote_handler(event_handler)
    signal.signal(signal.SIGINT, handler)
    signal.signal(signal.SIGQUIT, handler)

    while True:
         time.sleep(10)

except Exception:
    pass

print "Stopped"


text:
local Helper = require('spec.helper.helper')
local Promise = require('promise')

local dummy = { dummy = 'dummy' } -- we fulfill or reject with this when we don't intend to test against it
local sentinel = { sentinel = 'sentinel' } -- a sentinel fulfillment value to test for with strict equality

local function testPromiseResolution(it, xFactory, test)
  it("via return from a fulfilled promise", function (done)
    local promise = Helper.resolved(dummy):next(function()
      return xFactory()
    end)

    test(promise, done)
  end)

  it("via return from a rejected promise", function(done)
    local promise = Helper.rejected(dummy):next(nil, function()
      return xFactory()
    end)

    test(promise, done)
  end)
end

describe("2.3.2: If `x` is a promise, adopt its state", function()
  describe("2.3.2.1: If `x` is pending, `promise` must remain pending until `x` is fulfilled or rejected.", function()
    local function xFactory()
      return Promise.new()
    end

    testPromiseResolution(it, xFactory, function (promise, done)
      async()

      local fulfillment = spy.new(function() end)
      local rejection = spy.new(function() end)

      promise:next(fulfillment, rejection)

      Helper.timeout(0.1, function()
        assert.spy(fulfillment).was_not_called()
        assert.spy(rejection).was_not_called()
        done()
      end)
    end)
  end)

  describe("2.3.2.2: If/when `x` is fulfilled, fulfill `promise` with the same value.", function()
    describe("`x` is already-fulfilled", function()
      local function xFactory()
        return Helper.resolved(sentinel)
      end

      testPromiseResolution(xFactory, function (promise, done)
        async()

        promise:next(function(value)
          assert.are.equals(value, sentinel)
          done()
        end)
      end)
    end)

    describe("`x` is eventually-fulfilled", function()
      local function xFactory()
        local p = Promise.new()

        Helper.timeout(0.05, function()
          p:resolve(sentinel)
        end)

        return p
      end

      testPromiseResolution(it, xFactory, function(promise, done)
        async()

        promise:next(function(value)
          assert.are_equals(value, sentinel)
          done()
        end)
      end)
    end)
  end)

  describe("2.3.2.3: If/when `x` is rejected, reject `promise` with the same reason.", function()
    describe("`x` is already-rejected", function()
      local function xFactory()
        return Helper.rejected(sentinel)
      end

      testPromiseResolution(it, xFactory, function(promise, done)
        async()

        promise:next(nil, function(reason)
          assert.are_equals(reason, sentinel)
          done()
        end)
      end)
    end)

    describe("`x` is eventually-rejected", function()
      local function xFactory()
        local p = Promise.new()

        Helper.timeout(0.05, function()
          p:reject(sentinel)
        end)

        return p
      end

      testPromiseResolution(it, xFactory, function(promise, done)
        async()

        promise:next(nil, function(reason)
          assert.are_equals(reason, sentinel)
          done()
        end)
      end)
    end)
  end)
end)


text:
package com.sae.event.core.bean;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.sae.event.core.Session;

import java.sql.Timestamp;

/**
 * Created by ralmeida on 1/7/16.
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class SessionItem {
    private String device;
    private String app;
    private String ip;
    private UserItem user;
    private String token;

    @JsonFormat(shape= JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm:ss z")
    private Timestamp updated_at;
    @JsonFormat(shape= JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm:ss z")
    private Timestamp created_at;

    public SessionItem(){
    }

    public SessionItem(Session session){
        device = session.getDevice();
        app = session.getApp();
        ip = session.getIp();
        updated_at = session.getUpdated_at();
        created_at = session.getCreated_at();
        user = new UserItem(session.getUser());
        user.setLast_active(session.getUpdated_at());
        token = session.getToken();
    }

    public String getDevice() {
        return device;
    }

    public void setDevice(String device) {
        this.device = device;
    }

    public String getApp() {
        return app;
    }

    public void setApp(String app) {
        this.app = app;
    }

    public Timestamp getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at(Timestamp updated_at) {
        this.updated_at = updated_at;
    }

    public Timestamp getCreated_at() {
        return created_at;
    }

    public void setCreated_at(Timestamp created_at) {
        this.created_at = created_at;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public UserItem getUser() {
        return user;
    }

    public void setUser(UserItem user) {
        this.user = user;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
}


text:
package javay.state;

/**
 * 沸水状态实现类
 */
public class WasteWaterStateImpl implements IWaterState {
  @Override
  public void printState() {
    System.out.println("水的状态:沸水!");
  }
}


text:
using WJStore.Domain.Entities;
using WJStore.Domain.Interfaces.Repository.Common;

namespace WJStore.Domain.Interfaces.Repository.ReadOnly
{
    public interface ICategoryReadOnlyRepository : IReadOnlyRepository<Category>
    {
        Category GetWithProducts(string categoryName);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated by org.testng.reporters.JUnitReportReporter -->
<testsuite hostname="PC" name="Dennis.HomePageTest" tests="2" failures="0" timestamp="2 Sep 2015 05:23:04 GMT" time="1.374" errors="0">
  <testcase name="test2" time="0.010" classname="Dennis.HomePageTest"/>
  <testcase name="testH1Existing" time="1.364" classname="Dennis.HomePageTest"/>
</testsuite> <!-- Dennis.HomePageTest -->


text:
#ifndef LayoutSVGText_h
#define LayoutSVGText_h

#include "core/layout/svg/LayoutSVGBlock.h"

namespace blink {

class LayoutSVGInlineText;
class SVGTextElement;

class LayoutSVGText final : public LayoutSVGBlock {
 public:
  explicit LayoutSVGText(SVGTextElement*);
  ~LayoutSVGText() override;

  bool isChildAllowed(LayoutObject*, const ComputedStyle&) const override;

  void setNeedsPositioningValuesUpdate() {
    m_needsPositioningValuesUpdate = true;
  }
  void setNeedsTransformUpdate() override { m_needsTransformUpdate = true; }
  void setNeedsTextMetricsUpdate() { m_needsTextMetricsUpdate = true; }
  FloatRect visualRectInLocalSVGCoordinates() const override;
  FloatRect objectBoundingBox() const override;
  FloatRect strokeBoundingBox() const override;
  bool isObjectBoundingBoxValid() const;

  void addOutlineRects(Vector<LayoutRect>&,
                       const LayoutPoint& additionalOffset,
                       IncludeBlockVisualOverflowOrNot) const override;

  static LayoutSVGText* locateLayoutSVGTextAncestor(LayoutObject*);
  static const LayoutSVGText* locateLayoutSVGTextAncestor(const LayoutObject*);

  bool needsReordering() const { return m_needsReordering; }
  const Vector<LayoutSVGInlineText*>& descendantTextNodes() const {
    return m_descendantTextNodes;
  }

  void subtreeChildWasAdded();
  void subtreeChildWillBeRemoved();
  void subtreeTextDidChange();

  const char* name() const override { return "LayoutSVGText"; }

 private:
  bool isOfType(LayoutObjectType type) const override {
    return type == LayoutObjectSVGText || LayoutSVGBlock::isOfType(type);
  }

  void paint(const PaintInfo&, const LayoutPoint&) const override;
  bool nodeAtFloatPoint(HitTestResult&,
                        const FloatPoint& pointInParent,
                        HitTestAction) override;
  PositionWithAffinity positionForPoint(const LayoutPoint&) override;

  void layout() override;

  void absoluteQuads(Vector<FloatQuad>&,
                     MapCoordinatesFlags mode = 0) const override;

  void addChild(LayoutObject* child,
                LayoutObject* beforeChild = nullptr) override;
  void removeChild(LayoutObject*) override;
  void willBeDestroyed() override;

  void invalidateTreeIfNeeded(const PaintInvalidationState&) override;

  RootInlineBox* createRootInlineBox() override;

  void invalidatePositioningValues(LayoutInvalidationReasonForTracing);

  bool m_needsReordering : 1;
  bool m_needsPositioningValuesUpdate : 1;
  bool m_needsTransformUpdate : 1;
  bool m_needsTextMetricsUpdate : 1;
  Vector<LayoutSVGInlineText*> m_descendantTextNodes;
};

DEFINE_LAYOUT_OBJECT_TYPE_CASTS(LayoutSVGText, isSVGText());

}  // namespace blink

#endif