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

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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>

    <!-- Default set of monitored resources. If one of these changes, the    -->
    <!-- web application will be reloaded.                                   -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>

    <!-- Uncomment thisdeactivateable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->

    <!--Production config-->
    <Resource name="jdbc/simple_booking_service"
              auth="Container"
              type="javax.sql.DataSource"
              url="jdbc:mysql://localhost:3306/booking_service"
              username="root"
              password="0707Flbvhaim"
              driverClassName="com.mysql.jdbc.Driver"
              maxActive="20"
              maxIdle="10"

              maxWait="10000"
              removeAbandoned="true"
              removeAbandonedTimeout="300"

              validationQuery="SELECT 1"
              testOnBorrow="true"
              testWhileIdle="true"
              timeBetweenEvictionRunsMillis="10000"
              minEvictableIdleTimeMillis="60000"/>

    <!--Development config-->
    <!--<Resource name="jdbc/simple_booking_service"-->
              <!--auth="Container"-->
              <!--type="javax.sql.DataSource"-->
              <!--url="jdbc:mysql://localhost:3306/booking_service"-->
              <!--username="root"-->
              <!--password="0707Flbvhaim"-->
              <!--driverClassName="com.mysql.jdbc.Driver"-->
              <!--validationQuery="SELECT 1"-->
              <!--maxTotal="20"-->
              <!--minIdle="2"-->
              <!--maxWaitMillis="20000"-->
              <!--initialSize="2"-->
              <!--maxIdle="10"-->
              <!--testOnBorrow="true"-->
              <!--removeAbandonedOnBorrow="true"-->
              <!--testWhileIdle="true"/>-->

</Context>


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 RevisaPeru.DataAccess.DAO;

import RevisaPeru.DataAccess.*;
//import RevisaPeru.DataAccess.DAO.*;
import RevisaPeru.Entities.*;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author user
 */
public class ModelDAO implements IModelDAO {
    //Acceso a objetos embebidos
    IMarkDAO markDAO =null;
 //obtener instacia del objeto de coneccion base de datos
    Objectdb db=null;
    //Lista de objetos
    List<Model> models = null;
    ResultSet modelRS=null;
    //Stored procedure requierd
    CallableStatement modelStmt=null;
    //Objeto embebido
    Mark mark=null;
    //Constructor
    public ModelDAO()
    {
        markDAO= new MarkDAO();
        db= Objectdb.getIntacia();
    }

    @Override
    public void insertModel(Model model) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void modifyModel(Model model) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void deleteFromModeById(int id) {
        try {
            modelStmt = db.conexion.prepareCall("{CALL deleteFromModeById(?)}");
            modelStmt.setInt(1, id);
            modelStmt.execute();
        } catch (SQLException ex) {
            Logger.getLogger(ModelDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void deleteModel(Model model) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public int getIdModel() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Model getFromModelById(int id) {
        Model model=null;
        try {
            modelStmt = db.conexion.prepareCall("{CALL getFromModelById(?)}");
            modelStmt.setInt(1, id);
            modelStmt.execute();
            modelRS = modelStmt.getResultSet();
            while(modelRS.next())
            {
                if ((model==null) && (modelRS.getRow()==0))
                {
                    model = new Model(
                        modelRS.getInt("id"),
                        modelRS.getString("name"),
                        modelRS.getString("trany"),
                        modelRS.getString("year"),
                        modelRS.getString("vClass"),
                        modelRS.getString("cylinders"),
                        modelRS.getString("drive"),
                        modelRS.getString("fuelType"),
                        modelRS.getString("fuelType1"),
                        modelRS.getString("fuelType2"),
                        modelRS.getString("atvType"),
                        modelRS.getInt("markId")
                    );
                }
                //models.add(model);
            }
        } catch (SQLException ex) {
            Logger.getLogger(MarkDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return model;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<Model> getAllFromModel() {
        models = new ArrayList<Model>();
        try {
            modelStmt = db.conexion.prepareCall("{CALL getAllFromModel()}");
            //markStmt.setString(1, parameter);
            modelStmt.execute();
            modelRS = modelStmt.getResultSet();
            db.cerrarBD();
            while(modelRS.next())
            {
                Model model = new Model(
                        modelRS.getInt("id"),
                        modelRS.getString("name"),
                        modelRS.getString("trany"),
                        modelRS.getString("year"),
                        modelRS.getString("vClass"),
                        modelRS.getString("cylinders"),
                        modelRS.getString("drive"),
                        modelRS.getString("fuelType"),
                        modelRS.getString("fuelType1"),
                        modelRS.getString("fuelType2"),
                        modelRS.getString("atvType"),
                        modelRS.getInt("markId")
                    );
                mark= markDAO.getFromMarkById(model.getMarkId());
                model.setMark(mark);
                models.add(model);
            }
        } catch (SQLException ex) {
            Logger.getLogger(MarkDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return models;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<Model> getCustomizedFromModel(String searchValue, String searchYear, Integer makerId) {
        models = new ArrayList<Model>();
        try {
            modelStmt = db.conexion.prepareCall("{CALL getCustomizedFromModel(?,?,?)}");
            modelStmt.setString(1, searchValue);
            modelStmt.setString(2, searchYear);
            modelStmt.setInt(3, makerId);
            //markStmt.setString(1, parameter);
            modelStmt.execute();
            modelRS = modelStmt.getResultSet();
            db.cerrarBD();
            while(modelRS.next())
            {
                 Model model = new Model(
                        modelRS.getInt("id"),
                        modelRS.getString("name"),
                        modelRS.getString("trany"),
                        modelRS.getString("year"),
                        modelRS.getString("vClass"),
                        modelRS.getString("cylinders"),
                        modelRS.getString("drive"),
                        modelRS.getString("fuelType"),
                        modelRS.getString("fuelType1"),
                        modelRS.getString("fuelType2"),
                        modelRS.getString("atvType"),
                        modelRS.getInt("markId")
                    );
                mark= markDAO.getFromMarkById(model.getMarkId());
                model.setMark(mark);
                models.add(model);
            }
        } catch (SQLException ex) {
            Logger.getLogger(MarkDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return models;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

redpajama_set_name: RedPajamaGithub


text:
Ludum Dare 29. Contributors:

  * Arne Roomann-Kurrik
  * Kalev Roomann-Kurrik
  * Wes Goodman

Theme: "Beneath the surface"

## Tasks

  * [x] Come up with idea.
  * [x] Main game loop.
  * [x] Level loading.
  * [x] Vertical level switching.
  * [x] Music loading.
  * [x] Player movement.
  * [x] Collision detection.
  * [x] Water tracking / gauge.
  * [x] Items.
  * [x] Pump item type and pump events.
  * [x] Menus.
  * [x] Load player sprite sheet.
  * [x] Triggers for running over items and transition tiles.
  * [x] Destructable item framework.
  * [x] Health bar.
  * [x] Show picked up items.
  * [x] End state.
  * [x] Splash screen.
  * [x] Level tiles for dry, partial, drowned levels.
  * [x] Sound effects.
  * [x] Snorkel.
  * [x] Pickaxe and barrier tiles.
  * [x] Pump tile.
  * [x] Map work.

## Brainstorming

  * Ground.
  * Change over time.
  * Digging holes, top down, holes have different depths,
    can only go adjacent levels.
  * Submarine.
  * Underground pathways.
  * More depth than initially expected.
  * Tremors the game.
  * Character that has to duck out of the way.
  * Revealing something about NPCs.
  * Tremors from monster's point of view.
    * NPCs on rocks, running to some goal.
    * Can go around rocks, eat NPCs if you touch them.
    * Need to wait for them to expose themselves.
    * Pathfinding with preferences to stay on rock.
  * Dungeon, go deeper.
  * Motivations for going beneath the surface:
    * Escape from surface
    * Escape from below

  * Well Idea:
    * Start at the top of a well.
    * Raining.
    * Climb down and levels strip away.
    * Need to find a way down.
    * Powerup items: Move faster, hold breath longer, etc.
    * Well starts to fill with water, so you need to be fast.
    * Can return to top of well to pump water out.
    * Need to get to bottom to get more loot.
    * Further down, better loot.
    * Levels fill with water slowly, eventually you
      hold your breath, take damage, etc.

## Setup

Complete the setup steps for the twodee lib.

Also:

	go get -u github.com/kurrik/tmxgo

Run:

	git submodule init
	git submodule update


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DMT.Partition.Interfaces;
using DMT.Partition.Module.Remote;

namespace DMT.Partition.Module
{
    internal class PartitionSelector
    {
        private MatcherRegistry matcherRegistry;
        private PartitionRegistry partitionRegistry;

        public PartitionSelector(MatcherRegistry matcherRegistry, PartitionRegistry partitionRegistry)
        {
            this.matcherRegistry = matcherRegistry;
            this.partitionRegistry = partitionRegistry;
        }

        /// <summary>
        /// Select a partition from the registry.
        /// </summary>
        /// <param name="matcherId">the matcher id to select the partition for</param>
        /// <returns>the partition</returns>
        /// <exception cref="InvalidOperationException">when the matcher already has a partition</exception>
        public IPartition Select(Guid matcherId)
        {
            var matcher = this.matcherRegistry.GetById(matcherId);
            var partition = this.partitionRegistry.GetNextPartition();

            if (matcher.Partition != null)
            {
                throw new InvalidOperationException(
                    string.Format("A partition ({0}) was already sent to the matcher ({1}).", matcher.Partition.Id, matcher.Id));
            }

            // set the partition for the matcher
            matcher.Partition = partition;

            return partition;
        }

    }
}


text:
package edu.unc.ils.mrc.hive.api;

import edu.unc.ils.mrc.hive.HiveException;
import edu.unc.ils.mrc.hive.api.impl.elmo.SKOSSchemeImpl;
import junit.framework.Assert;
import junit.framework.TestCase;

public class SKOSSchemeTest extends TestCase {

	public void testStats() {

		try {
			String configpath = "conf";
			SKOSScheme scheme = new SKOSSchemeImpl(configpath, "agrovoc", false);
			long numBroader = scheme.getNumberOfBroader();
			Assert.assertEquals(numBroader, 27688);

			long numConcepts = scheme.getNumberOfConcepts();
			Assert.assertEquals(numConcepts, 28174);

			long numNarrower = scheme.getNumberOfNarrower();
			Assert.assertEquals(numNarrower, 27686);

			long numRelated = scheme.getNumberOfRelated();
			Assert.assertEquals(numRelated, 27712);

			long totalRelations = scheme.getNumberOfRelations();
			Assert.assertEquals(totalRelations, 83086);
			scheme.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


text:
module Cryptoexchange::Exchanges
  module Gdac
    module Services
      class Market < Cryptoexchange::Services::Market
        class << self
          def supports_individual_ticker_query?
            false
          end
        end

        def fetch
          ctx = OpenSSL::SSL::SSLContext.new
          ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE

          output = Cryptoexchange::Cache.ticker_cache.fetch(ticker_url) do
            HTTP.get(ticker_url, ssl_context: ctx).parse(:json)
          end

          adapt_all(output)
        end

        def ticker_url
          "#{Cryptoexchange::Exchanges::Gdac::Market::API_URL}/public/marketsummaries"
        end

        def adapt_all(output)
          output['result'].map { |market_data| adapt(market_data) }
        end

        def adapt(market_data)
          target, base = market_data['marketName'].split('-')
          ticker = Cryptoexchange::Models::Ticker.new
          ticker.base = base
          ticker.target = target
          ticker.market = Gdac::Market::NAME
          ticker.ask = NumericHelper.to_d(market_data['ask'])
          ticker.bid = NumericHelper.to_d(market_data['bid'])
          ticker.last = NumericHelper.to_d(market_data['last'])
          ticker.high = NumericHelper.to_d(market_data['high'])
          ticker.low = NumericHelper.to_d(market_data['low'])
          ticker.volume = NumericHelper.to_d(market_data['volume'])
          ticker.timestamp = nil
          ticker.payload = market_data
          ticker
        end
      end
    end
  end
end


text:
"""
Created on Wed Nov  5 01:18:59 2014

@author: Mehmet Emre
"""

from .base import BaseAgent
import numpy as np
import params

# parameters

B = params.argv.buffer_levels # buffer levels
B_lvl_size = params.B / (B - 1) if params.B % (B - 1) else params.B / B + 1
beta_overflow = 1000
beta_idle = params.argv.beta_idle # coefficient cost of staying idle
beta_md = 1 # misdetection punishment coefficient
beta_loss = 4 # punishment for data loss in channel
eps = 0.03 # exploration probability
discount = 0.2 # discount factor, gamma
N_P_levels = len(params.P_levels)

class IndividualQ(BaseAgent):
    '''An agent that chooses a random channel and transmits over that channel.'''

    def __init__(self, *args, **kwargs):
        super(self.__class__, self).__init__(*args, **kwargs)
        # state = (current channel, buffer level)
        # action = (transmit, channel, power level) + (idle)
        # but representing (idle) is hard here, we're representing transmit
        # by multiplying channel with power level, so idle=N_channel*len(P_levels)

        # initialize Q-values to random values in a good range
        self.Q = np.random.rand(
            params.N_channel,
            B,
            params.N_channel * N_P_levels + 1 # this is actions
        ) * params.P_tx * params.t_slot

        # store number of visits to a state-action pair
        self.visit = np.zeros([
            params.N_channel,
            B,
            params.N_channel * N_P_levels + 1 # this is actions
        ])

        self.idle_action = params.N_channel * N_P_levels

    def policy(self):
        # epsilon part of epsilon-greedy - choose a random action
        if np.random.rand() < eps:
            return np.random.randint(0, params.N_channel * N_P_levels + 1)
        # the greedy part - choose max. action
        return self.Q[self.chan, self.B_empty / B_lvl_size].argmax()

    def act(self):
        '''Return an action for current state. Choose a random channel and
        transmit over that channel. If there are multiple of such channels,
        choose randomly.'''
        super(self.__class__, self).act()

        # choose an action by policy
        self.a = self.policy()
        # store old state for feedback
        self.state = (self.chan, self.B_empty / B_lvl_size)
        self.visit[self.chan, self.state[1], self.a] += 1

        if self.a == self.idle_action:
            return self.idle()

        # get channel from action
        chan = self.a / N_P_levels
        # switch to channel
        self.switch(chan)
        # if there is traffic detected on the channel, stay idle
        if self.sense():
            return self.idle()

        # get transmission power
        self.P_tx = P_tx = params.P_levels[self.a / params.N_channel]
        bitrate = self.env.channels[chan].capacity(P_tx)
        pkgs_to_send = int((self.t_remaining * bitrate) / params.pkg_size)

        if self.B - self.B_empty < pkgs_to_send:
            pkgs_to_send = self.B - self.B_empty

        if pkgs_to_send == 0:
            return self.idle()

        return self.transmit(P_tx, pkgs_to_send)

    def alpha(self):
        "Learning rate, decreasing over time"
        return 0.1 + 0.9 / (1. + self.visit[self.state[0], self.state[1], self.a])

    def feedback(self, collision, success, idle=False, buf_overflow=False, N_pkt=0):
        super(self.__class__, self).feedback(collision, success, idle, buf_overflow, N_pkt)
        r = 0
        # disable buffer overflow punishment for now
        #if buf_overflow:
        #    if self.a == self.idle_action:
        #        # buffer overflow occurred due to staying idle
        #        r = - beta_overflow * params.P_tx * params.t_slot # get punishment for buffer overflow
        #    else:
        #        return
        #    return # disable buffer overflow punishment for now
        if idle:
            # agent stayed idle
            r = - beta_idle * self.E_slot
        elif success:
            # successful transmission, [r] = [K] * bits/J ~= J
            K = (self.P_tx) ** 2 * params.t_slot / (params.chan_bw ** 2 / self.env.channels[self.chan].capacity(self.P_tx))
            r = K * (params.pkg_size) * N_pkt / self.E_slot
        elif collision:
            # collision (not necessarily with PU)
            r = - beta_md * self.E_slot
        else:
            # all packets lost in channel
            r = - beta_loss * self.E_slot
        self.Q[self.state[0], self.state[1], self.a] += self.alpha() * (r + discount * self.Q[self.chan, self.B_empty / B_lvl_size].max() - self.Q[self.state[0], self.state[1], self.a])


text:
package com.pungwe.cms.config;

import com.pungwe.cms.core.block.services.BlockConfigServiceImpl;
import com.pungwe.cms.core.menu.impl.MenuConfigServiceImpl;
import com.pungwe.cms.core.menu.impl.MenuInfoServiceImpl;
import com.pungwe.cms.core.module.config.ModuleContextConfig;
import com.pungwe.cms.core.module.services.impl.ModuleConfigServiceImpl;
import com.pungwe.cms.core.security.service.UserManagementService;
import com.pungwe.cms.core.security.service.UserManagementServiceImpl;
import com.pungwe.cms.core.theme.services.impl.ThemeConfigServiceImpl;
import com.pungwe.cms.core.utils.services.HookService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(ModuleContextConfig.class)
public class TestConfig {

    @Bean
    public ModuleConfigServiceImpl moduleConfigService() {
        return new ModuleConfigServiceImpl();
    }

    @Bean
    public ThemeConfigServiceImpl themeConfigService() {
        return new ThemeConfigServiceImpl();
    }

    @Bean
    public MenuConfigServiceImpl menuConfigService() {
        return new MenuConfigServiceImpl();
    }

    @Bean
    public MenuInfoServiceImpl menuInfoService() {
        return new MenuInfoServiceImpl();
    }

    @Bean
    public BlockConfigServiceImpl blockConfigService() {
        return new BlockConfigServiceImpl();
    }

    @Bean
    public UserManagementServiceImpl userManagementService() {
        return new UserManagementServiceImpl();
    }
}


text:
console.log('module 1');

(function ($) {

    //set jquery to use parent frame scope by default
    isolate.modules.setJqueryToParentScope(function(){
		console.log('jquery scope set to be parent frame');
	});

})(window.jQuery);


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Requests – HTTP for Humans — Pythonista Documentation</title>
    <link rel="stylesheet" href="../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Pythonista Documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Pythonista Documentation" href="../index.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          modules |

Pythonista Documentation »

Requests – HTTP for Humans¶

This part of the documentation covers all the interfaces of Requests.

Note

Pythonista’s documentation only includes the core API documentation for <tt class="xref py py-mod docutils literal">requests</tt>. For a tutorial and more in-depth information, please visit the requests website.

Main Interface¶

All of Request’s functionality can be accessed by these 7 methods.
They all return an instance of the <tt class="xref py py-class docutils literal">Response</tt> object.

<tt class="descclassname">requests.</tt><tt class="descname">request</tt><big>(</big>method, url, **kwargs<big>)</big>¶

Constructs and sends a <tt class="xref py py-class docutils literal">Request</tt>.
Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

method – method for the new <tt class="xref py py-class docutils literal">Request</tt> object.

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

params – (optional) Dictionary or bytes to be sent in the query string for the <tt class="xref py py-class docutils literal">Request</tt>.

data – (optional) Dictionary, bytes, or file-like object to send in the body of the <tt class="xref py py-class docutils literal">Request</tt>.

headers – (optional) Dictionary of HTTP Headers to send with the <tt class="xref py py-class docutils literal">Request</tt>.

cookies – (optional) Dict or CookieJar object to send with the <tt class="xref py py-class docutils literal">Request</tt>.

files – (optional) Dictionary of ‘name’: file-like-objects (or {‘name’: (‘filename’, fileobj)}) for multipart encoding upload.

auth – (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.

timeout – (optional) Float describing the timeout of the request.

allow_redirects – (optional) Boolean. Set to True if POST/PUT/DELETE redirect following is allowed.

proxies – (optional) Dictionary mapping protocol to the URL of the proxy.

verify – (optional) if <tt class="xref docutils literal">True</tt>, the SSL cert will be verified. A CA_BUNDLE path can also be provided.

stream – (optional) if <tt class="xref docutils literal">False</tt>, the response content will be immediately downloaded.

cert – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

Usage:

>>> import requests
>>> req = requests.request('GET', 'http://httpbin.org/get')
<Response [200]>

class <tt class="descclassname">requests.</tt><tt class="descname">Response</tt>¶

The <tt class="xref py py-class docutils literal">Response</tt> object, which contains a
server’s response to an HTTP request.

<tt class="descname">apparent_encoding</tt>¶

The apparent encoding, provided by the lovely Charade library
(Thanks, Ian!).

<tt class="descname">content</tt>¶

Content of the response, in bytes.

<tt class="descname">cookies</tt>¶

A CookieJar of Cookies the server sent back.

<tt class="descname">elapsed</tt>¶

The amount of time elapsed between sending the request
and the arrival of the response (as a timedelta)

<tt class="descname">encoding</tt>¶

Encoding to decode with when accessing r.text.

<tt class="descname">headers</tt>¶

Case-insensitive Dictionary of Response Headers.
For example, <tt class="docutils literal">headers['content-encoding']</tt> will return the
value of a <tt class="docutils literal">'Content-Encoding'</tt> response header.

<tt class="descname">history</tt>¶

A list of <tt class="xref py py-class docutils literal">Response</tt> objects from
the history of the Request. Any redirect responses will end
up here. The list is sorted from the oldest to the most recent request.

<tt class="descname">iter_content</tt><big>(</big>chunk_size=1, decode_unicode=False<big>)</big>¶

Iterates over the response data.  When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses.  The chunk size is the number of bytes it should
read into memory.  This is not necessarily the length of each item
returned as decoding can take place.

<tt class="descname">iter_lines</tt><big>(</big>chunk_size=512, decode_unicode=None<big>)</big>¶

Iterates over the response data, one line at a time.  When
stream=True is set on the request, this avoids reading the
content at once into memory for large responses.

<tt class="descname">json</tt><big>(</big>**kwargs<big>)</big>¶

Returns the json-encoded content of a response, if any.

<col class="field-name" />
<col class="field-body" />

Parameters:	**kwargs – Optional arguments that <tt class="docutils literal">json.loads</tt> takes.

<tt class="descname">links</tt>¶

Returns the parsed header links of the response, if any.

<tt class="descname">raise_for_status</tt><big>(</big><big>)</big>¶

Raises stored <tt class="xref py py-class docutils literal">HTTPError</tt>, if one occurred.

<tt class="descname">raw</tt>¶

File-like object representation of response (for advanced usage).
Requires that ``stream=True` on the request.

<tt class="descname">status_code</tt>¶

Integer Code of responded HTTP Status.

<tt class="descname">text</tt>¶

Content of the response, in unicode.

if Response.encoding is None and chardet module is available, encoding
will be guessed.

<tt class="descname">url</tt>¶

Final URL location of Response.

<tt class="descclassname">requests.</tt><tt class="descname">head</tt><big>(</big>url, **kwargs<big>)</big>¶

Sends a HEAD request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descclassname">requests.</tt><tt class="descname">get</tt><big>(</big>url, **kwargs<big>)</big>¶

Sends a GET request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descclassname">requests.</tt><tt class="descname">post</tt><big>(</big>url, data=None, **kwargs<big>)</big>¶

Sends a POST request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

data – (optional) Dictionary, bytes, or file-like object to send in the body of the <tt class="xref py py-class docutils literal">Request</tt>.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descclassname">requests.</tt><tt class="descname">put</tt><big>(</big>url, data=None, **kwargs<big>)</big>¶

Sends a PUT request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

data – (optional) Dictionary, bytes, or file-like object to send in the body of the <tt class="xref py py-class docutils literal">Request</tt>.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descclassname">requests.</tt><tt class="descname">patch</tt><big>(</big>url, data=None, **kwargs<big>)</big>¶

Sends a PATCH request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

data – (optional) Dictionary, bytes, or file-like object to send in the body of the <tt class="xref py py-class docutils literal">Request</tt>.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descclassname">requests.</tt><tt class="descname">delete</tt><big>(</big>url, **kwargs<big>)</big>¶

Sends a DELETE request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descclassname">requests.</tt><tt class="descname">session</tt><big>(</big><big>)</big>¶

Returns a <tt class="xref py py-class docutils literal">Session</tt> for context-management.

Exceptions¶

exception <tt class="descclassname">requests.</tt><tt class="descname">RequestException</tt>¶

There was an ambiguous exception that occurred while handling your
request.

exception <tt class="descclassname">requests.</tt><tt class="descname">ConnectionError</tt>¶

A Connection error occurred.

exception <tt class="descclassname">requests.</tt><tt class="descname">HTTPError</tt><big>(</big>*args, **kwargs<big>)</big>¶

An HTTP error occurred.

exception <tt class="descclassname">requests.</tt><tt class="descname">URLRequired</tt>¶

A valid URL is required to make a request.

exception <tt class="descclassname">requests.</tt><tt class="descname">TooManyRedirects</tt>¶

Too many redirects.

Configurations¶

Internals¶

These items are an internal component to Requests, and should never be
seen by the end user (developer). This part of the API documentation
exists for those who are extending the functionality of Requests.

Classes¶

class <tt class="descclassname">requests.</tt><tt class="descname">Response</tt>

The <tt class="xref py py-class docutils literal">Response</tt> object, which contains a
server’s response to an HTTP request.

<tt class="descname">apparent_encoding</tt>

The apparent encoding, provided by the lovely Charade library
(Thanks, Ian!).

<tt class="descname">content</tt>

Content of the response, in bytes.

<tt class="descname">cookies</tt>

A CookieJar of Cookies the server sent back.

<tt class="descname">elapsed</tt>

The amount of time elapsed between sending the request
and the arrival of the response (as a timedelta)

<tt class="descname">encoding</tt>

Encoding to decode with when accessing r.text.

<tt class="descname">headers</tt>

Case-insensitive Dictionary of Response Headers.
For example, <tt class="docutils literal">headers['content-encoding']</tt> will return the
value of a <tt class="docutils literal">'Content-Encoding'</tt> response header.

<tt class="descname">history</tt>

A list of <tt class="xref py py-class docutils literal">Response</tt> objects from
the history of the Request. Any redirect responses will end
up here. The list is sorted from the oldest to the most recent request.

<tt class="descname">iter_content</tt><big>(</big>chunk_size=1, decode_unicode=False<big>)</big>

Iterates over the response data.  When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses.  The chunk size is the number of bytes it should
read into memory.  This is not necessarily the length of each item
returned as decoding can take place.

<tt class="descname">iter_lines</tt><big>(</big>chunk_size=512, decode_unicode=None<big>)</big>

Iterates over the response data, one line at a time.  When
stream=True is set on the request, this avoids reading the
content at once into memory for large responses.

<tt class="descname">json</tt><big>(</big>**kwargs<big>)</big>

Returns the json-encoded content of a response, if any.

<col class="field-name" />
<col class="field-body" />

Parameters:	**kwargs – Optional arguments that <tt class="docutils literal">json.loads</tt> takes.

<tt class="descname">links</tt>

Returns the parsed header links of the response, if any.

<tt class="descname">raise_for_status</tt><big>(</big><big>)</big>

Raises stored <tt class="xref py py-class docutils literal">HTTPError</tt>, if one occurred.

<tt class="descname">raw</tt>

File-like object representation of response (for advanced usage).
Requires that ``stream=True` on the request.

<tt class="descname">status_code</tt>

Integer Code of responded HTTP Status.

<tt class="descname">text</tt>

Content of the response, in unicode.

if Response.encoding is None and chardet module is available, encoding
will be guessed.

<tt class="descname">url</tt>

Final URL location of Response.

class <tt class="descclassname">requests.</tt><tt class="descname">Request</tt><big>(</big>method=None, url=None, headers=None, files=None, data={}, params={}, auth=None, cookies=None, hooks=None<big>)</big>¶

A user-created <tt class="xref py py-class docutils literal">Request</tt> object.

Used to prepare a <tt class="xref py py-class docutils literal">PreparedRequest</tt>, which is sent to the server.

<col class="field-name" />
<col class="field-body" />

Parameters:

method – HTTP method to use.

url – URL to send.

headers – dictionary of headers to send.

files – dictionary of {filename: fileobject} files to multipart upload.

data – the body to attach the request. If a dictionary is provided, form-encoding will take place.

params – dictionary of URL parameters to append to the URL.

auth – Auth handler or (user, pass) tuple.

cookies – dictionary or CookieJar of cookies to attach to this request.

hooks – dictionary of callback hooks, for internal usage.

Usage:

>>> import requests
>>> req = requests.Request('GET', 'http://httpbin.org/get')
>>> req.prepare()
<PreparedRequest [GET]>

<tt class="descname">deregister_hook</tt><big>(</big>event, hook<big>)</big>¶

Deregister a previously registered hook.
Returns True if the hook existed, False if not.

<tt class="descname">prepare</tt><big>(</big><big>)</big>¶

Constructs a <tt class="xref py py-class docutils literal">PreparedRequest</tt> for transmission and returns it.

<tt class="descname">register_hook</tt><big>(</big>event, hook<big>)</big>¶

Properly register a hook.

class <tt class="descclassname">requests.</tt><tt class="descname">Session</tt>¶

A Requests session.

Provides cookie persistience, connection-pooling, and configuration.

Basic Usage:

>>> import requests
>>> s = requests.Session()
>>> s.get('http://httpbin.org/get')
200

<tt class="descname">auth</tt>¶

Default Authentication tuple or object to attach to
<tt class="xref py py-class docutils literal">Request</tt>.

<tt class="descname">cert</tt>¶

SSL certificate default.

<tt class="descname">close</tt><big>(</big><big>)</big>¶

Closes all adapters and as such the session

<tt class="descname">delete</tt><big>(</big>url, **kwargs<big>)</big>¶

Sends a DELETE request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descname">get</tt><big>(</big>url, **kwargs<big>)</big>¶

Sends a GET request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descname">get_adapter</tt><big>(</big>url<big>)</big>¶

Returns the appropriate connnection adapter for the given URL.

<tt class="descname">head</tt><big>(</big>url, **kwargs<big>)</big>¶

Sends a HEAD request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descname">headers</tt>¶

A case-insensitive dictionary of headers to be sent on each
<tt class="xref py py-class docutils literal">Request</tt> sent from this
<tt class="xref py py-class docutils literal">Session</tt>.

<tt class="descname">hooks</tt>¶

Event-handling hooks.

<tt class="descname">max_redirects</tt>¶

Maximum number of redirects allowed. If the request exceeds this
limit, a <tt class="xref py py-class docutils literal">TooManyRedirects</tt> exception is raised.

<tt class="descname">mount</tt><big>(</big>prefix, adapter<big>)</big>¶

Registers a connection adapter to a prefix.

Adapters are sorted in descending order by key length.

<tt class="descname">options</tt><big>(</big>url, **kwargs<big>)</big>¶

Sends a OPTIONS request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descname">params</tt>¶

Dictionary of querystring data to attach to each
<tt class="xref py py-class docutils literal">Request</tt>. The dictionary values may be lists for
representing multivalued query parameters.

<tt class="descname">patch</tt><big>(</big>url, data=None, **kwargs<big>)</big>¶

Sends a PATCH request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

data – (optional) Dictionary, bytes, or file-like object to send in the body of the <tt class="xref py py-class docutils literal">Request</tt>.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descname">post</tt><big>(</big>url, data=None, **kwargs<big>)</big>¶

Sends a POST request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

data – (optional) Dictionary, bytes, or file-like object to send in the body of the <tt class="xref py py-class docutils literal">Request</tt>.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descname">proxies</tt>¶

Dictionary mapping protocol to the URL of the proxy (e.g.
{‘http’: ‘foo.bar:3128’}) to be used on each
<tt class="xref py py-class docutils literal">Request</tt>.

<tt class="descname">put</tt><big>(</big>url, data=None, **kwargs<big>)</big>¶

Sends a PUT request. Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

data – (optional) Dictionary, bytes, or file-like object to send in the body of the <tt class="xref py py-class docutils literal">Request</tt>.

**kwargs – Optional arguments that <tt class="docutils literal">request</tt> takes.

<tt class="descname">request</tt><big>(</big>method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None<big>)</big>¶

Constructs a <tt class="xref py py-class docutils literal">Request</tt>, prepares it and sends it.
Returns <tt class="xref py py-class docutils literal">Response</tt> object.

<col class="field-name" />
<col class="field-body" />

Parameters:

method – method for the new <tt class="xref py py-class docutils literal">Request</tt> object.

url – URL for the new <tt class="xref py py-class docutils literal">Request</tt> object.

params – (optional) Dictionary or bytes to be sent in the query
string for the <tt class="xref py py-class docutils literal">Request</tt>.

data – (optional) Dictionary or bytes to send in the body of the
<tt class="xref py py-class docutils literal">Request</tt>.

headers – (optional) Dictionary of HTTP Headers to send with the
<tt class="xref py py-class docutils literal">Request</tt>.

cookies – (optional) Dict or CookieJar object to send with the
<tt class="xref py py-class docutils literal">Request</tt>.

files – (optional) Dictionary of ‘filename’: file-like-objects
for multipart encoding upload.

auth – (optional) Auth tuple or callable to enable
Basic/Digest/Custom HTTP Auth.

timeout – (optional) Float describing the timeout of the
request.

allow_redirects – (optional) Boolean. Set to True by default.

proxies – (optional) Dictionary mapping protocol to the URL of
the proxy.

stream – (optional) whether to immediately download the response
content. Defaults to <tt class="xref docutils literal">False</tt>.

verify – (optional) if <tt class="xref docutils literal">True</tt>, the SSL cert will be verified.
A CA_BUNDLE path can also be provided.

cert – (optional) if String, path to ssl client cert file (.pem).
If Tuple, (‘cert’, ‘key’) pair.

<tt class="descname">resolve_redirects</tt><big>(</big>resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None<big>)</big>¶

Receives a Response. Returns a generator of Responses.

<tt class="descname">send</tt><big>(</big>request, **kwargs<big>)</big>¶

Send a given PreparedRequest.

<tt class="descname">stream</tt>¶

Stream response content default.

<tt class="descname">trust_env</tt>¶

Should we trust the environment?

<tt class="descname">verify</tt>¶

SSL Verification default.

    © Copyright 1990-2016, Python Software Foundation.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on Jun 10, 2016.
    Found a bug?

    Created using Sphinx 1.0.7.


text:
require 'test_helper'

class ActivityTypesControllerTest < ActionController::TestCase
  setup do
    @activity_type = activity_types(:one)
  end

  test "should get index" do
    get :index
    assert_response :success
    assert_not_nil assigns(:activity_types)
  end

  test "should get new" do
    get :new
    assert_response :success
  end

  test "should create activity_type" do
    assert_difference('ActivityType.count') do
      post :create, activity_type: { activity_category_id: @activity_type.activity_category_id, description: @activity_type.description, name: @activity_type.name }
    end

    assert_redirected_to activity_type_path(assigns(:activity_type))
  end

  test "should show activity_type" do
    get :show, id: @activity_type
    assert_response :success
  end

  test "should get edit" do
    get :edit, id: @activity_type
    assert_response :success
  end

  test "should update activity_type" do
    patch :update, id: @activity_type, activity_type: { activity_category_id: @activity_type.activity_category_id, description: @activity_type.description, name: @activity_type.name }
    assert_redirected_to activity_type_path(assigns(:activity_type))
  end

  test "should destroy activity_type" do
    assert_difference('ActivityType.count', -1) do
      delete :destroy, id: @activity_type
    end

    assert_redirected_to activity_types_path
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Sydowia 4: 89 (1961)

#### Original name
Cyphella marginata McAlpine

### Remarks
null


text:
<FindBugsFilter>
	<!--For artem-zinnatullin/qualitymatters
	https://github.com/artem-zinnatullin/qualitymatters/blob/master/code_quality_tools/findbugs-filter.xml-->
	<!-- Do not check auto-generated resources classes -->
	<Match>
		<Class name="~.*R\$.*"/>
	</Match>

	<!-- Do not check auto-generated manifest classes -->
	<Match>
		<Class name="~.*Manifest\$.*"/>
	</Match>

	<!-- Do not check auto-generated classes (Dagger puts $ into class names) -->
	<Match>
		<Class name="~.*Dagger*.*"/>
	</Match>

	<!-- Do not check for non-initialized fields in tests because usually we initialize them in @Before -->
	<Match>
		<Class name="~.*Test"/>
		<Bug pattern="UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR"
			 type="UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR"/>
	</Match>

	<!-- Ignore UPM in lambdas from Retrolambda, FindBugs does not correctly understand them -->
	<Match>
		<Bug code="UPM"/>
		<Class name="~.*\$\$Lambda\$.*"/>
	</Match>

	<!-- Ignore Butterknife auto-generated classes -->
	<Match>
		<Class name="~.*\$\$ViewBinder*"/>
	</Match>
	<Match>
		<Class name="~.*\$\$ViewBinder\$InnerUnbinder*"/>
	</Match>

	<!--CUSTOM-->
	<Match>
		<Class name="~.*\.R\$.*"/>
	</Match>
	<!--В основном это класс для Retrofit запросов-->
	<Match>
		<Bug pattern="URF_UNREAD_FIELD"/>
	</Match>
</FindBugsFilter>


text:
// Statement Renderer
// Michael Dream Team, 2014

$(document).ready(function() {
	$("#statement-print").on("click", function(e) {
		window.print();
	});
});

/*

	$('#donor_statement_year').on("change", function(e) {

		// Get Donor Statement
		var statement_start_date = new Date($("#donor_statement_year").val(),0,1);
		var statement_end_date = new Date($("#donor_statement_year").val(),11,31);
		var pretty_start_date = statement_start_date.getFullYear() + "-" + statement_start_date.getMonth() + "-" + statement_start_date.getDate();
		var pretty_end_date = statement_end_date.getFullYear() + "-" + statement_end_date.getMonth() + "-" + statement_end_date.getDate();

		$.ajax({

			url: GLOBAL.SERVER_URL + '/api/donors/donations.json',
			method: 'GET',
			data: {"start_date" : "2014-01-01", "end_date" : "2014-12-31" },
			contentType: "application/json",
			dataType:"json",

			success: function(response) {
				// need to do response.donations.each
				// response looks like: {"donations":[{"donation":{"created_at":"2013-12-01T01:52:34Z","donor_id":6,"endowment_id":11,"gross_amount":333.0,"id":3,"net_amount":323.043,"payment_account_id":2,"shares_added":"0.00323043","transaction_fees":9.957,"updated_at":"2013-12-01T01:52:34Z"}}],"total":333.0}
					var donations = { date: 'funDate', description: "funDescription", amount: "funAmount" };
					$(".table-striped tbody").children().remove();
					$("#donation-row-template").tmpl(donations).appendTo(".table-striped tbody");

				// console.log(data)

			},
			failure: function(response) {
				//console.log(data);
				window.location.href = "index.html";
			}

		});
	});
});
*/


text:
dir = File.dirname(__FILE__)

gem 'slim-rails'
gem 'simple_form', github: 'plataformatec/simple_form', branch: 'master'
gem 'ransack'
gem 'kaminari'
gem 'active_decorator'

use_bootstrap = if yes?('Use Bootstrap?')
                  uncomment_lines 'Gemfile', "gem 'therubyracer'"
                  gem 'less-rails'
                  gem 'twitter-bootstrap-rails'
                  true
                else
                  false
                end

use_unicorn = if yes?('Use unicorn?')
                uncomment_lines 'Gemfile', "gem 'unicorn'"
                true
              else
                false
              end

gem 'whenever', require: false if yes?('Use whenever?')
use_devise = if yes?('Use devise?')
               gem 'devise'
               gem 'devise-i18n'
               devise_model = ask 'Please input devise model name. ex) User, Admin: '
               true
             else
               false
             end

use_cancan = if yes?('Use cancan?')
               gem 'cancan'
               true
             else
               false
             end

use_heroku = if yes?('Use heroku?')
               gem 'rails_12factor', group: :production
               true
             else
               false
             end

gem_group :development, :test do
  gem 'rspec-rails'
  gem "factory_girl_rails"
  gem 'capybara'
  gem 'capybara-webkit'
end

gem_group :development do
  gem 'pry-rails'
  gem 'parallel_tests'
  gem 'better_errors'
  gem "binding_of_caller"
  gem 'spring'
  gem 'letter_opener'
  gem 'annotate'
end

gem_group :test do
  gem 'database_cleaner'
  gem 'timecop'
  gem 'launchy'
  gem 'webmock', require: 'webmock/rspec'
end

run_bundle
generate 'kaminari:config'
generate 'rspec:install'
remove_dir 'test'

if use_bootstrap
  generate 'bootstrap:install', 'less'
  generate 'simple_form:install', '--bootstrap'
  if yes?("Use responsive layout?")
    generate 'bootstrap:layout', 'application fluid'
  else
    generate 'bootstrap:layout', 'application fixed'
    append_to_file 'app/assets/stylesheets/application.css' do
      "body { padding-top:60px }"
    end
  end
  remove_file 'app/views/layouts/application.html.erb'
else
  generate 'simple_form:install'
end

# Application settings
# ----------------------------------------------------------------
application do
  %q{
    config.active_record.default_timezone = :local
    config.time_zone = 'Tokyo'
    config.i18n.default_locale = :ja

    config.generators do |g|
      g.orm :active_record
      g.test_framework :rspec, fixture: true, fixture_replacement: :factory_girl
      g.view_specs false
      g.controller_specs false
      g.routing_specs false
      g.helper_specs false
      g.request_specs false
      g.assets false
      g.helper false
    end

    config.autoload_paths += %W(#{config.root}/lib)
  }
end

# Environment setting
# ----------------------------------------------------------------
comment_lines 'config/environments/production.rb', "config.serve_static_assets = false"
environment 'config.serve_static_assets = true', env: 'production'
environment 'config.action_mailer.delivery_method = :letter_opener', env: 'development'

# RSpec setting
# ----------------------------------------------------------------
remove_file 'spec'
directory File.expand_path('spec', dir), 'spec', recursive: true

if use_devise
  uncomment_lines 'spec/spec_helper.rb', 'include Warden::Test::Helpers'
  uncomment_lines 'spec/spec_helper.rb', 'config.include Devise::TestHelpers, type: :controller'
  uncomment_lines 'spec/spec_helper.rb', 'config.include Devise::TestHelpers, type: :view'
  uncomment_lines 'spec/spec_helper.rb', 'Warden.test_mode!'
  uncomment_lines 'spec/spec_helper.rb', 'Warden.test_reset!'
  generate 'devise:install'
end

if use_cancan
  generate 'cancan:ability'
end

append_to_file '.rspec' do
  "--format documentation\n--format ParallelTests::RSpec::FailuresLogger --out tmp/failing_specs.log"
end

# Unicorn setting
# ----------------------------------------------------------------
if use_unicorn
  copy_file File.expand_path('config/unicorn.rb', dir), 'config/unicorn.rb'
  create_file 'Procfile' do
    body = <<EOS
web: bundle exec unicorn -p $PORT -c ./config/unicorn.rb
EOS
  end
else
  create_file 'Procfile' do
    body = <<EOS
web: bundle exec rails server -p $PORT
EOS
  end
end

create_file '.foreman' do
  body = <<EOS
port: 3000
EOS
end

# .gitignore settings
# ----------------------------------------------------------------
remove_file '.gitignore'
create_file '.gitignore' do
  body = <<EOS
/.bundle
/db/*.sqlite3
/log/*.log
/tmp
.DS_Store
/public/assets*
/config/database.yml
newrelic.yml
.foreman
.env
doc/
*.swp
*~
.project
.idea
.secret
/*.iml
EOS
end

# Root path settings
# ----------------------------------------------------------------
generate 'controller', 'home index'
route "root to: 'home#index'"

# Create directories
# ----------------------------------------------------------------
empty_directory 'app/decorators'
create_file 'app/decorators/.gitkeep'

# Database settings
# ----------------------------------------------------------------
case gem_for_database
  when 'pg', 'mysql2'
    run "sed -i -e \"s/#{app_name}_test/#{app_name}_test<%= ENV[\\'TEST_ENV_NUMBER\\']%>/g\" config/database.yml"
  when 'sqlite3'
    run "sed -i -e \"s/db\\/test.sqlite3/db\\/test<%= ENV[\\'TEST_ENV_NUMBER\\']%>.sqlite3/g\" config/database.yml"
  else
end

run "cp config/database.yml config/database.yml.sample"

case gem_for_database
  when 'pg'
    run "createuser -h localhost -d #{app_name}"
  else
end

rake 'db:drop'
rake 'db:create'
rake 'db:migrate'
rake 'parallel:create'
rake 'parallel:prepare'

# git
# ----------------------------------------------------------------
git :init
git add: "."
git commit: %Q{ -m 'Initial commit' }

# Bitbucket
# ----------------------------------------------------------------
use_bitbucket = if yes?('Push Bitbucket?')
                  git_uri = `git config remote.origin.url`.strip
                  if git_uri.size == 0
                    username = ask "What is your Bitbucket username?"
                    password = ask "What is your Bitbucket password?"
                    run "curl -k -X POST --user #{username}:#{password} 'https://api.bitbucket.org/1.0/repositories' -d 'name=#{app_name}&is_private=true'"
                    git remote: "add origin git@bitbucket.org:#{username}/#{app_name}.git"
                    git push: 'origin master'
                  else
                    say "Repository already exists:"
                    say "#{git_uri}"
                  end
                  true
                else
                  false
                end

if use_heroku
  if yes?('Deploy heroku staging?')
    run 'heroku create --remote staging'
    git push: 'staging master'
  end
end

if use_devise
  environment "config.action_mailer.default_url_options = { host: 'localhost:3000' }", env: 'development'
  environment "config.action_mailer.default_url_options = { host: 'localhost:3000' }", env: 'test'
  generate "devise #{devise_model}"
  generate 'devise:views'
  git add: "."
  git commit: %Q{ -m 'Add devise model and views.' }
  if use_bitbucket
    git push: 'origin master'
  end
  say "!!! Please set up #{devise_model} migration file and rake db:migrate !!!"
end
exit


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using osu.Game.Rulesets.Catch.Judgements;
using osu.Game.Rulesets.Judgements;

namespace osu.Game.Rulesets.Catch.Objects
{
    public class Droplet : CatchHitObject
    {
        public override Judgement CreateJudgement() => new CatchDropletJudgement();
    }
}


text:
package hudson.plugins.grizz;

import static org.mockito.Mockito.mock;
import hudson.model.AbstractProject;
import junit.framework.TestCase;

public class BeardDescriptorTest extends TestCase {

	private BeardDescriptor descriptor;

	public void setUp() {
		descriptor = new BeardDescriptor();
	}

	public void testGetDisplayName() {
		assertEquals("Activate Grizz", descriptor.getDisplayName());
	}

	public void testIsApplicableGivesTrue() {
		assertTrue(descriptor.isApplicable(mock(AbstractProject.class)
				.getClass()));
	}
}


text:
using System.ComponentModel;
using System.Windows.Forms;

namespace Wolf
{
    partial class ImageViewer
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            //
            // pictureBox1
            //
            this.pictureBox1.BackColor = System.Drawing.Color.Fuchsia;
            this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pictureBox1.Location = new System.Drawing.Point(0, 0);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(284, 261);
            this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            //
            // ImageViewer
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.AutoSize = true;
            this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.ClientSize = new System.Drawing.Size(284, 261);
            this.Controls.Add(this.pictureBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.MaximumSize = new System.Drawing.Size(1280, 720);
            this.Name = "ImageViewer";
            this.Text = "ImageViewer";
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private PictureBox pictureBox1;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace Hydra.Framework.RssToolkit.Rss
{
    /// <summary>
    ///  RssTextInput class
    /// </summary>
    [Serializable]
    public class RssTextInput
    {
        private string _title;
        private string _description;
        private string _name;
        private string _link;

        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        /// <value>The description.</value>
        [XmlElement("description")]
        public string Description
        {
            get
            {
                return _description;
            }

            set
            {
                _description = value;
            }
        }

        /// <summary>
        /// Gets or sets the link.
        /// </summary>
        /// <value>The link.</value>
        [XmlElement("link")]
        public string Link
        {
            get
            {
                return _link;
            }

            set
            {
                _link = value;
            }
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        /// <value>The name.</value>
        [XmlElement("name")]
        public string Name
        {
            get
            {
                return _name;
            }

            set
            {
                _name = value;
            }
        }

        /// <summary>
        /// Gets or sets the title.
        /// </summary>
        /// <value>The title.</value>
        [XmlElement("title")]
        public string Title
        {
            get
            {
                return _title;
            }

            set
            {
                _title = value;
            }
        }
    }
}


text:
/* */
var baseClone = require('./_baseClone');
function clone(value) {
  return baseClone(value, false, true);
}
module.exports = clone;


text:
using System.IO;
using System.Text;

namespace SyslogNet.Client.Serialization
{
    /// <summary>
    /// syslog message serializer.
    /// </summary>
    public interface ISyslogMessageSerializer
    {
        /// <summary>
        /// Serializes a message to a stream.
        /// </summary>
        /// <param name="message">Message.</param>
        /// <param name="stream">Stream.</param>
        void Serialize(SyslogMessage message, Stream stream);

        /// <summary>
        /// Gets the encoding.
        /// </summary>
        /// <value>The encoding used for serialization.</value>
        Encoding Encoding { get; }
    }
}


text:
<form name="editForm" role="form" novalidate ng-submit="save()">

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true"
                ng-click="clear()">×</button>

Create or edit a Allocation

        <jh-alert-error></jh-alert-error>

            ID
            <input type="text" class="form-control" id="id" name="id"
                    ng-model="allocation.id" readonly />

            Fte
            <input type="number" class="form-control" name="fte" id="field_fte"
                    ng-model="allocation.fte"
                     />

            Year
            <input type="number" class="form-control" name="year" id="field_year"
                    ng-model="allocation.year"
                     />

            Month
            <input type="number" class="form-control" name="month" id="field_month"
                    ng-model="allocation.month"
                     />

            projectCountry
            <select class="form-control" id="field_projectCountry" name="projectCountry" ng-model="allocation.projectCountryId" ng-options="projectCountry.id as projectCountry.id for projectCountry in projectcountrys | orderBy:'id'">
                <option value=""></option>
            </select>

            employment
            <select class="form-control" id="field_employment" name="employment" ng-model="allocation.employmentId" ng-options="employment.id as employment.id for employment in employments | orderBy:'id'">
                <option value=""></option>
            </select>

            skill
            <select class="form-control" id="field_skill" name="skill" ng-model="allocation.skillId" ng-options="skill.id as skill.id for skill in skills | orderBy:'id'">
                <option value=""></option>
            </select>

        <button type="button" class="btn btn-default" data-dismiss="modal" ng-click="clear()">
             Cancel
        </button>
        <button type="submit" ng-disabled="editForm.$invalid || isSaving" class="btn btn-primary">
             Save
        </button>

</form>


text:
# fh-rest-express-router

[![Circle CI](https://travis-ci.org/feedhenry-staff/fh-rest-express-router.svg?branch=master)](https://travis-ci.org/feedhenry-staff/fh-rest-express-router)
[![node](https://img.shields.io/node/v/gh-badges.svg?maxAge=2592000)](https://github.com/feedhenry-staff/fh-rest-express-router)

Spend less time writing repetitive integrations, and more time building awesome
mobile APIs!

## What?
Building RESTful APIs in node.js typically has many decisions involved that
aren't immediately apparent. For example, how do you plan to sanatise inputs
that might contain invalid querystring parameters? Should you use an existing
library to do this?
How can you achieve it in a DRY (don't repeat yourself) manner whilst retaining
flexility to add new rules in the future? A series of if/else statements? Sure
that works, but are you aware of how JavaScript handles _parseInt_,
the _Number_, and _NaN_ types? Do you want to unit test for all of those Number
type edge cases? What about your URL structure and use of HTTP verbs? Should you
use PUT or POST for updates?

It's a little overwhelming unless you're happy to invest a significant amount of
time and effort to figure these things out. Thankfully *fh-rest-express-router*
makes sensible decisions for you so you can save time on these details and do
the real integration work required to power your API.

Using microservices (MBaaS Services), built with *fh-rest*, running on the
Red Hat Mobile Application Platform MBaaS enables enterprises to create
lightweight, reusable APIs that meet the goals listed above and avoid the
pitfalls we discussed above. These APIs can then be leveraged as part of their
wider mobility strategy.

## How?
Red Hat Mobile Application Platform creates microservices using the express web
framework. Utilising the modular nature of node.js and express allowed us to
create *fh-rest-express-router*.

*fh-rest-express-router* creates a series of RESTful route handlers for a
_dataset_ identified with a *String:name*, and interfaces with an underlying
data store via an adapter/interface. Essentially this is a HTTP API that can be
used to perform CRUDL operations on the underlying dataset through the adapter.
Typically this dataset is a legacy SOAP system, Oracle Database, or some form of
ESB.

Your created can be called by a Cloud Application on RHMAP by using
*fh.service* and, as an added bonus, the created RESTful API can be utilised
by *fh-rest-sync-proxy* since the format exposed is compatible with the
FH.Sync SDK; this means you can synchronise backend data to mobile devices and
perform CRUDL operations with a ludicrously small amount of code. You can also
use cURL and Postman.

## Adapters
In the last section we mentioned that adapters perform the heavy lifting for
your RESTful API that is created by _fh-rest-express-router_, by performing
database calls, disk read/write, or other functions to support your RESTful API.
We currently have a number of adapters that can be used for common data stores.

* _fh-rest-mysql-adapter_ - reads and writes data to a table in MySQL
* _fh-rest-mongodb-adapter_ - reads and writes data to a MongoDB collection
* _fh-rest-memory-adapter_ - stores data in the node.js microservice memory,
this is volatile and therefore should not be used if data must be persisted

## Install

```
cd $YOUR_PROJECT_DIR
npm install fh-rest-express-router --save
npm install express@4.14 --save
```

## Usage

```js
'use strict';

/**
 * filename: application.js
 * The entry point of our RHAMP MBaaS Service
 */

const express = require('express')
const mbaasApi = require('fh-mbaas-api')
const mbaasExpress = mbaasApi.mbaasExpress()
const app = module.exports = express()
const log = require('fh-bunyan').getLogger(__filename);
const Joi = require('joi');

const port = process.env.FH_PORT || process.env.VCAP_APP_PORT || 8001;

log.info('starting application');

// Note: the order which we add middleware to Express here is important!
app.use('/sys', mbaasExpress.sys([]));
app.use('/mbaas', mbaasExpress.mbaas);

// Note: important that this is added just before your own Routes
app.use(mbaasExpress.fhmiddleware());

// Module used to create RESTful router instances
const fhRestExpressRouter = require('fh-rest-express-router');

// Module that RESTful router will use to retrieve data
// Note: this is not yet developed
const fhRestMemoryAdapter = require('fh-rest-memory-adapter');

// Creates a handler for incoming HTTP requests that want to perform CRUDL
// operations on the "orders" table in your MySQL database
const ordersRouter = fhRestExpressRouter({
  // The name of this router
  name: 'orders',

  // Joi schemas that validate the querystring/body is safe to pass to
  // an adapter instance. Only for list, create, update and read
  bodyAndQueryValidations: {
    'list': [{
      schema: require('./validate-list-schema.js'),
      options: {
        stripUnknown: true //Allow parameters not in Joi schema through
      }
    }],
    'create': [{
      schema: require('./validate-create-schema.js'),
      options: {
        allowUnknown: true // Remove parameters not in Joi schema
      }
    }],
    'update': [{
      schema: require('./validate-update-schema.js'),
      options: {
        noDefaults: true // Do not use default values set in Joi schema
      }
    })],
    'read': [{
      schema: require('./validate-read-schema.js'),
      options: {
        abortEarly: false // Run all validations and return any and all errors
      }
    }]
  },

  // Similar to the bodyAndQueryValidations, but operates on route params,
  // AKA the variable parts of a url, e.g in "/orders/:id" the "id" is variable
  routeParamValidations: {
    'read': [{
      schema: Joi.object().keys({
        // Verify the id in the URL is an integer, if it's not then the request
        // receives a "400 Bad Request" explaining this error
        id: Joi.number().required()
      }),
      options: { /* optional joi options */ }
    }]
  },
  // The adapter that performs CRUDL functions on your behalf
  adapter: fhRestMemoryAdapter()
});

ordersRouter.events.on('create-success', function (data) {
  // Do something with the data
  console.log('created order with data', data);
});

ordersRouter.events.on('create-fail', function (data) {
  // Take an action to handle the error, e.g report it somewhere
});

// Expose a RESTful API to orders data, e.g:
// GET /orders/12345
app.use('/orders', ordersRouter);

// Important that this is last!
app.use(mbaasExpress.errorHandler());

app.listen(port, function() {
  log.info('app started on port: %s', port);
});
```

## API
This module is a factory function. Simply require it, then call it with
options to make it return preconfigured instances of _express.Router_ as shown
in the example above.

### Options
It supports being passed the following options:

* [Required] adapter - adapter instance that will handle CRUDL operations
* [Required] name - a name that will identify this adapter in logs
* [Optional] bodyAndQueryValidations - Array containing Joi schemas and Joi
options that will be used to validate data passed to create, update, and list
operations is safe.
* [Optional] routeParamValidations - Array containing Joi schemas and Joi
options that will be used to validate parameters in a route (URL) are valid.

### Events
Events can be accessed using the *router.events* which is an EventEmitter
instance. It emits the following events:

* create-fail
* read-fail
* update-fail
* delete-fail
* list-fail
* create-success
* read-success
* update-success
* delete-success
* list-success

Success event callbacks are passed the response the adapter generated. Error
events are passed the _Error_ instance that has been generated. Check the
/examples folder for more information.

## RESTful (HTTP) API Definition
The example provided above exposes a RESTful API that uses JSON as the data
interchange format. Below we cover the routes it exposes that will facilitate
the CRUDL operations discussed.

In the below examples *dataset-name* can be anything you like, e.g "orders"
from the example above, or "users" in the sample below.

#### Try it Out
If all this talk of RESTful APIs and routes has you confused, fear not. We've
included a sample server and set of requests to help.

To run the server type `npm install` inside this folder, followed by
`npm run example` when that has completed. Congratulations you're now running
a RESTful API locally.

To hit your local server try using the *postman_collection* file included.
Download Postman, then use *Collections => Import* to load the sample requests
file included, *fh-rest-express-router.json.postman_collection*. After doing
this you can use Postman to make CRUDL calls to the local server. Take note of
the ID (uid) returned from create operations so you can update URLs accordingly
in Postman, i.e change "1" to whatever uid was returned by create or list calls.

Note: You can use cURL or any other HTTP client to hit the example server, but
Postman is a nice cross platform tool for doing so.

#### Request Definition
Each incoming request should have the *Content-Type* header set to
*application/json*. If you plan to use our *fh.service* API then this will be
taken care of for you.

#### GET /dataset-name (LIST)
Generic list endpoint that returns an Object containing key value pairs based
on a querystring. Keys must be unique IDs and values must be Objects.

Sample URL: GET /users?group=admin

Sample response:

```json
{
  "02833": {
    "group": "admin",
    "firstname": "shadow",
    "lastname": "man"
  },
  "02834": {
    "group": "admin",
    "firstname": "red",
    "lastname": "hat"
  }
}
```

#### GET /dataset-name/:id (READ)
Returns an Object from the store based on the passed _id_.

Sample URL: GET /users/02834

Sample response:

```json
{
  "group": "admin",
  "firstname": "red",
  "lastname": "hat"
}
```

#### POST /dataset-name/ (CREATE)
Accepts an Object that contains data to create a new entry in the backend store.
Returns the created Object data and unique ID (uid).

Sample URL: POST /users

Sample response:

```json
{
  "uid": "02834",
  "data": {
    "group": "admin",
    "firstname": "red",
    "lastname": "hat"
  }
}
```

#### PUT /dataset-name/:id (UPDATE)
Accepts an Object that contains data to update an entry in the backend store.
Returns the updated Object.

Sample URL: PUT /users/02834

Sample response:

```json
{
  "group": "admin",
  "firstname": "red",
  "lastname": "hatter"
}
```

#### DELETE - /dataset-name/:id (DELETE)
Deletes the data associated with the given _id_ from the backend store. Returns
the deleted data.

Sample URL: DELETE /users/02834

Sample response:

```json
{
  "group": "admin",
  "firstname": "red",
  "lastname": "hat"
}
```

## Contributors
* @jimdillon
* @matzew

## Changelog

* 10.0.0
  * Querystrings with Joi validation support are available for read operations.

* 0.9.0
  * Update router events so that the signature has changed from fn(newData) to
  fn(newData, extraData). In an adapter function simply pass a third param to
  the callback and it will be the _extraData_ in the related router.event.

* 0.8.0
  * Expand on previous Joi additions by utilising these for validation of URL
  parameters. Take a look at the updated examples for usage since it has
  changed slightly from 0.7.0.

* 0.7.0
  * Support for Joi validate options to be used during Joi validations for
  create, update, and list operations.

* 0.6.0
  * Now return a 405 for CRUDL functions that are missing; was a 500 error
  previously
  * Reduce package size using "files" in package.json

* 0.5.0
  * Add events for "success" and "fail" on on CRUDL calls. This might change to
  be emitted by adapters in the future.

* 0.4.1 - 0.4.3
  * Struggles with peerDependencies. Ultimately we will retain this config

* 0.4.0
  * Support for Joi validations on incoming request body and querystrings for
  create, update, and list operations
  * Add Apache Licence (thanks @matzew)
  * Update example code
  * Include Postman file for demonstration of requests
  * Only support node.js 4.0 and above (due to inclusion of Joi)

* 0.3.0 - 0.3.1
  * Return 404 if adapter returns a null result (for delete or read)
  * Pass route params that developers define on their app.use
  * Support nested APIs (thanks @jimdillon)
  * Adapter responses are validated to ensure compliance with FH.Sync Object
  format

* 0.2.0
  * Restructure codebase
  * Instead of multiple args, an options object is now expected
  * Place routing structure responsibility on developers (opts.name is not used
  to create the /routeName anymore)
  * Add 404 response for GET calls for specific resouce IDs that do not exist

* 0.1.0 - Initial realease


text:
require 'puppet/util/execution'

Puppet::Type.type(:php_extension).provide(:php_source) do
  include Puppet::Util::Execution
  desc "Provides PHP extensions which are bundled with the PHP source code"

  # Build and install our PHP extension
  def create

    # Let's get a few things straight
    @work_dir = "#{@resource[:phpenv_root]}/php-src/ext/#{@resource[:extension]}"
    @php_version_prefix = "#{@resource[:phpenv_root]}/versions/#{@resource[:php_version]}"
    @resource[:compiled_name] ||= "#{@resource[:extension]}.so"

    # First check we have a cached copy of the php source code repository, with this version tag
    confirm_cached_source

    # Checkout the version as a build branch and prepare for building
    prep_build

    # PHPize, build & install
    phpize
    configure
    make
    install
  end

  def destroy
    @resource[:compiled_name] ||= "#{@resource[:extension]}.so"
    FileUtils.rm_rf("#{@resource[:phpenv_root]}/versions/#{@resource[:php_version]}/modules/#{@resource[:extension]}.so")
  end

  def exists?
    @resource[:compiled_name] ||= "#{@resource[:extension]}.so"
    File.exists?("#{@resource[:phpenv_root]}/versions/#{@resource[:php_version]}/modules/#{@resource[:compiled_name]}")
  end

protected

  # Check that the cached repository is in place, and the version requested exists
  # as a tag in the repository
  #
  def confirm_cached_source
    raise "PHP Source repository is not present" if !File.directory? "#{@resource[:phpenv_root]}/php-src/.git"

    # Check if tag exists in current repo, if not fetch & recheck
    if !version_present_in_cache?
      update_repository
      raise "Version #{@resource[:php_version]} not found in PHP source" if !version_present_in_cache?
    end
  end

  # Update and fetch new tags from the remote repository
  #
  def update_repository
    %x( cd #{@resource[:phpenv_root]}/php-src/ && git fetch --tags )
  end

  # Check for a specific version within the PHP source repository
  #
  def version_present_in_cache?
    tag = %x( cd #{@resource[:phpenv_root]}/php-src/ && git tag -l "php-#{@resource[:php_version]}" )
    tag.strip == "php-#{@resource[:php_version]}"
  end

  # Prepare the source repository for building by checking out the correct
  # tag, and cleaning the source tree
  #
  def prep_build
    # Reset back to master and ensure the build branch is removed
    %x( cd #{@resource[:phpenv_root]}/php-src/ && git checkout -f master && git branch -D build &> /dev/null )

    # Checkout version as build branch
    %x( cd #{@resource[:phpenv_root]}/php-src/ && git checkout php-#{@resource[:php_version]} -b build )

    # Clean everything
    %x( cd #{@resource[:phpenv_root]}/php-src/ && git clean -f -d -x )
  end

  # PHPize the extension, using the correct version of PHP
  def phpize
    %x( export PHP_AUTOCONF=#{autoconf} && export PHP_AUTOHEADER=#{autoheader} && export PKG_CONFIG=#{@resource[:homebrew_path]}/bin/pkg-config && cd #{@work_dir} && #{@php_version_prefix}/bin/phpize )
  end

  # Configure with the correct version of php-config and prefix and any additional configure parameters
  def configure
    %x( export PKG_CONFIG=#{@resource[:homebrew_path]}/bin/pkg-config && cd #{@work_dir} && ./configure --prefix=#{@php_version_prefix} --with-php-config=#{@php_version_prefix}/bin/php-config #{@resource[:configure_params]})
  end

  # Make the module
  def make
    %x( cd #{@work_dir} && make )
    raise "Failed to build module #{@resource[:name]}" unless File.exists?("#{@work_dir}/modules/#{@resource[:compiled_name]}")
  end

  # Make the module
  def install
    %x( cp #{@work_dir}/modules/#{@resource[:compiled_name]} #{@php_version_prefix}/modules/#{@resource[:compiled_name]} )
    raise "Failed to install module #{@resource[:name]}" unless File.exists?("#{@php_version_prefix}/modules/#{@resource[:compiled_name]}")
  end

  # Define fully qualified paths to autoconf & autoheader

  def autoconf
    autoconf = "#{@resource[:homebrew_path]}/bin/autoconf"

    # We need an old version of autoconf for PHP 5.3...
    autoconf << "213" if @resource[:php_version].match(/5\.3\../)

    autoconf
  end

  def autoheader
    autoheader = "#{@resource[:homebrew_path]}/bin/autoheader"

    # We need an old version of autoheader for PHP 5.3...
    autoheader << "213" if @resource[:php_version].match(/5\.3\../)

    autoheader
  end

end


text:
class RegisterContextFreeBSD_i386 : public lldb_private::RegisterInfoInterface {
public:
  RegisterContextFreeBSD_i386(const lldb_private::ArchSpec &target_arch);

  size_t GetGPRSize() const override;

  const lldb_private::RegisterInfo *GetRegisterInfo() const override;

  uint32_t GetRegisterCount() const override;
};

#endif


text:
namespace sword
{
namespace net
{

class EventLoop;
class TimerQueue: public nocopyable
{
 public:
  TimerQueue(EventLoop* loop);
  ~TimerQueue();

  TimerId addTimer(Timestamp when, double interval,
                  const TimerCallback& callback);
  void cancel(TimerId timerId);

  void start();
 private:
  typedef std::pair<Timestamp, Timer*> Entry;
  typedef std::set<Entry> TimerList;
  EventLoop *loop_;
  int timerFd_;
  std::tr1::shared_ptr<Channel> timerCh_;
  TimerList timers_;

  void handleTimerout();
  std::vector<Entry> getExpiredTimers(Timestamp now);
  void addTimerInLoopThread(const Entry& timerEntry);
  void cancelTimerInLoopThread(Timer* timer);
};

}
}

#endif


text:
package de.danielbasedow.prospecter.core.document;

import de.danielbasedow.prospecter.core.Token;

import java.util.List;

/**
 * Represents a field of a document.
 */
public class Field {
    protected final String name;
    protected final List<Token> tokens;

    /**
     * @param name   name of the field
     * @param tokens List of tokens in the field
     */
    public Field(String name, List<Token> tokens) {
        this.name = name;
        this.tokens = tokens;
    }

    public List<Token> getTokens() {
        return tokens;
    }

    public String getName() {
        return name;
    }

}


text:
import java.util.Scanner;

public class Solution {

	public static void main(String[] args) {
		Scanner read = new Scanner(System.in);

		int n = read.nextInt();
		read.nextLine(); // clear buffer

		boolean isGoodContest = false;
		for (int i = 0; i < n; ++i) {
			String[] line = read.nextLine().split(" ");

			String name = line[0];
			int before = Integer.parseInt(line[1]);
			int after = Integer.parseInt(line[2]);

			if (before >= 2400 && after > before) {
				isGoodContest = true;
				break;
			}
		}

		if (isGoodContest) {
			System.out.println("YES");
		}
		else {
			System.out.println("NO");
		}

		// Close scanner
		read.close();
	}

}


text:
<?php
/**
 * @package modx
 */
/**
 * Stores records of all manager actions.
 *
 * @property int $user The user ID of the actor
 * @property datetime $occurred The time the action occurred.
 * @property string $action The action key that occurred.
 * @property string $classKey The class name of the object that was acted upon.
 * @property string $item The PK of the class type defined by classKey that was acted upon.
 *
 * @package modx
 */
class modManagerLog extends xPDOSimpleObject {}


text:
require 'spec_helper'

RSpec.describe Pohoda do
  let(:xml) do
    raw = File.read "./spec/fixtures/complete_invoice.xml"
    xml = Pohoda.parse(raw)
  end

  let(:number) { xml.data_pack_item.first.invoice.invoice_header.number }

  describe '#to_h' do
    it 'returns proper hash' do
      expected_hash = {
        attributes: {},
        id: '1',
        id_attributes: {},
        ids: 'something',
        ids_attributes: {},
        number_requested: '2016001938',
        number_requested_attributes: {}
      }

      expect(number.to_h).to eq expected_hash
    end
  end
end


text:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Arrays;
import java.util.Scanner;

public class AnagramFinder {

	static HashMap<String, String> words = new HashMap<String, String>(300000);

	public static HashMap<String, String> getSortedDictionary() throws IOException {

		BufferedReader br = new BufferedReader(new FileReader("SINGLE.txt"));
		String input = "";

		while ((input = br.readLine()) != null) {

			//sort the string
			char[] inputChars = input.toCharArray();
			Arrays.sort(inputChars);
			String sortedInput = String.valueOf(inputChars);

			if (words.get(sortedInput) == null) {
				words.put(sortedInput, input);
			}

			else {
				String previousValue = words.get(sortedInput);
				words.put(sortedInput, previousValue + "; " + input);
			}
		}

		br.close();

		return words;
	}

	public static void printAnagrams(String s) {

		int length = s.length();
		int combsSize = (int) (Math.pow(2, (double)length)-1);

		//hash set to indicate if a combination has been tried before to prevent printing duplicates
		HashMap<String, String> tried = new HashMap<String, String>(300000);

		for (int j=0; j<combsSize; j++) {

			String mask = Integer.toBinaryString(j+1);
			String buffer = "";

			int maskLength = mask.length();

			for (int k=maskLength-1; k>=0; k--) {

				if (mask.charAt(k)=='1') {
					int getChar = length - (maskLength - k);
					buffer = s.charAt(getChar) + buffer;
				}
			}
			//sort buffer
			char[] bufferChars = buffer.toCharArray();
			Arrays.sort(bufferChars);
			String sortedBuffer = String.valueOf(bufferChars);

			//if the combination has been tried before, skip to the next combination
			if (tried.get(sortedBuffer) != null) { }

			//print the anagram if it is found in the dictionary
			else {
				//add the tried combination to the hash set
				tried.put(sortedBuffer, "");
				String dictVal = "";
				if ((dictVal = words.get(sortedBuffer)) != null) {
					String[] dictValSplit = dictVal.split("; ");
					for (int m=0; m<dictValSplit.length; m++) {
						System.out.println(dictValSplit[m] +"\t("+dictValSplit[m].length()+")");
					}
				}
			}
		}
	}

	public static void main (String args[]) {

		//import dictionary
		long start = System.currentTimeMillis();
		try {words = getSortedDictionary(); }
		catch (IOException e) {e.printStackTrace(); }
		long finish = System.currentTimeMillis();

		System.out.println("Time taken to import dictionary: " + (finish-start) + " ms\n");

		Scanner input = new Scanner(System.in);

		while(true) {

			String word = "";
			System.out.print("Enter the word: ");
			word = input.nextLine();

			long start2 = System.currentTimeMillis();
			printAnagrams(word);
			long finish2 = System.currentTimeMillis();

			System.out.println("Time taken to generate anagrams: " + (finish2 - start2) + " ms");
			System.out.println("Length of word: " + word.length());
		}
	}
}


text:
<?php

use Illuminate\Database\Seeder;

class ArticleTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        //Make random ten articles
        $article = factory(App\Article::class,10)->create();
    }
}


text:
/**
 * Created by Administrator on 2016/4/14.
 */

'use strict';

angular.module('myApp.wedding_service', ['ngRoute'])

    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/wedding_service', {
            templateUrl: 'wedding_service/wedding_service.html',
            controller: 'WeddingServiceCtl',
            reloadOnSearch:false
        });
    }])

    .controller('WeddingServiceCtl', function($scope, $timeout, utilFun) {

        utilFun.enableMenuTitle('wedding-service');
        $('#wedding-service-content').hide();

        $scope.$on('$viewContentLoaded', function(){
            $timeout(function(){
                $('#wedding-service-content').addClass("animated fadeInDown").show();
            });
            utilFun.tabs('');

        })

    });


text:
package org.apache.hadoop.metrics2.impl;

import org.apache.commons.configuration.SubsetConfiguration;
import org.apache.hadoop.metrics2.lib.MetricMutableCounterLong;
import org.apache.hadoop.metrics2.lib.MetricMutableStat;
import org.apache.hadoop.metrics2.lib.MetricMutableGaugeLong;
import org.apache.hadoop.metrics2.lib.AbstractMetricsSource;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import static org.apache.hadoop.test.MoreAsserts.*;
import org.apache.hadoop.metrics2.Metric;
import org.apache.hadoop.metrics2.MetricsRecord;
import org.apache.hadoop.metrics2.MetricsSink;
import org.apache.hadoop.metrics2.MetricsTag;

/**
 * Test the MetricsSystemImpl class
 */
@RunWith(MockitoJUnitRunner.class)
public class TestMetricsSystemImpl {
  private static final Log LOG = LogFactory.getLog(TestMetricsSystemImpl.class);
  @Captor private ArgumentCaptor<MetricsRecord> r1;
  @Captor private ArgumentCaptor<MetricsRecord> r2;
  @Captor private ArgumentCaptor<MetricsRecord> r3;
  private static String hostname = MetricsSystemImpl.getHostname();

  @Test public void testInitFirst() throws Exception {
    ConfigBuilder cb = new ConfigBuilder().add("default.period", 8)
        .add("source.filter.class",
             "org.apache.hadoop.metrics2.filter.GlobFilter")
        .add("test.*.source.filter.class", "${source.filter.class}")
        .add("test.*.source.filter.exclude", "s1*")
        .add("test.sink.sink3.source.filter.class", "${source.filter.class}")
        .add("test.sink.sink3.source.filter.exclude", "s2*")
        .save(TestMetricsConfig.getTestFilename("hadoop-metrics2-test"));
    MetricsSystemImpl ms = new MetricsSystemImpl("Test");
    ms.start();
    TestSource s1 = ms.register("s1", "s1 desc", new TestSource("s1rec"));
    TestSource s2 = ms.register("s2", "s2 desc", new TestSource("s2rec"));
    TestSource s3 = ms.register("s3", "s3 desc", new TestSource("s3rec"));
    s1.s1.add(0);
    s2.s1.add(0);
    s3.s1.add(0);
    MetricsSink sink1 = mock(MetricsSink.class);
    MetricsSink sink2 = mock(MetricsSink.class);
    MetricsSink sink3 = mock(MetricsSink.class);
    ms.register("sink1", "sink1 desc", sink1);
    ms.register("sink2", "sink2 desc", sink2);
    ms.register("sink3", "sink3 desc", sink3);
    ms.onTimerEvent();  // trigger something interesting
    ms.stop();

    verify(sink1, times(3)).putMetrics(r1.capture()); // 2 + 1 sys source
    List<MetricsRecord> mr1 = r1.getAllValues();
    verify(sink2, times(3)).putMetrics(r2.capture()); // ditto
    List<MetricsRecord> mr2 = r2.getAllValues();
    verify(sink3, times(2)).putMetrics(r3.capture()); // 1 + 1 (s1, s2 filtered)
    List<MetricsRecord> mr3 = r3.getAllValues();
    checkMetricsRecords(mr1, "s2rec");
    assertEquals("output", mr1, mr2);
    checkMetricsRecords(mr3, "s3rec");
  }

  static void checkMetricsRecords(List<MetricsRecord> recs, String expected) {
    LOG.debug(recs);
    MetricsRecord r = recs.get(0);
    assertEquals("name", expected, r.name());
    assertEquals("tags", new MetricsTag[] {
      new MetricsTag("context", "Metrics context", "test"),
      new MetricsTag("hostName", "Local hostname", hostname)}, r.tags());
    assertEquals("metrics", new Metric[] {
      new MetricCounterLong("c1", "c1 desc", 1),
      new MetricGaugeLong("g1", "g1 desc", 2),
      new MetricCounterLong("s1_num_ops", "Number of ops for s1 desc", 1),
      new MetricGaugeDouble("s1_avg_time", "Average time for s1 desc", 0)},
      r.metrics());

    // Skip the system metrics for now.
    // MetricsRecord r1 = recs.get(1);
  }

  private static class TestSource extends AbstractMetricsSource {
    final MetricMutableCounterLong c1;
    final MetricMutableGaugeLong g1;
    final MetricMutableStat s1;

    TestSource(String name) {
      super(name);
      registry.setContext("test");
      c1 = registry.newCounter("c1", "c1 desc", 1L);
      g1 = registry.newGauge("g1", "g1 desc", 2L);
      s1 = registry.newStat("s1", "s1 desc", "ops", "time");
    }
  }

}


text:
from tapi_server.models.tapi_common_context import TapiCommonContext

context = TapiCommonContext()

def service_interface_point_list ():
    """Retrieve all ServiceInterfacePoints

    :rtype: List(ServiceInterfacePoint)
    """
    return context.service_interface_point

def service_interface_point (sip_uuid):
    """Retrieve ServiceInterfacePoint by ID

    :param sip_uuid: ID of ServiceInterfacePoint
    :type sip_uuid: str

    :rtype: ServiceInterfacePoint
    """
    for sip in context.service_interface_point:
        if sip.uuid == sip_uuid:
            return sip

def topology_list ():
    """Retrieve all Topology

    :rtype: List(Topology)
    """
    return context.topology_context.topology

def topology (topo_uuid):
    """Retrieve Topology by ID

    :param topo_uuid: ID of Topology
    :type topo_uuid: str

    :rtype: Topology
    """
    for topo in context.topology_context.topology:
        if topo.uuid == topo_uuid:
            return topo

def node (topo_uuid, node_uuid):
    """Retrieve Node by ID

    :param topo_uuid: ID of Topology
    :type topo_uuid: str
    :param node_uuid: ID of Node
    :type node_uuid: str

    :rtype: Node
    """
    for topo in context.topology_context.topology:
        if topo.uuid == topo_uuid:
            for node in topo.node:
                if node.uuid == node_uuid:
                    return node

def link (topo_uuid, link_uuid):
    """Retrieve Link by ID

    :param topo_uuid: ID of Topology
    :type topo_uuid: str
    :param link_uuid: ID of Link
    :type link_uuid: str

    :rtype: Link
    """
    for topo in context.topology_context.topology:
        if topo.uuid == topo_uuid:
            for link in topo.link:
                if link.uuid == link_uuid:
                    return link

def node_edge_point (topo_uuid, node_uuid, nep_uuid):
    """Retrieve NodeEdgePoint by ID

    :param topo_uuid: ID of Topology
    :type uuid: str
    :param node_uuid: ID of Node
    :type node_uuid: str
    :param nep_uuid: ID of NodeEdgePoint
    :type nep_uuid: str

    :rtype: NodeEdgePoint
    """
    for topo in context.topology_context.topology:
        if topo.uuid == topo_uuid:
            for node in topo.node:
                if node.uuid == node_uuid:
                    for nep in node.owned_node_edge_point:
                        if nep.uuid == nep_uuid:
                            return nep

def connection_end_point (id, node_uuid, nep_uuid, cep_uuid):
    """Retrieve NodeEdgePoint by ID

    :param topo_uuid: ID of Topology
    :type uuid: str
    :param node_uuid: ID of Node
    :type node_uuid: str
    :param nep_uuid: ID of NodeEdgePoint
    :type nep_uuid: str
    :param cep_uuid: ID of ConnectionEndPoint
    :type cep_uuid: str

    :rtype: ConnectionEndPoint
    """
    for topo in context.topology_context.topology:
        if topo.uuid == topo_uuid:
            for node in topo.node:
                if node.uuid == node_uuid:
                    for nep in node.owned_node_edge_point:
                        if nep.uuid == nep_uuid:
                            for cep in nep.cep_list.connection_end_point:
                                if cep.uuid == cep_uuid:
                                    return cep

def connectivity_service_list ():
    """Retrieve all ConnectivityService

    :rtype: List(ConnectivityService)
    """
    return context.connectivity_context.connectivity_service

def connectivity_service (cs_uuid):
    """Retrieve ConnectivityService by ID

    :param cs_uuid: ID of ConnectivityService
    :type cs_uuid: str

    :rtype: Topology
    """
    for cs in context.connectivity_context.connectivity_service:
        if cs.uuid == cs_uuid:
            return cs

def connection (conn_uuid):
    """Retrieve Connection by ID

    :param conn_uuid: ID of Connection
    :type conn_uuid: str

    :rtype: Connection
    """
    for conn in context.connectivity_context.connection:
        if conn.uuid == conn_uuid:
            return conn