text:
struct HomeStatus
{
    enum HomeStatusEnum
    {
        Home,
        Away,
        Reset
    };
};

class BlindSwitch
{
    public:
        // ctor.
        BlindSwitch(SwitchSchedulerConfiguration*, SparkTime*);

        // Method that configures the initial state of the app. This method
        // assumes that the parameters have been configured previously.
        void initialize();

        void addSchedule(SwitchSchedulerTask*);

        // Initailize the pin used to control the outlet switch.
        void setOutletSwitchPin(int pin);

        void tick();

        // Initialize when teh app turns on the outlet switch.
        // void setOutletSwitchOnTime(String timeString);

        // Initalize when the app turns off the outlet switch.
        // void setOutletSwitchOffTime(String timeString);

        // Gets the current state of the app and sets the string variable
        // passed in to the method.
        const char* getCurrentState();

        // Accepts a JSON string and parses out configuration options that
        // can be set remotely. See configKeys for a list of settings that
        // can be configured.
        int configureHandler(String command);

        // Check to see if the outlet switch needs to be turned on. If so,
        // turn it on!
        // void toggleOutletSwitchOn();

        // Check ot see if the outlet switch needs to be turned off. If so,
        // turn it off!
        // void toggleOutletSwitchOff();

        // Toggle the outlet switch on or off based on the parameter. True
        // for on, false otherwise.
        void toggleOutletSwitch(bool isEnabled);

        // Get the current state of the outlet switch. True for on, false
        // otherwise.
        bool getOutletSwitchState();

        // Checks to see if the outlet switch should be toggled on.
        // bool shouldOutletSwitchBeEnabled();

        void schedulerCallback(SwitchSchedulerEvent::SwitchSchedulerEventEnum);
    private:
        SwitchScheduler* scheduler;
        SparkTime* rtc;

        // Reference to SparkTime. Mostly using it just for the DST testing
        // capabilities.
        // SparkTime rtc;

        // The timezone offset for the device.
        // int timezoneOffset;

        // The time that the sunset will occur for today.
        // time_t sunsetTime;

        // The last time the outlet switch was set to on.
        // time_t lastToggleOutletSwitchOnTime;

        // The last time the outlet switch was set to off.
        // time_t lastToggleOutletSwitchOffTime;

        // // The last time the sunset API was checked.
        // time_t lastSunsetApiCheckTime;

        time_t lastToggleOutletSwitchTime;

        // When the app checks for sunset data.
        // String sunsetApiCheckTime;

        // When the app turns on the outlet switch.
        // String outletSwitchOnTime;

        // When the app turns off the outlet switch.
        // String outletSwitchOffTime;

        // Pin used to control whether the outlet switch is enabled or not.
        int outletSwitchPin;

        // The current state of the outlet switch.
        bool outletSwitchState;

        // Weather API url strings.
        // String weatherApiBaseUrl;
        // String sunsetApiUrl;

        // Used by the code to pull out the right configuration key from
        // the configKeys string array.
        struct BlindSwitchConfig
        {
            enum BlindSwitchConfigEnum
            {
                IsToggled = 0,
                // TimezoneOffset,
                SunsetApiUrl,
                SunsetApiCheckTime,
                IsSchedulerEnabled,
                IsHomeOnlyModeEnabled,
                HomeStatus,
                MobileId
                // OutletSwitchOffTime
            };
        };

        // Configuration keys for the JSON object used to configure settings
        // remotely.
        const char* configKeys[8] =
        {
            "IsToggled",
            // "TimezoneOffset",
            "SunsetApiUrl",
            "SunsetApiCheckTime",
            "IsSchedulerEnabled",
            "IsHomeOnlyModeEnabled",
            "HomeStatus",
            "MobileId"
            // "OutletSwitchOffTime"
        };

        // True if the app should turn on the outlet switch by using the
        // sunset time or if it should use a time specified by the
        // configuration.
        // bool useSunsetOnTime();

        // Gets the switch off time as a Unix timestamp.
        // time_t getOutletSwitchOffTime();

        // Gets the switch on time as a Unix timestamp.
        // time_t getOutletSwitchOnTime();
};


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fr.esecure.banking.metier;

import fr.esecure.banking.modele.client.entities.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static junit.framework.Assert.assertNotNull;
import org.junit.Assert;

/**
 *
 * @author sniang
 */
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = {"classpath:test-metier-config.xml"})
@ContextConfiguration(locations = {"file:src/test/resources/test-metier-config.xml"})
public class TestMetier {

    public TestMetier() {
    }

    @Autowired
    IEsecureMetier metier;
    public Long idUserCreated = 0L;

    User userTest=null;

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
     userTest=createUser();
    }

    @After
    public void tearDown() {
        if(userTest != null && userTest.getIdUser() != null){
            metier.delete(userTest.getIdUser(), User.class);
        }
    }

    @Test
    public void save_delete_remove() {
        //Création d'un nouveau compte et initialisation des variables
        Compte cpt = new Compte();
        cpt.setDateCreation();
        cpt.setEtatCompte(1);
        cpt.setLogin("loginTest2");
        cpt.setPassword("password2");

        //Création d'un compte rendu
        CompteRendu cr = new CompteRendu(new Date(), "le compte rendu bis", "ok");
        //creation d'un nouveau utilisateur par une initialisation via controlleur
        User newUser = createUser();
        newUser.setCompte(cpt);
       // assertNotNull(metier.saveObject(newUser));
      //Creéation de la liste des adresses
        List<Adresse> adresses = new ArrayList<Adresse>();
        //Adresse adresse = new Adresse(24, "bayonne", "chemin d'aranchette", 3, 301);
       // Adresse adresse1 = new Adresse(1, "Toulouse", "Impasse andré", 2, 216);
       // adresses.add(adresse);
       // adresses.add(adresse1);

        //Banque banque = new Banque("12", adresse.toString(),null, null);

      //  ParamAcces param = new ParamAcces("localhost", 80, "127.0.0.1", "admin", "admin",banque );

        AccuseReception accuse = new AccuseReception(new Date(), "transaction passée avec succés", "ok");

        CompteRendu compteRendu = new CompteRendu(new Date(), "c'est bon", "ok");

        InfoFormulaire infoFormulaire = new InfoFormulaire("seydou", "niang", "123456", "1245 1234 2530", "douseyi@live.com", "24", "medina centre", "appartement", "le cayor","10000", "nioro");

        Client client = new Client("seydou", "oumar", "123456", "douseyi@hotmail.com", adresses);

        CarteBancaire carteBancaire = new CarteBancaire("6452 3214 2314 5623", new Date(), 123, "visa", client);

//        Transaction transaction = new Transaction(2015, 1, new Date(),"EBAY", "www.ebay.com", Transaction.TRANSACTION_STATES.CANCELLED, carteBancaire, adresse);

        //metier.saveObject(transaction);
       // assertNotNull(metier.findAllTransaction());

    }

    @Test
    public void create_new_user() {

        User newUser2 = createUser();
        assertNotNull(newUser2);
        idUserCreated=newUser2.getIdUser();

    }

    private User createUser() {
        if(userTest != null)
            return userTest;
        User newUser2 = new User("esecureTest@gmail.com", 1, "Diom Yero", "SOW", "33669932494");
        newUser2.addRole(new Role("ROLE_ADMIN"));
        newUser2.setUserLogged(0);
        newUser2 = (User) metier.createNewUserAccount(newUser2);
        return newUser2;
    }

   // @Test
    public void is_user_with_email_exist() {
        User newUser2 = createUser();
        boolean isOk=metier.isUserWithEmailExist(newUser2.getUserMail());
        System.out.println("Valeur de la methode isUserWithEmailExist "+isOk);
        Compte u = metier.getAccountWithLoginExist(newUser2.getCompte().getLogin());
        System.out.println("Valeur de retour la methode getAccountWithLoginExist "+u.getLogin());
        Assert.assertTrue(isOk);

    }

   // @Test
    public void is_compte_with_login_exist() {
        User newUser2 = createUser();
        Assert.assertTrue(metier.isAccountWithLoginExist(newUser2.getCompte().getLogin()));
    }

}

redpajama_set_name: RedPajamaGithub


text:
package dev.nick.tiles.tile;

import android.content.Context;
import android.support.annotation.NonNull;

public abstract class QuickTile extends Tile {

    private Context mContext;
    private TileListener mListener;

    public QuickTile(@NonNull Context context, TileListener listener) {
        mContext = context;
        mListener = listener;
    }

    public Context getContext() {
        return mContext;
    }

    TileListener getListener() {
        return mListener;
    }

    public void setEnabled(boolean enabled) {
        if (getTileView() != null)
            getTileView().setEnabled(enabled);
    }
}


text:
namespace mojo {
class View;
}

namespace html_viewer {

class HTMLDocument;
class HTMLFrameTreeManager;
class GlobalState;

// DocumentResourceWaiter waits for the necessary resources needed to load an
// HTMLDocument. Once ready it calls to HTMLDocument::Load(). Once ready it is
// assumed HTMLDocument will call back for the FrameTreeClient and FrameData.
class DocumentResourceWaiter : public web_view::FrameTreeClient,
                               public HTMLFrameTreeManagerObserver,
                               public mojo::ViewObserver {
 public:
  DocumentResourceWaiter(GlobalState* global_state,
                         mojo::URLResponsePtr response,
                         HTMLDocument* document);
  ~DocumentResourceWaiter() override;

  // Releases all the resources that have been accumulated.
  void Release(mojo::InterfaceRequest<web_view::FrameTreeClient>*
                   frame_tree_client_request,
               web_view::FrameTreeServerPtr* frame_tree_server,
               mojo::Array<web_view::FrameDataPtr>* frame_data,
               uint32_t* view_id,
               uint32_t* change_id,
               web_view::ViewConnectType* view_connect_type,
               OnConnectCallback* on_connect_callback);

  uint32_t change_id() const { return change_id_; }

  mojo::URLResponsePtr ReleaseURLResponse();

  // See class description.
  bool is_ready() const { return is_ready_; }

  void SetRoot(mojo::View* root);
  mojo::View* root() { return root_; }

  void Bind(mojo::InterfaceRequest<web_view::FrameTreeClient> request);

 private:
  // Updates |is_ready_|, and if ready starts the Load() in the document.
  void UpdateIsReady();

  // web_view::FrameTreeClient:
  void OnConnect(web_view::FrameTreeServerPtr server,
                 uint32_t change_id,
                 uint32_t view_id,
                 web_view::ViewConnectType view_connect_type,
                 mojo::Array<web_view::FrameDataPtr> frame_data,
                 const OnConnectCallback& callback) override;
  void OnFrameAdded(uint32_t change_id,
                    web_view::FrameDataPtr frame_data) override;
  void OnFrameRemoved(uint32_t change_id, uint32_t frame_id) override;
  void OnFrameClientPropertyChanged(uint32_t frame_id,
                                    const mojo::String& name,
                                    mojo::Array<uint8_t> new_value) override;
  void OnPostMessageEvent(uint32_t source_frame_id,
                          uint32_t target_frame_id,
                          web_view::HTMLMessageEventPtr event) override;
  void OnWillNavigate(uint32_t target_frame_id) override;

  // ViewObserver:
  void OnViewViewportMetricsChanged(
      mojo::View* view,
      const mojo::ViewportMetrics& old_metrics,
      const mojo::ViewportMetrics& new_metrics) override;
  void OnViewDestroyed(mojo::View* view) override;

  // HTMLFrameTreeManagerObserver:
  void OnHTMLFrameTreeManagerChangeIdAdvanced() override;
  void OnHTMLFrameTreeManagerDestroyed() override;

  GlobalState* global_state_;
  HTMLDocument* document_;
  mojo::URLResponsePtr response_;
  mojo::View* root_;
  web_view::FrameTreeServerPtr server_;
  mojo::Array<web_view::FrameDataPtr> frame_data_;
  uint32_t change_id_;
  uint32_t view_id_;
  web_view::ViewConnectType view_connect_type_;
  OnConnectCallback on_connect_callback_;

  // Once we get OnConnect() we unbind |frame_tree_client_binding_| and put it
  // here.
  mojo::InterfaceRequest<web_view::FrameTreeClient> frame_tree_client_request_;
  mojo::Binding<web_view::FrameTreeClient> frame_tree_client_binding_;

  bool is_ready_;

  // See comments in UpdateIsReady() for details of this.
  //
  // While |waiting_for_change_id_| is true DocumentResourceWaiter is an
  // HTMLFrameTreeManagerObserver on |target_frame_tree_|.
  bool waiting_for_change_id_;

  HTMLFrameTreeManager* target_frame_tree_;

  DISALLOW_COPY_AND_ASSIGN(DocumentResourceWaiter);
};

}  // namespace html_viewer

#endif  // COMPONENTS_HTML_VIEWER_DOCUMENT_RESOURCE_WAITER_H_


text:
from django.core.urlresolvers import get_mod_func
from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponsePermanentRedirect
from django.conf import settings
from django.template import RequestContext
from mako.exceptions import TopLevelLookupException, html_error_template
from mako.lookup import TemplateLookup
import os, os.path, re, mimetypes, importlib
import urllib.request, urllib.parse, urllib.error

# set up the logger
import logging
log = logging.getLogger('django')

##############################################################
###   The front controller of all views on the site.
###   urls.py routes everything through this method.

def route_request(request):
    '''The main router for all calls coming in to the system.'''
    # output the variables so the programmer can debug where this is routing
    log.debug('base_app.controller.py :: HtmlPageServer processing: app=%s, page=%s, funcname=%s, urlparams=%s' % (request.controller_app, request.controller_page, request.controller_funcname, request.urlparams))

    # first try going to the view function for this request
    # we look for a views/name.py file where name is the same name as the HTML file
    response = None
    request.controller_view_function = 'process_request%s' % (request.controller_funcname)
    request.controller_view_module = '.'.join([ request.controller_app, 'views', request.controller_page ])

    # this next line assumes that base_app.controller.py is one level below the settings.py file (hence the '..')
    full_module_filename = os.path.normpath(os.path.join(settings.BASE_DIR, request.controller_view_module.replace('.', '/') + '.py'))
    while True:
      try:
        # look for the module
        if os.path.exists(full_module_filename):
          module_obj = importlib.import_module(request.controller_view_module)
          if hasattr(module_obj, request.controller_view_function):
            log.debug('base_app.controller.py :: calling view function %s.%s' % (request.controller_view_module, request.controller_view_function))
            try:
              response = getattr(module_obj, request.controller_view_function)(request)
            except RedirectException as e: # redirect to another page
              log.debug('base_app.controller.py :: view function %s.%s redirected processing to %s' % (request.controller_view_module, request.controller_view_function, e.redirect_to))
              if e.permanent:
                return HttpResponsePermanentRedirect(e.redirect_to)
              return HttpResponseRedirect(e.redirect_to)
          else:
            log.debug('base_app.controller.py :: view function %s not in module %s; returning 404 not found' % (request.controller_view_function, request.controller_view_module))
            raise Http404
        else:
          log.debug('base_app.controller.py :: module %s not found; sending processing directly to the template' % (request.controller_view_module))
        break
      except InternalViewRedirectException as ivr:
        request.controller_view_module = ivr.redirect_module
        request.controller_view_function = ivr.redirect_function
        full_module_filename = os.path.normpath(os.path.join(settings.BASE_DIR, request.controller_view_module.replace('.', '/') + '.py'))
        log.debug('base_app.controller.py :: received an InternalViewRedirect to %s -> %s' % (full_module_filename, request.controller_view_function))

    # if we get here, a matching view wasn't found; look for a matching template
    if response == None and request.controller_app in TEMPLATE_RENDERERS:
        response = TEMPLATE_RENDERERS[request.controller_app].render_to_response(request, '%s.html' % request.controller_page)

    # return the response
    if response == None:
      raise Http404

    return response

###############################################################
###   Exceptions used to direct the base_app.controller

class InternalViewRedirectException(Exception):
  '''View functions can throw this exception to indicate that a new view
     should be called by the HtmlPageServer.  The current view function
     will end immediately, and processing will be passed to the new view function.
  '''
  def __init__(self, redirect_module, redirect_function):
    '''Indicates the new view to be called.  The view should be given relative to the project root.'''
    super().__init__()
    self.redirect_module = redirect_module
    self.redirect_function = redirect_function

class TemplateException(Exception):
  '''A template exception while rendering Mako templates'''
  def __init__(self, error, message):
    self.error = error
    Exception.__init__(self, message)

class RedirectException(Exception):
  '''Immediately stops processing of a view function or template and redirects to the given page.
     Note that this exception only works when urls.py routes the call through the classes in this
     module.  Django should have shipped with this one.  Perhaps it takes a little too much liberty
     with exceptions, but it makes returning from a huge call stack really nice.'''
  def __init__(self, redirect_to, permanent=False):
    self.redirect_to = redirect_to
    self.permanent = permanent

##############################################################
###   Renders Mako templates

class MakoTemplateRenderer:
  '''Renders Mako templates.  Note that the following defaults are used:
       templates_dir  => project_path/app_path/templates/  (assuming settings.base_app.controller_TEMPLATES_DIR is set to 'templates')
       cache_dir      => project_path/template_cache/      (assuming settings.MAKO_TEMPLATES_CACHE_DIR is set to 'template_cache/applications/)
       cache_size     => 2000
  '''
  def __init__(self, app_path, template_subdir='templates'):
    '''Creates a renderer to the given path (relateive to the project root where settings.STATIC_ROOT points to)'''
    project_path = os.path.normpath(settings.BASE_DIR)
    self.app_path = app_path
    self.template_search_dirs = [ os.path.abspath(os.path.join(project_path, self.app_path, template_subdir)) ] + settings.MAKO_TEMPLATES_DIRS
    self.cache_root = os.path.abspath(os.path.join(project_path, app_path, settings.MAKO_TEMPLATES_CACHE_DIR, template_subdir))
    self.tlookup = TemplateLookup(directories=self.template_search_dirs, imports=settings.MAKO_DEFAULT_TEMPLATE_IMPORTS, module_directory=self.cache_root, collection_size=2000, filesystem_checks=settings.DEBUG)

  def render(self, request, template, params={}):
    '''Runs a template and returns a string.  Normally, you probably want to call render_to_response instead
       because it gives a full HttpResponse or Http404.

       This method raises a TopLevelLookupException if the template is not found.

       @request  The context request from Django
       @template The template file path to render.  This is relative to the app_path/base_app.controller_TEMPLATES_DIR/ directory.
                 For example, to render app_path/templates/page1, set template="page1.html", assuming you have
                 set up the variables as described in the documentation above.
       @params   A dictionary of name=value variables to send to the template page.

    '''
    # Django's RequestContext automatically runs all the TEMPLATE_CONTEXT_PROCESSORS and populates with variables
    context = RequestContext(request, params)
    context_dict = { 'request': request, 'settings': settings }  # this allows the template to access the request
    # must convert the request context to a real dict to use the ** below
    for d in context:
      context_dict.update(d)
    # render the response with the given template and params
    template_obj = self.tlookup.get_template(template)
    if not hasattr(template_obj, 'template_path'):
      template_obj.template_path = template
    if not hasattr(template_obj, 'template_full_path'):
      template_obj.template_full_path = template_obj.filename
    if not hasattr(template_obj, 'mako_template_renderer'):  # if the first time, add a reference to this renderer object
      template_obj.mako_template_renderer = self
    log.debug('base_app.controller.py :: rendering template %s' % template_obj.filename)
    if settings.DEBUG:
      try:
        return template_obj.render_unicode(**context_dict)
      except:
        return html_error_template().render_unicode()
    else:
      return template_obj.render_unicode(**context_dict)

  def render_to_response(self, request, template, params={}):
    '''Runs a template and returns an HttpRequest object to it.

       @request  The context request from Django
       @template The template file path to render.  This is relative to the app_path/base_app.controller_TEMPLATES_DIR/ directory.
                 For example, to render app_path/templates/page1, set template="page1.html", assuming you have
                 set up the variables as described in the documentation above.
       @params   A dictionary of name=value variables to send to the template page.
    '''
    try:
      content_type = mimetypes.types_map.get(os.path.splitext(template)[1].lower(), 'text/html')
      content = self.render(request, template, params)
      return HttpResponse(content.encode(settings.DEFAULT_CHARSET), content_type='%s; charset=%s' % (content_type, settings.DEFAULT_CHARSET))
    except TopLevelLookupException: # template file not found
      log.debug('base_app.controller.py :: template "%s" not found in search path: %s.' % (template, self.template_search_dirs))
      raise Http404()
    except RedirectException as e: # redirect to another page
      if e.permanent:
        return HttpResponsePermanentRedirect(e.redirect_to)
      return HttpResponseRedirect(e.redirect_to)

# these are the apps we can render templates for - it is used in route_request at the top
TEMPLATE_RENDERERS = {}
for appname in settings.MAKO_ENABLED_APPS:
  TEMPLATE_RENDERERS[appname] = MakoTemplateRenderer(appname)

##########################################################
###   Middleware the prepares the request for
###   use with the base_app.controller

class RequestInitMiddleware:
  '''Adds several fields to the request that our base_app.controller needs.

     This class MUST be included in settings.py -> MIDDLEWARE_CLASSES.
  '''

  def process_request(self, request):
    '''Called for each browser request.  This adds the following fields to the request object:

       request.controller_app       The Django application (such as "calculator").
       request.controller_page      The view module (such as "calc" for calc.py).
       request.controller_funcname  The function within the view module to be called (usually "process_request").
       request.urlparams            A list of the remaining url parts (see the calc.py example).
    '''
    # split the path
    path_parts = request.path[1:].split('/') # [1:] to remove the leading /

    # get the app
    if len(path_parts) >= 1 and path_parts[0] == '':  # app specified by empty, so revert to default app
      path_parts[0] = settings.MAKO_DEFAULT_APP
    elif len(path_parts) < 1 or path_parts[0] not in settings.MAKO_ENABLED_APPS:  # app not specified, or invalid app, so insert the default app into the path_parts
      path_parts.insert(0, settings.MAKO_DEFAULT_APP)
    request.controller_app = path_parts[0]

    # get the page
    if len(path_parts) < 2:  # page not specified, so insert the default page into the path_parts (we'll validate later in the controller)
      path_parts.insert(1, settings.MAKO_DEFAULT_PAGE)
    elif path_parts[1] == '':  # page specified by empty
      path_parts[1] = settings.MAKO_DEFAULT_PAGE
    request.controller_page = path_parts[1]

    # see if a function is specified with the page (the __ separates a function name)
    du_pos = request.controller_page.find('__')
    if du_pos < 0:
      request.controller_funcname = ''
    else:
      request.controller_funcname = request.controller_page[du_pos:]
      request.controller_page = request.controller_page[:du_pos]

    # set up the urlparams with the reamining path parts
    request.urlparams = URLParamList([ urllib.parse.unquote_plus(s) for s in path_parts[2:] ])

class URLParamList(list):
  '''A simple extension to Python's list that returns '' for indices that don't exist.
     For example, if the object is ['a', 'b'] and you call obj[5], it will return ''
     rather than throwing an IndexError.  This makes dealing with url parameters
     simpler since you don't have to check the length of the list.'''
  def __getitem__(self, idx):
    '''Returns the element at idx, or '' if idx is beyond the length of the list'''
    # if the index is beyond the length of the list, return ''
    if isinstance(idx, int) and (idx >= len(self) or idx < -1 * len(self)):
      return ''
    # else do the regular list function (for int, splice types, etc.)
    return list.__getitem__(self, idx)


text:
export class NavFooter{
	constructor(){
		this.currentYear = new Date().getFullYear();
	}

}


text:
package org.menacheri.jetserver.service;

import org.menacheri.jetserver.app.Game;
import org.menacheri.jetserver.app.GameRoom;
import org.menacheri.jetserver.app.Player;
import org.menacheri.jetserver.util.Credentials;

public interface LookupService
{
	/**
	 * Get a game room based on a reference key. This allows the connection
	 * service to connect to a game room of a game.
	 *
	 * @param gameContextKey
	 *            This is the key the flex front end passes to handshake
	 *            service.
	 * @return Returns the game room associated with this key or null if no such
	 *         game room exists.
	 */
	public abstract GameRoom gameRoomLookup(Object gameContextKey);

	/**
	 * Get a game based on a reference key. This allows the player session to
	 * get its associated game.
	 *
	 * @param gameContextKey
	 * @return Returns the game instance based on the key provided. Null if
	 *         invalid key is provided.
	 */
	public abstract Game gameLookup(Object gameContextKey);

	/**
	 * Lookup a gamer based on a context key.
	 *
	 * @param loginDetail Contains the username and password.
	 * @return Returns the gamer instance based on the key provided. Null if
	 *         invalid key is provided.
	 */
	public abstract Player playerLookup(Credentials loginDetail);

}


text:
package org.apache.hadoop.lib.lang;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import org.apache.hadoop.test.HTestCase;
import org.junit.Test;

public class TestXException extends HTestCase {

  public enum TestERROR implements XException.ERROR {
    TC;

    @Override
    public String getTemplate() {
      return "{0}";
    }
  }

  @Test
  public void testXException() throws Exception {
    XException ex = new XException(TestERROR.TC);
    assertEquals(ex.getError(), TestERROR.TC);
    assertEquals(ex.getMessage(), "TC: {0}");
    assertNull(ex.getCause());

    ex = new XException(TestERROR.TC, "msg");
    assertEquals(ex.getError(), TestERROR.TC);
    assertEquals(ex.getMessage(), "TC: msg");
    assertNull(ex.getCause());

    Exception cause = new Exception();
    ex = new XException(TestERROR.TC, cause);
    assertEquals(ex.getError(), TestERROR.TC);
    assertEquals(ex.getMessage(), "TC: " + cause.toString());
    assertEquals(ex.getCause(), cause);

    XException xcause = ex;
    ex = new XException(xcause);
    assertEquals(ex.getError(), TestERROR.TC);
    assertEquals(ex.getMessage(), xcause.getMessage());
    assertEquals(ex.getCause(), xcause);
  }

}


text:
/**
 * Background mechanism classes.
 *
 * @author The eFaps Team
 */
package org.efaps.api.background;


text:
Follow Up Form

	                                  Dashboard

	                                 Follow Up Form

					<form role="form" action="<?php echo base_url()."index.php/SalesAdmin/followup/"?>" method="post" enctype="multipart/form-data" enctype="multipart/form-data">

<?php echo $this->session->flashdata('msg'); ?>

                            Select Customer :
                                   <select class="form-control" name="lead">
                                        <?php foreach($data as $d){ ?>
                                        <option value="<?php echo $d['id_lead']?>"><?php echo $d['id_lead']?> || <?php echo $d['customer']?></option>
                                        <?php } ?>
                                    </select>

                                Follow up date :
                                <input type="date" class="form-control" id="datepick" name="fu_date" required="required">

                                Follow Up Via :
                                <select class="form-control" name="via">
                                <option>Telepon</option>
                                <option>Email</option>
                                <option>Chat</option>
                              </select>

                                PIC
                                <input class="form-control" name="pic">

                                Phone
                                <input class="form-control" name="phone">

                                E-mail
                                <input class="form-control" name="email" type="email">

                                Position
                                <input class="form-control" name="pos">

                                Upload File
								<?php echo form_open_multipart('upload/do_upload');?>
								<?php echo form_upload('document'); ?>

Comment & Question

	                        <textarea id="editor1" class="form-control" name="editor1" rows="10" cols="80" maxlength="255">
							</textarea>

                            <button type="submit" class="btn btn-default">Submit</button>
                            <button type="reset" class="btn btn-default">Reset</button>

                        </form>


text:
package com.leftso.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.util.StringUtils;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

/**
 * mongodb 配置类
 *
 * @author leftso
 *
 */
@Configuration
public class MongoDBConfig {
	@Autowired
	MongoProperty mongoProperties;

	/**
	 * 注入mongodb的工厂类
	 *
	 * @return
	 */
	@Bean
	public MongoDbFactory mongoDbFactory() {
		// uri格式mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
		String mongoURI = "mongodb://" + mongoProperties.getHost();
		if (!StringUtils.isEmpty(mongoProperties.getUser())) {
			mongoURI = "mongodb://" + mongoProperties.getUser() + ":" + mongoProperties.getPwd() + "@"
					+ mongoProperties.getHost();
		}
		// 为了方便实现mongodb多数据库和数据库的负债均衡这里使用url方式创建工厂
		MongoClientURI mongoClientURI = new MongoClientURI(mongoURI);
		MongoClient mongoClient = new MongoClient(mongoClientURI);
		MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, mongoProperties.getName());
		// 注意:以下构造函数已经弃用:
		// SimpleMongoDbFactory(com.mongodb.Mongo mongo, String databaseName);
		// 弃用版本1.7
		// SimpleMongoDbFactory(com.mongodb.Mongo mongo, String databaseName,
		// UserCredentials credentials);弃用版本1.7
		// SimpleMongoDbFactory(com.mongodb.Mongo mongo, String databaseName,
		// UserCredentials credentials, String
		// authenticationDatabaseName);弃用版本1.7
		// SimpleMongoDbFactory(com.mongodb.MongoURI uri);弃用版本1.7
		return mongoDbFactory;
	}

	/**
	 * 获取操作实例
	 *
	 * @param mongoDbFactory
	 * @return
	 */
	@Bean
	public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory) {
		return new MongoTemplate(mongoDbFactory);
	}

}


text:
package client

import (
	"net/url"

	"golang.org/x/net/context"

	"github.com/cockroachdb/cockroach/base"
	"github.com/cockroachdb/cockroach/proto"
	"github.com/cockroachdb/cockroach/util/retry"
)

const (
	// KVDBEndpoint is the URL path prefix which accepts incoming
	// HTTP requests for the KV API.
	KVDBEndpoint = "/kv/db/"
	// StatusTooManyRequests indicates client should retry due to
	// server having too many requests.
	StatusTooManyRequests = 429
)

func init() {
	f := func(u *url.URL, ctx *base.Context, retryOpts retry.Options) (Sender, error) {
		ctx.Insecure = (u.Scheme != "https")
		return newHTTPSender(u.Host, ctx, retryOpts)
	}
	RegisterSender("http", f)
	RegisterSender("https", f)
}

// httpSender is an implementation of Sender which exposes the
// Key-Value database provided by a Cockroach cluster by connecting
// via HTTP to a Cockroach node.
type httpSender struct {
	ctx PostContext
}

// newHTTPSender returns a new instance of httpSender.
func newHTTPSender(server string, ctx *base.Context, retryOpts retry.Options) (*httpSender, error) {
	sender := &httpSender{
		ctx: PostContext{
			Server:    server,
			Endpoint:  KVDBEndpoint,
			Context:   ctx,
			RetryOpts: retryOpts,
		},
	}
	// Ensure that the context returns an HTTPClient.
	if _, err := ctx.GetHTTPClient(); err != nil {
		return nil, err
	}
	return sender, nil
}

// Send sends call to Cockroach via an HTTP post. HTTP response codes
// which are retryable are retried with backoff in a loop using the
// default retry options.
func (s *httpSender) Send(_ context.Context, call proto.Call) {
	if err := HTTPPost(s.ctx, call.Args, call.Reply, call.Method()); err != nil {
		call.Reply.Header().SetGoError(err)
	}
}


text:
title: Development Goodies – Un-bundling a git bundle and Valgrind
author: Brad McCormack
type: post
date: 2012-05-02T10:37:50+00:00
url: /development/development-goodies-un-bundling-a-git-bundle-and-valgrind/
spacious_page_layout:
  - default_layout
dsq_thread_id:
  - 3363635044
categories:
  - Development

---
### Git Bundles

So I've inherited a git bundle. I was trying to unbundle it incorrectly, and after a bit of enlightenment from a collegue I thought it'd be best to note it here for the future and impart some wisdom upon any reader.

The correct syntax to fetch from the bundle for instance is

[code language="bash"]

git fetch name.bundle remotebranchname:localbranchname

[/code]

This will fetch remotebranchname into the local branch "localbranchname" from the bundle aptly named name.bundle.

### Valgrind

If you are a little rusty with lower level languages and managing memory yourself, a tool like Valgrind is invaluable. For a quick overview of how healthy your program is in terms of releasing memory use the following syntax.

[code language="bash"]

valgrind program args

//If you want more detailed information use the following syntax

valgrind –leak–check=full program args

[/code]

Finally, if you'd like to see some information about other errors use the syntax

[code language="bash"]

valgrind -v program args

[/code]

Enjoy 🙂


text:
@interface YR_ArticleDetailUserModel : YR_BaseModel

@property (nonatomic, strong) NSNumber *num_followed;

@property (nonatomic, strong) NSNumber *num_work;

@property (nonatomic, copy) NSString *uid;

@property (nonatomic, copy) NSString *version;

@property (nonatomic, copy) NSString *domain;

@property (nonatomic, copy) NSString *is_del;

@property (nonatomic, copy) NSString *uname;

@property (nonatomic, copy) NSString *rank;

@property (nonatomic, copy) NSString *rank_points;

@property (nonatomic, copy) NSString *cover;

@property (nonatomic, copy) NSString *city;

@property (nonatomic, copy) NSString *role;

@property (nonatomic, copy) NSString *resume;

@property (nonatomic, copy) NSString *is_verfiy;

@end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Spondias acuminata Roxb.

### Remarks
null


text:
import { SET_SYNC_STATE } from '../constants/ActionTypes';

const initialState = {
	text: 'unknown'
};

const syncState = ( state = initialState, action = {} ) => {

	switch ( action.type ) {

		case SET_SYNC_STATE:

			return { text: action.text };

		default:

			return state;

	}

};

export default syncState;


text:
from warnings import warn
from email.Utils import formatdate
from twisted.python import log
from zope.interface import implements
from buildbot.process.buildstep import LoggingBuildStep, LoggedRemoteCommand
from buildbot.interfaces import BuildSlaveTooOldError, IRenderable
from buildbot.status.builder import SKIPPED

class _ComputeRepositoryURL(object):
    implements(IRenderable)

    def __init__(self, repository):
        self.repository = repository

    def getRenderingFor(self, build):
        '''
        Helper function that the repository URL based on the parameter the
        source step took and the Change 'repository' property
        '''

        s = build.getSourceStamp()

        repository = self.repository

        if not repository:
            return str(s.repository)
        else:
            if callable(repository):
                return str(build.render(repository(s.repository)))
            elif isinstance(repository, dict):
                return str(build.render(repository.get(s.repository)))
            elif isinstance(repository, str) or isinstance(repository, unicode):
                try:
                    return str(repository % s.repository)
                except TypeError:
                    # that's the backward compatibility case
                    return build.render(repository)
            else:
                return str(build.render(repository))

class Source(LoggingBuildStep):
    """This is a base class to generate a source tree in the buildslave.
    Each version control system has a specialized subclass, and is expected
    to override __init__ and implement computeSourceRevision() and
    startVC(). The class as a whole builds up the self.args dictionary, then
    starts a LoggedRemoteCommand with those arguments.
    """

    renderables = [ 'workdir' ]

    # if the checkout fails, there's no point in doing anything else
    haltOnFailure = True
    flunkOnFailure = True
    notReally = False

    branch = None # the default branch, should be set in __init__

    def __init__(self, workdir=None, mode='update', alwaysUseLatest=False,
                 timeout=20*60, retry=None, **kwargs):
        """
        @type  workdir: string
        @param workdir: local directory (relative to the Builder's root)
                        where the tree should be placed

        @type  mode: string
        @param mode: the kind of VC operation that is desired:
           - 'update': specifies that the checkout/update should be
             performed directly into the workdir. Each build is performed
             in the same directory, allowing for incremental builds. This
             minimizes disk space, bandwidth, and CPU time. However, it
             may encounter problems if the build process does not handle
             dependencies properly (if you must sometimes do a 'clean
             build' to make sure everything gets compiled), or if source
             files are deleted but generated files can influence test
             behavior (e.g. python's .pyc files), or when source
             directories are deleted but generated files prevent CVS from
             removing them. When used with a patched checkout, from a
             previous buildbot try for instance, it will try to "revert"
             the changes first and will do a clobber if it is unable to
             get a clean checkout. The behavior is SCM-dependent.

           - 'copy': specifies that the source-controlled workspace
             should be maintained in a separate directory (called the
             'copydir'), using checkout or update as necessary. For each
             build, a new workdir is created with a copy of the source
             tree (rm -rf workdir; cp -R -P -p copydir workdir). This
             doubles the disk space required, but keeps the bandwidth low
             (update instead of a full checkout). A full 'clean' build
             is performed each time.  This avoids any generated-file
             build problems, but is still occasionally vulnerable to
             problems such as a CVS repository being manually rearranged
             (causing CVS errors on update) which are not an issue with
             a full checkout.

           - 'clobber': specifies that the working directory should be
             deleted each time, necessitating a full checkout for each
             build. This insures a clean build off a complete checkout,
             avoiding any of the problems described above, but is
             bandwidth intensive, as the whole source tree must be
             pulled down for each build.

           - 'export': is like 'clobber', except that e.g. the 'cvs
             export' command is used to create the working directory.
             This command removes all VC metadata files (the
             CVS/.svn/{arch} directories) from the tree, which is
             sometimes useful for creating source tarballs (to avoid
             including the metadata in the tar file). Not all VC systems
             support export.

        @type  alwaysUseLatest: boolean
        @param alwaysUseLatest: whether to always update to the most
        recent available sources for this build.

        Normally the Source step asks its Build for a list of all
        Changes that are supposed to go into the build, then computes a
        'source stamp' (revision number or timestamp) that will cause
        exactly that set of changes to be present in the checked out
        tree. This is turned into, e.g., 'cvs update -D timestamp', or
        'svn update -r revnum'. If alwaysUseLatest=True, bypass this
        computation and always update to the latest available sources
        for each build.

        The source stamp helps avoid a race condition in which someone
        commits a change after the master has decided to start a build
        but before the slave finishes checking out the sources. At best
        this results in a build which contains more changes than the
        buildmaster thinks it has (possibly resulting in the wrong
        person taking the blame for any problems that result), at worst
        is can result in an incoherent set of sources (splitting a
        non-atomic commit) which may not build at all.

        @type  retry: tuple of ints (delay, repeats) (or None)
        @param retry: if provided, VC update failures are re-attempted up
                      to REPEATS times, with DELAY seconds between each
                      attempt. Some users have slaves with poor connectivity
                      to their VC repository, and they say that up to 80% of
                      their build failures are due to transient network
                      failures that could be handled by simply retrying a
                      couple times.

        """

        LoggingBuildStep.__init__(self, **kwargs)
        self.addFactoryArguments(workdir=workdir,
                                 mode=mode,
                                 alwaysUseLatest=alwaysUseLatest,
                                 timeout=timeout,
                                 retry=retry,
                                 )

        assert mode in ("update", "copy", "clobber", "export")
        if retry:
            delay, repeats = retry
            assert isinstance(repeats, int)
            assert repeats > 0
        self.args = {'mode': mode,
                     'timeout': timeout,
                     'retry': retry,
                     'patch': None, # set during .start
                     }
        # This will get added to args later, after properties are rendered
        self.workdir = workdir

        self.alwaysUseLatest = alwaysUseLatest

        # Compute defaults for descriptions:
        description = ["updating"]
        descriptionDone = ["update"]
        if mode == "clobber":
            description = ["checkout"]
            # because checkingouting takes too much space
            descriptionDone = ["checkout"]
        elif mode == "export":
            description = ["exporting"]
            descriptionDone = ["export"]
        self.description = description
        self.descriptionDone = descriptionDone

    def setStepStatus(self, step_status):
        LoggingBuildStep.setStepStatus(self, step_status)

    def setDefaultWorkdir(self, workdir):
        self.workdir = self.workdir or workdir

    def describe(self, done=False):
        if done:
            return self.descriptionDone
        return self.description

    def computeSourceRevision(self, changes):
        """Each subclass must implement this method to do something more
        precise than -rHEAD every time. For version control systems that use
        repository-wide change numbers (SVN, P4), this can simply take the
        maximum such number from all the changes involved in this build. For
        systems that do not (CVS), it needs to create a timestamp based upon
        the latest Change, the Build's treeStableTimer, and an optional
        self.checkoutDelay value."""
        return None

    def start(self):
        if self.notReally:
            log.msg("faking %s checkout/update" % self.name)
            self.step_status.setText(["fake", self.name, "successful"])
            self.addCompleteLog("log",
                                "Faked %s checkout/update 'successful'\n" \
                                % self.name)
            return SKIPPED

        # Allow workdir to be WithProperties
        self.args['workdir'] = self.workdir

        # what source stamp would this build like to use?
        s = self.build.getSourceStamp()
        # if branch is None, then use the Step's "default" branch
        branch = s.branch or self.branch
        # if revision is None, use the latest sources (-rHEAD)
        revision = s.revision
        if not revision and not self.alwaysUseLatest:
            revision = self.computeSourceRevision(s.changes)
            # the revision property is currently None, so set it to something
            # more interesting
            if revision is not None:
                self.setProperty('revision', str(revision), "Source")

        # if patch is None, then do not patch the tree after checkout

        # 'patch' is None or a tuple of (patchlevel, diff, root)
        # root is optional.
        patch = s.patch
        if patch:
            self.addCompleteLog("patch", patch[1])

        if self.alwaysUseLatest:
            revision = None
        self.startVC(branch, revision, patch)

    def commandComplete(self, cmd):
        if cmd.updates.has_key("got_revision"):
            got_revision = cmd.updates["got_revision"][-1]
            if got_revision is not None:
                self.setProperty("got_revision", str(got_revision), "Source")

class BK(Source):
    """I perform BitKeeper checkout/update operations."""

    name = 'bk'

    renderables = [ 'bkurl', 'baseURL' ]

    def __init__(self, bkurl=None, baseURL=None,
                 directory=None, extra_args=None, **kwargs):
        """
        @type  bkurl: string
        @param bkurl: the URL which points to the BitKeeper server.

        @type  baseURL: string
        @param baseURL: if branches are enabled, this is the base URL to
                        which a branch name will be appended. It should
                        probably end in a slash. Use exactly one of
                        C{bkurl} and C{baseURL}.
        """

        self.bkurl = _ComputeRepositoryURL(bkurl)
        self.baseURL = _ComputeRepositoryURL(baseURL)
        self.extra_args = extra_args

        Source.__init__(self, **kwargs)
        self.addFactoryArguments(bkurl=bkurl,
                                 baseURL=baseURL,
                                 directory=directory,
                                 extra_args=extra_args,
                                 )

        if bkurl and baseURL:
            raise ValueError("you must use exactly one of bkurl and baseURL")

    def computeSourceRevision(self, changes):
        return changes.revision

    def startVC(self, branch, revision, patch):

        warnings = []
        slavever = self.slaveVersion("bk")
        if not slavever:
            m = "slave does not have the 'bk' command"
            raise BuildSlaveTooOldError(m)

        if self.bkurl:
            assert not branch # we need baseURL= to use branches
            self.args['bkurl'] = self.bkurl
        else:
            self.args['bkurl'] = self.baseURL + branch
        self.args['revision'] = revision
        self.args['patch'] = patch
        self.args['branch'] = branch
        if self.extra_args is not None:
            self.args['extra_args'] = self.extra_args

        revstuff = []
        revstuff.append("[branch]")
        if revision is not None:
            revstuff.append("r%s" % revision)
        if patch is not None:
            revstuff.append("[patch]")
        self.description.extend(revstuff)
        self.descriptionDone.extend(revstuff)

        cmd = LoggedRemoteCommand("bk", self.args)
        self.startCommand(cmd, warnings)

class CVS(Source):
    """I do CVS checkout/update operations.

    Note: if you are doing anonymous/pserver CVS operations, you will need
    to manually do a 'cvs login' on each buildslave before the slave has any
    hope of success. XXX: fix then, take a cvs password as an argument and
    figure out how to do a 'cvs login' on each build
    """

    name = "cvs"

    renderables = [ "cvsroot" ]

    #progressMetrics = ('output',)
    #
    # additional things to track: update gives one stderr line per directory
    # (starting with 'cvs server: Updating ') (and is fairly stable if files
    # is empty), export gives one line per directory (starting with 'cvs
    # export: Updating ') and another line per file (starting with U). Would
    # be nice to track these, requires grepping LogFile data for lines,
    # parsing each line. Might be handy to have a hook in LogFile that gets
    # called with each complete line.

    def __init__(self, cvsroot=None, cvsmodule="",
                 global_options=[], branch=None, checkoutDelay=None,
                 checkout_options=[], export_options=[], extra_options=[],
                 login=None,
                 **kwargs):

        """
        @type  cvsroot: string
        @param cvsroot: CVS Repository from which the source tree should
                        be obtained. '/home/warner/Repository' for local
                        or NFS-reachable repositories,
                        ':pserver:anon@foo.com:/cvs' for anonymous CVS,
                        'user@host.com:/cvs' for non-anonymous CVS or
                        CVS over ssh. Lots of possibilities, check the
                        CVS documentation for more.

        @type  cvsmodule: string
        @param cvsmodule: subdirectory of CVS repository that should be
                          retrieved

        @type  login: string or None
        @param login: if not None, a string which will be provided as a
                      password to the 'cvs login' command, used when a
                      :pserver: method is used to access the repository.
                      This login is only needed once, but must be run
                      each time (just before the CVS operation) because
                      there is no way for the buildslave to tell whether
                      it was previously performed or not.

        @type  branch: string
        @param branch: the default branch name, will be used in a '-r'
                       argument to specify which branch of the source tree
                       should be used for this checkout. Defaults to None,
                       which means to use 'HEAD'.

        @type  checkoutDelay: int or None
        @param checkoutDelay: if not None, the number of seconds to put
                              between the last known Change and the
                              timestamp given to the -D argument. This
                              defaults to exactly half of the parent
                              Build's .treeStableTimer, but it could be
                              set to something else if your CVS change
                              notification has particularly weird
                              latency characteristics.

        @type  global_options: list of strings
        @param global_options: these arguments are inserted in the cvs
                               command line, before the
                               'checkout'/'update' command word. See
                               'cvs --help-options' for a list of what
                               may be accepted here.  ['-r'] will make
                               the checked out files read only. ['-r',
                               '-R'] will also assume the repository is
                               read-only (I assume this means it won't
                               use locks to insure atomic access to the
                               ,v files).

        @type  checkout_options: list of strings
        @param checkout_options: these arguments are inserted in the cvs
                               command line, after 'checkout' but before
                               branch or revision specifiers.

        @type  export_options: list of strings
        @param export_options: these arguments are inserted in the cvs
                               command line, after 'export' but before
                               branch or revision specifiers.

        @type  extra_options: list of strings
        @param extra_options: these arguments are inserted in the cvs
                               command line, after 'checkout' or 'export' but before
                               branch or revision specifiers.
                               """

        self.checkoutDelay = checkoutDelay
        self.branch = branch
        self.cvsroot = _ComputeRepositoryURL(cvsroot)

        Source.__init__(self, **kwargs)
        self.addFactoryArguments(cvsroot=cvsroot,
                                 cvsmodule=cvsmodule,
                                 global_options=global_options,
                                 checkout_options=checkout_options,
                                 export_options=export_options,
                                 extra_options=extra_options,
                                 branch=branch,
                                 checkoutDelay=checkoutDelay,
                                 login=login,
                                 )

        self.args.update({'cvsmodule': cvsmodule,
                          'global_options': global_options,
                          'checkout_options':checkout_options,
                          'export_options':export_options,
                          'extra_options':extra_options,
                          'login': login,
                          })

    def computeSourceRevision(self, changes):
        if not changes:
            return None
        lastChange = max([c.when for c in changes])
        if self.checkoutDelay is not None:
            when = lastChange + self.checkoutDelay
        else:
            lastSubmit = max([br.submittedAt for br in self.build.requests])
            when = (lastChange + lastSubmit) / 2
        return formatdate(when)

    def startVC(self, branch, revision, patch):
        if self.slaveVersionIsOlderThan("cvs", "1.39"):
            # the slave doesn't know to avoid re-using the same sourcedir
            # when the branch changes. We have no way of knowing which branch
            # the last build used, so if we're using a non-default branch and
            # either 'update' or 'copy' modes, it is safer to refuse to
            # build, and tell the user they need to upgrade the buildslave.
            if (branch != self.branch
                and self.args['mode'] in ("update", "copy")):
                m = ("This buildslave (%s) does not know about multiple "
                     "branches, and using mode=%s would probably build the "
                     "wrong tree. "
                     "Refusing to build. Please upgrade the buildslave to "
                     "buildbot-0.7.0 or newer." % (self.build.slavename,
                                                   self.args['mode']))
                log.msg(m)
                raise BuildSlaveTooOldError(m)

        if self.slaveVersionIsOlderThan("cvs", "2.10"):
            if self.args['extra_options'] or self.args['export_options']:
                m = ("This buildslave (%s) does not support export_options "
                     "or extra_options arguments to the CVS step."
                     % (self.build.slavename))
                log.msg(m)
                raise BuildSlaveTooOldError(m)
            # the unwanted args are empty, and will probably be ignored by
            # the slave, but delete them just to be safe
            del self.args['export_options']
            del self.args['extra_options']

        if branch is None:
            branch = "HEAD"
        self.args['cvsroot'] = self.cvsroot
        self.args['branch'] = branch
        self.args['revision'] = revision
        self.args['patch'] = patch

        if self.args['branch'] == "HEAD" and self.args['revision']:
            # special case. 'cvs update -r HEAD -D today' gives no files
            # TODO: figure out why, see if it applies to -r BRANCH
            self.args['branch'] = None

        # deal with old slaves
        warnings = []
        slavever = self.slaveVersion("cvs", "old")

        if slavever == "old":
            # 0.5.0
            if self.args['mode'] == "export":
                self.args['export'] = 1
            elif self.args['mode'] == "clobber":
                self.args['clobber'] = 1
            elif self.args['mode'] == "copy":
                self.args['copydir'] = "source"
            self.args['tag'] = self.args['branch']
            assert not self.args['patch'] # 0.5.0 slave can't do patch

        cmd = LoggedRemoteCommand("cvs", self.args)
        self.startCommand(cmd, warnings)

class SVN(Source):
    """I perform Subversion checkout/update operations."""

    name = 'svn'
    branch_placeholder = '%%BRANCH%%'

    renderables = [ 'svnurl', 'baseURL' ]

    def __init__(self, svnurl=None, baseURL=None, defaultBranch=None,
                 directory=None, username=None, password=None,
                 extra_args=None, keep_on_purge=None, ignore_ignores=None,
                 always_purge=None, depth=None, **kwargs):
        """
        @type  svnurl: string
        @param svnurl: the URL which points to the Subversion server,
                       combining the access method (HTTP, ssh, local file),
                       the repository host/port, the repository path, the
                       sub-tree within the repository, and the branch to
                       check out. Use exactly one of C{svnurl} and C{baseURL}.

        @param baseURL: if branches are enabled, this is the base URL to
                        which a branch name will be appended. It should
                        probably end in a slash. Use exactly one of
                        C{svnurl} and C{baseURL}.

        @param defaultBranch: if branches are enabled, this is the branch
                              to use if the Build does not specify one
                              explicitly. It will simply be appended
                              to C{baseURL} and the result handed to
                              the SVN command.

        @type  username: string
        @param username: username to pass to svn's --username

        @type  password: string
        @param password: password to pass to svn's --password
        """

        if not 'workdir' in kwargs and directory is not None:
            # deal with old configs
            warn("Please use workdir=, not directory=", DeprecationWarning)
            kwargs['workdir'] = directory

        self.svnurl = svnurl and _ComputeRepositoryURL(svnurl)
        self.baseURL = _ComputeRepositoryURL(baseURL)
        self.branch = defaultBranch
        self.username = username
        self.password = password
        self.extra_args = extra_args
        self.keep_on_purge = keep_on_purge
        self.ignore_ignores = ignore_ignores
        self.always_purge = always_purge
        self.depth = depth

        Source.__init__(self, **kwargs)
        self.addFactoryArguments(svnurl=svnurl,
                                 baseURL=baseURL,
                                 defaultBranch=defaultBranch,
                                 directory=directory,
                                 username=username,
                                 password=password,
                                 extra_args=extra_args,
                                 keep_on_purge=keep_on_purge,
                                 ignore_ignores=ignore_ignores,
                                 always_purge=always_purge,
                                 depth=depth,
                                 )

        if svnurl and baseURL:
            raise ValueError("you must use either svnurl OR baseURL")

    def computeSourceRevision(self, changes):
        if not changes or None in [c.revision for c in changes]:
            return None
        lastChange = max([int(c.revision) for c in changes])
        return lastChange

    def checkCompatibility(self):
        ''' Handle compatibility between old slaves/svn clients '''

        slavever = self.slaveVersion("svn", "old")

        if not slavever:
            m = "slave does not have the 'svn' command"
            raise BuildSlaveTooOldError(m)

        if self.slaveVersionIsOlderThan("svn", "1.39"):
            # the slave doesn't know to avoid re-using the same sourcedir
            # when the branch changes. We have no way of knowing which branch
            # the last build used, so if we're using a non-default branch and
            # either 'update' or 'copy' modes, it is safer to refuse to
            # build, and tell the user they need to upgrade the buildslave.
            if (self.args['branch'] != self.branch
                and self.args['mode'] in ("update", "copy")):
                m = ("This buildslave (%s) does not know about multiple "
                     "branches, and using mode=%s would probably build the "
                     "wrong tree. "
                     "Refusing to build. Please upgrade the buildslave to "
                     "buildbot-0.7.0 or newer." % (self.build.slavename,
                                                   self.args['mode']))
                raise BuildSlaveTooOldError(m)

        if (self.depth is not None) and self.slaveVersionIsOlderThan("svn","2.9"):
            m = ("This buildslave (%s) does not support svn depth "
                    "arguments.  Refusing to build. "
                    "Please upgrade the buildslave." % (self.build.slavename))
            raise BuildSlaveTooOldError(m)

        if (self.username is not None or self.password is not None) \
        and self.slaveVersionIsOlderThan("svn", "2.8"):
            m = ("This buildslave (%s) does not support svn usernames "
                 "and passwords.  "
                 "Refusing to build. Please upgrade the buildslave to "
                 "buildbot-0.7.10 or newer." % (self.build.slavename,))
            raise BuildSlaveTooOldError(m)

    def getSvnUrl(self, branch, revision, patch):
        ''' Compute the svn url that will be passed to the svn remote command '''
        if self.svnurl:
            return self.svnurl
        else:
            if branch is None:
                m = ("The SVN source step belonging to builder '%s' does not know "
                     "which branch to work with. This means that the change source "
                     "did not specify a branch and that defaultBranch is None." \
                     % self.build.builder.name)
                raise RuntimeError(m)

            computed = self.baseURL

            if self.branch_placeholder in self.baseURL:
                return computed.replace(self.branch_placeholder, branch)
            else:
                return computed + branch

    def startVC(self, branch, revision, patch):
        warnings = []

        self.checkCompatibility()

        self.args['svnurl'] = self.getSvnUrl(branch, revision, patch)
        self.args['revision'] = revision
        self.args['patch'] = patch
        self.args['always_purge'] = self.always_purge

        #Set up depth if specified
        if self.depth is not None:
            self.args['depth'] = self.depth

        if self.username is not None:
            self.args['username'] = self.username
        if self.password is not None:
            self.args['password'] = self.password

        if self.extra_args is not None:
            self.args['extra_args'] = self.extra_args

        revstuff = []
        #revstuff.append(self.args['svnurl'])
        if self.args['svnurl'].find('trunk') == -1:
            revstuff.append("[branch]")
        if revision is not None:
            revstuff.append("r%s" % revision)
        if patch is not None:
            revstuff.append("[patch]")
        self.description.extend(revstuff)
        self.descriptionDone.extend(revstuff)

        cmd = LoggedRemoteCommand("svn", self.args)
        self.startCommand(cmd, warnings)

class Darcs(Source):
    """Check out a source tree from a Darcs repository at 'repourl'.

    Darcs has no concept of file modes. This means the eXecute-bit will be
    cleared on all source files. As a result, you may need to invoke
    configuration scripts with something like:

    C{s(step.Configure, command=['/bin/sh', './configure'])}
    """

    name = "darcs"

    renderables = [ 'repourl', 'baseURL' ]

    def __init__(self, repourl=None, baseURL=None, defaultBranch=None,
                 **kwargs):
        """
        @type  repourl: string
        @param repourl: the URL which points at the Darcs repository. This
                        is used as the default branch. Using C{repourl} does
                        not enable builds of alternate branches: use
                        C{baseURL} to enable this. Use either C{repourl} or
                        C{baseURL}, not both.

        @param baseURL: if branches are enabled, this is the base URL to
                        which a branch name will be appended. It should
                        probably end in a slash. Use exactly one of
                        C{repourl} and C{baseURL}.

        @param defaultBranch: if branches are enabled, this is the branch
                              to use if the Build does not specify one
                              explicitly. It will simply be appended to
                              C{baseURL} and the result handed to the
                              'darcs pull' command.
        """
        self.repourl = _ComputeRepositoryURL(repourl)
        self.baseURL = _ComputeRepositoryURL(baseURL)
        self.branch = defaultBranch
        Source.__init__(self, **kwargs)
        self.addFactoryArguments(repourl=repourl,
                                 baseURL=baseURL,
                                 defaultBranch=defaultBranch,
                                 )
        assert self.args['mode'] != "export", \
               "Darcs does not have an 'export' mode"
        if repourl and baseURL:
            raise ValueError("you must provide exactly one of repourl and"
                             " baseURL")

    def startVC(self, branch, revision, patch):
        slavever = self.slaveVersion("darcs")
        if not slavever:
            m = "slave is too old, does not know about darcs"
            raise BuildSlaveTooOldError(m)

        if self.slaveVersionIsOlderThan("darcs", "1.39"):
            if revision:
                # TODO: revisit this once we implement computeSourceRevision
                m = "0.6.6 slaves can't handle args['revision']"
                raise BuildSlaveTooOldError(m)

            # the slave doesn't know to avoid re-using the same sourcedir
            # when the branch changes. We have no way of knowing which branch
            # the last build used, so if we're using a non-default branch and
            # either 'update' or 'copy' modes, it is safer to refuse to
            # build, and tell the user they need to upgrade the buildslave.
            if (branch != self.branch
                and self.args['mode'] in ("update", "copy")):
                m = ("This buildslave (%s) does not know about multiple "
                     "branches, and using mode=%s would probably build the "
                     "wrong tree. "
                     "Refusing to build. Please upgrade the buildslave to "
                     "buildbot-0.7.0 or newer." % (self.build.slavename,
                                                   self.args['mode']))
                raise BuildSlaveTooOldError(m)

        if self.repourl:
            assert not branch # we need baseURL= to use branches
            self.args['repourl'] = self.repourl
        else:
            self.args['repourl'] = self.baseURL + branch
        self.args['revision'] = revision
        self.args['patch'] = patch

        revstuff = []
        if branch is not None and branch != self.branch:
            revstuff.append("[branch]")
        self.description.extend(revstuff)
        self.descriptionDone.extend(revstuff)

        cmd = LoggedRemoteCommand("darcs", self.args)
        self.startCommand(cmd)

class Git(Source):
    """Check out a source tree from a git repository 'repourl'."""

    name = "git"

    renderables = [ 'repourl' ]

    def __init__(self, repourl=None,
                 branch="master",
                 submodules=False,
                 ignore_ignores=None,
                 reference=None,
                 shallow=False,
                 progress=False,
                 **kwargs):
        """
        @type  repourl: string
        @param repourl: the URL which points at the git repository

        @type  branch: string
        @param branch: The branch or tag to check out by default. If
                       a build specifies a different branch, it will
                       be used instead of this.

        @type  submodules: boolean
        @param submodules: Whether or not to update (and initialize)
                       git submodules.

        @type  reference: string
        @param reference: The path to a reference repository to obtain
                          objects from, if any.

        @type  shallow: boolean
        @param shallow: Use a shallow or clone, if possible

        @type  progress: boolean
        @param progress: Pass the --progress option when fetching. This
                         can solve long fetches getting killed due to
                         lack of output, but requires Git 1.7.2+.
        """
        Source.__init__(self, **kwargs)
        self.repourl = _ComputeRepositoryURL(repourl)
        self.branch = branch
        self.addFactoryArguments(repourl=repourl,
                                 branch=branch,
                                 submodules=submodules,
                                 ignore_ignores=ignore_ignores,
                                 reference=reference,
                                 shallow=shallow,
                                 progress=progress,
                                 )
        self.args.update({'submodules': submodules,
                          'ignore_ignores': ignore_ignores,
                          'reference': reference,
                          'shallow': shallow,
                          'progress': progress,
                          })

    def computeSourceRevision(self, changes):
        if not changes:
            return None
        return changes[-1].revision

    def startVC(self, branch, revision, patch):
        self.args['branch'] = branch
        self.args['repourl'] = self.repourl
        self.args['revision'] = revision
        self.args['patch'] = patch

        # check if there is any patchset we should fetch from Gerrit
        try:
            # GerritChangeSource
            self.args['gerrit_branch'] = self.build.getProperty("event.patchSet.ref")
            self.setProperty("gerrit_branch", self.args['gerrit_branch'])
        except KeyError:
            try:
                # forced build
                change = self.build.getProperty("gerrit_change").split('/')
                if len(change) == 2:
                    self.args['gerrit_branch'] = "refs/changes/%2.2d/%d/%d" \
                                                 % (int(change[0]) % 100, int(change[0]), int(change[1]))
                    self.setProperty("gerrit_branch", self.args['gerrit_branch'])
            except:
                pass

        slavever = self.slaveVersion("git")
        if not slavever:
            raise BuildSlaveTooOldError("slave is too old, does not know "
                                        "about git")
        cmd = LoggedRemoteCommand("git", self.args)
        self.startCommand(cmd)

class Repo(Source):
    """Check out a source tree from a repo repository described by manifest."""

    name = "repo"

    renderables = [ "manifest_url" ]

    def __init__(self,
                 manifest_url=None,
                 manifest_branch="master",
                 manifest_file="default.xml",
                 tarball=None,
                 **kwargs):
        """
        @type  manifest_url: string
        @param manifest_url: The URL which points at the repo manifests repository.

        @type  manifest_branch: string
        @param manifest_branch: The manifest branch to check out by default.

        @type  manifest_file: string
        @param manifest_file: The manifest to use for sync.

        """
        Source.__init__(self, **kwargs)
        self.manifest_url = _ComputeRepositoryURL(manifest_url)
        self.addFactoryArguments(manifest_url=manifest_url,
                                 manifest_branch=manifest_branch,
                                 manifest_file=manifest_file,
                                 tarball=tarball,
                                 )
        self.args.update({'manifest_branch': manifest_branch,
                          'manifest_file': manifest_file,
                          'tarball': tarball,
                          })

    def computeSourceRevision(self, changes):
        if not changes:
            return None
        return changes[-1].revision

    def parseDownloadProperty(self, s):
        """
         lets try to be nice in the format we want
         can support several instances of "repo download proj number/patch" (direct copy paste from gerrit web site)
         or several instances of "proj number/patch" (simpler version)
         This feature allows integrator to build with several pending interdependant changes.
         returns list of repo downloads sent to the buildslave
         """
        import re
        if s == None:
            return []
        re1 = re.compile("repo download ([^ ]+) ([0-9]+/[0-9]+)")
        re2 = re.compile("([^ ]+) ([0-9]+/[0-9]+)")
        re3 = re.compile("([^ ]+)/([0-9]+/[0-9]+)")
        ret = []
        for cur_re in [re1, re2, re3]:
            res = cur_re.search(s)
            while res:
                ret.append("%s %s" % (res.group(1), res.group(2)))
                s = s[:res.start(0)] + s[res.end(0):]
                res = cur_re.search(s)
        return ret

    def startVC(self, branch, revision, patch):
        self.args['manifest_url'] = self.manifest_url

        # only master has access to properties, so we must implement this here.
        downloads = []

        # download patches based on GerritChangeSource events
        for change in self.build.allChanges():
            if (change.properties.has_key("event.type") and
                change.properties["event.type"] == "patchset-created"):
                downloads.append("%s %s/%s"% (change.properties["event.change.project"],
                                              change.properties["event.change.number"],
                                              change.properties["event.patchSet.number"]))

        # download patches based on web site forced build properties:
        # "repo_d", "repo_d0", .., "repo_d9"
        # "repo_download", "repo_download0", .., "repo_download9"
        for propName in ["repo_d"] + ["repo_d%d" % i for i in xrange(0,10)] + \
          ["repo_download"] + ["repo_download%d" % i for i in xrange(0,10)]:
            try:
                s = self.build.getProperty(propName)
                downloads.extend(self.parseDownloadProperty(s))
            except KeyError:
                pass

        if downloads:
            self.args["repo_downloads"] = downloads
            self.setProperty("repo_downloads", downloads)

        slavever = self.slaveVersion("repo")
        if not slavever:
            raise BuildSlaveTooOldError("slave is too old, does not know "
                                        "about repo")
        cmd = LoggedRemoteCommand("repo", self.args)
        self.startCommand(cmd)

    def commandComplete(self, cmd):
        if cmd.updates.has_key("repo_downloaded"):
            repo_downloaded = cmd.updates["repo_downloaded"][-1]
            if repo_downloaded:
                self.setProperty("repo_downloaded", str(repo_downloaded), "Source")

class Bzr(Source):
    """Check out a source tree from a bzr (Bazaar) repository at 'repourl'.

    """

    name = "bzr"

    renderables = [ 'repourl', 'baseURL' ]

    def __init__(self, repourl=None, baseURL=None, defaultBranch=None,
                 forceSharedRepo=None,
                 **kwargs):
        """
        @type  repourl: string
        @param repourl: the URL which points at the bzr repository. This
                        is used as the default branch. Using C{repourl} does
                        not enable builds of alternate branches: use
                        C{baseURL} to enable this. Use either C{repourl} or
                        C{baseURL}, not both.

        @param baseURL: if branches are enabled, this is the base URL to
                        which a branch name will be appended. It should
                        probably end in a slash. Use exactly one of
                        C{repourl} and C{baseURL}.

        @param defaultBranch: if branches are enabled, this is the branch
                              to use if the Build does not specify one
                              explicitly. It will simply be appended to
                              C{baseURL} and the result handed to the
                              'bzr checkout pull' command.

        @param forceSharedRepo: Boolean, defaults to False. If set to True,
                                the working directory will be made into a
                                bzr shared repository if it is not already.
                                Shared repository greatly reduces the amount
                                of history data that needs to be downloaded
                                if not using update/copy mode, or if using
                                update/copy mode with multiple branches.
        """
        self.repourl = _ComputeRepositoryURL(repourl)
        self.baseURL = _ComputeRepositoryURL(baseURL)
        self.branch = defaultBranch
        Source.__init__(self, **kwargs)
        self.addFactoryArguments(repourl=repourl,
                                 baseURL=baseURL,
                                 defaultBranch=defaultBranch,
                                 forceSharedRepo=forceSharedRepo
                                 )
        self.args.update({'forceSharedRepo': forceSharedRepo})
        if repourl and baseURL:
            raise ValueError("you must provide exactly one of repourl and"
                             " baseURL")

    def computeSourceRevision(self, changes):
        if not changes:
            return None
        lastChange = max([int(c.revision) for c in changes])
        return lastChange

    def startVC(self, branch, revision, patch):
        slavever = self.slaveVersion("bzr")
        if not slavever:
            m = "slave is too old, does not know about bzr"
            raise BuildSlaveTooOldError(m)

        if self.repourl:
            assert not branch # we need baseURL= to use branches
            self.args['repourl'] = self.repourl
        else:
            self.args['repourl'] = self.baseURL + branch
        self.args['revision'] = revision
        self.args['patch'] = patch

        revstuff = []
        if branch is not None and branch != self.branch:
            revstuff.append("[" + branch + "]")
        if revision is not None:
            revstuff.append("r%s" % revision)
        self.description.extend(revstuff)
        self.descriptionDone.extend(revstuff)

        cmd = LoggedRemoteCommand("bzr", self.args)
        self.startCommand(cmd)

class Mercurial(Source):
    """Check out a source tree from a mercurial repository 'repourl'."""

    name = "hg"

    renderables = [ 'repourl', 'baseURL' ]

    def __init__(self, repourl=None, baseURL=None, defaultBranch=None,
                 branchType='dirname', clobberOnBranchChange=True, **kwargs):
        """
        @type  repourl: string
        @param repourl: the URL which points at the Mercurial repository.
                        This uses the 'default' branch unless defaultBranch is
                        specified below and the C{branchType} is set to
                        'inrepo'.  It is an error to specify a branch without
                        setting the C{branchType} to 'inrepo'.

        @param baseURL: if 'dirname' branches are enabled, this is the base URL
                        to which a branch name will be appended. It should
                        probably end in a slash.  Use exactly one of C{repourl}
                        and C{baseURL}.

        @param defaultBranch: if branches are enabled, this is the branch
                              to use if the Build does not specify one
                              explicitly.
                              For 'dirname' branches, It will simply be
                              appended to C{baseURL} and the result handed to
                              the 'hg update' command.
                              For 'inrepo' branches, this specifies the named
                              revision to which the tree will update after a
                              clone.

        @param branchType: either 'dirname' or 'inrepo' depending on whether
                           the branch name should be appended to the C{baseURL}
                           or the branch is a mercurial named branch and can be
                           found within the C{repourl}

        @param clobberOnBranchChange: boolean, defaults to True. If set and
                                      using inrepos branches, clobber the tree
                                      at each branch change. Otherwise, just
                                      update to the branch.
        """
        self.repourl = _ComputeRepositoryURL(repourl)
        self.baseURL = _ComputeRepositoryURL(baseURL)
        self.branch = defaultBranch
        self.branchType = branchType
        self.clobberOnBranchChange = clobberOnBranchChange
        Source.__init__(self, **kwargs)
        self.addFactoryArguments(repourl=repourl,
                                 baseURL=baseURL,
                                 defaultBranch=defaultBranch,
                                 branchType=branchType,
                                 clobberOnBranchChange=clobberOnBranchChange,
                                 )
        if repourl and baseURL:
            raise ValueError("you must provide exactly one of repourl and"
                             " baseURL")

    def startVC(self, branch, revision, patch):
        slavever = self.slaveVersion("hg")
        if not slavever:
            raise BuildSlaveTooOldError("slave is too old, does not know "
                                        "about hg")

        if self.repourl:
            # we need baseURL= to use dirname branches
            assert self.branchType == 'inrepo' or not branch
            self.args['repourl'] = self.repourl
            if branch:
                self.args['branch'] = branch
        else:
            self.args['repourl'] = self.baseURL + (branch or '')
        self.args['revision'] = revision
        self.args['patch'] = patch
        self.args['clobberOnBranchChange'] = self.clobberOnBranchChange
        self.args['branchType'] = self.branchType

        revstuff = []
        if branch is not None and branch != self.branch:
            revstuff.append("[branch]")
        self.description.extend(revstuff)
        self.descriptionDone.extend(revstuff)

        cmd = LoggedRemoteCommand("hg", self.args)
        self.startCommand(cmd)

    def computeSourceRevision(self, changes):
        if not changes:
            return None
        # without knowing the revision ancestry graph, we can't sort the
        # changes at all. So for now, assume they were given to us in sorted
        # order, and just pay attention to the last one. See ticket #103 for
        # more details.
        if len(changes) > 1:
            log.msg("Mercurial.computeSourceRevision: warning: "
                    "there are %d changes here, assuming the last one is "
                    "the most recent" % len(changes))
        return changes[-1].revision

class P4(Source):
    """ P4 is a class for accessing perforce revision control"""
    name = "p4"

    renderables = [ 'p4base' ]

    def __init__(self, p4base=None, defaultBranch=None, p4port=None, p4user=None,
                 p4passwd=None, p4extra_views=[], p4line_end='local',
                 p4client='buildbot_%(slave)s_%(builder)s', **kwargs):
        """
        @type  p4base: string
        @param p4base: A view into a perforce depot, typically
                       "//depot/proj/"

        @type  defaultBranch: string
        @param defaultBranch: Identify a branch to build by default. Perforce
                              is a view based branching system. So, the branch
                              is normally the name after the base. For example,
                              branch=1.0 is view=//depot/proj/1.0/...
                              branch=1.1 is view=//depot/proj/1.1/...

        @type  p4port: string
        @param p4port: Specify the perforce server to connection in the format
                       <host>:<port>. Example "perforce.example.com:1666"

        @type  p4user: string
        @param p4user: The perforce user to run the command as.

        @type  p4passwd: string
        @param p4passwd: The password for the perforce user.

        @type  p4extra_views: list of tuples
        @param p4extra_views: Extra views to be added to
                              the client that is being used.

        @type  p4line_end: string
        @param p4line_end: value of the LineEnd client specification property

        @type  p4client: string
        @param p4client: The perforce client to use for this buildslave.
        """

        self.p4base = _ComputeRepositoryURL(p4base)
        self.branch = defaultBranch
        Source.__init__(self, **kwargs)
        self.addFactoryArguments(p4base=p4base,
                                 defaultBranch=defaultBranch,
                                 p4port=p4port,
                                 p4user=p4user,
                                 p4passwd=p4passwd,
                                 p4extra_views=p4extra_views,
                                 p4line_end=p4line_end,
                                 p4client=p4client,
                                 )
        self.args['p4port'] = p4port
        self.args['p4user'] = p4user
        self.args['p4passwd'] = p4passwd
        self.args['p4extra_views'] = p4extra_views
        self.args['p4line_end'] = p4line_end
        self.p4client = p4client

    def setBuild(self, build):
        Source.setBuild(self, build)
        self.args['p4client'] = self.p4client % {
            'slave': build.slavename,
            'builder': build.builder.name,
        }

    def computeSourceRevision(self, changes):
        if not changes:
            return None
        lastChange = max([int(c.revision) for c in changes])
        return lastChange

    def startVC(self, branch, revision, patch):
        slavever = self.slaveVersion("p4")
        assert slavever, "slave is too old, does not know about p4"
        args = dict(self.args)
        args['p4base'] = self.p4base
        args['branch'] = branch or self.branch
        args['revision'] = revision
        args['patch'] = patch
        cmd = LoggedRemoteCommand("p4", args)
        self.startCommand(cmd)

class P4Sync(Source):
    """This is a partial solution for using a P4 source repository. You are
    required to manually set up each build slave with a useful P4
    environment, which means setting various per-slave environment variables,
    and creating a P4 client specification which maps the right files into
    the slave's working directory. Once you have done that, this step merely
    performs a 'p4 sync' to update that workspace with the newest files.

    Each slave needs the following environment:

     - PATH: the 'p4' binary must be on the slave's PATH
     - P4USER: each slave needs a distinct user account
     - P4CLIENT: each slave needs a distinct client specification

    You should use 'p4 client' (?) to set up a client view spec which maps
    the desired files into $SLAVEBASE/$BUILDERBASE/source .
    """

    name = "p4sync"

    def __init__(self, p4port, p4user, p4passwd, p4client, **kwargs):
        assert kwargs['mode'] == "copy", "P4Sync can only be used in mode=copy"
        self.branch = None
        Source.__init__(self, **kwargs)
        self.addFactoryArguments(p4port=p4port,
                                 p4user=p4user,
                                 p4passwd=p4passwd,
                                 p4client=p4client,
                                )
        self.args['p4port'] = p4port
        self.args['p4user'] = p4user
        self.args['p4passwd'] = p4passwd
        self.args['p4client'] = p4client

    def computeSourceRevision(self, changes):
        if not changes:
            return None
        lastChange = max([int(c.revision) for c in changes])
        return lastChange

    def startVC(self, branch, revision, patch):
        slavever = self.slaveVersion("p4sync")
        assert slavever, "slave is too old, does not know about p4"
        cmd = LoggedRemoteCommand("p4sync", self.args)
        self.startCommand(cmd)

class Monotone(Source):
    """Check out a source tree from a monotone repository 'repourl'."""

    name = "mtn"

    renderables = [ 'repourl' ]

    def __init__(self, repourl=None, branch=None, progress=False, **kwargs):
        """
        @type  repourl: string
        @param repourl: the URI which points at the monotone repository.

        @type  branch: string
        @param branch: The branch or tag to check out by default. If
                       a build specifies a different branch, it will
                       be used instead of this.

        @type  progress: boolean
        @param progress: Pass the --ticker=dot option when pulling. This
                         can solve long fetches getting killed due to
                         lack of output.
        """
        Source.__init__(self, **kwargs)
        self.repourl = _ComputeRepositoryURL(repourl)
        if (not repourl):
            raise ValueError("you must provide a repository uri in 'repourl'")
        if (not branch):
            raise ValueError("you must provide a default branch in 'branch'")
        self.addFactoryArguments(repourl=repourl,
                                 branch=branch,
                                 progress=progress,
                                 )
        self.args.update({'branch': branch,
                          'progress': progress,
                          })

    def startVC(self, branch, revision, patch):
        slavever = self.slaveVersion("mtn")
        if not slavever:
            raise BuildSlaveTooOldError("slave is too old, does not know "
                                        "about mtn")

        self.args['repourl'] = self.repourl
        if branch:
            self.args['branch'] = branch
        self.args['revision'] = revision
        self.args['patch'] = patch

        cmd = LoggedRemoteCommand("mtn", self.args)
        self.startCommand(cmd)

    def computeSourceRevision(self, changes):
        if not changes:
            return None
        # without knowing the revision ancestry graph, we can't sort the
        # changes at all. So for now, assume they were given to us in sorted
        # order, and just pay attention to the last one. See ticket #103 for
        # more details.
        if len(changes) > 1:
            log.msg("Monotone.computeSourceRevision: warning: "
                    "there are %d changes here, assuming the last one is "
                    "the most recent" % len(changes))
        return changes[-1].revision


text:
<?php

namespace Geocoder\Provider\MaxMind\Tests;

use Geocoder\IntegrationTest\ProviderIntegrationTest;
use Geocoder\Provider\MaxMind\MaxMind;
use Psr\Http\Client\ClientInterface;

/**
 * @author Tobias Nyholm <tobias.nyholm@gmail.com>
 */
class IntegrationTest extends ProviderIntegrationTest
{
    protected $testAddress = false;

    protected $testReverse = false;

    protected function createProvider(ClientInterface $httpClient)
    {
        return new MaxMind($httpClient, $this->getApiKey());
    }

    protected function getCacheDir()
    {
        return __DIR__.'/.cached_responses';
    }

    protected function getApiKey()
    {
        if (!isset($_SERVER['MAXMIND_API_KEY'])) {
            $this->markTestSkipped('No MaxMind API key');
        }

        return $_SERVER['MAXMIND_API_KEY'];
    }
}


text:
package it.gemmed.servlet;

import it.gemmed.database.CreateUtenteFederaleDatabase;
import it.gemmed.resource.UtenteFederale;
import it.gemmed.resource.Message;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet che aggiunge al database il profilo  * di un utente federale
 * con propria email e password
 *
 * @author GEMMED
 * @version 1.00
 */
@SuppressWarnings("serial")
public class CreateUtenteFederaleServlet extends AbstractDatabaseServlet {

	/**
	 * @param req
	 *            Richiesta HTTP del client.
	 * @param res
	 *            Risposta HTTP del server.
	 *
	 * @throws ServletException
	 *             Se si verificano degli errori eseguendo la servlet.
	 * @throws IOException
	 *             Se si verificano degli errori nel comunicazione tra client/server.
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {

		// request parameters
		String email = null;
		String password = null;

		// model
		UtenteFederale u  = null;
		Message m = null;

		try{
			// retrieves the request parameters
			email = req.getParameter("email");
			password = req.getParameter("password");

			// creates a new employee from the request parameters
			u = new UtenteFederale(email, password);

			// creates a new object for accessing the database and stores the employee
			new CreateUtenteFederaleDatabase(DS.getConnection(), u).createUtenteFederale();

			m = new Message("Utente federale successfully created.");

		} catch (NumberFormatException ex) {
			m = new Message("Cannot create the employee. Invalid input parameters: identifier, age, and salary must be integer.",
					"E100", ex.getMessage());
		} catch (SQLException ex) {
//			if (e
//					.getSQLState()
//					.equals("23505")) {
//				m = new Message("Cannot create the employee: employee  already exists.",
//						"E300", ex.getMessage());
//			} else {
				m = new Message("Cannot create the employee: unexpected error while accessing the database.",
						"E200", ex.getMessage());
//			}
		}

		// stores the employee and the message as a request attribute
		req.setAttribute("federale", u);
		req.setAttribute("message", m);

		// forwards the control to the createEmployeeResult JSP
		req.getRequestDispatcher("/jsp/profilo-federazione.jsp").forward(req, res);

	}

}