text:
package com.espen.ws.model;

import java.util.Collection;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.Digits;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

@Entity
@Table(name = "users")
public class User implements UserDetails {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@Id
	@NotNull
	@Size(min = 5, max = 80)
	private String username;

	@NotNull
	@Size(min = 5, max = 80)
	@Column(name = "last_name")
	private String lastname;

	@NotNull
	@Size(min = 5, max = 80)
	@Column(name = "first_name")
	private String firstname;

	@NotNull
	@Size(min = 5, max = 100)
	private String password;

	@NotNull
	@Size(min = 5, max = 100)
	@Email
	private String email;

	private String authority;

	@NotNull
	@Digits(integer = 20, fraction = 0)
	private String phone;

	public User() {
		this.authority = "ROLE_USER";
	}

	public User(String username, String lastname, String firstname, String password, String email, String phone) {
		this.username = username;
		this.lastname = lastname;
		this.firstname = firstname;
		this.password = password;
		this.email = email;
		this.phone = phone;
		this.authority = "ROLE_USER";
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getLastname() {
		return lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	public String getFirstname() {
		return firstname;
	}

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAuthority() {
		return authority;
	}

	public void setAuthority(String authority) {
		this.authority = authority;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((authority == null) ? 0 : authority.hashCode());
		result = prime * result + ((email == null) ? 0 : email.hashCode());
		result = prime * result + ((firstname == null) ? 0 : firstname.hashCode());
		result = prime * result + ((lastname == null) ? 0 : lastname.hashCode());
		result = prime * result + ((phone == null) ? 0 : phone.hashCode());
		result = prime * result + ((username == null) ? 0 : username.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (authority == null) {
			if (other.authority != null)
				return false;
		} else if (!authority.equals(other.authority))
			return false;
		if (email == null) {
			if (other.email != null)
				return false;
		} else if (!email.equals(other.email))
			return false;
		if (firstname == null) {
			if (other.firstname != null)
				return false;
		} else if (!firstname.equals(other.firstname))
			return false;
		if (lastname == null) {
			if (other.lastname != null)
				return false;
		} else if (!lastname.equals(other.lastname))
			return false;
		if (phone == null) {
			if (other.phone != null)
				return false;
		} else if (!phone.equals(other.phone))
			return false;
		if (username == null) {
			if (other.username != null)
				return false;
		} else if (!username.equals(other.username))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "User [username=" + username + ", lastname=" + lastname + ", firstname=" + firstname + ", email=" + email
				+ ", authority=" + authority + ", phone=" + phone + "]";
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {

		return AuthorityUtils.createAuthorityList(authority);
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

}


text:
layout: post
title: My First Ticket
---

```
As an ads ops
When I work with our sites
Then I would like to use the new GPT tags for serving ads
```

This was my first ticket. Such responsibility. Much cool. Many wow. So where to start?

A little googling and light reading later, I understood that Google were deprecating their previous ad library, the DART implementation, in favour of the newer Google Publisher Tag, or GPT library. This was a small javascript library that then allowed you to access and display google ads of various sizes on your site. The javascript and implementation looked fairly straight forward. Within the Head of your HTML, you load the library and instantiate it, then define the various ad slots that are to appear on that particular page. Then in the body, you simply create a div element that holds a small script to load the specific ad for that location. To get this up and running on a small site in raw HTML / Javascript would have been perfectly simple.

Unfortunately, the key factor in determining the difficulty of actually making this change lies in line 2 of the user story, specifically the use of the plural - sites. I was not to be working on just one small site, directly in the HTML and Javascript, this was to be done on the CMS level. A CMS covering multiple sites. A CMS that itself included and relied upon multiple plugins and controls. A CMS that was written largely in C#... with just a little VB thrown in for good measure...

Welcome to web development!

My coding education and practice so far at this point had excluded one vital part of the puzzle of web development, coming to a large project that isn't your own and making changes. Through my experience working on this ticket, I've managed to break down my approach into 4 steps:

1. Understand What It Does
2. Break It
3. Fix It
4. Scrap It

### 1. Understand What It Does
This is easier said than done and was probably the hardest step for me. It felt a little like gazing up at a gargantuan oppressive skyscraper, before stepping inside to find a maze of corridors and rooms with little direction. Where to even begin?

Part of the answer it turned out was sat next to me, a colleague with far more experience with the current codebase than me. They were fortunately willing to be my guide, and saved me a lot of blank staring at functions that might not have borne any significance to the task at hand. I feel this should be the first step of any programmer interacting with someone else's work - grab the author, or at least someone who knows more about it than you. This can help immensely in breaking down a large codebase and quickly helping you focus on the code you're interested in.

The next step was more granular, with the help of my colleague I'd honed in on the area of interest. I'd seen function names and variables that I recognised but still wasn't entirely sure how it all fit together. Now you need to debug. Set a few break points on areas you think are interesting, build, run and see what happens. Stepping through the code as it's running is invaluable in determining what calls on what, mapping dependencies and generally putting back together the puzzle pieces to form a picture of what you're dealing with.

This process becomes even more valuable during the next two steps.

### 2. Break It
So you're the man. You've stepped through the code, seen the processes firing off and got a map of how it all works in your head? No, you don't. Unless the code is immensely simple, you'll never reach that level of code understanding enlightenment simply by reading through line by line and having a few debug run throughs.

To get to grips with a codebase, one must break it. To truly get to grips with a codebase, one must break it and understand why it broke.

This step is easy, and fun! Try writing the code that you wish you had. Try using objects that exist already in new and exciting ways. Try things that you know won't work just to see if things break as you expect. Also try not to commit any of your changes!

### 3. Fix It
Breaking things is easy, now to fix them.

This is the part where I felt things start to come together. I feel like the key here is to keep track of the larger picture as you fix the nitty gritty details. Step through the broken code and fix it bit by bit and you'll end up with a much clearer idea of the route through your program.

### 4. Scrap It
Finally, after breaking the code, and fixing it again, perhaps even adding a few features that actually work, you'll want to scrap it all and git reset hard to a point before you'd even touched the code.

Once you've mopped up the tears of frustration after having just deleted all the code you'd been working on for the last few hours/days/weeks - you'll be ready for some TDD!

It may seem foolish abandoning code that works, but that code was tainted, written while you were exploring and written without the backup of robust tests. You're also now in a much better position to write fresh code, you'll know exactly what to test and key aspects to look out for. This is the process that helped me get to grips with my first task, and I hope others might find it useful too.

Bonus steps:

### 5. ????

### 6. Profit

redpajama_set_name: RedPajamaGithub


text:
require File.dirname(__FILE__) + '/test_helper.rb'

class PersonTest < Test::Unit::TestCase #:nodoc:
  include TestHelper

  # Tests construction of a person from a JSON entry
  def test_initialization
    json = load_json('person.json')
    person = OpenSocial::Person.new(json['entry'])

    assert_equal 'example.org:34KJDCSKJN2HHF0DW20394', person.id
    assert_equal String, person.id.class

    assert_equal Hash, person.name.class
    assert_equal 'Jane Doe', person.name['unstructured']
    assert_equal '', person.long_name

    assert_equal Hash, person.gender.class
    assert_equal '女性', person.gender['displayvalue']
    assert_equal 'FEMALE', person.gender['key']

    assert person.is_owner
    assert person.is_viewer
  end

  # Tests construction of a person from a stubbed HTTP request
  def test_fetch_person_request
    json = load_json('person.json')

    c = OpenSocial::Connection.new(NO_AUTH)
    request = OpenSocial::FetchPersonRequest.new(c)
    request.stubs(:send_request).returns(json)
    person = request.send

    assert_equal 'example.org:34KJDCSKJN2HHF0DW20394', person.id
    assert_equal String, person.id.class

    assert_equal Hash, person.name.class
    assert_equal 'Jane Doe', person.name['unstructured']
    assert_equal '', person.long_name

    assert_equal Hash, person.gender.class
    assert_equal '女性', person.gender['displayvalue']
    assert_equal 'FEMALE', person.gender['key']

    assert person.is_owner
    assert person.is_viewer
  end

  # Tests construction of a collection of people from a stubbed HTTP request
  def test_fetch_people_request
    json = load_json('people.json')

    c = OpenSocial::Connection.new(NO_AUTH)
    request = OpenSocial::FetchPeopleRequest.new(c)
    request.stubs(:send_request).returns(json)
    people = request.send

    # Check properties of the collection
    assert_equal OpenSocial::Collection, people.class
    assert_equal 2, people.length

    # Check properties of the first person
    first = people['example.org:34KJDCSKJN2HHF0DW20394']
    assert_equal 'example.org:34KJDCSKJN2HHF0DW20394', first.id
    assert_equal String, first.id.class

    assert_equal Hash, first.name.class
    assert_equal 'Jane Doe', first.name['unstructured']
    assert_equal '', first.long_name

    assert_equal Hash, first.gender.class
    assert_equal '女性', first.gender['displayvalue']
    assert_equal 'FEMALE', first.gender['key']

    assert first.is_owner
    assert first.is_viewer

    # Check properties of the second person
    second = people['example.org:34KJDCSKJN2HHF0DW20395']
    assert_equal 'example.org:34KJDCSKJN2HHF0DW20395', second.id
    assert_equal String, second.id.class

    assert_equal Hash, second.name.class
    assert_equal 'Jane Doe2', second.name['unstructured']
    assert_equal '', second.long_name

    assert_equal Hash, second.gender.class
    assert_equal '女性', second.gender['displayvalue']
    assert_equal 'FEMALE', second.gender['key']

    assert !second.is_owner
    assert !second.is_viewer
  end

  def test_sends_extra_parameter

    c = OpenSocial::Connection.new(NO_AUTH)
    json = load_json('people.json')

    request = OpenSocial::FetchPeopleRequest.new(c, "@me", "@friends", :count => 500)
    request.expects(:send_request).with(
      'people',
      '@me',
      '@friends',
      nil,
      false,
      {
        :count => 500,
        :fields => OpenSocial::FetchPersonRequest::DEFAULT_FIELDS.join(",")
      }
    ).returns(json)
    people = request.send
  end

  # Tests construction of a person from a stubbed HTTP request
  def test_fetch_person_request_asks_for_display_name
    c = OpenSocial::Connection.new(NO_AUTH)
    json = load_json('person.json')

    request = OpenSocial::FetchPersonRequest.new(c)
    expected_fields_requested = "id,dateOfBirth,name,emails,gender,state,postalCode,ethnicity,relationshipStatus,thumbnailUrl,displayName"
    request.expects(:send_request).with('people', '@me', '@self', nil, false, :fields => expected_fields_requested).returns(json)
    people = request.send
  end

end


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__wchar_t_environment_printf_51b.c
Label Definition File: CWE134_Uncontrolled_Format_String.label.xml
Template File: sources-sinks-51b.tmpl.c
*/
/*
 * @description
 * CWE: 134 Uncontrolled Format String
 * BadSource: environment Read input from an environment variable
 * GoodSource: Copy a fixed string into data
 * Sinks: printf
 *    GoodSink: wprintf with "%s" as the first argument and data as the second
 *    BadSink : wprintf with only data as an argument
 * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

#define ENV_VARIABLE L"ADD"

#ifdef _WIN32
#define GETENV _wgetenv
#else
#define GETENV getenv
#endif

#ifndef OMITBAD

void CWE134_Uncontrolled_Format_String__wchar_t_environment_printf_51b_badSink(wchar_t * data)
{
    /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
    wprintf(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE134_Uncontrolled_Format_String__wchar_t_environment_printf_51b_goodG2BSink(wchar_t * data)
{
    /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
    wprintf(data);
}

/* goodB2G uses the BadSource with the GoodSink */
void CWE134_Uncontrolled_Format_String__wchar_t_environment_printf_51b_goodB2GSink(wchar_t * data)
{
    /* FIX: Specify the format disallowing a format string vulnerability */
    wprintf(L"%s\n", data);
}

#endif /* OMITGOOD */


text:
from test_base import TestCase
from sockjs.transports import xhr

class XhrTransportTests(TestCase):

    TRANSPORT_CLASS = xhr.XHRTransport

    def test_process(self):
        transp = self.make_transport()
        transp.handle_session = self.make_fut(1)
        resp = self.loop.run_until_complete(transp.process())
        self.assertTrue(transp.handle_session.called)
        self.assertEqual(resp.status, 200)

    def test_process_OPTIONS(self):
        transp = self.make_transport(method='OPTIONS')
        resp = self.loop.run_until_complete(transp.process())
        self.assertEqual(resp.status, 204)


text:
namespace llvm {

class LinePrinter;

class CompilandDumper : public PDBSymDumper {
public:
  CompilandDumper(LinePrinter &P);

  void start(const PDBSymbolCompiland &Symbol, bool Children);

  void dump(const PDBSymbolCompilandDetails &Symbol) override;
  void dump(const PDBSymbolCompilandEnv &Symbol) override;
  void dump(const PDBSymbolData &Symbol) override;
  void dump(const PDBSymbolFunc &Symbol) override;
  void dump(const PDBSymbolLabel &Symbol) override;
  void dump(const PDBSymbolThunk &Symbol) override;
  void dump(const PDBSymbolTypeTypedef &Symbol) override;
  void dump(const PDBSymbolUnknown &Symbol) override;

private:
  LinePrinter &Printer;
};
}

#endif


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: update.proto

package com.protos;

public final class UpdateProtos {
  private UpdateProtos() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
  }
  public interface UpdateOrBuilder extends
      // @@protoc_insertion_point(interface_extends:com.protos.Update)
      com.google.protobuf.MessageOrBuilder {

    /**
     * required string type = 1;
     */
    boolean hasType();
    /**
     * required string type = 1;
     */
    java.lang.String getType();
    /**
     * required string type = 1;
     */
    com.google.protobuf.ByteString
        getTypeBytes();

    /**
     * required string tag = 2;
     */
    boolean hasTag();
    /**
     * required string tag = 2;
     */
    java.lang.String getTag();
    /**
     * required string tag = 2;
     */
    com.google.protobuf.ByteString
        getTagBytes();

    /**
     * required string name = 3;
     */
    boolean hasName();
    /**
     * required string name = 3;
     */
    java.lang.String getName();
    /**
     * required string name = 3;
     */
    com.google.protobuf.ByteString
        getNameBytes();
  }
  /**
   * Protobuf type {@code com.protos.Update}
   */
  public static final class Update extends
      com.google.protobuf.GeneratedMessage implements
      // @@protoc_insertion_point(message_implements:com.protos.Update)
      UpdateOrBuilder {
    // Use Update.newBuilder() to construct.
    private Update(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
      super(builder);
      this.unknownFields = builder.getUnknownFields();
    }
    private Update(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }

    private static final Update defaultInstance;
    public static Update getDefaultInstance() {
      return defaultInstance;
    }

    public Update getDefaultInstanceForType() {
      return defaultInstance;
    }

    private final com.google.protobuf.UnknownFieldSet unknownFields;
    @java.lang.Override
    public final com.google.protobuf.UnknownFieldSet
        getUnknownFields() {
      return this.unknownFields;
    }
    private Update(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      initFields();
      int mutable_bitField0_ = 0;
      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
          com.google.protobuf.UnknownFieldSet.newBuilder();
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            default: {
              if (!parseUnknownField(input, unknownFields,
                                     extensionRegistry, tag)) {
                done = true;
              }
              break;
            }
            case 10: {
              com.google.protobuf.ByteString bs = input.readBytes();
              bitField0_ |= 0x00000001;
              type_ = bs;
              break;
            }
            case 18: {
              com.google.protobuf.ByteString bs = input.readBytes();
              bitField0_ |= 0x00000002;
              tag_ = bs;
              break;
            }
            case 26: {
              com.google.protobuf.ByteString bs = input.readBytes();
              bitField0_ |= 0x00000004;
              name_ = bs;
              break;
            }
          }
        }
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.setUnfinishedMessage(this);
      } catch (java.io.IOException e) {
        throw new com.google.protobuf.InvalidProtocolBufferException(
            e.getMessage()).setUnfinishedMessage(this);
      } finally {
        this.unknownFields = unknownFields.build();
        makeExtensionsImmutable();
      }
    }
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return com.protos.UpdateProtos.internal_static_com_protos_Update_descriptor;
    }

    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.protos.UpdateProtos.internal_static_com_protos_Update_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.protos.UpdateProtos.Update.class, com.protos.UpdateProtos.Update.Builder.class);
    }

    public static com.google.protobuf.Parser<Update> PARSER =
        new com.google.protobuf.AbstractParser<Update>() {
      public Update parsePartialFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
        return new Update(input, extensionRegistry);
      }
    };

    @java.lang.Override
    public com.google.protobuf.Parser<Update> getParserForType() {
      return PARSER;
    }

    private int bitField0_;
    public static final int TYPE_FIELD_NUMBER = 1;
    private java.lang.Object type_;
    /**
     * required string type = 1;
     */
    public boolean hasType() {
      return ((bitField0_ & 0x00000001) == 0x00000001);
    }
    /**
     * required string type = 1;
     */
    public java.lang.String getType() {
      java.lang.Object ref = type_;
      if (ref instanceof java.lang.String) {
        return (java.lang.String) ref;
      } else {
        com.google.protobuf.ByteString bs =
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          type_ = s;
        }
        return s;
      }
    }
    /**
     * required string type = 1;
     */
    public com.google.protobuf.ByteString
        getTypeBytes() {
      java.lang.Object ref = type_;
      if (ref instanceof java.lang.String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        type_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    public static final int TAG_FIELD_NUMBER = 2;
    private java.lang.Object tag_;
    /**
     * required string tag = 2;
     */
    public boolean hasTag() {
      return ((bitField0_ & 0x00000002) == 0x00000002);
    }
    /**
     * required string tag = 2;
     */
    public java.lang.String getTag() {
      java.lang.Object ref = tag_;
      if (ref instanceof java.lang.String) {
        return (java.lang.String) ref;
      } else {
        com.google.protobuf.ByteString bs =
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          tag_ = s;
        }
        return s;
      }
    }
    /**
     * required string tag = 2;
     */
    public com.google.protobuf.ByteString
        getTagBytes() {
      java.lang.Object ref = tag_;
      if (ref instanceof java.lang.String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        tag_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    public static final int NAME_FIELD_NUMBER = 3;
    private java.lang.Object name_;
    /**
     * required string name = 3;
     */
    public boolean hasName() {
      return ((bitField0_ & 0x00000004) == 0x00000004);
    }
    /**
     * required string name = 3;
     */
    public java.lang.String getName() {
      java.lang.Object ref = name_;
      if (ref instanceof java.lang.String) {
        return (java.lang.String) ref;
      } else {
        com.google.protobuf.ByteString bs =
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          name_ = s;
        }
        return s;
      }
    }
    /**
     * required string name = 3;
     */
    public com.google.protobuf.ByteString
        getNameBytes() {
      java.lang.Object ref = name_;
      if (ref instanceof java.lang.String) {
        com.google.protobuf.ByteString b =
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        name_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    private void initFields() {
      type_ = "";
      tag_ = "";
      name_ = "";
    }
    private byte memoizedIsInitialized = -1;
    public final boolean isInitialized() {
      byte isInitialized = memoizedIsInitialized;
      if (isInitialized == 1) return true;
      if (isInitialized == 0) return false;

      if (!hasType()) {
        memoizedIsInitialized = 0;
        return false;
      }
      if (!hasTag()) {
        memoizedIsInitialized = 0;
        return false;
      }
      if (!hasName()) {
        memoizedIsInitialized = 0;
        return false;
      }
      memoizedIsInitialized = 1;
      return true;
    }

    public void writeTo(com.google.protobuf.CodedOutputStream output)
                        throws java.io.IOException {
      getSerializedSize();
      if (((bitField0_ & 0x00000001) == 0x00000001)) {
        output.writeBytes(1, getTypeBytes());
      }
      if (((bitField0_ & 0x00000002) == 0x00000002)) {
        output.writeBytes(2, getTagBytes());
      }
      if (((bitField0_ & 0x00000004) == 0x00000004)) {
        output.writeBytes(3, getNameBytes());
      }
      getUnknownFields().writeTo(output);
    }

    private int memoizedSerializedSize = -1;
    public int getSerializedSize() {
      int size = memoizedSerializedSize;
      if (size != -1) return size;

      size = 0;
      if (((bitField0_ & 0x00000001) == 0x00000001)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(1, getTypeBytes());
      }
      if (((bitField0_ & 0x00000002) == 0x00000002)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(2, getTagBytes());
      }
      if (((bitField0_ & 0x00000004) == 0x00000004)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(3, getNameBytes());
      }
      size += getUnknownFields().getSerializedSize();
      memoizedSerializedSize = size;
      return size;
    }

    private static final long serialVersionUID = 0L;
    @java.lang.Override
    protected java.lang.Object writeReplace()
        throws java.io.ObjectStreamException {
      return super.writeReplace();
    }

    public static com.protos.UpdateProtos.Update parseFrom(
        com.google.protobuf.ByteString data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static com.protos.UpdateProtos.Update parseFrom(
        com.google.protobuf.ByteString data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static com.protos.UpdateProtos.Update parseFrom(byte[] data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static com.protos.UpdateProtos.Update parseFrom(
        byte[] data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static com.protos.UpdateProtos.Update parseFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static com.protos.UpdateProtos.Update parseFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }
    public static com.protos.UpdateProtos.Update parseDelimitedFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input);
    }
    public static com.protos.UpdateProtos.Update parseDelimitedFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input, extensionRegistry);
    }
    public static com.protos.UpdateProtos.Update parseFrom(
        com.google.protobuf.CodedInputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static com.protos.UpdateProtos.Update parseFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }

    public static Builder newBuilder() { return Builder.create(); }
    public Builder newBuilderForType() { return newBuilder(); }
    public static Builder newBuilder(com.protos.UpdateProtos.Update prototype) {
      return newBuilder().mergeFrom(prototype);
    }
    public Builder toBuilder() { return newBuilder(this); }

    @java.lang.Override
    protected Builder newBuilderForType(
        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
      Builder builder = new Builder(parent);
      return builder;
    }
    /**
     * Protobuf type {@code com.protos.Update}
     */
    public static final class Builder extends
        com.google.protobuf.GeneratedMessage.Builder<Builder> implements
        // @@protoc_insertion_point(builder_implements:com.protos.Update)
        com.protos.UpdateProtos.UpdateOrBuilder {
      public static final com.google.protobuf.Descriptors.Descriptor
          getDescriptor() {
        return com.protos.UpdateProtos.internal_static_com_protos_Update_descriptor;
      }

      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
          internalGetFieldAccessorTable() {
        return com.protos.UpdateProtos.internal_static_com_protos_Update_fieldAccessorTable
            .ensureFieldAccessorsInitialized(
                com.protos.UpdateProtos.Update.class, com.protos.UpdateProtos.Update.Builder.class);
      }

      // Construct using com.protos.UpdateProtos.Update.newBuilder()
      private Builder() {
        maybeForceBuilderInitialization();
      }

      private Builder(
          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
        super(parent);
        maybeForceBuilderInitialization();
      }
      private void maybeForceBuilderInitialization() {
        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
        }
      }
      private static Builder create() {
        return new Builder();
      }

      public Builder clear() {
        super.clear();
        type_ = "";
        bitField0_ = (bitField0_ & ~0x00000001);
        tag_ = "";
        bitField0_ = (bitField0_ & ~0x00000002);
        name_ = "";
        bitField0_ = (bitField0_ & ~0x00000004);
        return this;
      }

      public Builder clone() {
        return create().mergeFrom(buildPartial());
      }

      public com.google.protobuf.Descriptors.Descriptor
          getDescriptorForType() {
        return com.protos.UpdateProtos.internal_static_com_protos_Update_descriptor;
      }

      public com.protos.UpdateProtos.Update getDefaultInstanceForType() {
        return com.protos.UpdateProtos.Update.getDefaultInstance();
      }

      public com.protos.UpdateProtos.Update build() {
        com.protos.UpdateProtos.Update result = buildPartial();
        if (!result.isInitialized()) {
          throw newUninitializedMessageException(result);
        }
        return result;
      }

      public com.protos.UpdateProtos.Update buildPartial() {
        com.protos.UpdateProtos.Update result = new com.protos.UpdateProtos.Update(this);
        int from_bitField0_ = bitField0_;
        int to_bitField0_ = 0;
        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
          to_bitField0_ |= 0x00000001;
        }
        result.type_ = type_;
        if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
          to_bitField0_ |= 0x00000002;
        }
        result.tag_ = tag_;
        if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
          to_bitField0_ |= 0x00000004;
        }
        result.name_ = name_;
        result.bitField0_ = to_bitField0_;
        onBuilt();
        return result;
      }

      public Builder mergeFrom(com.google.protobuf.Message other) {
        if (other instanceof com.protos.UpdateProtos.Update) {
          return mergeFrom((com.protos.UpdateProtos.Update)other);
        } else {
          super.mergeFrom(other);
          return this;
        }
      }

      public Builder mergeFrom(com.protos.UpdateProtos.Update other) {
        if (other == com.protos.UpdateProtos.Update.getDefaultInstance()) return this;
        if (other.hasType()) {
          bitField0_ |= 0x00000001;
          type_ = other.type_;
          onChanged();
        }
        if (other.hasTag()) {
          bitField0_ |= 0x00000002;
          tag_ = other.tag_;
          onChanged();
        }
        if (other.hasName()) {
          bitField0_ |= 0x00000004;
          name_ = other.name_;
          onChanged();
        }
        this.mergeUnknownFields(other.getUnknownFields());
        return this;
      }

      public final boolean isInitialized() {
        if (!hasType()) {

          return false;
        }
        if (!hasTag()) {

          return false;
        }
        if (!hasName()) {

          return false;
        }
        return true;
      }

      public Builder mergeFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
        com.protos.UpdateProtos.Update parsedMessage = null;
        try {
          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
          parsedMessage = (com.protos.UpdateProtos.Update) e.getUnfinishedMessage();
          throw e;
        } finally {
          if (parsedMessage != null) {
            mergeFrom(parsedMessage);
          }
        }
        return this;
      }
      private int bitField0_;

      private java.lang.Object type_ = "";
      /**
       * required string type = 1;
       */
      public boolean hasType() {
        return ((bitField0_ & 0x00000001) == 0x00000001);
      }
      /**
       * required string type = 1;
       */
      public java.lang.String getType() {
        java.lang.Object ref = type_;
        if (!(ref instanceof java.lang.String)) {
          com.google.protobuf.ByteString bs =
              (com.google.protobuf.ByteString) ref;
          java.lang.String s = bs.toStringUtf8();
          if (bs.isValidUtf8()) {
            type_ = s;
          }
          return s;
        } else {
          return (java.lang.String) ref;
        }
      }
      /**
       * required string type = 1;
       */
      public com.google.protobuf.ByteString
          getTypeBytes() {
        java.lang.Object ref = type_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b =
              com.google.protobuf.ByteString.copyFromUtf8(
                  (java.lang.String) ref);
          type_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * required string type = 1;
       */
      public Builder setType(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000001;
        type_ = value;
        onChanged();
        return this;
      }
      /**
       * required string type = 1;
       */
      public Builder clearType() {
        bitField0_ = (bitField0_ & ~0x00000001);
        type_ = getDefaultInstance().getType();
        onChanged();
        return this;
      }
      /**
       * required string type = 1;
       */
      public Builder setTypeBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000001;
        type_ = value;
        onChanged();
        return this;
      }

      private java.lang.Object tag_ = "";
      /**
       * required string tag = 2;
       */
      public boolean hasTag() {
        return ((bitField0_ & 0x00000002) == 0x00000002);
      }
      /**
       * required string tag = 2;
       */
      public java.lang.String getTag() {
        java.lang.Object ref = tag_;
        if (!(ref instanceof java.lang.String)) {
          com.google.protobuf.ByteString bs =
              (com.google.protobuf.ByteString) ref;
          java.lang.String s = bs.toStringUtf8();
          if (bs.isValidUtf8()) {
            tag_ = s;
          }
          return s;
        } else {
          return (java.lang.String) ref;
        }
      }
      /**
       * required string tag = 2;
       */
      public com.google.protobuf.ByteString
          getTagBytes() {
        java.lang.Object ref = tag_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b =
              com.google.protobuf.ByteString.copyFromUtf8(
                  (java.lang.String) ref);
          tag_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * required string tag = 2;
       */
      public Builder setTag(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000002;
        tag_ = value;
        onChanged();
        return this;
      }
      /**
       * required string tag = 2;
       */
      public Builder clearTag() {
        bitField0_ = (bitField0_ & ~0x00000002);
        tag_ = getDefaultInstance().getTag();
        onChanged();
        return this;
      }
      /**
       * required string tag = 2;
       */
      public Builder setTagBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000002;
        tag_ = value;
        onChanged();
        return this;
      }

      private java.lang.Object name_ = "";
      /**
       * required string name = 3;
       */
      public boolean hasName() {
        return ((bitField0_ & 0x00000004) == 0x00000004);
      }
      /**
       * required string name = 3;
       */
      public java.lang.String getName() {
        java.lang.Object ref = name_;
        if (!(ref instanceof java.lang.String)) {
          com.google.protobuf.ByteString bs =
              (com.google.protobuf.ByteString) ref;
          java.lang.String s = bs.toStringUtf8();
          if (bs.isValidUtf8()) {
            name_ = s;
          }
          return s;
        } else {
          return (java.lang.String) ref;
        }
      }
      /**
       * required string name = 3;
       */
      public com.google.protobuf.ByteString
          getNameBytes() {
        java.lang.Object ref = name_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b =
              com.google.protobuf.ByteString.copyFromUtf8(
                  (java.lang.String) ref);
          name_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * required string name = 3;
       */
      public Builder setName(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000004;
        name_ = value;
        onChanged();
        return this;
      }
      /**
       * required string name = 3;
       */
      public Builder clearName() {
        bitField0_ = (bitField0_ & ~0x00000004);
        name_ = getDefaultInstance().getName();
        onChanged();
        return this;
      }
      /**
       * required string name = 3;
       */
      public Builder setNameBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000004;
        name_ = value;
        onChanged();
        return this;
      }

      // @@protoc_insertion_point(builder_scope:com.protos.Update)
    }

    static {
      defaultInstance = new Update(true);
      defaultInstance.initFields();
    }

    // @@protoc_insertion_point(class_scope:com.protos.Update)
  }

  private static final com.google.protobuf.Descriptors.Descriptor
    internal_static_com_protos_Update_descriptor;
  private static
    com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internal_static_com_protos_Update_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n\014update.proto\022\ncom.protos\"1\n\006Update\022\014\n\004" +
      "type\030\001 \002(\t\022\013\n\003tag\030\002 \002(\t\022\014\n\004name\030\003 \002(\tB\032\n" +
      "\ncom.protosB\014UpdateProtos"
    };
    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
        new com.google.protobuf.Descriptors.FileDescriptor.    InternalDescriptorAssigner() {
          public com.google.protobuf.ExtensionRegistry assignDescriptors(
              com.google.protobuf.Descriptors.FileDescriptor root) {
            descriptor = root;
            return null;
          }
        };
    com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
        }, assigner);
    internal_static_com_protos_Update_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_com_protos_Update_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessage.FieldAccessorTable(
        internal_static_com_protos_Update_descriptor,
        new java.lang.String[] { "Type", "Tag", "Name", });
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
using namespace p4p;
using namespace p4p::app;

int main() {

	ISP* isp = new ISP();
	isp->setDataSourceServer("p4p-8.cs.yale.edu", 6871);
	isp->loadP4PInfo();

	ISPManager isp_mgr;
	isp_mgr.addISP("CT", isp);

	PGMSelectionManager pgm_mgr;
	pgm_mgr.setISPManager(&isp_mgr);
	pgm_mgr.setDefaultOptions(PeeringGuidanceMatrixOptions::FilesharingSwarmDependent());
	pgm_mgr.initGuidance("p4p-8.cs.yale.edu", 6673);

	const PeeringGuidanceMatrix* matrix = pgm_mgr.getGuidanceMatrix(isp);
	std::cout << "Options: " << matrix->getOptions().getOptType() << std::endl;
	pgm_mgr.releaseGuidanceMatrix(matrix);

	return 0;
}


text:
import os
import sys
import argparse
import ConfigParser

from fabric.api import local, env, run, settings

from contrail_provisioning.common.base import ContrailSetup

class WebuiSetup(ContrailSetup):
    def __init__(self, args_str = None):
        super(WebuiSetup, self).__init__()
        self._args = None
        if not args_str:
            args_str = ' '.join(sys.argv[1:])

        self.global_defaults = {
            'cfgm_ip': '127.0.0.1',
            'keystone_ip': '127.0.0.1',
            'openstack_ip': '127.0.0.1',
            'collector_ip' : '127.0.0.1',
            'admin_user': 'admin',
            'admin_password': 'contrail123',
            'admin_tenant_name': 'admin',
            'keystone_version': 'v2.0',
            'keystone_auth_protocol': 'http',
            'apiserver_auth_protocol': 'http',
        }
        self.parse_args(args_str)

    def parse_args(self, args_str):
        '''
        Eg. setup-vnc-webui --cfgm_ip 10.84.12.11 --keystone_ip 10.84.12.12
            --openstack_ip 10.84.12.12 --collector_ip 10.84.12.12
            --cassandra_ip_list 10.1.5.11 10.1.5.12 --internal_vip 10.84.12.200
            --contrail_internal_vip 10.84.12.250
            --cfgm_ip_list 10.84.12.11 10.84.12.12
            --collector_ip_list 10.84.12.11 10.84.12.12
            --dns_server_ip_list 10.84.12.11 10.84.12.12
        '''
        parser = self._parse_args(args_str)

        parser.add_argument("--cfgm_ip", help = "IP Address of the cfgm node")
        parser.add_argument("--keystone_ip", help = "IP Address of the keystone node")
        parser.add_argument("--openstack_ip", help = "IP Address of the openstack controller")
        parser.add_argument("--collector_ip", help = "IP Address of the Collector node")
        parser.add_argument("--cassandra_ip_list", help = "List of IP Addresses of cassandra nodes",
                            nargs='+', type=str)
        parser.add_argument("--cfgm_ip_list", help = "List of IP Addresses of cfgm nodes",
                            nargs='+', type=str)
        parser.add_argument("--collector_ip_list", help = "List of IP Addresses of collector nodes",
                            nargs='+', type=str)
        parser.add_argument("--dns_server_ip_list", help = "List of IP Addresses of DNS server nodes",
                            nargs='+', type=str)
        parser.add_argument("--orchestrator", help = "Orchestrator used, example openstack, vcenter")
        parser.add_argument("--internal_vip", help = "VIP Address of openstack  nodes")
        parser.add_argument("--contrail_internal_vip", help = "VIP Address of config  nodes")
        parser.add_argument("--vcenter_ip", help = "vcenter ip to connect to")
        parser.add_argument("--vcenter_port", help = "vcenter port to connect to")
        parser.add_argument("--vcenter_auth", help = "vcenter auth http or https")
        parser.add_argument("--vcenter_datacenter", help = "vcenter datacenter name")
        parser.add_argument("--vcenter_dvswitch", help = "vcenter dvswitch name")
        parser.add_argument("--admin_user",
                            help = "Identity Manager admin user name.")
        parser.add_argument("--admin_password",
                            help = "Identity Manager admin user's password.")
        parser.add_argument("--admin_tenant_name",
                            help = "Identity Manager admin tenant name.")
        parser.add_argument("--redis_password", help = "Redis password")
        parser.add_argument("--keystone_version", choices=['v2.0', 'v3'],
            help = "Keystone Version")
        parser.add_argument("--keystone_auth_protocol",
            help = "Auth protocol used to talk to keystone")
        parser.add_argument("--apiserver_auth_protocol",
            help = "Auth protocol used to talk to apiserver/neutron")
        self._args = parser.parse_args(self.remaining_argv)

    def  fixup_config_files(self):
        self.fixup_config_global_js()

    def fixup_config_global_js(self):
        openstack_ip = self._args.openstack_ip
        keystone_ip = self._args.keystone_ip
        keystone_version = self._args.keystone_version
        internal_vip = self._args.internal_vip
        contrail_internal_vip = self._args.contrail_internal_vip or internal_vip
        admin_user = self._args.admin_user
        admin_password = self._args.admin_password
        admin_tenant_name = self._args.admin_tenant_name
        add_cert_path = False
        keys_path = '/etc/contrail/webui_ssl/'
        keys_re_path = '\/etc\/contrail\/webui_ssl\/'

        #Dynamically create keys
        with settings(warn_only=True):
            server_options = local('cat /etc/contrail/config.global.js | grep config.server_options', capture=True)
            keys_path_specified = local('cat /etc/contrail/config.global.js | grep config.server_options.key_file', capture=True)
            cert_path_specified = local('cat /etc/contrail/config.global.js | grep config.server_options.cert_file', capture=True)
        try:
            if not (keys_path_specified and cert_path_specified):
                local("sudo mkdir -p %s" %(keys_path))
                key_cmd = ('sudo openssl req -new -newkey rsa:2048 -nodes -out %s%s -keyout %s%s -subj "/C=US/ST=CA/L=Sunnyvale/O=Juniper Networks/OU=Juniper CA/CN=ContrailCA"') %(keys_path, 'certrequest.csr', keys_path, 'cs-key.pem')
                local(key_cmd)
                cert_cmd = ('sudo openssl x509 -req -days 730 -in %s%s -signkey %s%s -out %s%s') %(keys_path, 'certrequest.csr', keys_path, 'cs-key.pem', keys_path, 'cs-crt.crt',)
                local(cert_cmd)
                local('sudo cat %s%s %s%s > %s%s' %(keys_path, 'cs-key.pem', keys_path, 'cs-crt.crt', keys_path, 'cs-cert.pem'))
                if os.path.isfile(keys_path + 'cs-key.pem') == True and \
                    os.path.isfile(keys_path + 'cs-cert.pem') == True:
                    add_cert_path = True
        except:
            add_cert_path = False

        local("sudo sed \"s/config.cnfg.server_ip.*/config.cnfg.server_ip = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(contrail_internal_vip or self._args.cfgm_ip))
        local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        if self._args.cfgm_ip_list:
            local("sudo sed \"s/config.cnfg.server_ip.*/config.cnfg.server_ip = %s;/g\" /etc/contrail/config.global.js > config.global.js.new" %(str(self._args.cfgm_ip_list)))
            local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        local("sudo sed \"s/config.networkManager.ip.*/config.networkManager.ip = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(contrail_internal_vip or self._args.cfgm_ip))
        local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        local("sudo sed \"s/config.imageManager.ip.*/config.imageManager.ip = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(internal_vip or openstack_ip))
        local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        local("sudo sed \"s/config.computeManager.ip.*/config.computeManager.ip = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(internal_vip or openstack_ip))
        local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        local("sudo sed \"s/config.identityManager.ip.*/config.identityManager.ip = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(internal_vip or keystone_ip))
        local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        local("sudo sed -si \"s/config.identityManager.authProtocol.*/config.identityManager.authProtocol = '%s';/g\" /etc/contrail/config.global.js" % self._args.keystone_auth_protocol)
        local("sudo sed -si \"s/config.networkManager.authProtocol.*/config.networkManager.authProtocol = '%s';/g\" /etc/contrail/config.global.js" % self._args.apiserver_auth_protocol)
        local("sudo sed -si \"s/^config.identityManager.apiVersion.*/config.identityManager.apiVersion = ['%s'];/g\" /etc/contrail/config.global.js" %(keystone_version))
        local("sudo sed \"s/config.storageManager.ip.*/config.storageManager.ip = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(internal_vip or openstack_ip))
        local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        if admin_user:
            local("sudo sed \"s/auth.admin_user.*/auth.admin_user = '%s';/g\" /etc/contrail/contrail-webui-userauth.js > contrail-webui-userauth.js.new" %(admin_user))
            local("sudo mv contrail-webui-userauth.js.new /etc/contrail/contrail-webui-userauth.js")
        if admin_password:
            local("sudo sed \"s/auth.admin_password.*/auth.admin_password = '%s';/g\" /etc/contrail/contrail-webui-userauth.js > contrail-webui-userauth.js.new" %(admin_password))
            local("sudo mv contrail-webui-userauth.js.new /etc/contrail/contrail-webui-userauth.js")
        if admin_tenant_name:
            local("sudo sed \"s/auth.admin_tenant_name.*/auth.admin_tenant_name = '%s';/g\" /etc/contrail/contrail-webui-userauth.js > contrail-webui-userauth.js.new" %(admin_tenant_name))
            local("sudo mv contrail-webui-userauth.js.new /etc/contrail/contrail-webui-userauth.js")

        if self._args.collector_ip:
            local("sudo sed \"s/config.analytics.server_ip.*/config.analytics.server_ip = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(contrail_internal_vip or self._args.collector_ip))
            local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        if self._args.collector_ip_list:
            local("sudo sed \"s/config.analytics.server_ip.*/config.analytics.server_ip = %s;/g\" /etc/contrail/config.global.js > config.global.js.new" %(str(self._args.collector_ip_list)))
            local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        if self._args.cassandra_ip_list:
            local("sudo sed \"s/config.cassandra.server_ips.*/config.cassandra.server_ips = %s;/g\" /etc/contrail/config.global.js > config.global.js.new" %(str(self._args.cassandra_ip_list)))
            local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        if self._args.dns_server_ip_list:
            local("sudo sed \"s/config.dns.server_ip.*/config.dns.server_ips = %s;/g\" /etc/contrail/config.global.js > config.global.js.new" %(str(self._args.dns_server_ip_list)))
            local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        if self._args.redis_password:
            local("sudo sed \"s/config.redis_password.*/config.redis_password = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(self._args.redis_password))
            local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        with settings(warn_only=True):
            if add_cert_path == True:
                local("sudo sed \"/config.getDomainsFromApiServer/ a \\\n// server_options\\nconfig.server_options = {};\" /etc/contrail/config.global.js > config.global.js.new")
                local("sudo mv config.global.js.new /etc/contrail/config.global.js")
                local("sudo sed \"/config.server_options/ a \\\n// key_file \\nconfig.server_options.key_file = '" + keys_path + "cs-key.pem';\" /etc/contrail/config.global.js > config.global.js.new")
                local("sudo mv config.global.js.new /etc/contrail/config.global.js")
                local("sudo sed \"/config.server_options.key_file/ a \\\n// cert_file \\nconfig.server_options.cert_file = '" + keys_path + "cs-cert.pem';\" /etc/contrail/config.global.js > config.global.js.new")
                local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        if self._args.vcenter_ip:
            orchestrator = 'vcenter'
            local("sudo sed \"s/config.vcenter.server_ip.*/config.vcenter.server_ip = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(self._args.vcenter_ip))
            local("sudo mv config.global.js.new /etc/contrail/config.global.js")
            local("sudo sed \"s/config.orchestration.Manager.*/config.orchestration.Manager = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(orchestrator))
            local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        if self._args.vcenter_port:
            local("sudo sed \"s/config.vcenter.server_port.*/config.vcenter.server_port = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(self._args.vcenter_port))
            local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        if self._args.vcenter_auth:
            local("sudo sed \"s/config.vcenter.authProtocol.*/config.vcenter.authProtocol= '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(self._args.vcenter_auth))
            local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        if self._args.vcenter_datacenter:
            local("sudo sed \"s/config.vcenter.datacenter.*/config.vcenter.datacenter = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(self._args.vcenter_datacenter))
            local("sudo mv config.global.js.new /etc/contrail/config.global.js")
        if self._args.vcenter_dvswitch:
            local("sudo sed \"s/config.vcenter.dvsswitch.*/config.vcenter.dvsswitch = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(self._args.vcenter_dvswitch))
            local("sudo mv config.global.js.new /etc/contrail/config.global.js")

        if self._args.orchestrator == 'vcenter':
           with settings(warn_only=True):
              mt_enable_variable = local('cat /etc/contrail/config.global.js | grep config.multi_tenancy', capture=True);
           if mt_enable_variable:
              local("sudo sed \"s/config.multi_tenancy.enabled.*/config.multi_tenancy.enabled = false;/g\" /etc/contrail/config.global.js > config.global.js.new")
              local("sudo mv config.global.js.new /etc/contrail/config.global.js")
           else:
              local("sudo sed \"/config.vcenter.wsdl/ a \\\n// multi_tenancy\\nconfig.multi_tenancy = {};\\nconfig.multi_tenancy.enabled = false;\" /etc/contrail/config.global.js > config.global.js.new")
              local("sudo mv config.global.js.new /etc/contrail/config.global.js")
           with settings(warn_only=True):
               static_auth = local('cat /etc/contrail/config.global.js | grep config.staticAuth', capture=True)
           if admin_user and admin_password :
              if static_auth:
                 local("sudo sed \"s/config.staticAuth\[0].username.*/config.staticAuth\[0].username = '" + admin_user + "';/g\" /etc/contrail/config.global.js > config.global.js.new")
                 local("sudo mv config.global.js.new /etc/contrail/config.global.js")
                 local("sudo sed \"s/config.staticAuth\[0].password.*/config.staticAuth\[0].password = '" + admin_password + "';/g\" /etc/contrail/config.global.js > config.global.js.new")
                 local("sudo mv config.global.js.new /etc/contrail/config.global.js")
                 local("sudo sed \"s/config.staticAuth\[0].roles.*/config.staticAuth\[0].roles = ['cloudAdmin'];/g\" /etc/contrail/config.global.js > config.global.js.new")
                 local("sudo mv config.global.js.new /etc/contrail/config.global.js")
              else:
                 local("sudo sed \"/config.multi_tenancy.enable/ a \\\n// staticAuth\\nconfig.staticAuth = [];\\nconfig.staticAuth[0] = {};\\nconfig.staticAuth[0].username = '" + admin_user + "';\\nconfig.staticAuth[0].password = '" + admin_password + "';\\nconfig.staticAuth[0].roles = ['cloudAdmin'];\" /etc/contrail/config.global.js > config.global.js.new")
                 local("sudo mv config.global.js.new /etc/contrail/config.global.js")

        if self._args.orchestrator == 'none':
           local("sudo sed \"s/config.orchestration.Manager.*/config.orchestration.Manager = '%s';/g\" /etc/contrail/config.global.js > config.global.js.new" %(self._args.orchestrator))
           local("sudo mv config.global.js.new /etc/contrail/config.global.js")
           with settings(warn_only=True):
              mt_enable_variable = local('cat /etc/contrail/config.global.js | grep config.multi_tenancy', capture=True);
           if mt_enable_variable:
              local("sudo sed \"s/config.multi_tenancy.enabled.*/config.multi_tenancy.enabled = false;/g\" /etc/contrail/config.global.js > config.global.js.new")
              local("sudo mv config.global.js.new /etc/contrail/config.global.js")
           else:
              local("sudo sed \"/config.orchestration.Manager/ a \\\n// multi_tenancy\\nconfig.multi_tenancy = {};\\nconfig.multi_tenancy.enabled = false;\" /etc/contrail/config.global.js > config.global.js.new")
              local("sudo mv config.global.js.new /etc/contrail/config.global.js")

    def restart_webui(self):
        local("sudo service supervisor-webui restart")

    def run_services(self):
        local("sudo webui-server-setup.sh")

def main(args_str = None):
    webui = WebuiSetup(args_str)
    webui.setup()

def fix_webui_config(args_str = None):
    webui = WebuiSetup(args_str)
    webui.fixup_config_files()
    webui.restart_webui()

if __name__ == "__main__":
    main()


text:
using UnityEngine;
using System.Collections;

public class CameraBehaviour : MonoBehaviour {

	public GameObject player;

	public Vector3 cameraToPlayerTranslation;
	public float cameraForwardPosition;

	private bool isShaking;
	private Vector3 shakeTransform;

	private float shakingForce;
	private float shakingForceAcceleration;

	public bool defaultActiveStatus;

	// Use this for initialization
	void Start ()
	{
		this.GetComponent<Animator> ().SetBool ("Visible", defaultActiveStatus);
		shakingForce = 0.01f;
		shakingForceAcceleration = 0;
	}

	// Update is called once per frame
	void Update ()
	{
		Vector3 cameraPosition = new Vector3 (player.transform.position.x + cameraToPlayerTranslation.x,
		                                      player.transform.position.y + cameraToPlayerTranslation.y,
		                                      cameraForwardPosition );
		if (isShaking)
		{
			shakeTransform = new Vector3(Random.Range(-shakingForce,shakingForce), Random.Range(-shakingForce,shakingForce), Random.Range(-shakingForce,shakingForce));
			shakingForce += shakingForceAcceleration;
			cameraPosition += shakeTransform;
		}

		this.transform.position = cameraPosition;
	}

	public void Shake(float shakingTime, float shakingPower, float shakingAcceleration)
	{
		shakingForce = shakingPower;
		shakingForceAcceleration = shakingAcceleration;
		isShaking = true;
		StartCoroutine(WaitAndStopShaking(shakingTime));
	}

	IEnumerator WaitAndStopShaking(float timer)
	{
		yield return new WaitForSeconds (timer);
		isShaking = false;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>servlet-jsp-dispatch-example</artifactId>
	<version>1.0-SNAPSHOT</version>
	<packaging>war</packaging>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>11</maven.compiler.source>
		<maven.compiler.target>11</maven.compiler.target>
		<jetty.version>10.0.0.alpha1</jetty.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.eclipse.jetty</groupId>
			<artifactId>jetty-servlet</artifactId>
			<scope>provided</scope>
		</dependency>
	</dependencies>

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-bom</artifactId>
				<version>${jetty.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<version>3.2.3</version>
				<configuration>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.eclipse.jetty</groupId>
				<artifactId>jetty-maven-plugin</artifactId>
				<version>${jetty.version}</version>
			</plugin>
		</plugins>
	</build>
</project>


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

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

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

.. _concepts:xcom:

XComs
=====

XComs (short for "cross-communications") are a mechanism that let :doc:`tasks` talk to each other, as by default Tasks are entirely isolated and may be running on entirely different machines.

An XCom is identified by a ``key`` (essentially its name), as well as the ``task_id`` and ``dag_id`` it came from. They can have any (serializable) value, but they are only designed for small amounts of data; do not use them to pass around large values, like dataframes.

XComs are explicitly "pushed" and "pulled" to/from their storage using the ``xcom_push`` and ``xcom_pull`` methods on Task Instances. Many operators will auto-push their results into an XCom key called ``return_value`` if the ``do_xcom_push`` argument is set to ``True`` (as it is by default), and ``@task`` functions do this as well.

``xcom_pull`` defaults to using this key if no key is passed to it, meaning it's possible to write code like this::

    # Pulls the return_value XCOM from "pushing_task"
    value = task_instance.xcom_pull(task_ids='pushing_task')

You can also use XComs in :ref:`templates <concepts:jinja-templating>`::

    SELECT * FROM {{ task_instance.xcom_pull(task_ids='foo', key='table_name') }}

XComs are a relative of :doc:`variables`, with the main difference being that XComs are per-task-instance and designed for communication within a DAG run, while Variables are global and designed for overall configuration and value sharing.

Custom Backends
---------------

The XCom system has interchangeable backends, and you can set which backend is being used via the ``xcom_backend`` configuration option.

If you want to implement your own backend, you should subclass :class:`~airflow.models.xcom.BaseXCom`, and override the ``serialize_value`` and ``deserialize_value`` methods.

There is also an ``orm_deserialize_value`` method that is called whenever the XCom objects are rendered for UI or reporting purposes; if you have large or expensive-to-retrieve values in your XComs, you should override this method to avoid calling that code (and instead return a lighter, incomplete representation) so the UI remains responsive.


text:
require 'spec_helper'

describe ILoveSudoku::BlockOfNine do

  describe "#hit!" do
    it "returns true when it solves a cell" do
      block = ILoveSudoku::BlockOfNine.new
      found_values = (1..6).to_a

      found_values.each do |num|
        block.add_cell(ILoveSudoku::Cell.new(num))
      end

      cell_a = ILoveSudoku::Cell.new
      cell_b = ILoveSudoku::Cell.new
      cell_c = ILoveSudoku::Cell.new

      [cell_a, cell_b, cell_c].each do |cell|
        found_values.each { |num| cell.remove!(num) }
      end

      cell_a.remove!(7)
      cell_b.remove!(7)

      block.add_cell(cell_a)
      block.add_cell(cell_b)
      block.add_cell(cell_c)

      expect(block.hit!).to eq true
    end

    it "returns true when it clears a possible value" do
      block = ILoveSudoku::BlockOfNine.new
      block.add_cell(ILoveSudoku::Cell.new(7))
      block.add_cell(ILoveSudoku::Cell.new)
      expect(block.hit!).to eq true
    end

    it "returns false when neither solves a cell nor clears any values" do
      block = ILoveSudoku::BlockOfNine.new
      found_values = (1..7).to_a

      found_values.each do |num|
        block.add_cell(ILoveSudoku::Cell.new(num))
      end

      cell_a = ILoveSudoku::Cell.new
      cell_b = ILoveSudoku::Cell.new

      [cell_a, cell_b].each do |cell|
        found_values.each { |num| cell.remove!(num) }
      end

      block.add_cell(cell_a)
      block.add_cell(cell_b)

      expect(block.hit!).to eq false
    end

  end
end


text:
require 'rails_helper'

describe ProjectDecorator, fast: true do
  describe '#visibility' do
    it "should return 'public' for a public project" do
      project = build :project, public: true
      expect(project.decorate.visibility).to eq 'public'
    end

    it "should return 'private' for a private project" do
      project = build :project, public: false
      expect(project.decorate.visibility).to eq 'private'
    end
  end
  # [:new_project, :ready, :in_progress, :abandoned, :completed]
  describe '#html_status' do
    let(:project_status_data) do
      {
        new_project: { class: 'label label-default', value: 0 },
        ready: { class: 'label label-info', value: 1 },
        in_progress: { class: 'label label-success', value: 2 },
        abandoned: { class: 'label label-warning', value: 3 },
        completed: { class: 'label label-primary', value: 4 }
      }.with_indifferent_access
    end

    it 'should properly format the text' do
      project_status_data.each do |status, data|
        project = build :project, project_status: data['value']
        expect(project.decorate.html_status).to match(/#{status.to_s.tr('_', ' ')}/)
      end
    end

    it 'should have the correct element and class' do
      project_status_data.each do |_status, data|
        project = build :project, project_status: data['value']
        expect(project.decorate.html_status).to have_css(
          "div.#{data[:class].tr(' ', '.')}"
        )
      end
    end
  end

  describe '#html_visibility' do
    context 'project is private' do
      let(:project) { build :project, public: false }
      it 'should have the correct text' do
        expect(project.decorate.html_visibility).to match(/Private/)
      end
      it 'should have the correct element and class' do
        expect(project.decorate.html_visibility).to have_css(
          'div.label-warning'
        )
      end
    end

    context 'project is public' do
      let(:project) { build :project, public: true }
      it 'should have the correct text' do
        expect(project.decorate.html_visibility).to match(/Public/)
      end
      it 'should have the correct element and class' do
        expect(project.decorate.html_visibility).to have_css(
          'div.label-success'
        )
      end
    end
  end
end


text:
package nl.ru.cs.ecalogic
package parser

import ast._
import util.{DefaultErrorHandler, ErrorHandler}
import ModelLexer.Tokens

import scala.io.Source

import java.io.File

class ModelParser(input: String, _errorHandler: ErrorHandler = new DefaultErrorHandler()) extends Parser(input, _errorHandler) {
  import ModelParser.First

  override protected val lexer = new ModelLexer(input)

  def numeral(follows: Pattern): BigInt = expect(Tokens.Numeral, BigInt(0))(follows)

  def component(follows: Pattern = Pattern.empty): Component = {
    val imps = parseSequenceOf(import_(Tokens.Class), Tokens.Import % "<import declaration>")(follows)

    nodeWithPosition {
      expect(Tokens.Component)(follows | Tokens.Identifier)
      val name = identifier(follows | Tokens.LParen)
      val variablesBuilder = Map.newBuilder[String, CompVarDecl]
      if (current(Tokens.LParen)) {
        do {
          advance()
          val varPos = position

          val varName = identifier(follows | Tokens.Colon)
          expect(Tokens.Colon)(follows | Tokens.Numeral)
          val (lower, upper) = range(follows | Tokens.Comma | Tokens.RParen)

          variablesBuilder += varName -> CompVarDecl(varName, lower, upper, None).withPosition(varPos)
        } while(current(Tokens.Comma))
        expect(Tokens.RParen)(follows | First.member | Tokens.End)
      }
      val definitions = parseSequenceOf(member, First.member)(follows | Tokens.End)
      expect(Tokens.End)(follows | Tokens.Component)
      expect(Tokens.Component)(follows)

      val imports            = checkSeqToMap(imps)(_.alias, "Import for")
      val initializers       = checkSeqToMap(definitions.collect { case i: Initializer => i })(_.name, "Initializer for")
      val componentFunctions = checkSeqToMap(definitions.collect { case c: CompFunDef  => c })(_.name, "Component function")
      val functions          = checkSeqToMap(definitions.collect { case f: FunDef      => f })(_.name, "Local function")

      val variables = variablesBuilder.result().mapValues {
        case CompVarDecl(name, lower, upper, initialValue) if initializers.contains(name) =>
          CompVarDecl(name, lower, upper, Some(initializers(name)))
        case v => v
      }

      (initializers.keySet &~ variables.keySet).foreach { v =>
        errorHandler.error(new ECAException(s"Undeclared component variable: '$v'.", initializers(v)))
      }

      Component(name, imports, variables, componentFunctions, functions)
    }
  }

  def range(follows: Pattern): (BigInt, BigInt) = {
    val lower = numeral(follows | Tokens.PeriodPeriod)
    expect(Tokens.PeriodPeriod)(follows | Tokens.Numeral)
    val upper = numeral(follows)

    (lower, upper)
  }

  def member(follows: Pattern) = tryParse[ASTNode](First.member)(follows) {
    case Tokens.Initial =>
      advance()
      val name = identifier(follows | Tokens.Assign)
      expect(Tokens.Assign)(follows | Tokens.Numeral)
      val value = literal(follows)

      Initializer(name, value)
    case Tokens.Component =>
      componentFunDef(follows)

    case Tokens.Function =>
      funDef(follows)
  }

  def componentFunDef(follows: Pattern): CompFunDef = nodeWithPosition {
    expect(Tokens.Component)(follows | Tokens.Function)
    expect(Tokens.Function)(follows | Tokens.Identifier)
    val name = identifier(follows | Tokens.LParen)
    val params = parameters(follows | Tokens.Uses | Tokens.Identifier)

    var time   = BigInt(0)
    var energy = BigInt(0)
    if (current(Tokens.Uses)) {
      advance()
      val n = numeral(follows | Tokens.Energy | Tokens.Time)

      tryParse(_ => unexpected(Tokens.Time | Tokens.Energy))(follows | Tokens.Identifier) {
        case Tokens.Energy =>
          advance()
          energy = n
          if (current(Tokens.Numeral)) {
            time = numeral(follows | Tokens.Time)
            expect(Tokens.Time)(follows | Tokens.Identifier)
          }
        case Tokens.Time =>
          advance()
          time = n
          if (current(Tokens.Numeral)) {
            energy = numeral(follows | Tokens.Energy)
            expect(Tokens.Energy)(follows | Tokens.Identifier)
          }
      }
    }

    val body = funBody(name)(follows)

    CompFunDef(name, params, energy, time, body)
  }

  override protected def bound(follows: Pattern) = None

  override protected def expRightExpr(follows: Pattern) = primary(follows)
  override protected def divRightExpr(follows: Pattern) = expExpr(follows)

}

object ModelParser {

  object First {

    val member =
      Tokens.Initial    % "<initial value definition>"      |
      Tokens.Component  % "<component function definition>" |
      Tokens.Function   % "<local function definition>"

  }

  def main(args: Array[String]) {
    import scala.util.control.Exception._

    val file = new File(args.headOption.getOrElse(sys.error("Missing argument.")))
    val source = Source.fromFile(file).mkString
    val errorHandler = new DefaultErrorHandler(sourceText = Some(source), sourceURI = Some(file.toURI))
    val parser = new ModelParser(source, errorHandler)
    val model = catching(classOf[ECAException]).opt(parser.component()).filterNot(_ => errorHandler.errorOccurred)
    println(model.getOrElse(sys.exit(1)))
  }

}


text:
<?php
namespace ConfigTree\Test\ReadingFiles;

use ConfigTree\FileParsing\ArrayableFileFactory;
use PHPUnit_Framework_TestCase as TestCase;

class ReadingVariousFileFormatTest extends TestCase
{
    /**
     * @dataProvider provideFilenames
     *
     * @param string $filename
     * @param string $errorMessage
     */
    public function testReadingFileContents($filename, $errorMessage)
    {
        // ARRANGE
        $arrayableFileFactory = new ArrayableFileFactory();
        $arrayableFile = $arrayableFileFactory->getArrayableFileFromPath(
            TEST_DIR . '/fixtures/file_formats/' . $filename
        );
        $expectedArray = ['node1' => ['node2' => 'value']];

        // ACT
        $arrayReadFromFile = $arrayableFile->toArray();

        // ASSERT
        $this->assertEquals($expectedArray, $arrayReadFromFile, $errorMessage);
    }

    public function provideFilenames()
    {
        return [
            ['config.ini',  'Error parsing .ini config file'],
            ['config.json', 'Error parsing .json config file'],
            ['config.php',  'Error parsing .php config file'],
            ['config.yml',  'Error parsing .yml config file'],
        ];
    }
}


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

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" href="docgen-resources/docgen.css" type="text/css">
  <meta name="generator" content="FreeMarker Docgen (DocBook 5)">
  <title>
    FreeMarker Manual - Charset issues
  </title>

        You are here:
          FreeMarker Manual
            >
          Programmer's Guide
            >
          Miscellaneous
            >
          Charset issues

Bookmarks:
Alpha. index, Expressions, ?builtins, #directives, .spec_vars, FAQ, Glossary, API, Home

Next page: Multithreading

Previous page

Parent page

Contents

Charset issues

            Page Contents

Intro.

        The charset of the input

        The charset of the output

FreeMarker, as most Java applications, works with "UNICODE text" (UTF-16). Nonetheless,
        there are situations when it must deal with charsets, because it has to exchange
        data with the outer world that may uses various other charsets.

The charset of the input

When FreeMarker has to load a template file (or an unparsed
          text file), then it must know the charset of the file, since files
          are just raw byte sequences. You can use the
          <tt style="color: #A03D10">encoding</tt> setting to specify the
          charset. This setting takes effect only when FreeMarker loads a
          template (parsed or unparsed) with the
          <tt style="color: #A03D10">getTemplate</tt> method of
          <tt style="color: #A03D10">Configuration</tt>. Note that the <tt>include</tt>
          directive uses this method internally, so the value of the
          <tt style="color: #A03D10">encoding</tt> setting is significant for an already
          loaded template if the template contains <tt style="color: #A03D10">include</tt>
          directive call.

The getter and setter method of the
          <tt style="color: #A03D10">encoding</tt> setting is special in the first
          (configuration) layer. The getter method guesses the return value
          based on a <tt style="color: #A03D10">Locale</tt> passed as parameter; it looks
          up the encoding in a table that maps locales to encodings (called
          encoding map), and if the locale was not found there, it returns the
          default encoding. You can fill the encoding map with the
          <tt style="color: #A03D10">setEncoding(Locale locale, String encoding)</tt>
          method of the configuration; the encoding map is initially empty.
          The default encoding is initially the value of the
          <tt style="color: #A03D10">file.encoding</tt> system property, but you always
          should set a default default with the
          <tt style="color: #A03D10">setDefaultEncoding</tt> method, rather than relying on
          that. For new projects, a popular default encoding is
          <tt style="color: #A03D10">utf-8</tt>.

You can give the charset directly by overriding the
          <tt style="color: #A03D10">encoding</tt> setting in the template layer or runtime
          environment layer (When you specify an encoding as the parameter of
          <tt style="color: #A03D10">getTemplate</tt> method, you override the
          <tt style="color: #A03D10">encoding</tt> setting in the template layer.). If you
          don't override it, the effective value will be what the
          <tt style="color: #A03D10">configuration.getEncoding(Locale)</tt> method returns
          for the effective value of the <tt style="color: #A03D10">locale</tt>
          setting.

Also, instead of relying on this charset guessing mechanism,
          you can specify the charset of the template in the template file
          itself, with the <tt>ftl</tt>
          directive, like <tt style="color: #A03D10"><#ftl
          encoding="utf-8"></tt>.

Note that the charset of the template is independent from the
          charset of the output that the tempalte generates (unless the
          enclosing software deliberately sets the output charset to the same
          as the template charset).

The charset of the output

Note

The <tt style="color: #A03D10">output_encoding</tt> setting/variable and
            the <tt>url</tt>
            built-in is available since FreeMarker 2.3.1. It doesn't
            exist in 2.3.

In principle FreeMarker does not deal with the charset
          of the output, since it writes the output to a
          <tt style="color: #A03D10">java.io.Writer</tt>. Since the
          <tt style="color: #A03D10">Writer</tt> is made by the software that encapsulates
          FreeMarker (such as a Web application framework), the output charset
          is controlled by the encapsulating software. Still, FreeMarker has a
          setting called <tt style="color: #A03D10">output_encoding</tt> (starting from
          FreeMarker version 2.3.1). The enclosing software should set this
          setting (to the charset that the <tt style="color: #A03D10">Writer</tt> uses), to
          inform FreeMarker what charset is used for the output (otherwise
          FreeMarker can't find it out). Some features, such as the <tt>url</tt> built-in,
          and the <tt>output_encoding</tt> special
          variable utilize this information. Thus, if the enclosing
          software doesn't set this setting then FreeMarker features that need
          to know the output charset can't be used.

If you write software that will use FreeMarker, you may wonder
          what output charset should you choose. Of course it depends on the
          consumer of the FreeMarker output, but if the consumer is flexible
          regarding this question, then the common practice is either using
          the charset of the template file for the output, or using UTF-8.
          Using UTF-8 is usually a better practice, because arbitrary text may
          comes from the data-model, which then possibly contains characters
          that couldn't be encoded with the charset of the template.

FreeMarker settings can be set for each individual template
          processing if you use
          <tt style="color: #A03D10">Template.createProcessingEnvironment(...)</tt>
          plus
          <tt style="color: #A03D10">Environment.process(...)</tt>
          instead of
          <tt style="color: #A03D10">Template.process(...)</tt>.
          Thus, you can set the <tt style="color: #A03D10">output_encoding</tt> setting for
          each template execution independently:

Writer w = new OutputStreamWriter(out, outputCharset);
Environment env = template.createProcessingEnvironment(dataModel, w);
env.setOutputEncoding(outputCharset);
env.process();

Next page: Multithreading

Previous page

Parent page

Contents

        You are here:
          FreeMarker Manual
            >
          Programmer's Guide
            >
          Miscellaneous
            >
          Charset issues

            FreeMarker Manual -- For FreeMarker 2.3.21

          HTML generated: 2014-10-12 18:53:30 GMT


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Class: Zlib::Fixnum</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />

  Class
Zlib::Fixnum

        In:

lib/zliby.rb

      Parent:

Object

Add a helper method to check bits

Methods

isbitset?

Public Instance methods

    isbitset?(bit_to_check)

[ show source ]

# File lib/zliby.rb, line 539
        def isbitset? bit_to_check
                if self & (2 ** bit_to_check)  == (2 ** bit_to_check) then true else false end
        end


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var numero_service_1 = require('./numero-service');
var numeroComponente = (function () {
    function numeroComponente(promesanumerosdelticket) {
        this.promesanumerosdelticket = promesanumerosdelticket;
    }
    numeroComponente.prototype.soltarNumerosDeTickets = function () {
        var _this = this;
        this.promesanumerosdelticket.agarrarMensajesDeNumero()
            .then(function (value) {
            _this.numeroList = value; //pasando los datos del json para enlistar
        }).catch(function (error) {
            console.log('es un error');
        });
    };
    numeroComponente.prototype.ngOnInit = function () {
        this.soltarNumerosDeTickets();
    };
    numeroComponente = __decorate([
        core_1.Component({
            selector: 'componente-de-numero',
            providers: [numero_service_1.PromesaNumerosDelTicket],
            styleUrls: ['../../public/pages/numero.style.scss'],
            template: "\n\n

{{x.puesto}}

\n\n    "
        }),
        __metadata('design:paramtypes', [numero_service_1.PromesaNumerosDelTicket])
    ], numeroComponente);
    return numeroComponente;
}());
exports.numeroComponente = numeroComponente;
//# sourceMappingURL=numero.componente.js.map