text:
@interface PodsDummy_TGLStackedViewController : NSObject
@end
@implementation PodsDummy_TGLStackedViewController
@end

redpajama_set_name: RedPajamaGithub


text:
package com.google.sampling.experiential.shared;

import java.io.Serializable;

import org.codehaus.jackson.annotate.JsonProperty;

public class Output implements Serializable {

  @JsonProperty("answer")
  private String value;

  private String name;

  public Output(String name, String value) {
    this.value = value;
    this.name = name;
  }

  @JsonProperty("answer")
  public String getValue() {
    return value;
  }

  @JsonProperty("answer")
  public void setValue(String value) {
    this.value = value;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?><module codename="org.netbeans.modules.project.libraries/1">
    <module_version install_time="1416339133086" last="true" origin="installer" specification_version="1.47.1">
        <file crc="1139217149" name="config/ModuleAutoDeps/org-netbeans-modules-project-libraries.xml"/>
        <file crc="2974763789" name="config/Modules/org-netbeans-modules-project-libraries.xml"/>
        <file crc="3228698805" name="modules/locale/org-netbeans-modules-project-libraries_ja.jar"/>
        <file crc="3003206598" name="modules/locale/org-netbeans-modules-project-libraries_pt_BR.jar"/>
        <file crc="2505872609" name="modules/locale/org-netbeans-modules-project-libraries_ru.jar"/>
        <file crc="80363258" name="modules/locale/org-netbeans-modules-project-libraries_zh_CN.jar"/>
        <file crc="1654775616" name="modules/org-netbeans-modules-project-libraries.jar"/>
    </module_version>
</module>


text:
require 'rspec/core'
require 'rails'
require 'simply_stored/couch'
require 'roles_simply_stored'

CouchPotato::Config.database_name = "http://localhost:5984/roles_simply_stored"

class User
  include SimplyStored::Couch

  property :name, :type => String

  belongs_to :role
end

class Role
  include SimplyStored::Couch

  has_many :users, :dependent => :destroy

  property :name, :type => String
end

User.all.each{|u| u.delete }
Role.all.each{|r| r.delete }

role1 = Role.create(:name => 'guest')
role2 = Role.create(:name => 'admin')

user = User.create(:name => 'The user', :role => role1)

puts "Roles created: #{Role.all}"

puts "User: #{User.first}"

found = Role.find_all_by_names('guest admin')

puts "Found #{found}"


text:
Let's start with the relationship between the two important components:

* **Kubernetes** is a container orchestration system, and is used to run
  containers on a cluster
* **KubeVirt** is an add-on which is installed on-top of Kubernetes, to be able
  to add basic virtualization functionality to Kubernetes.

KubeVirt is an add-on to Kubernetes, and they have several things in
common:

* Mostly written in golang
* Often related to distributed microservice architectures
* Declarative and Reactive (Operator pattern) approach

This short page shall help to get started with the projects and topics
surrounding them

## Contributing to KubeVirt

### Our workflow

Contributing to KubeVirt should be as simple as possible. Have a question? Want
to discuss something? Want to contribute something? Just open an
[Issue](https://github.com/kubevirt/kubevirt/issues), a [Pull
Request](https://github.com/kubevirt/kubevirt/pulls), or send a mail to our
[Google Group](https://groups.google.com/forum/#!forum/kubevirt-dev).

If you spot a bug or want to change something pretty simple, just go
ahead and open an Issue and/or a Pull Request, including your changes
at [kubevirt/kubevirt](https://github.com/kubevirt/kubevirt).

For larger changes that require more planning and discussion, using the KubeVirt
[design proposal template](https://github.com/kubevirt/community/blob/main/design-proposals/proposal-template.md) is highly encouraged.
The technical effort for these changes will impact a large section of the
development community, so they should be communicated widely.  Examples of these types
of changes:
- New APIs
- Architectural changes
- Code refactors
- API changes

### Getting started

To make yourself comfortable with the code, you might want to work on some
Issues marked with one or more of the following labels:
[good-first-issue](https://github.com/kubevirt/kubevirt/labels/good-first-issue),
[help wanted](https://github.com/kubevirt/kubevirt/labels/help%20wanted)
or [kind/bug](https://github.com/kubevirt/kubevirt/labels/kind%2Fbug).
Any help is highly appreciated.

### Testing

**Untested features do not exist**. To ensure that what the code really works,
relevant flows should be covered via unit tests and functional tests. So when
thinking about a contribution, also think about testability. All tests can be
run local without the need of CI. Have a look at the
[Testing](docs/getting-started.md#testing)
section in the [Developer Guide](docs/getting-started.md).

### Contributor compliance with Developer Certificate Of Origin (DCO)

We require every contributor to certify that they are legally permitted to contribute to our project.
A contributor expresses this by consciously signing their commits, and by this act expressing that
they comply with the [Developer Certificate Of Origin](https://developercertificate.org/)

A signed commit is a commit where the commit message contains the following content:

```
Signed-off-by: John Doe <jdoe@example.org>
```

This can be done by adding [`--signoff`](https://git-scm.com/docs/git-commit#Documentation/git-commit.txt---signoff) to your git command line.

### Getting your code reviewed/merged

Maintainers are here to help you enabling your use-case in a reasonable amount
of time. The maintainers will try to review your code and give you productive
feedback in a reasonable amount of time. However, if you are blocked on a
review, or your Pull Request does not get the attention you think it deserves,
reach out for us via Comments in your Issues, or ping us on Slack
[#kubevirt-dev @ kubernetes.slack.com](https://kubernetes.slack.com/?redir=%2Farchives%2FC0163DT0R8X).

Maintainers are tracked in [OWNERS
files](https://github.com/kubernetes/test-infra/blob/f7e21a3c18f4f4bbc7ee170675ed53e4544a0632/prow/plugins/approve/approvers/README.md)
and will be assigned by Prow.

### Becoming a member

Contributors that frequently contribute to the project may ask to join the
KubeVirt organization.

Please have a look at our [membership guidelines](https://github.com/kubevirt/community/blob/main/membership_policy.md).

## Projects & Communities

### [KubeVirt](https://github.com/kubevirt/)

* Getting started
  * [Developer Guide](docs/getting-started.md)
  * [Demo](https://github.com/kubevirt/demo)
  * [Documentation](docs/)

### [Kubernetes](http://kubernetes.io/)

* Getting started
  * [http://kubernetesbyexample.com](http://kubernetesbyexample.com)
  * [Hello Minikube - Kubernetes](https://kubernetes.io/docs/tutorials/stateless-application/hello-minikube/)
  * [User Guide - Kubernetes](https://kubernetes.io/docs/user-guide/)
* Details
  * [Declarative Management of Kubernetes Objects Using Configuration Files - Kubernetes](https://kubernetes.io/docs/concepts/tools/kubectl/object-management-using-declarative-config/)
  * [Kubernetes Architecture](https://github.com/kubernetes/community/blob/master/contributors/design-proposals/architecture/architecture.md)

## Additional Topics

* Golang
  * [Documentation - The Go Programming Language](https://golang.org/doc/)
  * [Getting Started - The Go Programming Language](https://golang.org/doc/install)
* Patterns
  * [Introducing Operators: Putting Operational Knowledge into Software](https://web.archive.org/web/20210210032403/https://coreos.com/blog/introducing-operators.html)
  * [Microservices](https://martinfowler.com/articles/microservices.html) nice
    content by Martin Fowler
* Testing
  * [Ginkgo - A Golang BDD Testing Framework](https://onsi.github.io/ginkgo/)


text:
from sqlalchemy import Column, ForeignKey, Index, Integer

from rdr_service.model.base import Base
from rdr_service.model.participant import Participant
from rdr_service.model.utils import UTCDateTime

class EhrReceipt(Base):
    """
    A receipt log recording when HPOs submit EHR data.
    """

    __tablename__ = "ehr_receipt"
    ehrReceiptId = Column("ehr_receipt_id", Integer, primary_key=True)
    organizationId = Column(
        "organization_id", Integer, ForeignKey("organization.organization_id", ondelete="CASCADE"), nullable=False
    )
    """An organization a participant is paired with or "unset" if none"""
    receiptTime = Column("receipt_time", UTCDateTime, nullable=False, index=True)

class ParticipantEhrReceipt(Base):
    """
    A receipt log recording when EHR data submissions are made for participants
    """

    __tablename__ = "participant_ehr_receipt"
    id = Column("id", Integer, primary_key=True, autoincrement=True, nullable=False)
    participantId = Column(
        "participant_id", Integer, ForeignKey(Participant.participantId, ondelete="CASCADE"), nullable=False
    )
    fileTimestamp = Column("file_timestamp", UTCDateTime, nullable=False)
    firstSeen = Column("first_seen", UTCDateTime, nullable=False)
    lastSeen = Column("last_seen", UTCDateTime, nullable=False)

Index(
    'idx_participant_ehr_receipt_participant_file_time',
    ParticipantEhrReceipt.participantId,
    ParticipantEhrReceipt.fileTimestamp,
    unique=True
)


text:
#include "tensorflow/contrib/lite/op_resolver.h"
#include "tensorflow/contrib/lite/context.h"

namespace tflite {

const TfLiteRegistration* MutableOpResolver::FindOp(tflite::BuiltinOperator op,
                                                    int version) const {
  auto it = builtins_.find(std::make_pair(op, version));
  return it != builtins_.end() ? &it->second : nullptr;
}

const TfLiteRegistration* MutableOpResolver::FindOp(const char* op,
                                                    int version) const {
  auto it = custom_ops_.find(std::make_pair(op, version));
  return it != custom_ops_.end() ? &it->second : nullptr;
}

void MutableOpResolver::AddBuiltin(tflite::BuiltinOperator op,
                                   TfLiteRegistration* registration,
                                   int min_version, int max_version) {
  for (int version = min_version; version <= max_version; ++version) {
    TfLiteRegistration new_registration = *registration;
    new_registration.builtin_code = op;
    new_registration.version = version;
    auto op_key = std::make_pair(op, version);
    builtins_[op_key] = new_registration;
  }
}

void MutableOpResolver::AddCustom(const char* name,
                                  TfLiteRegistration* registration,
                                  int min_version, int max_version) {
  for (int version = min_version; version <= max_version; ++version) {
    TfLiteRegistration new_registration = *registration;
    new_registration.builtin_code = BuiltinOperator_CUSTOM;
    new_registration.version = version;
    auto op_key = std::make_pair(name, version);
    custom_ops_[op_key] = new_registration;
  }
}

}  // namespace tflite


text:
require 'factories/profiles.rb'

describe CreditCardFormatValidator do

  let(:subject) { CreditCardFormatValidator }

  let( :attribute ) { :credit_card }
  let (:object) { Profile.new }

  invalid_credit_card_numbers = %w[9556494038121161 41128109359983 n396092084242542 535299462783972 1396092084242542]
  valid_credit_card_numbers = %w[4556494038121161 4112810935509983 4556828677360012 5396092084242542 5180466231664941 5352994627083972]

  context 'Wrong credit card format' do

    context 'No message is sent on the options' do
      it 'it returns error message expecified on the validator' do
        n  = subject.new( { attributes: attribute } )
        invalid_credit_card_numbers.each do |invalid_credit_card_number|
          expect(n.validate_each(object, attribute, invalid_credit_card_number)).to include('enter a valid credit card number (Visa or Mastercard)')
        end
      end
    end

    context 'Message is sent on the options' do
      it 'it returns error message expecified on the options' do
        n  = subject.new( { message: 'Test error message', attributes: :postal_code } )
        invalid_credit_card_numbers.each do |invalid_credit_card_number|
          expect(n.validate_each(object, attribute, invalid_credit_card_number)).to include('Test error message')
        end
      end
    end

  end

  context 'Correct credit card format' do

    context 'No message is sent on the options' do
      it 'it does not return error message' do
        n  = subject.new( { attributes: attribute } )
        valid_credit_card_numbers.each do |valid_credit_card_number|
          expect(n.validate_each(object, attribute, valid_credit_card_number)).to equal(nil)
        end
      end
    end

    context 'Message is sent on the options' do
      it 'it does not return error message' do
        n  = subject.new( { message: 'Test error message', attributes: attribute } )
        valid_credit_card_numbers.each do |valid_credit_card_number|
          expect(n.validate_each(object, attribute, valid_credit_card_number)).to equal(nil)
        end
      end
    end

  end

end


text:
package com.bridgelabz.programs;

import com.bridgelabz.utility.Utility;

public class TicTacToe {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String result=Utility.ticTacToe();
        System.out.println(result);
	}

}


text:
Recording Settings

		<form>
			<fieldset>

					Enable audio recording on this camera
					<input type="checkbox" id="enable_audio_recording" name="enable_audio_recording" />

					Enable manual recording
					<input type="checkbox" id="enable_manual_recording" name="enable_manual_recording" />

			</fieldset>
		</form>

		<form>
			<fieldset>

					Video compression
					<select id="1.encode_type" name="1.encode_type">
					</select>

					Resolution
					<select id="1.resolution" name="1.resolution">
					</select>

					Frame rate
					<select id="1.frame_rate" name="1.frame_rate">
					</select>

					Quality
					<select id="1.quality" name="1.quality">
					</select>

			</fieldset>
		</form>

		<form>
			<fieldset>

					Video compression
					<select id="0.encode_type" name="0.encode_type">
					</select>

					Resolution
					<select id="0.resolution" name="0.resolution">
					</select>

					Frame rate
					<select id="0.frame_rate" name="0.frame_rate">
					</select>

					Quality
					<select id="0.quality" name="0.quality">
					</select>

			</fieldset>
		</form>


text:
package org.wso2.carbon.apimgt.rest.api.publisher.dto;

import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.ArrayList;
import java.util.List;
import org.wso2.carbon.apimgt.rest.api.publisher.dto.LifecycleState_availableTransitionBeanListDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.dto.LifecycleState_checkItemBeanListDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.dto.LifecycleState_inputBeanListDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.dto.LifecycleState_permissionBeansDTO;
import org.wso2.carbon.apimgt.rest.api.publisher.dto.LifecycleState_validationBeansDTO;
import java.util.Objects;

/**
 * LifecycleStateDTO
 */
public class LifecycleStateDTO   {
  @SerializedName("lcName")
  private String lcName = null;

  @SerializedName("state")
  private String state = null;

  @SerializedName("lifecyelId")
  private String lifecyelId = null;

  @SerializedName("checkItemBeanList")
  private List<LifecycleState_checkItemBeanListDTO> checkItemBeanList = new ArrayList<LifecycleState_checkItemBeanListDTO>();

  @SerializedName("inputBeanList")
  private List<LifecycleState_inputBeanListDTO> inputBeanList = new ArrayList<LifecycleState_inputBeanListDTO>();

  @SerializedName("customCodeBeanList")
  private List<LifecycleState_validationBeansDTO> customCodeBeanList = new ArrayList<LifecycleState_validationBeansDTO>();

  @SerializedName("availableTransitionBeanList")
  private List<LifecycleState_availableTransitionBeanListDTO> availableTransitionBeanList = new ArrayList<LifecycleState_availableTransitionBeanListDTO>();

  @SerializedName("permissionBeanList")
  private List<LifecycleState_permissionBeansDTO> permissionBeanList = new ArrayList<LifecycleState_permissionBeansDTO>();

  public LifecycleStateDTO lcName(String lcName) {
    this.lcName = lcName;
    return this;
  }

   /**
   * Get lcName
   * @return lcName
  **/
  @ApiModelProperty(example = "API Lifecycle", value = "")
  public String getLcName() {
    return lcName;
  }

  public void setLcName(String lcName) {
    this.lcName = lcName;
  }

  public LifecycleStateDTO state(String state) {
    this.state = state;
    return this;
  }

   /**
   * Get state
   * @return state
  **/
  @ApiModelProperty(example = "Created", value = "")
  public String getState() {
    return state;
  }

  public void setState(String state) {
    this.state = state;
  }

  public LifecycleStateDTO lifecyelId(String lifecyelId) {
    this.lifecyelId = lifecyelId;
    return this;
  }

   /**
   * Get lifecyelId
   * @return lifecyelId
  **/
  @ApiModelProperty(example = "01234567-0123-0123-0123-012345678901", value = "")
  public String getLifecyelId() {
    return lifecyelId;
  }

  public void setLifecyelId(String lifecyelId) {
    this.lifecyelId = lifecyelId;
  }

  public LifecycleStateDTO checkItemBeanList(List<LifecycleState_checkItemBeanListDTO> checkItemBeanList) {
    this.checkItemBeanList = checkItemBeanList;
    return this;
  }

  public LifecycleStateDTO addCheckItemBeanListItem(LifecycleState_checkItemBeanListDTO checkItemBeanListItem) {
    this.checkItemBeanList.add(checkItemBeanListItem);
    return this;
  }

   /**
   * Get checkItemBeanList
   * @return checkItemBeanList
  **/
  @ApiModelProperty(value = "")
  public List<LifecycleState_checkItemBeanListDTO> getCheckItemBeanList() {
    return checkItemBeanList;
  }

  public void setCheckItemBeanList(List<LifecycleState_checkItemBeanListDTO> checkItemBeanList) {
    this.checkItemBeanList = checkItemBeanList;
  }

  public LifecycleStateDTO inputBeanList(List<LifecycleState_inputBeanListDTO> inputBeanList) {
    this.inputBeanList = inputBeanList;
    return this;
  }

  public LifecycleStateDTO addInputBeanListItem(LifecycleState_inputBeanListDTO inputBeanListItem) {
    this.inputBeanList.add(inputBeanListItem);
    return this;
  }

   /**
   * Get inputBeanList
   * @return inputBeanList
  **/
  @ApiModelProperty(value = "")
  public List<LifecycleState_inputBeanListDTO> getInputBeanList() {
    return inputBeanList;
  }

  public void setInputBeanList(List<LifecycleState_inputBeanListDTO> inputBeanList) {
    this.inputBeanList = inputBeanList;
  }

  public LifecycleStateDTO customCodeBeanList(List<LifecycleState_validationBeansDTO> customCodeBeanList) {
    this.customCodeBeanList = customCodeBeanList;
    return this;
  }

  public LifecycleStateDTO addCustomCodeBeanListItem(LifecycleState_validationBeansDTO customCodeBeanListItem) {
    this.customCodeBeanList.add(customCodeBeanListItem);
    return this;
  }

   /**
   * Get customCodeBeanList
   * @return customCodeBeanList
  **/
  @ApiModelProperty(value = "")
  public List<LifecycleState_validationBeansDTO> getCustomCodeBeanList() {
    return customCodeBeanList;
  }

  public void setCustomCodeBeanList(List<LifecycleState_validationBeansDTO> customCodeBeanList) {
    this.customCodeBeanList = customCodeBeanList;
  }

  public LifecycleStateDTO availableTransitionBeanList(List<LifecycleState_availableTransitionBeanListDTO> availableTransitionBeanList) {
    this.availableTransitionBeanList = availableTransitionBeanList;
    return this;
  }

  public LifecycleStateDTO addAvailableTransitionBeanListItem(LifecycleState_availableTransitionBeanListDTO availableTransitionBeanListItem) {
    this.availableTransitionBeanList.add(availableTransitionBeanListItem);
    return this;
  }

   /**
   * Get availableTransitionBeanList
   * @return availableTransitionBeanList
  **/
  @ApiModelProperty(value = "")
  public List<LifecycleState_availableTransitionBeanListDTO> getAvailableTransitionBeanList() {
    return availableTransitionBeanList;
  }

  public void setAvailableTransitionBeanList(List<LifecycleState_availableTransitionBeanListDTO> availableTransitionBeanList) {
    this.availableTransitionBeanList = availableTransitionBeanList;
  }

  public LifecycleStateDTO permissionBeanList(List<LifecycleState_permissionBeansDTO> permissionBeanList) {
    this.permissionBeanList = permissionBeanList;
    return this;
  }

  public LifecycleStateDTO addPermissionBeanListItem(LifecycleState_permissionBeansDTO permissionBeanListItem) {
    this.permissionBeanList.add(permissionBeanListItem);
    return this;
  }

   /**
   * Get permissionBeanList
   * @return permissionBeanList
  **/
  @ApiModelProperty(value = "")
  public List<LifecycleState_permissionBeansDTO> getPermissionBeanList() {
    return permissionBeanList;
  }

  public void setPermissionBeanList(List<LifecycleState_permissionBeansDTO> permissionBeanList) {
    this.permissionBeanList = permissionBeanList;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    LifecycleStateDTO lifecycleState = (LifecycleStateDTO) o;
    return Objects.equals(this.lcName, lifecycleState.lcName) &&
        Objects.equals(this.state, lifecycleState.state) &&
        Objects.equals(this.lifecyelId, lifecycleState.lifecyelId) &&
        Objects.equals(this.checkItemBeanList, lifecycleState.checkItemBeanList) &&
        Objects.equals(this.inputBeanList, lifecycleState.inputBeanList) &&
        Objects.equals(this.customCodeBeanList, lifecycleState.customCodeBeanList) &&
        Objects.equals(this.availableTransitionBeanList, lifecycleState.availableTransitionBeanList) &&
        Objects.equals(this.permissionBeanList, lifecycleState.permissionBeanList);
  }

  @Override
  public int hashCode() {
    return Objects.hash(lcName, state, lifecyelId, checkItemBeanList, inputBeanList, customCodeBeanList, availableTransitionBeanList, permissionBeanList);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class LifecycleStateDTO {\n");

    sb.append("    lcName: ").append(toIndentedString(lcName)).append("\n");
    sb.append("    state: ").append(toIndentedString(state)).append("\n");
    sb.append("    lifecyelId: ").append(toIndentedString(lifecyelId)).append("\n");
    sb.append("    checkItemBeanList: ").append(toIndentedString(checkItemBeanList)).append("\n");
    sb.append("    inputBeanList: ").append(toIndentedString(inputBeanList)).append("\n");
    sb.append("    customCodeBeanList: ").append(toIndentedString(customCodeBeanList)).append("\n");
    sb.append("    availableTransitionBeanList: ").append(toIndentedString(availableTransitionBeanList)).append("\n");
    sb.append("    permissionBeanList: ").append(toIndentedString(permissionBeanList)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
/*
Given a string S and a string T, count the number of distinct subsequences of T in S.

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

Here is an example:
S = "rabbbit", T = "rabbit"

Return 3.
first we check with a:

           *  *
      S = [acdabefbc]
mem[1] = [0111222222]
then we check with ab:

               *  * ]
      S = [acdabefbc]
mem[1] = [0111222222]
mem[2] = [0000022244]
*/

/**

 * @param {string} s

 * @param {string} t

 * @return {number}

 */

var numDistinct = function(s, t) {
	if (s.length === 0 || t.length === 0 || s.length < t.length) return 0;
	var dr = [];
	for (var i = 0; i < s.length; i++) {
		if()
	}

};


text:
<android.support.v7.widget.RecyclerView
    android:id="@+id/lista"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>


text:
/*
 *  This file was autogenerated by the GPUdb schema processor.
 *
 *  DO NOT EDIT DIRECTLY.
 */
package com.gpudb.protocol;

import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.avro.Schema;
import org.apache.avro.SchemaBuilder;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.IndexedRecord;

/**
 * A set of parameters for {@link
 * com.gpudb.GPUdb#createUserExternal(CreateUserExternalRequest)}.
 *

 * Creates a new external user (a user whose credentials are managed by an
 * external LDAP).
 */
public class CreateUserExternalRequest implements IndexedRecord {
    private static final Schema schema$ = SchemaBuilder
            .record("CreateUserExternalRequest")
            .namespace("com.gpudb")
            .fields()
                .name("name").type().stringType().noDefault()
                .name("options").type().map().values().stringType().noDefault()
            .endRecord();

    /**
     * This method supports the Avro framework and is not intended to be called
     * directly by the user.
     *
     * @return  the schema for the class.
     *
     */
    public static Schema getClassSchema() {
        return schema$;
    }

    /**
     * Optional parameters.
     *

     *
 {@link
     * com.gpudb.protocol.CreateUserExternalRequest.Options#CREATE_HOME_DIRECTORY
     * CREATE_HOME_DIRECTORY}: when true, a home directory in KiFS is created
     * for this user
     * Supported values:
     *

     *
 {@link
     * com.gpudb.protocol.CreateUserExternalRequest.Options#TRUE TRUE}
     *
 {@link
     * com.gpudb.protocol.CreateUserExternalRequest.Options#FALSE FALSE}
     *

     * The default value is {@link
     * com.gpudb.protocol.CreateUserExternalRequest.Options#TRUE TRUE}.
     *

     * The default value is an empty {@link Map}.
     * A set of string constants for the parameter {@code options}.
     */
    public static final class Options {

        /**
         * when true, a home directory in KiFS is created for this user
         * Supported values:
         *

         *
 {@link
         * com.gpudb.protocol.CreateUserExternalRequest.Options#TRUE TRUE}
         *
 {@link
         * com.gpudb.protocol.CreateUserExternalRequest.Options#FALSE FALSE}
         *

         * The default value is {@link
         * com.gpudb.protocol.CreateUserExternalRequest.Options#TRUE TRUE}.
         */
        public static final String CREATE_HOME_DIRECTORY = "create_home_directory";
        public static final String TRUE = "true";
        public static final String FALSE = "false";

        private Options() {  }
    }

    private String name;
    private Map<String, String> options;

    /**
     * Constructs a CreateUserExternalRequest object with default parameters.
     */
    public CreateUserExternalRequest() {
        name = "";
        options = new LinkedHashMap<>();
    }

    /**
     * Constructs a CreateUserExternalRequest object with the specified
     * parameters.
     *
     * @param name  Name of the user to be created. Must exactly match the
     *              user's name in the external LDAP, prefixed with a @. Must
     *              not be the same name as an existing user.
     * @param options  Optional parameters.
     *

     *
 {@link
     *                 com.gpudb.protocol.CreateUserExternalRequest.Options#CREATE_HOME_DIRECTORY
     *                 CREATE_HOME_DIRECTORY}: when true, a home directory in
     *                 KiFS is created for this user
     *                 Supported values:
     *

     *
 {@link
     *                 com.gpudb.protocol.CreateUserExternalRequest.Options#TRUE
     *                 TRUE}
     *
 {@link
     *                 com.gpudb.protocol.CreateUserExternalRequest.Options#FALSE
     *                 FALSE}
     *

     *                 The default value is {@link
     *                 com.gpudb.protocol.CreateUserExternalRequest.Options#TRUE
     *                 TRUE}.
     *

     *                 The default value is an empty {@link Map}.
     *
     */
    public CreateUserExternalRequest(String name, Map<String, String> options) {
        this.name = (name == null) ? "" : name;
        this.options = (options == null) ? new LinkedHashMap<String, String>() : options;
    }

    /**
     *
     * @return Name of the user to be created. Must exactly match the user's
     *         name in the external LDAP, prefixed with a @. Must not be the
     *         same name as an existing user.
     *
     */
    public String getName() {
        return name;
    }

    /**
     *
     * @param name  Name of the user to be created. Must exactly match the
     *              user's name in the external LDAP, prefixed with a @. Must
     *              not be the same name as an existing user.
     *
     * @return {@code this} to mimic the builder pattern.
     *
     */
    public CreateUserExternalRequest setName(String name) {
        this.name = (name == null) ? "" : name;
        return this;
    }

    /**
     *
     * @return Optional parameters.
     *

     *
 {@link
     *         com.gpudb.protocol.CreateUserExternalRequest.Options#CREATE_HOME_DIRECTORY
     *         CREATE_HOME_DIRECTORY}: when true, a home directory in KiFS is
     *         created for this user
     *         Supported values:
     *

     *
 {@link
     *         com.gpudb.protocol.CreateUserExternalRequest.Options#TRUE TRUE}
     *
 {@link
     *         com.gpudb.protocol.CreateUserExternalRequest.Options#FALSE
     *         FALSE}
     *

     *         The default value is {@link
     *         com.gpudb.protocol.CreateUserExternalRequest.Options#TRUE TRUE}.
     *

     *         The default value is an empty {@link Map}.
     *
     */
    public Map<String, String> getOptions() {
        return options;
    }

    /**
     *
     * @param options  Optional parameters.
     *

     *
 {@link
     *                 com.gpudb.protocol.CreateUserExternalRequest.Options#CREATE_HOME_DIRECTORY
     *                 CREATE_HOME_DIRECTORY}: when true, a home directory in
     *                 KiFS is created for this user
     *                 Supported values:
     *

     *
 {@link
     *                 com.gpudb.protocol.CreateUserExternalRequest.Options#TRUE
     *                 TRUE}
     *
 {@link
     *                 com.gpudb.protocol.CreateUserExternalRequest.Options#FALSE
     *                 FALSE}
     *

     *                 The default value is {@link
     *                 com.gpudb.protocol.CreateUserExternalRequest.Options#TRUE
     *                 TRUE}.
     *

     *                 The default value is an empty {@link Map}.
     *
     * @return {@code this} to mimic the builder pattern.
     *
     */
    public CreateUserExternalRequest setOptions(Map<String, String> options) {
        this.options = (options == null) ? new LinkedHashMap<String, String>() : options;
        return this;
    }

    /**
     * This method supports the Avro framework and is not intended to be called
     * directly by the user.
     *
     * @return the schema object describing this class.
     *
     */
    @Override
    public Schema getSchema() {
        return schema$;
    }

    /**
     * This method supports the Avro framework and is not intended to be called
     * directly by the user.
     *
     * @param index  the position of the field to get
     *
     * @return value of the field with the given index.
     *
     * @throws IndexOutOfBoundsException
     *
     */
    @Override
    public Object get(int index) {
        switch (index) {
            case 0:
                return this.name;

            case 1:
                return this.options;

            default:
                throw new IndexOutOfBoundsException("Invalid index specified.");
        }
    }

    /**
     * This method supports the Avro framework and is not intended to be called
     * directly by the user.
     *
     * @param index  the position of the field to set
     * @param value  the value to set
     *
     * @throws IndexOutOfBoundsException
     *
     */
    @Override
    @SuppressWarnings("unchecked")
    public void put(int index, Object value) {
        switch (index) {
            case 0:
                this.name = (String)value;
                break;

            case 1:
                this.options = (Map<String, String>)value;
                break;

            default:
                throw new IndexOutOfBoundsException("Invalid index specified.");
        }
    }

    @Override
    public boolean equals(Object obj) {
        if( obj == this ) {
            return true;
        }

        if( (obj == null) || (obj.getClass() != this.getClass()) ) {
            return false;
        }

        CreateUserExternalRequest that = (CreateUserExternalRequest)obj;

        return ( this.name.equals( that.name )
                 && this.options.equals( that.options ) );
    }

    @Override
    public String toString() {
        GenericData gd = GenericData.get();
        StringBuilder builder = new StringBuilder();
        builder.append( "{" );
        builder.append( gd.toString( "name" ) );
        builder.append( ": " );
        builder.append( gd.toString( this.name ) );
        builder.append( ", " );
        builder.append( gd.toString( "options" ) );
        builder.append( ": " );
        builder.append( gd.toString( this.options ) );
        builder.append( "}" );

        return builder.toString();
    }

    @Override
    public int hashCode() {
        int hashCode = 1;
        hashCode = (31 * hashCode) + this.name.hashCode();
        hashCode = (31 * hashCode) + this.options.hashCode();
        return hashCode;
    }

}


text:
layout: default
title: CAS - Web Flow Customization
---

#Webflow Customization
CAS uses [Spring Web Flow](projects.spring.io/spring-webflow) to do "script" processing of login and logout protocols. Spring Web Flow builds on Spring MVC and allows implementing the "flows" of a web application. A flow encapsulates a sequence of steps that guide a user through the execution of some business task. It spans multiple HTTP requests, has state, deals with transactional data, is reusable, and may be dynamic and long-running in nature. Each flow may contain among many other settings the following major elements:

- Actions: components that describe an executable task and return back a result
- Transitions: Routing the flow from one state to another; Transitions may be global to the entire flow.
- Views: Components that describe the presentation layer displayed back to the client
- Decisions: Components that conditionally route to other areas of flow and can make logical decisions

Spring Web Flow presents CAS with a pluggable architecture where custom actions, views and decisions may be injected into the flow to account for additional use cases and processes. Note that to customize the weblow, one must possess a reasonable level of understanding of the webflow's internals and injection policies. The intention of this document is not to describe Spring Web Flow, but merely to demonstrate how the framework is used by CAS to carry out various aspects of the protocol and business logic execution.

##Login Flow
The flow in CAS is given a unique id that is registered inside a `flowRegistry` component. Support is enabled via the following configuration snippets in `cas-servlet.xml`:

###Components
{% highlight xml %}

<webflow:flow-executor id="loginFlowExecutor" flow-registry="loginFlowRegistry">
	<webflow:flow-execution-attributes>
	  <webflow:always-redirect-on-pause value="false" />
	  <webflow:redirect-in-same-state value="false" />
	</webflow:flow-execution-attributes>
	<webflow:flow-execution-listeners>
	  <webflow:listener ref="terminateWebSessionListener" />
	</webflow:flow-execution-listeners>
</webflow:flow-executor>

...

<webflow:flow-registry id="loginFlowRegistry" flow-builder-services="builder">
    <webflow:flow-location path="/WEB-INF/login-webflow.xml" id="login" />
</webflow:flow-registry>

{% endhighlight %}

###login-flow.xml Overview
The login flow is at a high level composed of the following phases:

- Initialization of the flow
- Validation of Ticket Granting Ticket (TGT)
- Validation of requesting service and ensuring that it is authorized to use CAS
- Generation of the Login Ticket (LT)
- Presentation of the Login Form
- Generation of TGT upon successful authentication
- Generation of Service Ticket (ST) for the requesting service
- Issuing a redirect back to the authenticating web service

A high-level diagram detailing major states in the flow is presented here:

![](http://i.imgur.com/SBDUGbH.png)

Acceptance of user credentials and invoking the authentication handler components is carried out by:

{% highlight xml %}
<bean id="authenticationViaFormAction" class="org.jasig.cas.web.flow.AuthenticationViaFormAction"
        p:centralAuthenticationService-ref="centralAuthenticationService"
        p:warnCookieGenerator-ref="warnCookieGenerator"/>

{% endhighlight %}

Handling authentication failures, mapping the result of which event to a new state is carried out by:

{% highlight xml %}
<bean id="authenticationExceptionHandler" class="org.jasig.cas.web.flow.AuthenticationExceptionHandler" />

...

<action-state id="realSubmit">
	<evaluate expression="authenticationViaFormAction.submit(flowRequestContext, flowScope.credential, messageContext)" />

  	<transition on="success" to="sendTicketGrantingTicket" />
    <transition on="authenticationFailure" to="handleAuthenticationFailure" />
    <transition on="error" to="generateLoginTicket" />
</action-state>

....
<action-state id="handleAuthenticationFailure">
    <evaluate expression="authenticationExceptionHandler.handle(currentEvent.attributes.error, messageContext)" />
    <transition on="AccountDisabledException" to="casAccountDisabledView"/>
    <transition on="AccountLockedException" to="casAccountLockedView"/>
    <transition on="CredentialExpiredException" to="casExpiredPassView"/>
    <transition on="InvalidLoginLocationException" to="casBadWorkstationView"/>
    <transition on="InvalidLoginTimeException" to="casBadHoursView"/>
    <transition on="FailedLoginException" to="generateLoginTicket"/>
    <transition on="AccountNotFoundException" to="generateLoginTicket"/>
    <transition on="UNKNOWN" to="generateLoginTicket"/>
</action-state>
{% endhighlight %}

Certain error conditions are also classified as global transitions, particularly in cases of unauthorized services attempting to use CAS:

{% highlight xml %}
<global-transitions>
    <transition to="viewLoginForm" on-exception="org.jasig.cas.services.UnauthorizedSsoServiceException"/>
    <transition to="viewServiceErrorView" on-exception="org.springframework.webflow.execution.repository.NoSuchFlowExecutionException" />
    <transition to="viewServiceErrorView" on-exception="org.jasig.cas.services.UnauthorizedServiceException" />
</global-transitions>
{% endhighlight %}

##Logout Flow
The flow in CAS is given a unique id that is registered inside a `flowRegistry` component. Support is enabled via the following configuration snippets in `cas-servlet.xml`:

###Components
{% highlight xml %}
<webflow:flow-executor id="logoutFlowExecutor" flow-registry="logoutFlowRegistry">
    <webflow:flow-execution-attributes>
      <webflow:always-redirect-on-pause value="false" />
      <webflow:redirect-in-same-state value="false" />
    </webflow:flow-execution-attributes>
    <webflow:flow-execution-listeners>
      <webflow:listener ref="terminateWebSessionListener" />
    </webflow:flow-execution-listeners>
</webflow:flow-executor>

...

<webflow:flow-registry id="logoutFlowRegistry" flow-builder-services="builder">
	<webflow:flow-location path="/WEB-INF/logout-webflow.xml" id="logout" />
</webflow:flow-registry>
{% endhighlight %}

###logout-flow.xml Overview
The logout flow is at a high level composed of the following phases:

- Termination of the SSO session and destruction of the TGT
- Initiating the Logout protocol
- Handling various methods of logout (front-channel, back-channel, etc)

The Logout protocol is initiated by the following component:

{% highlight xml %}
<bean id="logoutAction" class="org.jasig.cas.web.flow.LogoutAction"
        p:servicesManager-ref="servicesManager"
        p:followServiceRedirects="${cas.logout.followServiceRedirects:false}"/>

{% endhighlight %}

Front-channel method of logout is specifically handled by the following component:
{% highlight xml %}
<bean id="frontChannelLogoutAction" class="org.jasig.cas.web.flow.FrontChannelLogoutAction"
        c:logoutManager-ref="logoutManager"/>

{% endhighlight %}

##Termination of Web Flow Sessions
Each flow is registered with a `TerminateWebSessionListener` whose job is expire the web session as soon as the webflow is ended. The goal is to decrease memory consumption by deleting as soon as possible the web sessions created mainly for login and logout processes. By default, the webflow session is configured to be destroyed in 2 seconds, once the session has ended.

##Extending the Webflow
The CAS webflow provides discrete points to inject new functionality. Thus, the only thing to modify is the flow definition where new beans and views can be added easily with the Maven overlay build method.

###Adding Actions
Adding Spring Web Flow actions typically involves the following steps:

- Adding a SWF-specific Spring bean type that extends `org.springframework.webflow.action.AbstractAction`
- Access to the flow scope object also accessible in the flow definition file
- `doExecute()` method contains business logic and returns `success()` or `error()` Event types
- Returned Event types are evaluated in the flow definition file

Once the action bean is configured, you may define it inside the `login-webflow.xml`:

{% highlight xml %}
<action-state id="actionStateId">
	<action bean="customActionBeanId" />
	<transition on="success" to="doThis" />
	<transition on="error" to="doThat" />
</action-state>
{% endhighlight %}

###Adding Views
Adding Spring Web Flow views involves the following steps:

- The name of the view directly referenced from the flow definition file
- The name of the view must match the view file name

A sample is presented here:

{% highlight bash %}
### View for password update
passwordUpdateView.(class)=org.springframework.web.servlet.view.JstlView
passwordUpdateView.url=/WEB-INF/view/jsp/default/ui/passwordUpdateView.jsp

{% endhighlight %}


text:
title: Kalendar
inshort: Outlookov kalendar
translator: Microsoft Cognitive Services
---

Kalendar je kalendar programa Outlook i prikazuje u sustavu Office 365.

Resursa
---------

-[Povezivanje SharePoint kalendara u
    Outlook](http://icsh.pt/SPandOutlook) \[icansharepoint blog\]

Slične aplikacije
--------------------

-Google kalendar

-Apple kalendar

Metapodataka
--------

-Vanjski dijeljenje je podržan

-Aplikacija za desktop i mobilne


text:
package net.blackhacker.crypto;

import net.blackhacker.crypto.utils.Validator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;

/**
 *  Abstract base class for both symmetric and asymmetric encryption algorithms
 *
 *  @author Benjamin King aka Blackhacker(bh@blackhacker.net)
 */
public class Crypto {

    final private Transformation transformation;

    /**
     * Cipher
     */
    final private Cipher cipher;

    /**
     * SecureRandom
     */
    final private SecureRandom secureRandom = new SecureRandom();

    /**
     * Constructor
     *
     * @param transformation Transformation object
     * @throws CryptoException
     */
    public  Crypto(Transformation transformation) throws CryptoException {
        this.transformation = Validator.notNull(transformation, "transformation");

        try {
            cipher = Cipher.getInstance(transformation.toString());
        } catch (NoSuchAlgorithmException | NoSuchPaddingException ex) {
            String msg = String.format(Strings.COULDNT_CREATE_CIPHER_MSG_FMT,
                    transformation.getAlgorithmString(),
                    ex.getLocalizedMessage());
            throw new CryptoException(msg, ex);
        }
    }

    /*  Getters and Setters */

    /**
     * The internal Cipher object
     *
     * @return Cipher
     * @see Cipher
     */
    final public Cipher getCipher()  {
        return cipher;
    }

    /**
     * The internal SecureRandom
     *
     * @return SecureRandom object
     * @see SecureRandom
     */
    final public SecureRandom getSecureRandom() {
        return secureRandom;
    }

    /**
     * Transformation
     *
     * @return internal Transformation object
     * @see Transformation
     */
    final public Transformation getTransformation() {
        return transformation;
    }

    /**
     * Generates a new Initialization Vector (IV)
     *
     * @return new IV in the form a byte target
     */
    final public byte[] generateIV() {
        byte[] iv = new byte[ transformation.getBlockSizeBytes()];
        secureRandom.nextBytes(iv);
        return iv;
    }

    /**
     * Randomly generates salt bytes
     *
     * @return salt
     */
    final public byte[] generateSalt() {
        byte[] salt = new byte[transformation.getSaltSizeBytes()];
        secureRandom.nextBytes(salt);
        return salt;
    }

    /**
     *  Builds {@link AlgorithmParameterSpec} based on the Transformation and the
     * parameters are passed in
     *
     * @param parameters inputs to parameterspec
     * @return AlgorithmParameterSpec
     * @throws CryptoException errors
     * @see AlgorithmParameterSpec
     */
    final public AlgorithmParameterSpec makeParameterSpec(Object... parameters)
            throws CryptoException {
        return transformation.makeParameterSpec(parameters);
    }

    /**
     *
     * @param parameters inputs
     * @return KeySpec object
     * @throws CryptoException errors
     * @see KeySpec
     */
    final public KeySpec makeKeySpec(Object... parameters)
            throws CryptoException {
        return transformation.makeKeySpec(parameters);
    }

    /**
     *
     * @param params
     * @return
     * @throws CryptoException
     * @see KeySpec
     */
    final public KeySpec makePublicKeySpec(Object... params)
            throws CryptoException {
        return transformation.makePublicKeySpec(params);
    }

    /**
     * Returns the block size for the algorithm described in the internal
     * Transformation
     *
     * @return block size
     */
    final public int getBlockSizeBytes(){
        return transformation.getBlockSizeBytes();
    }

    /**
     * Returns true if the Mode uses an Initialization Vector (IV), otherwise
     * false
     *
     * @return true if the Mode uses an IV, otherwise false
     */
    public boolean hasIV() {
        return transformation.hasIV();
    }

    /**
     * Returns true if the Transformation describes a Password Based Encryption
     * (PBE)
     *
     * @return true if this is a PBE
     */
    public boolean isPBE() {
        return transformation.isPBE();
    }

    /**
     * Returns true if this object represents an asymmetric algorithm
     *
     * @return true is the object represents an asymmetric algorithm
     */
    public boolean isAsymetric() {
        return transformation.isAsymmetric();
    }

    /**
     *
     * @return
     */
    public String getAlgorithmString() {
        return transformation.getAlgorithmString();
    }

}


text:
import { List as makeImmutableList } from 'immutable';
import {
  playerStates,
  captionsStates,
  sessionActionTypes,
  videoActionTypes,
  videoDefaults,
} from 'lib/constants/videoConstants';
import { isPlayingState, timeIsPastRestricted } from 'lib/helpers/videoHelpers';
import { createTransform } from 'redux-persist';

export const initialState = {
  videoUrl: null,
  watchNextVideoUrl: null,
  nextVideoSubmissionExists: false,
  playerState: playerStates.UNSTARTED,
  playerProgress: 0,
  duration: videoDefaults.placeHolderDuration,
  bufferProgress: 0,
  playerVolume: videoDefaults.volume,
  playbackRate: 1,
  captionsState: captionsStates.NOT_LOADED,
  restrictContentAfter: null,
  forceSeek: false,
  initialSeekTime: null,
  sessionId: null,
  sessionSequenceNum: 0,
  sessionEvents: makeImmutableList(),
  sessionClosed: false,
};

export const persistTransform = createTransform(
  inboundState => ({ ...inboundState, sessionEvents: inboundState.sessionEvents.toJS() }),
  outboundState => ({ ...outboundState, sessionEvents: makeImmutableList(outboundState.sessionEvents) }),
  { whitelist: ['video'] }
);

/**
 * Calculates the state changes required for a playerProgress update.
 *
 * If the new suggested time exceeds the restrictContentAfter time, it is adjusted back to restrictContentAfter.
 * Additionally, forceSeek will be set and playerState will be set to PAUSED so that the video freezes at
 * restrictContentAfter.
 * @param state The Redux video state
 * @param suggestedTime The time provided by the action to adjust time to
 * @param forceSeek If the forceSeek flag is requested to be set by an action
 * @returns {Object} An object with states to merge into Redux
 */
function computeTimeAdjustChange(state, suggestedTime, forceSeek = false) {
  const stateChange = {
    playerProgress: suggestedTime,
    forceSeek,
    playerState: state.playerState,
  };
  if (timeIsPastRestricted(state.restrictContentAfter, stateChange.playerProgress)) {
    stateChange.playerProgress = state.restrictContentAfter;
    stateChange.forceSeek = true;
    stateChange.playerState = playerStates.PAUSED;
  }

  stateChange.playerProgress = Math.max(0, Math.min(state.duration, stateChange.playerProgress));
  // No point seeking if the progress is not changed
  stateChange.forceSeek = stateChange.forceSeek && stateChange.playerProgress !== state.playerProgress;
  return stateChange;
}

/**
 * Computes the new player state based on the new state an action provides and the current player progress.
 *
 * If the player is past the restricted time, then the playerState will be forced into a non-playing state (either the
 * old state or playerStates.PAUSED).
 *
 * If the new playing state BUFFERING but the player was not even playing to begin with, the old player state is
 * returned instead.
 *
 * If neither are true, the newPlayerState returned.
 * @param state The entire video Redux state
 * @param newPlayerState The new playerState to be set
 * @returns {playerStates} The new playerState to set into Redux
 */
function computePlayerState(state, newPlayerState) {
  if (timeIsPastRestricted(state.restrictContentAfter, state.playerProgress) && isPlayingState(newPlayerState)) {
    return isPlayingState(state.playerState) ? playerStates.PAUSED : state.playerState;
  }

  if (newPlayerState === playerStates.BUFFERING && !isPlayingState(state.playerState)) {
    return state.playerState;
  }

  return newPlayerState;
}

/**
 * Generates a state transformer function that merges changes into state and produces a new state object.
 *
 * The generated transformer is a pure function and does not modify original state.
 *
 * The forceSeek flag is always set to false by the transformer unless explicitly turned on within changes.
 * @param state The original state object
 * @returns {function(Object): Object} A function that produces the next state object when changes are provided
 */
function generateStateTransformer(state) {
  return changes => ({ ...state, forceSeek: false, ...changes });
}

/**
 * The reducer to transform the video state excluding session data.
 *
 * This reducer changes the video's UI states, such as playback rate, volume, and player progress.
 * @param state The original state object.
 * @param action The action the reducer is to process
 * @return {*} The transformed state.
 */
function videoStateReducer(state = initialState, action) {
  // Only forceSeek if explicitly specified
  const transformState = generateStateTransformer(state);

  switch (action.type) {
    case videoActionTypes.CHANGE_PLAYER_STATE:
      return transformState({ playerState: computePlayerState(state, action.playerState) });
    case videoActionTypes.CHANGE_PLAYER_VOLUME:
      return transformState({ playerVolume: action.playerVolume });
    case videoActionTypes.CHANGE_CAPTIONS_STATE:
      return transformState({ captionsState: action.captionsState });
    case videoActionTypes.CHANGE_PLAYBACK_RATE:
      return transformState({ playbackRate: action.playbackRate });
    case videoActionTypes.UPDATE_PLAYER_PROGRESS:
      return transformState(computeTimeAdjustChange(state, action.playerProgress, action.forceSeek));
    case videoActionTypes.UPDATE_BUFFER_PROGRESS:
      return transformState({ bufferProgress: Math.max(0, Math.min(state.duration, action.bufferProgress)) });
    case videoActionTypes.UPDATE_PLAYER_DURATION:
      return transformState({ duration: action.duration });
    case videoActionTypes.UPDATE_RESTRICTED_TIME:
      return transformState({ restrictContentAfter: action.restrictContentAfter });
    default:
      return state;
  }
}

/**
 * Generates a session event based on the event type.
 *
 * This function produces a base event, recording the player progress and playback rate, as well as assign a sequence
 * number based on the value stored in the state. These parameters can be extended or overwritten with the params
 * argument.
 * @param state The original state object.
 * @param type The event type.
 * @param params The parameters to overwrite or extend the base evnt with.
 * @return {*} The event object to record.
 */
function generateEvent(state, type, params = {}) {
  return {
    sequence_num: state.sessionSequenceNum,
    event_type: type,
    video_time: Math.round(state.playerProgress),
    playback_rate: state.playbackRate,
    event_time: new Date(),
    ...params,
  };
}

/**
 * Handles the session state change for a player state change.
 *
 * This function produces a new state with a new session event included on a player state change. If the player state
 * will not change, or if the new player state does not need recording, the original state is returned.
 * @param state The original state object.
 * @param action The action to process.
 * @return {*} The transformed state object.
 */
function handleSessionChangeState(state, action) {
  let stateChange = null;
  if (state.playerState === action.playerState) {
    return state;
  } if (action.playerState === playerStates.PLAYING) {
    stateChange = 'play';
  } else if (action.playerState === playerStates.PAUSED) {
    stateChange = 'pause';
  } else if (action.playerState === playerStates.BUFFERING && isPlayingState(state.playerState)) {
    stateChange = 'buffer';
  } else if (action.playerState === playerStates.ENDED) {
    stateChange = 'end';
  } else {
    return state;
  }

  return {
    ...state,
    sessionSequenceNum: state.sessionSequenceNum + 1,
    sessionEvents: state.sessionEvents.push(generateEvent(state, stateChange)),
  };
}

/**
 * The reducer to transform the session data.
 *
 * This reducer listens to actions that we want to record and creates a new event in state.sessionEvents. The exception
 * is the REMOVE_EVENTS action, where specified events will be removed.
 * @param state The original state object.
 * @param action The action the reducer is to process
 * @return {*} The transformed state.
 */
function videoSessionReducer(state = initialState, action) {
  if (!state.sessionId) {
    return state;
  }
  const events = state.sessionEvents;
  switch (action.type) {
    case videoActionTypes.CHANGE_PLAYBACK_RATE:
      return {
        ...state,
        sessionSequenceNum: state.sessionSequenceNum + 1,
        sessionEvents: events.push(generateEvent(state, 'speed_change', { playback_rate: action.playbackRate })),
      };
    case videoActionTypes.CHANGE_PLAYER_STATE:
      return handleSessionChangeState(state, action);
    case videoActionTypes.SEEK_START:
      return {
        ...state,
        sessionSequenceNum: state.sessionSequenceNum + 1,
        sessionEvents: events.push(generateEvent(state, 'seek_start')),
      };
    case videoActionTypes.SEEK_END:
      return {
        ...state,
        sessionSequenceNum: state.sessionSequenceNum + 1,
        sessionEvents: events.push(generateEvent(state, 'seek_end')),
      };
    case sessionActionTypes.REMOVE_EVENTS:
      return {
        ...state,
        sessionEvents: events.filterNot(event => action.sequenceNums.has(event.sequence_num)),
        sessionClosed: action.sessionClosed,
      };
    default:
      return state;
  }
}

export default function (state = initialState, action) {
  return videoStateReducer(videoSessionReducer(state, action), action);
}


text:
import * as React from 'react'
import {Container} from '../../../components'

export default class ContainerChildren extends React.Component {
  render () {
    return (
      <div>
        <Container style={{background: '#eee', height: '50px'}}/>
      </div>
    )
  }
}


text:
IISLog
======

IIS Log Analysis


text:
package album

import (
	"context"
	validation "github.com/go-ozzo/ozzo-validation/v3"
	"github.com/qiangxue/go-restful-api/internal/entity"
	"github.com/qiangxue/go-restful-api/pkg/log"
	"time"
)

// Service encapsulates usecase logic for albums.
type Service interface {
	Get(ctx context.Context, id string) (Album, error)
	Query(ctx context.Context, offset, limit int) ([]Album, error)
	Count(ctx context.Context) (int, error)
	Create(ctx context.Context, input CreateAlbumRequest) (Album, error)
	Update(ctx context.Context, id string, input UpdateAlbumRequest) (Album, error)
	Delete(ctx context.Context, id string) (Album, error)
}

// Album represents the data about an album.
type Album struct {
	entity.Album
}

// CreateAlbumRequest represents an album creation request.
type CreateAlbumRequest struct {
	Name string `json:"name"`
}

// Validate validates the CreateAlbumRequest fields.
func (m CreateAlbumRequest) Validate() error {
	return validation.ValidateStruct(&m,
		validation.Field(&m.Name, validation.Required, validation.Length(0, 128)),
	)
}

// UpdateAlbumRequest represents an album update request.
type UpdateAlbumRequest struct {
	Name string `json:"name"`
}

// Validate validates the CreateAlbumRequest fields.
func (m UpdateAlbumRequest) Validate() error {
	return validation.ValidateStruct(&m,
		validation.Field(&m.Name, validation.Required, validation.Length(0, 128)),
	)
}

type service struct {
	repo   Repository
	logger log.Logger
}

// NewService creates a new album service.
func NewService(repo Repository, logger log.Logger) Service {
	return service{repo, logger}
}

// Get returns the album with the specified the album ID.
func (s service) Get(ctx context.Context, id string) (Album, error) {
	album, err := s.repo.Get(ctx, id)
	if err != nil {
		return Album{}, err
	}
	return Album{album}, nil
}

// Create creates a new album.
func (s service) Create(ctx context.Context, req CreateAlbumRequest) (Album, error) {
	if err := req.Validate(); err != nil {
		return Album{}, err
	}
	id := entity.GenerateID()
	now := time.Now()
	err := s.repo.Create(ctx, entity.Album{
		ID:        id,
		Name:      req.Name,
		CreatedAt: now,
		UpdatedAt: now,
	})
	if err != nil {
		return Album{}, err
	}
	return s.Get(ctx, id)
}

// Update updates the album with the specified ID.
func (s service) Update(ctx context.Context, id string, req UpdateAlbumRequest) (Album, error) {
	if err := req.Validate(); err != nil {
		return Album{}, err
	}

	album, err := s.Get(ctx, id)
	if err != nil {
		return album, err
	}
	album.Name = req.Name
	album.UpdatedAt = time.Now()

	if err := s.repo.Update(ctx, album.Album); err != nil {
		return album, err
	}
	return album, nil
}

// Delete deletes the album with the specified ID.
func (s service) Delete(ctx context.Context, id string) (Album, error) {
	album, err := s.Get(ctx, id)
	if err != nil {
		return Album{}, err
	}
	if err = s.repo.Delete(ctx, id); err != nil {
		return Album{}, err
	}
	return album, nil
}

// Count returns the number of albums.
func (s service) Count(ctx context.Context) (int, error) {
	return s.repo.Count(ctx)
}

// Query returns the albums with the specified offset and limit.
func (s service) Query(ctx context.Context, offset, limit int) ([]Album, error) {
	items, err := s.repo.Query(ctx, offset, limit)
	if err != nil {
		return nil, err
	}
	result := []Album{}
	for _, item := range items {
		result = append(result, Album{item})
	}
	return result, nil
}


text:
"""
pghoard - unit test setup

Copyright (c) 2015 Ohmu Ltd
See LICENSE for details
"""
# pylint: disable=attribute-defined-outside-init
from pghoard.config import find_pg_binary, set_and_check_config_defaults
from pghoard.rohmu import compat
from shutil import rmtree
from tempfile import mkdtemp
import logging
import os
import psycopg2.extras

CONSTANT_TEST_RSA_PUBLIC_KEY = """\
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDQ9yu7rNmu0GFMYeQq9Jo2B3d9
hv5t4a+54TbbxpJlks8T27ipgsaIjqiQP7+uXNfU6UCzGFEHs9R5OELtO3Hq0Dn+
JGdxJlJ1prxVkvjCICCpiOkhc2ytmn3PWRuVf2VyeAddslEWHuXhZPptvIr593kF
lWN+9KPe+5bXS8of+wIDAQAB
-----END PUBLIC KEY-----"""

CONSTANT_TEST_RSA_PRIVATE_KEY = """\
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAND3K7us2a7QYUxh
5Cr0mjYHd32G/m3hr7nhNtvGkmWSzxPbuKmCxoiOqJA/v65c19TpQLMYUQez1Hk4
Qu07cerQOf4kZ3EmUnWmvFWS+MIgIKmI6SFzbK2afc9ZG5V/ZXJ4B12yURYe5eFk
+m28ivn3eQWVY370o977ltdLyh/7AgMBAAECgYEAkuAobRFhL+5ndTiZF1g1zCQT
aLepvbITwaL63B8GZz55LowRj5PL18/tyvYD1JqNWalZQIim67MKdOmGoRhXSF22
gUc6/SeqD27/9rsj8I+j0TrzLdTZwn88oX/gtndNutZuryCC/7KbJ8j18Jjn5qf9
ZboRKbEc7udxOb+RcYECQQD/ZLkxIvMSj0TxPUJcW4MTEsdeJHCSnQAhreIf2omi
hf4YwmuU3qnFA3ROje9jJe3LNtc0TK1kvAqfZwdpqyAdAkEA0XY4P1CPqycYvTxa
dxxWJnYA8K3g8Gs/Eo8wYKIciP+K70Q0GRP9Qlluk4vrA/wJJnTKCUl7YuAX6jDf
WdV09wJALGHXoQde0IHfTEEGEEDC9YSU6vJQMdpg1HmAS2LR+lFox+q5gWR0gk1I
YAJgcI191ovQOEF+/HuFKRBhhGZ9rQJAXOt13liNs15/sgshEq/mY997YUmxfNYG
v+P3kRa5U+kRKD14YxukARgNXrT2R+k54e5zZhVMADvrP//4RTDVVwJBAN5TV9p1
UPZXbydO8vZgPuo001KoEd9N3inq/yNcsHoF/h23Sdt/rcdfLMpCWuIYs/JAqE5K
nkMAHqg9PS372Cs=
-----END PRIVATE KEY-----"""

class PGHoardTestCase:
    @classmethod
    def setup_class(cls):
        cls.log = logging.getLogger(cls.__name__)

    def config_template(self, override=None):
        # NOTE: we set pg_receivexlog_path and pg_basebackup_path per site and globally mostly to verify that
        # it works, the config keys are deprecated and will be removed in a future release at which point we'll
        # switch to using pg_bin_directory config.
        bindir, ver = find_pg_binary("")

        if hasattr(psycopg2.extras, "PhysicalReplicationConnection"):
            active_backup_mode = "walreceiver"
        else:
            active_backup_mode = "pg_receivexlog"

        # Instantiate a fake PG data directory
        pg_data_directory = os.path.join(str(self.temp_dir), "PG_DATA_DIRECTORY")
        os.makedirs(pg_data_directory)
        open(os.path.join(pg_data_directory, "PG_VERSION"), "w").write(ver)

        config = {
            "alert_file_dir": os.path.join(str(self.temp_dir), "alerts"),
            "backup_location": os.path.join(str(self.temp_dir), "backupspool"),
            "backup_sites": {
                self.test_site: {
                    "active_backup_mode": active_backup_mode,
                    "object_storage": {
                        "storage_type": "local",
                        "directory": os.path.join(self.temp_dir, "backups"),
                    },
                    "pg_data_directory": pg_data_directory,
                    "pg_receivexlog_path": os.path.join(bindir, "pg_receivexlog"),
                },
            },
            "json_state_file_path": os.path.join(self.temp_dir, "state.json"),
            "pg_basebackup_path": os.path.join(bindir, "pg_basebackup"),
        }
        if ver == "10":
            config["backup_sites"][self.test_site]["pg_receivexlog_path"] = os.path.join(bindir, "pg_receivewal")
        if override:
            all_site_overrides = override.pop("backup_sites", None)
            for site_name, site_override in (all_site_overrides or {}).items():
                if site_name in config["backup_sites"]:
                    config["backup_sites"][site_name].update(site_override)
                else:
                    config["backup_sites"][site_name] = site_override
            config.update(override)

        compat.makedirs(config["alert_file_dir"], exist_ok=True)
        return set_and_check_config_defaults(config)

    def setup_method(self, method):
        self.temp_dir = mkdtemp(prefix=self.__class__.__name__)
        self.test_site = "site_{}".format(method.__name__)

    def teardown_method(self, method):  # pylint: disable=unused-argument
        rmtree(self.temp_dir)


text:
using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.ServiceProcess;
using System.Threading;
using log4net;

namespace SIPSorcery.SIPRegistrar {
    public class Service : System.ServiceProcess.ServiceBase {
        public const string DEFAULT_STARTUPERRORLOG_PATH = @"c:\temp\sipregistrar.strarterror.log";
        public const string DEFAULT_SHUTDOWNERRORLOG_PATH = @"c:\temp\sipregistrar.stoperror.log";

        private SIPRegistrarDaemon m_daemon;

        public Service(SIPRegistrarDaemon daemon) {
            this.CanShutdown = true;
            this.CanStop = true;
            m_daemon = daemon;
        }

        protected override void Dispose(bool disposing) {
            base.Dispose(disposing);
        }

        protected override void OnStart(string[] args) {
            try {
                Thread daemonThread = new Thread(m_daemon.Start);
                daemonThread.Start();
            }
            catch (Exception excp) {
                StreamWriter errorLog = new StreamWriter(DEFAULT_STARTUPERRORLOG_PATH, true);
                errorLog.WriteLine(DateTime.Now.ToString("dd MMM yyyy HH:mm:ss") + " Exception Starting Service. " + excp.Message);
                errorLog.Close();
                throw excp;
            }
        }

        protected override void OnStop() {
            try {
                m_daemon.Stop();
            }
            catch (Exception excp) {
                StreamWriter errorLog = new StreamWriter(DEFAULT_SHUTDOWNERRORLOG_PATH, true);
                errorLog.WriteLine(DateTime.Now.ToString("dd MMM yyyy HH:mm:ss") + " Exception Stopping Service. " + excp.Message);
                errorLog.Close();
            }
        }
    }
}


text:
<?php
/**
 * Date: 23.01.14
 * Time: 1:27
 */

namespace mihaildev\elfinder;

use Yii;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\widgets\InputWidget;

class InputFile extends InputWidget{
	public $language;

	public $filter;

	public $buttonTag = 'button';
	public $buttonName = 'Browse';
	public $buttonOptions = [];

	protected $_managerOptions;

	public $width = 'auto';
	public $height = 'auto';

	public $template = '{input}{button}';

	public $controller = 'elfinder';

	public $path; // work with PathController

	public $multiple;

	public function init()
	{
		parent::init();

		if(empty($this->language))
			$this->language = ElFinder::getSupportedLanguage(Yii::$app->language);

		if(empty($this->buttonOptions['id']))
			$this->buttonOptions['id'] = $this->options['id'].'_button';

		$this->buttonOptions['type'] = 'button';

		$managerOptions = [];
		if(!empty($this->filter))
			$managerOptions['filter'] = $this->filter;

		$managerOptions['callback'] = $this->options['id'];

		if(!empty($this->language))
			$managerOptions['lang'] = $this->language;

		if (!empty($this->multiple))
			$managerOptions['multiple'] = $this->multiple;

		if(!empty($this->path))
			$managerOptions['path'] = $this->path;

		$this->_managerOptions['url'] = ElFinder::getManagerUrl($this->controller, $managerOptions);
		$this->_managerOptions['width'] = $this->width;
		$this->_managerOptions['height'] = $this->height;
		$this->_managerOptions['id'] = $this->options['id'];
	}

	/**
	 * Runs the widget.
	 */
	public function run()
	{
		if ($this->hasModel()) {
			$replace['{input}'] = Html::activeTextInput($this->model, $this->attribute, $this->options);
		} else {
			$replace['{input}'] = Html::textInput($this->name, $this->value, $this->options);
		}

		$replace['{button}'] = Html::tag($this->buttonTag,$this->buttonName, $this->buttonOptions);

		echo strtr($this->template, $replace);

		AssetsCallBack::register($this->getView());

		if (!empty($this->multiple))
			$this->getView()->registerJs("mihaildev.elFinder.register(" . Json::encode($this->options['id']) . ", function(files, id){ var _f = []; for (var i in files) { _f.push(files[i].url); } \$('#' + id).val(_f.join(', ')).trigger('change', [files, id]); return true;}); $(document).on('click','#" . $this->buttonOptions['id'] . "', function(){mihaildev.elFinder.openManager(" . Json::encode($this->_managerOptions) . ");});");
		else
			$this->getView()->registerJs("mihaildev.elFinder.register(" . Json::encode($this->options['id']) . ", function(file, id){ \$('#' + id).val(file.url).trigger('change', [file, id]);; return true;}); $(document).on('click', '#" . $this->buttonOptions['id'] . "', function(){mihaildev.elFinder.openManager(" . Json::encode($this->_managerOptions) . ");});");
	}
}


text:
from ginga.gtkw import ColorBar
from ginga.gtkw import GtkHelp, gtksel
from ginga.misc import Bunch
from ginga.misc.plugins import CatalogsBase

import gobject
import gtk

class Catalogs(CatalogsBase.CatalogsBase):

    def __init__(self, fv, fitsimage):
        super(Catalogs, self).__init__(fv, fitsimage)

    def build_gui(self, container, future=None):
        vbox1 = gtk.VBox()

        self.msgFont = self.fv.getFont('sansFont', 12)
        tw = gtk.TextView()
        tw.set_wrap_mode(gtk.WRAP_WORD)
        tw.set_left_margin(4)
        tw.set_right_margin(4)
        tw.set_editable(False)
        tw.set_left_margin(4)
        tw.set_right_margin(4)
        tw.modify_font(self.msgFont)
        self.tw = tw

        fr = gtk.Frame(label=" Instructions ")
        fr.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
        fr.set_label_align(0.1, 0.5)
        fr.add(tw)
        vbox1.pack_start(fr, padding=4, fill=True, expand=False)

        nb = gtk.Notebook()
        #nb.set_group_id(group)
        #nb.connect("create-window", self.detach_page, group)
        nb.set_tab_pos(gtk.POS_BOTTOM)
        nb.set_scrollable(True)
        nb.set_show_tabs(True)
        nb.set_show_border(False)
        vbox1.pack_start(nb, padding=4, fill=True, expand=True)

        vbox0 = gtk.VBox()
        hbox = gtk.HBox(spacing=4)

        vbox = gtk.VBox()
        fr = gtk.Frame(label=" Image Server ")
        fr.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        fr.set_label_align(0.5, 0.5)
        fr.add(vbox)

        captions = (('Server', 'xlabel'),
                    ('@Server', 'combobox'),
                    ('Use DSS channel', 'checkbutton'),
                    ('Get Image', 'button'))
        w, self.w = GtkHelp.build_info(captions)
        self.w.nb = nb
        self.w.get_image.connect('clicked', lambda w: self.getimage_cb())
        self.w.use_dss_channel.set_active(self.use_dss_channel)
        self.w.use_dss_channel.connect('toggled', self.use_dss_channel_cb)

        vbox.pack_start(w, padding=4, fill=True, expand=False)

        self.w.img_params = gtk.VBox()
        vbox.pack_start(self.w.img_params, padding=4, fill=True, expand=False)

        combobox = self.w.server
        index = 0
        self.image_server_options = self.fv.imgsrv.getServerNames(kind='image')
        for name in self.image_server_options:
            combobox.insert_text(index, name)
            index += 1
        index = 0
        combobox.set_active(index)
        combobox.sconnect('changed', self.setup_params_image)
        if len(self.image_server_options) > 0:
            self.setup_params_image(combobox, redo=False)

        hbox.pack_start(fr, fill=True, expand=True)

        vbox = gtk.VBox()
        fr = gtk.Frame(label=" Catalog Server ")
        fr.set_shadow_type(gtk.SHADOW_ETCHED_IN)
        fr.set_label_align(0.5, 0.5)
        fr.add(vbox)

        captions = (('Server', 'xlabel'),
                    ('@Server', 'combobox'),
                    ('Limit stars to area', 'checkbutton'),
                    ('Search', 'button'))
        w, self.w2 = GtkHelp.build_info(captions)
        self.w2.search.connect('clicked', lambda w: self.getcatalog_cb())
        self.w2.limit_stars_to_area.set_active(self.limit_stars_to_area)
        self.w2.limit_stars_to_area.connect('toggled', self.limit_area_cb)

        vbox.pack_start(w, padding=4, fill=True, expand=False)

        self.w2.cat_params = gtk.VBox()
        vbox.pack_start(self.w2.cat_params, padding=4, fill=True, expand=False)

        combobox = self.w2.server
        index = 0
        self.catalog_server_options = self.fv.imgsrv.getServerNames(kind='catalog')
        for name in self.catalog_server_options:
            combobox.insert_text(index, name)
            index += 1
        index = 0
        combobox.set_active(index)
        combobox.sconnect('changed', self.setup_params_catalog)
        if len(self.catalog_server_options) > 0:
            self.setup_params_catalog(combobox, redo=False)

        hbox.pack_start(fr, fill=True, expand=True)
        vbox0.pack_start(hbox, fill=True, expand=True)

        btns = gtk.HButtonBox()
        btns.set_layout(gtk.BUTTONBOX_START)
        btns.set_spacing(4)

        btn = gtk.RadioButton(None, "Rectangle")
        if self.drawtype == 'rectangle':
            btn.set_active(True)
        btn.connect('toggled', self.set_drawtype_cb, 'rectangle')
        btns.add(btn)
        btn = gtk.RadioButton(btn, "Circle")
        if self.drawtype == 'circle':
            btn.set_active(True)
        btn.connect('toggled', self.set_drawtype_cb, 'circle')
        btns.add(btn)
        btn = gtk.Button("Entire image")
        btn.connect('clicked', lambda w: self.setfromimage())
        btns.add(btn)
        vbox0.pack_start(btns, padding=4, fill=True, expand=False)

        sw = gtk.ScrolledWindow()
        sw.set_border_width(2)
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        sw.add_with_viewport(vbox0)

        lbl = gtk.Label("Params")
        self.w.params = sw
        nb.append_page(sw, lbl)

        vbox = gtk.VBox()
        self.table = CatalogListing(self.logger, vbox)

        hbox = gtk.HBox()
        scale = gtk.HScrollbar()
        adj = scale.get_adjustment()
        #adj.configure(0, 0, 0, 1, 10, self.plot_limit)
        adj.configure(0, 0, 0, 1, 10, 0)
        #scale.set_size_request(200, -1)
        scale.set_tooltip_text("Choose subset of stars plotted")
        if not gtksel.have_gtk3:
            #scale.set_update_policy(gtk.UPDATE_DELAYED)
            scale.set_update_policy(gtk.UPDATE_CONTINUOUS)
        self.w.plotgrp = scale
        scale.connect('value-changed', self.plot_pct_cb)
        hbox.pack_start(scale, padding=2, fill=True, expand=True)

        sb = GtkHelp.SpinButton()
        adj = sb.get_adjustment()
        adj.configure(self.plot_limit, 10, self.plot_max, 10, 100, 0)
        self.w.plotnum = sb
        sb.set_tooltip_text("Adjust size of subset of stars plotted")
        sb.connect('value-changed', self.plot_limit_cb)
        hbox.pack_start(sb, padding=2, fill=False, expand=False)
        vbox.pack_start(hbox, padding=0, fill=False, expand=False)

        #vbox1.pack_start(vbox, padding=4, fill=True, expand=True)
        lbl = gtk.Label("Listing")
        self.w.listing = vbox
        nb.append_page(vbox, lbl)

        btns = gtk.HButtonBox()
        btns.set_layout(gtk.BUTTONBOX_START)
        btns.set_spacing(3)
        #btns.set_child_size(15, -1)
        self.w.buttons = btns

        btn = gtk.Button("Close")
        btn.connect('clicked', lambda w: self.close())
        btns.add(btn)

        if future:
            btn = gtk.Button('Ok')
            btn.connect('clicked', lambda w: self.ok())
            btns.add(btn)
            btn = gtk.Button('Cancel')
            btn.connect('clicked', lambda w: self.cancel())
            btns.add(btn)
        vbox1.pack_start(btns, padding=4, fill=True, expand=False)

        vbox1.show_all()
        cw = container.get_widget()
        cw.pack_start(vbox1, padding=0, fill=True, expand=True)

    def limit_area_cb(self, w):
        self.limit_stars_to_area = w.get_active()
        return True

    def use_dss_channel_cb(self, w):
        self.use_dss_channel = w.get_active()
        return True

    def plot_pct_cb(self, rng):
        val = rng.get_value()
        self.plot_start = int(val)
        self.replot_stars()
        return True

    def _update_plotscroll(self):
        num_stars = len(self.starlist)
        if num_stars > 0:
            adj = self.w.plotgrp.get_adjustment()
            page_size = self.plot_limit
            self.plot_start = min(self.plot_start, num_stars-1)
            adj.configure(self.plot_start, 0, num_stars, 1,
                          page_size, 0)

        self.replot_stars()

    def plot_limit_cb(self, rng):
        val = rng.get_value()
        self.plot_limit = int(val)
        self._update_plotscroll()
        return True

    def set_message(self, msg):
        buf = self.tw.get_buffer()
        buf.set_text(msg)
        self.tw.modify_font(self.msgFont)

    def _raise_tab(self, w):
        num = self.w.nb.page_num(w)
        self.w.nb.set_current_page(num)

    def _get_cbidx(self, w):
        return w.get_active()

    def _setup_params(self, obj, container):
        params = obj.getParams()
        captions = []
        paramList = sorted(params.values(), key=lambda b: b.order)
        for bnch in paramList:
            text = bnch.name
            if 'label' in bnch:
                text = bnch.label
            #captions.append((text, 'entry'))
            captions.append((text, 'xlabel', '@'+bnch.name, 'entry'))

        # TODO: put RA/DEC first, and other stuff not in random orders
        w, b = GtkHelp.build_info(captions)

        # remove old widgets
        children = container.get_children()
        for child in children:
            container.remove(child)

        # add new widgets
        container.pack_start(w, fill=False, expand=False)
        container.show_all()
        return b

    def setup_params_image(self, combobox, redo=True):
        index = combobox.get_active()
        key = self.image_server_options[index]

        # Get the parameter list and adjust the widget
        obj = self.fv.imgsrv.getImageServer(key)
        b = self._setup_params(obj, self.w.img_params)
        self.image_server_params = b

        if redo:
            self.redo()

    def setup_params_catalog(self, combobox, redo=True):
        index = combobox.get_active()
        key = self.catalog_server_options[index]

        # Get the parameter list and adjust the widget
        obj = self.fv.imgsrv.getCatalogServer(key)
        b = self._setup_params(obj, self.w2.cat_params)
        self.catalog_server_params = b

        if redo:
            self.redo()

    def instructions(self):
        self.set_message("""Draw a rectangle or circle to enclose search area.""")

    def _update_widgets(self, d):
        for bnch in (self.image_server_params,
                     self.catalog_server_params):
            if bnch is not None:
                for key in bnch.keys():
                    if key in d:
                        bnch[key].set_text(str(d[key]))

    def get_params(self, bnch):
        params = {}
        for key in bnch.keys():
            params[key] = bnch[key].get_text()
        return params

    def set_drawtype_cb(self, w, drawtype):
        tf = w.get_active()
        if tf:
            self.drawtype = drawtype
            self.canvas.set_drawtype(self.drawtype, color='cyan',
                                     linestyle='dash')

    def __str__(self):
        return 'catalogs'

class CatalogListing(CatalogsBase.CatalogListingBase):

    def _build_gui(self, container):
        self.mframe = container

        vbox = gtk.VBox()

        sw = gtk.ScrolledWindow()
        sw.set_border_width(2)
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
        self.sw = sw

        vbox.pack_start(sw, fill=True, expand=True)

        self.cbar = ColorBar.ColorBar(self.logger)
        self.cbar.set_cmap(self.cmap)
        self.cbar.set_imap(self.imap)

        vbox.pack_start(self.cbar, padding=4, fill=True, expand=False)

        btns = gtk.HBox()
        btns.set_spacing(2)

        combobox = GtkHelp.combo_box_new_text()
        options = []
        index = 0
        for name in self.cmap_names:
            options.append(name)
            combobox.insert_text(index, name)
            index += 1
        cmap_name = self.magcmap
        try:
            index = self.cmap_names.index(cmap_name)
        except Exception:
            index = self.cmap_names.index('ramp')
        combobox.set_active(index)
        combobox.sconnect('changed', self.set_cmap_cb)
        self.btn['cmap'] = combobox
        btns.add(combobox)

        combobox = GtkHelp.combo_box_new_text()
        options = []
        index = 0
        for name in self.imap_names:
            options.append(name)
            combobox.insert_text(index, name)
            index += 1
        imap_name = self.magimap
        try:
            index = self.imap_names.index(imap_name)
        except Exception:
            index = self.imap_names.index('ramp')
        combobox.set_active(index)
        combobox.sconnect('changed', self.set_imap_cb)
        self.btn['imap'] = combobox
        btns.add(combobox)

        vbox.pack_start(btns, padding=4, fill=True, expand=False)

        btns = gtk.HBox()
        btns.set_spacing(2)

        for name in ('Plot', 'Clear', #'Close'
                     ):
            btn = gtk.Button(name)
            btns.add(btn)
            self.btn[name.lower()] = btn

        combobox = GtkHelp.combo_box_new_text()
        options = []
        index = 0
        for name in ['Mag']:
            options.append(name)
            combobox.insert_text(index, name)
            index += 1
        combobox.set_active(0)
        combobox.sconnect('changed', self.set_field_cb)
        self.btn['field'] = combobox
        btns.add(combobox)

        self.btn.plot.connect('clicked', lambda w: self.replot_stars())
        self.btn.clear.connect('clicked', lambda w: self.clear())
        #self.btn.close.connect('clicked', lambda w: self.close())

        vbox.pack_start(btns, padding=4, fill=True, expand=False)
        vbox.show_all()

        # create the table
        info = Bunch.Bunch(columns=self.columns, color='Mag')
        self.build_table(info)

        self.mframe.pack_start(vbox, expand=True, fill=True)
        self.mframe.show_all()

    def build_table(self, info):
        columns = info.columns
        self.columns = columns

        # remove old treeviews, if any
        children = self.sw.get_children()
        for child in children:
            self.sw.remove(child)

        # create the TreeView
        treeview = gtk.TreeView()
        self.treeview = treeview

        self.cell_sort_funcs = []
        for kwd, key in columns:
            self.cell_sort_funcs.append(self._mksrtfnN(key))

        # Set up the field selector
        fidx = 0
        combobox = self.btn['field']
        try:
            combobox.clear()
        except Exception as e:
            self.logger.error("Error clearing field selector: %s" % (
                str(e)))

        # create the TreeViewColumns to display the data
        tvcolumn = [None] * len(columns)
        for n in range(0, len(columns)):
            cell = gtk.CellRendererText()
            cell.set_padding(2, 0)
            header, kwd = columns[n]
            tvc = gtk.TreeViewColumn(header, cell)
            tvc.set_spacing(4)
            tvc.set_resizable(True)
            tvc.connect('clicked', self.sort_cb, n)
            tvc.set_clickable(True)
            tvcolumn[n] = tvc
            fn_data = self._mkcolfnN(kwd)
            tvcolumn[n].set_cell_data_func(cell, fn_data)
            treeview.append_column(tvcolumn[n])

            combobox.insert_text(n, header)
            if header == info.color:
                fidx = n

        combobox.set_active(fidx)

        self.sw.add(treeview)
        self.treeview.connect('cursor-changed', self.select_star_cb)
        self.sw.show_all()

        fieldname = self.columns[fidx][1]
        self.mag_field = fieldname

    def _mkcolfnN(self, kwd):
        def fn(*args):
            column, cell, model, iter = args[:4]
            bnch = model.get_value(iter, 0)
            cell.set_property('text', bnch[kwd])
        return fn

    def sort_cb(self, column, idx):
        treeview = column.get_tree_view()
        model = treeview.get_model()
        model.set_sort_column_id(idx, gtk.SORT_ASCENDING)
        fn = self.cell_sort_funcs[idx]
        model.set_sort_func(idx, fn)
        self.replot_stars()
        return True

    def _mksrtfnN(self, key):
        def fn(*args):
            model, iter1, iter2 = args[:3]
            bnch1 = model.get_value(iter1, 0)
            bnch2 = model.get_value(iter2, 0)
            val1, val2 = bnch1[key], bnch2[key]
            if isinstance(val1, str):
                val1 = val1.lower()
                val2 = val2.lower()
            res = cmp(val1, val2)
            return res
        return fn

    def show_table(self, catalog, info, starlist):
        self.starlist = starlist
        self.catalog = catalog
        # info is ignored, for now
        #self.info = info
        self.selected = []

        # rebuild the table
        self.build_table(info)

        # Update the starlist info
        listmodel = gtk.ListStore(object)
        for star in starlist:
            # TODO: find mag range
            listmodel.append([star])

        self.treeview.set_model(listmodel)

    def _get_star_path(self, star):
        model = self.treeview.get_model()
        # find path containing this star in the treeview
        # TODO: is there a more efficient way to do this?
        for path in range(len(self.starlist)):
            iter = model.get_iter(path)
            cstar = model.get_value(iter, 0)
            if cstar == star:
                return path
        return None

    def get_subset_from_starlist(self, fromidx, toidx):
        model = self.treeview.get_model()
        res = []
        for idx in range(fromidx, toidx):
            iter = model.get_iter(idx)
            star = model.get_value(iter, 0)
            res.append(star)
        return res

    def _select_tv(self, star, fromtable=False):
        treeselection = self.treeview.get_selection()
        star_idx = self._get_star_path(star)
        if star_idx is None:
            return
        treeselection.select_path(star_idx)
        if not fromtable:
            # If the user did not select the star from the table, scroll
            # the table so they can see the selection
            self.treeview.scroll_to_cell(star_idx, use_align=True,
                                         row_align=0.5)

    def _unselect_tv(self, star, fromtable=False):
        treeselection = self.treeview.get_selection()
        star_idx = self._get_star_path(star)
        if star_idx is None:
            return
        treeselection.unselect_path(star_idx)

    def select_star_cb(self, treeview):
        """This method is called when the user selects a star from the table.
        """
        path, column = treeview.get_cursor()
        model = treeview.get_model()
        iter = model.get_iter(path)
        star = model.get_value(iter, 0)
        self.logger.debug("selected star: %s" % (str(star)))
        self.mark_selection(star, fromtable=True)
        return True

    def set_cmap_cb(self, w):
        index = w.get_active()
        name = self.cmap_names[index]
        self.set_cmap_byname(name)

    def set_imap_cb(self, w):
        index = w.get_active()
        name = self.imap_names[index]
        self.set_imap_byname(name)

    def set_field_cb(self, w):
        index = w.get_active()
        fieldname = self.columns[index][1]
        self.set_field(fieldname)

# END


text:
package com.epam.ta.reportportal.ws.converter.resource.handler.attribute.launch;

import com.epam.ta.reportportal.entity.ItemAttribute;
import com.epam.ta.reportportal.ws.converter.resource.handler.attribute.ResourceAttributeHandler;
import com.epam.ta.reportportal.ws.model.launch.LaunchResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;

/**
 * @author Ivan Budayeu
 */
public class LaunchResourceAttributeLogger implements ResourceAttributeHandler<LaunchResource> {

	private static final Logger LOGGER = LoggerFactory.getLogger(LaunchResourceAttributeLogger.class);

	private final String baseMessage;

	public LaunchResourceAttributeLogger(String baseMessage) {
		this.baseMessage = baseMessage;
	}

	@Override
	public void handle(LaunchResource resource, Collection<ItemAttribute> attributes) {
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug(baseMessage + " Launch - {}, attributes - {}", resource.getLaunchId(), attributes);
		}
	}
}


text:
import unittest2
import uuid

from st2common.services import coordination
import st2tests.config as tests_config

class SynchronizationTest(unittest2.TestCase):
    coordinator = None

    @classmethod
    def setUpClass(cls):
        super(SynchronizationTest, cls).setUpClass()
        tests_config.parse_args()
        cls.coordinator = coordination.get_coordinator()

    @classmethod
    def tearDownClass(cls):
        coordination.coordinator_teardown(cls.coordinator)
        super(SynchronizationTest, cls).tearDownClass()

    def test_lock(self):
        name = uuid.uuid4().hex

        # Acquire lock.
        lock = self.coordinator.get_lock(name)
        self.assertTrue(lock.acquire())

        # Release lock.
        lock.release()

    def test_multiple_acquire(self):
        name = uuid.uuid4().hex

        # Acquire lock.
        lock1 = self.coordinator.get_lock(name)
        self.assertTrue(lock1.acquire())

        # Error is expected if trying to acquire lock again.
        lock2 = self.coordinator.get_lock(name)
        self.assertFalse(lock2.acquire(blocking=False))

        # Release from the first lock instance.
        lock1.release()

        # Acquire the lock again from the second lock instance.
        self.assertTrue(lock2.acquire())

        # Release from the second lock instance.
        lock2.release()

    def test_lock_expiry_on_session_close(self):
        name = uuid.uuid4().hex

        # Acquire lock.
        lock1 = self.coordinator.get_lock(name)
        self.assertTrue(lock1.acquire())

        # Error is expected if trying to acquire lock again.
        lock2 = self.coordinator.get_lock(name)
        self.assertFalse(lock2.acquire(blocking=False))

        # Recycle the session.
        self.coordinator.stop()
        self.coordinator.start()

        # Acquire lock.
        lock3 = self.coordinator.get_lock(name)
        self.assertTrue(lock3.acquire())
        lock3.release()


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "source".
 *
 * @property integer $id
 * @property integer $id_product
 * @property integer $id_engine
 * @property string  $id_src_product
 *
 * @property Price[]  $prices
 * @property Quantity $quantity
 * @property Engine   $engine
 * @property Product  $product
 */
class Source extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'source';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_product', 'id_engine', 'id_src_product'], 'required'],
            [['id_product', 'id_engine'], 'integer'],
            [['id_src_product'], 'string', 'max' => 128]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'id_product' => 'Id Product',
            'id_engine' => 'Id Engine',
            'id_src_product' => 'Id Src Product',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPrices()
    {
        return $this->hasMany(Price::className(), ['id_source' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getQuantity()
    {
        return $this->hasOne(Quantity::className(), ['id_source' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEngine()
    {
        return $this->hasOne(Engine::className(), ['id' => 'id_engine']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProduct()
    {
        return $this->hasOne(Product::className(), ['id' => 'id_product']);
    }

    /**
     * @inheritdoc
     * @return SourceQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new SourceQuery(get_called_class());
    }
}


text:
package me.alexrs.recyclerviewrenderers.items;

import me.alexrs.recyclerviewrenderers.demo.R;
import me.alexrs.recyclerviewrenderers.interfaces.Renderable;

/**
 * @author Alejandro Rodriguez <https://github.com/Alexrs95>
 */
public class ItemBender implements Renderable {

    private String title;

    private String summary;

    public ItemBender(String title, String summary) {
        this.title = title;
        this.summary = summary;
    }

    public String getTitle() {
        return title;
    }

    public String getSummary() {
        return summary;
    }

    @Override
    public int getRenderableId() {
        return R.layout.item_bender;
    }
}


text:
<query xmlns="http://labkey.org/data/xml/query">
    <metadata>
        <tables xmlns="http://labkey.org/data/xml">
            <table tableName="studyDataDateOnly" tableDbType="TABLE">
                <!--<tableUrl>/query/detailsQueryRow.view?schemaName=study&query.queryName=alerts&lsid=${lsid}</tableUrl>-->
                <columns>
                    <column columnName="lsid">
                        <isHidden>true</isHidden>
                        <isKeyField>true</isKeyField>
                    </column>
                </columns>
            </table>
        </tables>
    </metadata>
</query>