text:
package org.wso2.carbon.apimgt.api.model;

import org.apache.commons.lang3.StringUtils;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIConstants;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * This class represent an Environment.
 */
public class Environment implements Serializable {

    private static final long serialVersionUID = 1L;
    private String type = APIConstants.GATEWAY_ENV_TYPE_HYBRID;
    private String serverURL;
    private String userName;
    private String password;
    private String apiGatewayEndpoint;
    private String websocketGatewayEndpoint;
    private String webSubGatewayEndpoint;
    private boolean isDefault;

    // New fields added with dynamic environments
    private Integer id;
    private String uuid;
    private String name;
    private String displayName;
    private String description;
    private boolean isReadOnly;
    private List<VHost> vhosts = new ArrayList<>();

    public boolean isDefault() {
        return isDefault;
    }

    public void setDefault(boolean aDefault) {
        isDefault = aDefault;
    }

    public String getWebsocketGatewayEndpoint() {
        return websocketGatewayEndpoint;
    }

    public void setWebsocketGatewayEndpoint(String websocketGatewayEndpoint) {
        this.websocketGatewayEndpoint = websocketGatewayEndpoint;
    }

    public String getWebSubGatewayEndpoint() {
        return webSubGatewayEndpoint;
    }

    public void setWebSubGatewayEndpoint(String webSubGatewayEndpoint) {
        this.webSubGatewayEndpoint = webSubGatewayEndpoint;
    }

    public boolean isShowInConsole() {
        return showInConsole;
    }

    public void setShowInConsole(boolean showInConsole) {
        this.showInConsole = showInConsole;
    }

    private boolean showInConsole = true;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getServerURL() {
        return serverURL;
    }

    public void setServerURL(String serverURL) {
        this.serverURL = serverURL;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

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

    public String getApiGatewayEndpoint() {
        return apiGatewayEndpoint;
    }

    public void setApiGatewayEndpoint(String apiGatewayEndpoint) {
        this.apiGatewayEndpoint = apiGatewayEndpoint;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUuid() {
        return uuid;
    }

    public void setUuid(String uuid) {
        this.uuid = uuid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        if (StringUtils.isEmpty(this.uuid)) {
            this.uuid = name;
        }
        if (StringUtils.isEmpty(this.displayName)) {
            this.displayName = name;
        }
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public boolean isReadOnly() {
        return isReadOnly;
    }

    public void setReadOnly(boolean readOnly) {
        isReadOnly = readOnly;
    }

    public List<VHost> getVhosts() {
        return vhosts;
    }

    public void setVhosts(List<VHost> vhosts) {
        this.vhosts = vhosts;
        // set gateway endpoint if it is empty
        if (StringUtils.isEmpty(apiGatewayEndpoint) && StringUtils.isEmpty(websocketGatewayEndpoint) && !vhosts.isEmpty()) {
            VHost vhost = vhosts.get(0);
            String endpointFormat = "%s%s:%s%s"; // {protocol}://{host}:{port}/{context}

            String httpContext = StringUtils.isEmpty(vhost.getHttpContext()) ? "" : "/" + vhost.getHttpContext();
            String gwHttpEndpoint = String.format(endpointFormat, APIConstants.HTTP_PROTOCOL_URL_PREFIX,
                    vhost.getHost(), vhost.getHttpPort(), httpContext);
            String gwHttpsEndpoint = String.format(endpointFormat, APIConstants.HTTPS_PROTOCOL_URL_PREFIX,
                    vhost.getHost(), vhost.getHttpsPort(), httpContext);
            apiGatewayEndpoint = gwHttpsEndpoint + "," + gwHttpEndpoint;

            String gwWsEndpoint = String.format(endpointFormat, APIConstants.WS_PROTOCOL_URL_PREFIX,
                    vhost.getHost(), vhost.getWsPort(), "");
            String gwWssEndpoint = String.format(endpointFormat, APIConstants.WSS_PROTOCOL_URL_PREFIX,
                    vhost.getHost(), vhost.getWssPort(), "");
            websocketGatewayEndpoint = gwWssEndpoint + "," + gwWsEndpoint;
        }
    }

    public void setEndpointsAsVhost() throws APIManagementException {
        // Prefix websub endpoints with 'websub_', since API type will be identified with this URL.
        String modifiedWebSubGatewayEndpoint = webSubGatewayEndpoint.replaceAll("http://", "websub_http://")
                .replaceAll("https://", "websub_https://");
        String[] endpoints = (apiGatewayEndpoint + "," + websocketGatewayEndpoint + "," + modifiedWebSubGatewayEndpoint)
                .split(",", 6);
        getVhosts().add(VHost.fromEndpointUrls(endpoints));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Environment that = (Environment) o;

        if (!getName().equals(that.getName())) return false;
        if (!type.equals(that.getType())) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = type.hashCode();
        return  31 * result + getName().hashCode();
    }
}


text:
package com.handywedge.openidconnect;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

/**
 * Open ID ConnectのリクエストをハンドリングするServlet Filter
 *
 * @author takeuchi
 */
@WebFilter(filterName = "OCIFilter", urlPatterns = {"/*"},
    initParams = {@WebInitParam(name = "encoding", value = "utf-8")})
public class OICFilter implements jakarta.servlet.Filter {

  protected static Logger logger = LoggerFactory.getLogger(OICFilter.class);

  private OICService service;

  /**
   * Default constructor.
   */
  public OICFilter() {}

  /**
   * @see Filter#destroy()
   */
  @Override
  public void destroy() {}

  /**
   * @param request
   * @param response
   * @param chain
   * @throws java.io.IOException
   * @throws javax.servlet.ServletException
   * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
   */
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws ServletException, IOException {
    MDC.put("requestId", UUID.randomUUID().toString());
    logger.info("doFilter <start>");
    try {
      HttpServletRequest httpServletRequest = (HttpServletRequest) request;
      HttpServletResponse httpServletResponse = (HttpServletResponse) response;
      dump(httpServletRequest);

      if (httpServletRequest.getMethod().equalsIgnoreCase("GET")) {
        if (httpServletRequest.getServletPath()
            .equalsIgnoreCase(OICProperties.get(OICConst.RP_LOGIN_PATH))) {
          try {
            service.login(httpServletRequest, httpServletResponse);
          } catch (OICException e) {
            logger.error("doFilter <end> Login error.", e);
            throw new ServletException(e);
          }
        } else if (httpServletRequest.getServletPath()
            .equalsIgnoreCase(OICProperties.get(OICConst.OIC_LOGOUT_PATH))) {
          service.logout(httpServletRequest, httpServletResponse);
        } else {
          httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
      } else if (httpServletRequest.getMethod().equalsIgnoreCase("POST")) {
        if (httpServletRequest.getServletPath()
            .equalsIgnoreCase(OICProperties.get(OICConst.RP_AUTH_PATH))) {
          try {
            service.auth(httpServletRequest, httpServletResponse);
          } catch (OICException e) {
            logger.error("doFilter <end> Auth error.", e);
            throw new ServletException(e);
          }
        } else {
          httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
      } else {
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
      }

      logger.info("doFilter <end>");
    } finally {
      MDC.clear();
    }
  }

  /**
   * @param fConfig
   * @throws javax.servlet.ServletException
   * @see Filter#init(FilterConfig)
   */
  @Override
  public void init(FilterConfig fConfig) throws ServletException {

    logger.info("init <start>");
    try {
      service = OICService.getInstance();
    } catch (OICException e) {
      logger.error("Service Class instantion error", e);
      throw new ServletException(e);
    } finally {
      logger.info("init <end>");
    }
  }

  private void dump(HttpServletRequest request) {

    logger.trace("---------------------------------------------");
    logger.trace("doFilter : " + request.getMethod());
    logger.trace("doFilter : " + request.getContextPath());
    logger.trace("doFilter : " + request.getServletPath());
    logger.trace("doFilter : " + request.getQueryString());
    Enumeration<String> e = request.getHeaderNames();
    while (e.hasMoreElements()) {
      String key = e.nextElement();
      logger.trace("doFilter : Header key=" + key + " val=" + request.getHeader(key));
    }
    Map<String, String[]> m = request.getParameterMap();
    Iterator<String> i = m.keySet().iterator();
    while (i.hasNext()) {
      String key = i.next();
      logger.trace("doFilter : Param key=" + key);
      String[] v = m.get(key);
      if (v != null) {
        for (String s : v) {
          logger.trace("doFilter : Param key=" + key + " val=" + s);
        }
      }
    }
    logger.trace("---------------------------------------------");
  }
}

redpajama_set_name: RedPajamaGithub


text:
You have arrived at the source repository for the Salesforce Mobile SDK for iOS.  Welcome!  Starting with our 2.0 release, there are now three ways you can choose to work with the Mobile SDK:

- If you'd like to work with the source code of the SDK itself, you've come to the right place!  You can browse sample app source code and debug down through the layers to get a feel for how everything works under the covers.  Read on for instructions on how to get started with the SDK in your development environment.
- If you're just eager to start developing your own new application, the quickest way is to use our npm binary distribution package, called [forceios](https://npmjs.org/package/forceios), which is hosted on [npmjs.org](https://npmjs.org/).  Getting started is as simple as installing the npm package and launching your template app.  You'll find more details on the forceios package page.
- If you would like to add the Mobile SDK components to your existing native application, check out the [SalesforceMobileSDK-iOS-Distribution repository](https://github.com/forcedotcom/SalesforceMobileSDK-iOS-Distribution), which contains our binary distributions as well as information on how to add them to your native app.

Installation (do this first - really)
==
Working with this repository requires working with git.  Any workflow that leaves you with a functioning git clone of this repository should set you up for success.  Downloading the ZIP file from GitHub, on the other hand, is likely to put you at a dead end.

## Setting up the repo
First, clone the repo:

- Open the Terminal App
- `cd` to the parent directory where the repo directory will live
- `git clone https://github.com/forcedotcom/SalesforceMobileSDK-iOS.git`

After cloning the repo:

- `cd SalesforceMobileSDK-iOS`
- `./install.sh`

This script pulls the submodule dependencies from GitHub, to finalize setup of the workspace.  You can then work with the Mobile SDK by opening `SalesforceMobileSDK.xcworkspace` from Xcode.

See [build.md](build.md) for information on generating binary distributions and app templates.

The Salesforce Mobile SDK for iOS requires iOS 6.0 or greater.  The install.sh script checks for this, and aborts if the configured SDK version is incorrect.  Building from the command line has been tested using ant 1.8.  Older versions might work, but we recommend using the latest version of ant.

If you have problems building any of the projects, take a look at the online [FAQ](https://github.com/forcedotcom/SalesforceMobileSDK-iOS/wiki/FAQ) for troubleshooting tips.

Introduction
==

### What's New in 3.3

**SmartStore Library Enhancements**
- SmartStore now provides the ability to perform full text search (FTS). Refer to the SmartStore chapter in the Mobile SDK Development Guide for details on how to use this feature.
- An enhanced query syntax has been added to support this feature.

**Security Enhancements**
- It is now possible to use Touch ID instead of a numeric PIN on passcode enabled orgs.

**Other Technical Improvements**
- Upgraded SQLCipher to 3.3.
- Various bug fixes.

Check http://developer.force.com/mobilesdk for additional articles and tutorials

### Native Applications
The Salesforce Mobile SDK provides the essential libraries for quickly building native mobile apps that interact with the Salesforce cloud platform. The OAuth2 library abstracts away the complexity of securely storing the refresh token or fetching a new session ID when it expires. The SDK also provides Objective-C wrappers for the Salesforce REST API, making it easy to retrieve and manipulate data.

### Hybrid Applications
HTML5 is quickly emerging as a powerful technology for developing cross-platform mobile applications. While developers can create sophisticated apps with HTML5 and JavaScript alone, some vital limitations remain, specifically: session management and universal access to native device functionality like the camera, calendar and address book. The Salesforce Mobile Container (based on the industry-leading PhoneGap implementation) makes it possible to embed HTML5 apps stored on the device or delivered via Visualforce inside a thin native container, producing a hybrid application.

### Application Templates
The Mobile SDK provides the means to generate your new app from a template, to quickly construct the foundation of native and hybrid applications.  These apps come with a fully functioning demo app, as well as configurable Settings bundles that allow the user to log out of the app or switch between Production and Sandbox orgs.  See [build.md](build.md) for more information on how to generate and use the templates.

**Native App Template**
For native apps that need to access the Salesforce REST API, create your app using the native template.  The template includes a default AppDelegate implementation that you can customize to perform any app-specific interaction.

**Hybrid App Template**
To create hybrid apps that use the Salesforce REST API or access Visualforce pages, create your app using the hybrid app template. By providing the SalesforceOAuthPlugin for our PhoneGap-based container, HTML5 applications can quickly leverage OAuth tokens directly from JavaScript calls.  In addition, our SFSmartStorePlugin will allow you to store your app data securely on the device.

Documentation
==

* [Salesforce Mobile SDK Development Guide](https://github.com/forcedotcom/SalesforceMobileSDK-Shared/blob/master/doc/mobile_sdk.pdf?raw=true)
* [Salesforce Mobile SDK for iOS Reference](http://forcedotcom.github.io/SalesforceMobileSDK-iOS/Documentation/masterTOC.html)

Discussion
==

If you would like to make suggestions, have questions, or encounter any issues, we'd love to hear from you. Post any feedback you have on our [Google+ community](https://plus.google.com/communities/114225252149514546445).


text:
namespace FactoryPattern.Factories
{
    using FactoryPattern.Products;

    public abstract class BulbFactory
    {
        public abstract Bulb CreateBulb();
    }
}


text:
require 5.002;

#######################################################################
# bomblab-requestd.pl - The CS:APP Binary Bomb Request Daemon
#
# Copyright (c) 2003-2011, R. Bryant and D. O'Hallaron
#
# The request daemon is a simple special purpose HTTP server that
# allows students to use their Web browser to request binary bombs
# and to view the realtime scoreboard.
#
# Students request a bomb by pointing their browser at
#
#     http://$SERVER_NAME:$REQUESTD_PORT
#
# After they submit the resulting form with their personal
# information, the server builds a custom bomb for the student, tars
# it up and returns the tar file to the browser.
#
# Students check the realtime scoreboard by pointing their browser at
#
#    http://$SERVER_NAME:$REQUESTD_PORT/scoreboard
#
#######################################################################

use strict 'vars';
use Getopt::Std;
use Socket;
use Sys::Hostname;

use lib ".";
use Bomblab;

#
# Generic settings
#
$| = 1;          # Autoflush output on every print statement
$0 =~ s#.*/##s;  # Extract the base name from argv[0]

#
# Ignore any SIGPIPE signals caused by the server writing
# to a connection that has already been closed by the client
#
$SIG{PIPE} = 'IGNORE';

#
# Canned client error messages
#
my $bad_usermail_msg = "Invalid email address.";
my $bad_username_msg = "You forgot to enter a user name.";
my $usermail_taint_msg = "The email address contains an illegal character.";
my $username_taint_msg = "The user name contains an illegal character.";

#
# Configuration variables from Bomblab.pm
#
my $server_port = $Bomblab::REQUESTD_PORT;
my $labid = $Bomblab::LABID;
my $server_dname = $Bomblab::SERVER_NAME;

#
# Other variables
#
my $notifyflag;
my ($client_port, $client_dname, $client_iaddr);
my $request_hdr;
my $content;
my ($usermail, $username);
my ($bombnum, $maxbombnum);
my $item;
my $tarfilename;
my $buffer;
my @bombs=();

##############
# Main routine
##############

#
# Parse and check the command line arguments
#
no strict 'vars';
getopts('hsq');
if ($opt_h) {
    usage("");
}

$notifyflag = "-n";
if ($opt_s) {
    $notifyflag = "";
}

$Bomblab::QUIET = 0;
if ($opt_q) {
    $Bomblab::QUIET = 1;
}
use strict 'vars';

#
# Print a startup message
#
log_msg("Request server started on $server_dname:$server_port");

#
# Make sure the files and directories we need are available
#
(-e $Bomblab::MAKEBOMB and -x $Bomblab::MAKEBOMB)
    or log_die("Error: Couldn't find an executable $Bomblab::MAKEBOMB script.");

(-e $Bomblab::BOMBDIR)
    or system("mkdir ./$Bomblab::BOMBDIR");

#
# Establish a listening descriptor
#
socket(SERVER, PF_INET, SOCK_STREAM, getprotobyname('tcp'))
    or log_die("socket: $!");
setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1)
    or log_die("setsockopt: $!");
bind(SERVER, sockaddr_in($server_port, INADDR_ANY))
    or log_die("Couldn't bind to port $server_port: $!");
listen(SERVER, SOMAXCONN)
    or log_die("listen: $!");

#
# Repeatedly wait for scoreboard, form, and bomb requests
#
while (1) {

    #
    # Wait for a connection request from a client
    #
    my $client_paddr = accept(CLIENT, SERVER)
        or die "accept: $!\n";
    ($client_port, $client_iaddr) = sockaddr_in($client_paddr);
    $client_dname = gethostbyaddr($client_iaddr, AF_INET);

    #
    # Read the request header (the first text line in the request)
    #
    $request_hdr = <CLIENT>;
    chomp($request_hdr);

    #
    # Ignore requests for favicon.ico
    #
    # NOTE: To avoid memory leak, be careful to close CLIENT fd before
    # each "next" statement in this while loop.
    #
    if ($request_hdr =~ /favicon/) {
        #log_msg("Ignoring favicon request");
        close CLIENT;
        next;
    }

    #
    # If this is a scoreboard request, then simply return the scoreboard
    #
    if ($request_hdr =~ /\/scoreboard/) {
        $content = "No scoreboard yet...";
        if (-e $Bomblab::SCOREBOARDPAGE) {
            $content = `cat $Bomblab::SCOREBOARDPAGE`;
        }
        sendform($content);
    }

    #
    # If there aren't any specific HTML form arguments, then we interpret
    # this as an initial request for an HTML form. So we build the
    # form and send it back to the client.
    #

    elsif (!($request_hdr =~ /usermail=/)) {
        #log_msg("Form request from $client_dname");
        sendform(buildform($server_dname, $server_port, $labid,
                           "", "", "", "", ""));
    }

    #
    # If this is a reset request, just send the client a clean form
    #
    elsif ($request_hdr =~ /reset=/) {
        #log_msg("Reset request from $client_dname");
        sendform(buildform($server_dname, $server_port, $labid,
                           "", "", "", "", ""));
    }

    #  Otherwise, since it's not a reset (clean form) request and the
    # URI contains a specific HTML form argument, we interpret this as
    # a bomb request.  So we parse the URI, build the bomb, tar it up,
    # and transfer it back over the connection to the client.

    else {

        #
        # Undo the browser's URI translations of special characters
        #
        $request_hdr =~ s/%25/%/g;  # Do first to handle %xx inputs

        $request_hdr =~ s/%20/ /g;
        $request_hdr =~ s/\+/ /g;
        $request_hdr =~ s/%21/!/g;
        $request_hdr =~ s/%23/#/g;
        $request_hdr =~ s/%24/\$/g;
        $request_hdr =~ s/%26/&/g;
        $request_hdr =~ s/%27/'/g;
        $request_hdr =~ s/%28/(/g;
        $request_hdr =~ s/%29/)/g;
        $request_hdr =~ s/%2A/*/g;
        $request_hdr =~ s/%2B/+/g;
        $request_hdr =~ s/%2C/,/g;
        $request_hdr =~ s/%2D/-/g;
        $request_hdr =~ s/%2d/-/g;
        $request_hdr =~ s/%2E/./g;
        $request_hdr =~ s/%2e/./g;
        $request_hdr =~ s/%2F/\//g;

        $request_hdr =~ s/%3A/:/g;
        $request_hdr =~ s/%3B/;/g;
        $request_hdr =~ s/%3C/</g;
        $request_hdr =~ s/%3D/=/g;
        $request_hdr =~ s/%3E/>/g;
        $request_hdr =~ s/%3F/?/g;

        $request_hdr =~ s/%40/@/g;

        $request_hdr =~ s/%5B/[/g;
        $request_hdr =~ s/%5C/\\/g;
        $request_hdr =~ s/%5D/[/g;
        $request_hdr =~ s/%5E/\^/g;
        $request_hdr =~ s/%5F/_/g;
        $request_hdr =~ s/%5f/_/g;

        $request_hdr =~ s/%60/`/g;

        $request_hdr =~ s/%7B/\{/g;
        $request_hdr =~ s/%7C/\|/g;
        $request_hdr =~ s/%7D/\}/g;
        $request_hdr =~ s/%7E/~/g;

        # Parse the request URI to get the user information
        $request_hdr =~ /username=(.*)&usermail=(.*)&/;
        $username = $1;
        $usermail = $2;

        #
        # For security purposes, make sure the form inputs contain only
        # non-shell metacharacters. The only legal characters are spaces,
        # letters, numbers, hyphens, underscores, at signs, and dots.
        #

        # email field
        if ($usermail ne "") {
            if (!($usermail =~ /^([\s-\@\w.]+)$/)) {
                log_msg ("Invalid bomb request from $client_dname: Illegal character in email address ($usermail):");
                sendform(buildform($server_dname, $server_port, $labid,
                                   $usermail, $username,
                                   $usermail_taint_msg));
                close CLIENT;
                next;
            }
        }

        # user name field
        if ($username ne "") {
            if (!($username =~ /^([\s-\@\w.]+)$/)) {
                log_msg ("Invalid bomb request from $client_dname: Illegal character in user name ($username):");
                sendform(buildform($server_dname, $server_port, $labid,
                                   $usermail, $username,
                                   $username_taint_msg));
                close CLIENT;
                next;
            }
        }

        # The user name field is also required. If it's not filled in,
        # or it's all blanks, then it's invalid
        if (!$username or $username eq "" or $username =~ /^ +$/) {
            log_msg ("Invalid bomb request from $client_dname: Missing user name:");

            sendform(buildform($server_dname, $server_port, $labid,
                               $usermail, $username,
                               $bad_username_msg));
            close CLIENT;
            next;
        }

        #
        # The user mail field is required. If it's not filled in,
        # or it's all blanks, or it doesn't have an @ sign, then it's invalid
        #
        if (!$usermail or $usermail eq "" or
            $usermail =~ /^ +$/ or
            !($usermail =~ /\@/)) {
            log_msg ("Invalid bomb request from $client_dname: Invalid email address ($usermail):");
            sendform(buildform($server_dname, $server_port, $labid,
                               $usermail, $username,
                               $bad_usermail_msg));
            close CLIENT;
            next;
        }

        #
        # Everything checks out OK. So now we build and deliver the
        # bomb to the client.
        #
        log_msg ("Bomb request from $client_dname:$username:$usermail:");

        # Get a list of all of the bombs in the bomb directory
        opendir(DIR, $Bomblab::BOMBDIR)
            or die "ERROR: Couldn't open $Bomblab::BOMBDIR\n";
        @bombs = grep(/bomb/, readdir(DIR));
        closedir(DIR);

        #
        # Find the largest bomb number, being careful to use numeric
        # instead of lexicographic comparisons.
        #
        map s/bomb//, @bombs;
        $maxbombnum = 0;
        foreach $item (@bombs) {
            if ($item > $maxbombnum) {
                $maxbombnum = $item;
            }
        }
        $bombnum = $maxbombnum + 1;

        #
        # Build a new bomb, being careful, for security reasons,
        # to invoke the list version of system and thus avoid
        # running a shell.
        #
        system("./$Bomblab::MAKEBOMB", "-q", "$notifyflag", "-l", "$labid", "-i", "$bombnum", "-b", "./$Bomblab::BOMBDIR", "-s", "./$Bomblab::BOMBSRC", "-u", "$usermail", "-v", "$username") == 0
            or die "ERROR: Couldn't make bomb$bombnum\n";

        #
        # Tar up the bomb
        #
        $tarfilename = "bomb$bombnum.tar";
        system("(cd $Bomblab::BOMBDIR; tar cf - bomb$bombnum/README bomb$bombnum/bomb.c bomb$bombnum/bomb > $tarfilename)") == 0
            or die "ERROR: Couldn't tar $tarfilename\n";

        #
        # Now send the bomb across the connection to the client
        #
        print CLIENT "HTTP/1.0 200 OK\r\n";
        print CLIENT "Connection: close\r\n";
        print CLIENT "MIME-Version: 1.0\r\n";
        print CLIENT "Content-Type: application/x-tar\r\n";
        print CLIENT "Content-Disposition: file; filename=\"$tarfilename\"\r\n";
        print CLIENT "\r\n";
        open(INFILE, "$Bomblab::BOMBDIR/$tarfilename")
            or die "ERROR: Couldn't open $tarfilename\n";
        binmode(INFILE, ":raw");
        binmode(CLIENT, ":raw");
        select((select(CLIENT), $| = 1)[0]);
        while (sysread(INFILE, $buffer, 1)) {
            syswrite(CLIENT, $buffer, 1);
        }
        close(INFILE);

        #
        # Log the successful delivery of the bomb to the browser
        #
        log_msg ("Sent bomb $bombnum to $client_dname:$username:$usermail:");

        #
        # Remove the tarfile
        #
        unlink("$Bomblab::BOMBDIR/$tarfilename")
            or die "ERROR: Couldn't delete $tarfilename: $!\n";

    } # if-then-elsif-else statement

    #
    # Close the client connection after each request/response pair
    #
    close CLIENT;

} # while loop

exit;

###################
# Helper functions
##################

#
# void usage(void) - print help message and terminate
#
sub usage
{
    printf STDERR "$_[0]\n";
    printf STDERR "Usage: $0 [-hqs]\n";
    printf STDERR "Options:\n";
    printf STDERR "  -h   Print this message.\n";
    printf STDERR "  -s   Silent. Build bombs with NONOTIFY option.\n";
    printf STDERR "  -q   Quiet. Send error and status msgs to $Bomblab::STATUSLOG instead of tty.\n";
    die "\n" ;
}

#
# char *buildform(char *hostname, int port, char *labid,
#                 char *usermail, char *username,
#                 *char *errmsg)
#
# This routine builds an HTML form as a single string.
# The <hostname,port> pair identifies the request daemon.
# The labid is the unique name for this instance of the Lab.
# The user* fields define the default values for the HTML form fields.
# The errmsg is optional and informs users about input mistakes.
#
sub buildform
{
    my $hostname = $_[0];
    my $port = $_[1];
    my $labid = $_[2];
    my $usermail = $_[3];
    my $username = $_[4];
    my $errmsg = $_[5];
    my $form = "";
    $form .= "<title>CS:APP Binary Bomb Request</title>\n";
    $form .= "\n";
    $form .= "
CS:APP Binary Bomb Request
\n";
    $form .= "
Fill in the form and then click the Submit button.
\n";
    $form .= "
Hit the Reset button to get a clean form.
\n";
    $form .= "
Legal characters are spaces, letters, numbers, underscores ('_'),
";
    $form .= "hyphens ('-'), at signs ('\@'), and dots ('.').
\n";
    $form .= "<form action=http://$hostname:$port method=get>\n";
    $form .= "
\n";
    $form .= "
\n";
    $form .= "User name
$Bomblab::USERNAME_HINT 	\n";
    $form .= "<input type=text size=$Bomblab::MAX_TEXTBOX maxlength=$Bomblab::MAX_TEXTBOX name=username value=\"$username\">	\n";
    $form .= "
\n";
    $form .= "
\n";
    $form .= "Email address	\n";
    $form .= "<input type=text size=$Bomblab::MAX_TEXTBOX maxlength=$Bomblab::MAX_TEXTBOX name=usermail value=\"$usermail\">	\n";
    $form .= "
\n";
    $form .= "

\n";
    $form .= "
\n";
    $form .= "<input type=submit name=submit value=\"Submit\">	\n";
    $form .= "<input type=submit name=reset value=\"Reset\">	\n";
    $form .= "
\n";
    $form .= "
</form>\n";
    if ($errmsg and $errmsg ne "") {
        $form .= "
$errmsg
\n";
    }
    $form .= "\n";
    return $form;
}

#
# void sendform(char *form) - Sends a form to the client
#
sub sendform
{
    my $form = $_[0];
    my $formlength = length($form);
    print CLIENT "HTTP/1.0 200 OK\r\n";
    print CLIENT "MIME-Version: 1.0\r\n";
    print CLIENT "Content-Type: text/html\r\n";
    print CLIENT "Content-Length: $formlength\r\n";
    print CLIENT "\r\n";
    print CLIENT $form;
}


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Jasmine Spec Runner v2.3.4</title>

  <link rel="shortcut icon" type="image/png" href="test/lib/jasmine-2.3.4/jasmine_favicon.png">
  <link rel="stylesheet" href="test/lib/jasmine-2.3.4/jasmine.css">

  <script src='//maps.googleapis.com/maps/api/js?sensor=false'></script>

  <script src="/lib/modernizr.js"></script>
  <script src="/lib/jquery/jquery.js"></script>
  <script src="/lib/foundation/foundation.js"></script>
  <script src="/lib/lodash.min.js"></script>

  <script src="test/lib/jasmine-2.3.4/jasmine.js"></script>
  <script src="test/lib/jasmine-2.3.4/jasmine-html.js"></script>
  <script src="test/lib/jasmine-2.3.4/boot.js"></script>

  <script src="public/lib/angular/angular.js"></script>
  <script src="public/lib/angular/angular-route.js"></script>
  <script src="public/lib/angular/angular-resource.js"></script>
  <script src="public/lib/angular/angular-animate.js"></script>
  <script src="public/lib/angular/angular-ui-router.js"></script>
  <script src="public/lib/angular/angular-sanitize.js"></script>
  <script src="public/lib/angular/angular-simple-logger.js"></script>
  <script src="public/lib/angular/angular-google-maps.min.js"></script>

  <script src="public/lib/angulartics.min.js"></script>
  <script src="public/lib/angulartics-google-analytics.min.js"></script>

  <script src="test/lib/angular/angular-mocks.js"></script>

  <!-- include source files here... -->
  <script src="public/js/app.js"></script>
  <script src="public/js/config.js"></script>

  <script src="public/js/controllers/cities.js"></script>
  <script src="public/js/controllers/reports.js"></script>

  <script src="public/js/services/services.js"></script>
  <script src="public/js/services/cities-service.js"></script>
  <script src="public/js/services/reports-service.js"></script>

  <!-- <script src="public/js/controllers.js"></script>
       <script src="public/js/directives.js"></script>
       <script src="public/js/filters.js"></script> -->

  <!-- include spec files here... -->
  <!-- <script src="test/unit/SpecHelper.js"></script>
       <script src="test/unit/directivesSpec.js"></script>
       <script src="test/unit/filtersSpec.js"></script> -->
  <script src="test/unit/servicesSpec.js"></script>
  <script src="test/unit/citiesSpec.js"></script>

</head>

<body>
</body>
</html>


text:
<?php echo sw_t(__('title_list_tags', null, 'swBlogTagsAdmin')) ?>

<?php /*

<?php echo __('title_filters', null, 'swBlogTagsAdmin') ?>

  <form action="<?php echo url_for('swBlogTagsAdmin/index') ?>" method="get" />
    <?php echo $sw_blog_tagList ?>

    <input type="submit" name="filters[filter]" value="<?php echo __('btn_filter', null, 'swBlogTagsAdmin') ?>" />
    <input type="submit" name="filters[reset]" value="<?php echo __('btn_reset', null, 'swBlogTagsAdmin') ?>" />
  </form>

*/ ?>

    <a class="sw-ui-btn-link ui-state-default ui-corner-all" href="<?php echo url_for('swBlogTagsAdmin/create') ?>">

      <?php echo __('link_create', null, 'swBlogTagsAdmin') ?>

        <?php echo __('th_name', null, 'swBlogTagsAdmin') ?>
        <?php echo __('th_actions', null, 'swBlogTagsAdmin') ?>

      <?php foreach ($sw_blog_tagList->getResults() as $sw_blog_tag): ?>

          <?php echo $sw_blog_tag['name'] ?>
          <a href="<?php echo url_for('swBlogTagsAdmin/edit?id='.$sw_blog_tag['id']) ?>" class='edit'><?php echo __('link_edit', null, 'swBlogTagsAdmin') ?>

      <?php endforeach; ?>

          <?php echo sw_pager_navigation($sw_blog_tagList, 'swBlogTagsAdmin/index') ?>


text:
package at.dafnik.ragemode.Shop.Creator;

import org.bukkit.Material;
import org.bukkit.entity.Player;

import at.dafnik.ragemode.API.Strings;
import at.dafnik.ragemode.Main.Main;
import at.dafnik.ragemode.MySQL.SQLCoins;

public class createAdvancedInventoryMenu_SpeedUpgrade extends createAdvancedInventoryMenuBasic{

	private static String wantsdisplayname = Strings.shop_item_speedupgrader_name;
	private static Material material = Material.FEATHER;
	private int upgradecost = 0;

	public createAdvancedInventoryMenu_SpeedUpgrade(Player player) {
		super(player, wantsdisplayname, material);

		this.upgradecost = Main.getInstance().getConfig().getInt("ragemode.shop.knifeupgradeprice");
	}

	@Override
	public void createAdvancedItem() {
		super.chooseitemmeta.setDisplayName(Strings.shop_item_speedupgrader_name);
		super.chooseitemlore.add(Strings.shop_item_speedupgrader_usage);

		super.bookmetalore.add(Strings.inventory_invmore_description_description + Strings.shop_item_speedupgrader_advanced_usage_0);
		super.bookmetalore.add(Strings.shop_item_speedupgrader_advanced_usage_1);

		if(SQLCoins.getSpeedUpgrade(player.getUniqueId().toString())) {
			super.buyitemmeta.setDisplayName(Strings.inventory_flint_bought);
		} else {
			if(SQLCoins.getCoins(player.getUniqueId().toString()) >= upgradecost) {
				super.buyitemmeta.setDisplayName(Strings.inventory_flint_buyable);
			} else {
				super.buyitemmeta.setDisplayName(Strings.inventory_flint_not_enough_coins);
				super.buyitemlore.add("§a" + upgradecost + " §6Coins");
			}
		}
	}
}


text:
import java.rmi.Remote;

public interface ReplicaInterface extends Remote {

}


text:
//
// C++ Interface: %{MODULE}
//
// Description:
//
//
// Author: %{AUTHOR} <%{EMAIL}>, (C) %{YEAR}
//
// Copyright: See COPYING file that comes with this distribution
//
//
#ifndef LANGELEMS_H
#define LANGELEMS_H

#include "langelem.h"

#include <list>
#include <map>
#include <string>

using std::list;
using std::map;
using std::string;

typedef list<LangElem *> LangElemsBase;

/**
collection of LangElem

@author Lorenzo Bettini
*/
// doublecpp: forward declarations, DO NOT MODIFY
class LangElemsPrinter; // file: langelemsprinter.h
class RegExpStateBuilder; // file: regexpstatebuilder.h
class RegExpStatePointer; // file: regexpstatebuilder.h
// doublecpp: end, DO NOT MODIFY

class LangElems : protected list<LangElem *>
{
  typedef list<LangElem *> base;
  typedef base::iterator Pointer;
  typedef list<Pointer> PointerList;
  typedef map<string, PointerList> ElemMap;

  ElemMap elem_map;

  public:
    using base::const_iterator;
    using base::begin;
    using base::end;
    using base::size;

    LangElems();

    virtual ~LangElems();

    void add(LangElem *el);
    void redef(LangElem *el);
    void subst(LangElem *el);

    const std::string toString() const;
    const std::string toStringOriginal() const;
// doublecpp: dispatch methods, DO NOT MODIFY
public:
virtual void dispatch_build(RegExpStateBuilder *, RegExpStatePointer state);
virtual void dispatch_collect_const(LangElemsPrinter *);
// doublecpp: end, DO NOT MODIFY
};

#endif


text:
package jp.gr.java_conf.kgd.library.cool.util.collection;

import java.util.Map;

import jp.gr.java_conf.kgd.library.cool.util.function.IFunction;

public interface ISharedKeyMapCreator<E>
{
	<V> Map<E, V> createSharedKeyMap();

//	<V> Map<E, V> createSharedKeyMap(IFunction<? extends V> defaultValueCreator);
	<V, S extends V> Map<E, V> createSharedKeyMap(IFunction<? extends S> defaultValueCreator);
	//こうすると、受け手の変数のジェネリクス引数(インターフェースorスーパークラス)と
	//ファクトリの引数(実装クラスorサブクラス)が違っても対応できる。
}


text:
'use strict';

var _ = require('underscore.string')
  , fs = require('fs')
  , path = require('path')
  , bowerDir = JSON.parse(fs.readFileSync('.bowerrc')).directory + path.sep;

module.exports = function (gulp, $, config) {
  var isProd = $.yargs.argv.stage === 'prod';

  // delete build directory
  gulp.task('clean', function () {
    return $.del(config.buildDir);
  });

  // compile markup files and copy into build directory
  gulp.task('markup', ['clean'], function () {
    return gulp.src([
      config.appMarkupFiles
    ])
      .pipe(gulp.dest(config.buildDir));
  });

  // compile styles and copy into build directory
  gulp.task('styles', ['clean'], function () {
    return gulp.src([
      config.appStyleFiles
    ])
      .pipe($.plumber({errorHandler: function (err) {
        $.notify.onError({
          title: 'Error linting at ' + err.plugin,
          subtitle: ' ', //overrides defaults
          message: err.message.replace(/\u001b\[.*?m/g, ''),
          sound: ' ' //overrides defaults
        })(err);

        this.emit('end');
      }}))
      .pipe($.less())
      .pipe($.autoprefixer())
      .pipe($.if(isProd, $.cssRebaseUrls()))
      .pipe($.if(isProd, $.modifyCssUrls({
        modify: function (url) {
          // determine if url is using http, https, or data protocol
          // cssRebaseUrls rebases these URLs, too, so we need to fix that
          if (url.indexOf('http:') > -1 || url.indexOf('https:') > -1 || url.indexOf('data:') > -1) {
            return url.substring(beginUrl, url.length);
          }

          // prepend all other urls
          return '../' + url;
        }
      })))
      .pipe($.if(isProd, $.concat('app.css')))
      .pipe($.if(isProd, $.cssmin()))
      .pipe($.if(isProd, $.rev()))
      .pipe(gulp.dest(config.buildCss));
  });

  // compile scripts and copy into build directory
  gulp.task('scripts', ['clean', 'analyze', 'markup'], function () {
    var htmlFilter = $.filter('**/*.html', {restore: true})
      , jsFilter = $.filter('**/*.js', {restore: true});

    return gulp.src([
      config.appScriptFiles,
      config.buildDir + '**/*.html',
      '!**/*_test.*',
      '!**/index.html'
    ])
      .pipe($.sourcemaps.init())
      .pipe($.if(isProd, htmlFilter))
      .pipe($.if(isProd, $.ngHtml2js({
        // lower camel case all app names
        moduleName: _.camelize(_.slugify(_.humanize(require('../package.json').name))),
        declareModule: false
      })))
      .pipe($.if(isProd, htmlFilter.restore))
      .pipe(jsFilter)
      .pipe($.if(isProd, $.angularFilesort()))
      .pipe($.if(isProd, $.concat('app.js')))
      .pipe($.if(isProd, $.ngAnnotate()))
      .pipe($.if(isProd, $.uglify()))
      .pipe($.if(isProd, $.rev()))
      .pipe($.sourcemaps.write('.'))
      .pipe(gulp.dest(config.buildJs))
      .pipe(jsFilter.restore);
  });

  // inject custom CSS and JavaScript into index.html
  gulp.task('inject', ['markup', 'styles', 'scripts'], function () {
    var jsFilter = $.filter('**/*.js', {restore: true});

    return gulp.src(config.buildDir + 'index.html')
      .pipe($.inject(gulp.src([
          config.buildCss + '**/*',
          config.buildJs + '**/*'
        ])
        .pipe(jsFilter)
        .pipe($.angularFilesort())
        .pipe(jsFilter.restore), {
          addRootSlash: false,
          ignorePath: config.buildDir
        })
      )
      .pipe(gulp.dest(config.buildDir));
  });

  // copy bower components into build directory
  gulp.task('bowerCopy', ['inject'], function () {
    var cssFilter = $.filter('**/*.css', {restore: true})
      , jsFilter = $.filter('**/*.js', {restore: true});

    return gulp.src($.mainBowerFiles({includeDev: true}), {base: bowerDir})
      .pipe(cssFilter)
      .pipe($.if(isProd, $.modifyCssUrls({
        modify: function (url, filePath) {
          if (url.indexOf('data:') === 0) {
            return url;
          }

          if (url.indexOf('http') !== 0) {
            filePath = path.dirname(filePath) + path.sep;
            filePath = filePath.substring(filePath.indexOf(bowerDir) + bowerDir.length,
              filePath.length);
          }
          url = path.normalize(filePath + url);
          url = url.replace(/[/\\]/g, '/');
          return url;
        }
      })))
      .pipe($.if(isProd, $.concat('vendor.css')))
      .pipe($.if(isProd, $.cssmin()))
      .pipe($.if(isProd, $.rev()))
      .pipe(gulp.dest(config.extDir))
      .pipe(cssFilter.restore)
      .pipe(jsFilter)
      .pipe($.if(isProd, $.concat('vendor.js')))
      .pipe($.if(isProd, $.uglify({
        preserveComments: $.uglifySaveLicense
      })))
      .pipe($.if(isProd, $.rev()))
      .pipe(gulp.dest(config.extDir))
      .pipe(jsFilter.restore);
  });

  // inject bower components into index.html
  gulp.task('bowerInject', ['bowerCopy'], function () {
    if (isProd) {
      return gulp.src(config.buildDir + 'index.html')
        .pipe($.inject(gulp.src([
          config.extDir + 'vendor*.css',
          config.extDir + 'vendor*.js'
        ], {
          read: false
        }), {
          starttag: '<!-- bower:{{ext}} -->',
          endtag: '<!-- endbower -->',
          addRootSlash: false,
          ignorePath: config.buildDir
        }))
        .pipe($.htmlmin({
          collapseWhitespace: true,
          removeComments: true
        }))
        .pipe(gulp.dest(config.buildDir));
    } else {
      return gulp.src(config.buildDir + 'index.html')
        .pipe($.wiredep.stream({
          devDependencies: true,
          verbose: true,
          exclude: [/bootstrap[.]js/],
          ignorePath: '../../' + bowerDir.replace(/\\/g, '/'),
          fileTypes: {
            html: {
              replace: {
                css: function (filePath) {
                  return '<link rel="stylesheet" href="' + config.extDir.replace(config.buildDir, '') +
                    filePath + '">';
                },
                js: function (filePath) {
                  return '<script src="' + config.extDir.replace(config.buildDir, '') +
                    filePath + '"></script>';
                }
              }
            }
          }
        }))
        // .pipe($.through2.obj(function(obj, enc, next) {
        //   this.push(obj.contents);
        //   next();
        // }))
        // .pipe(process.stdout)
        .pipe(gulp.dest(config.buildDir));
    }
  });

  // copy Bower fonts and images into build directory
  gulp.task('bowerAssets', ['clean'], function () {
    var assetFilter = $.filter('**/*.{eot,otf,svg,ttf,woff,woff2,gif,jpg,jpeg,png}', {restore: true});
    return gulp.src($.mainBowerFiles(), {base: bowerDir})
      .pipe(assetFilter)
      .pipe(gulp.dest(config.extDir))
      .pipe(assetFilter.restore);
  });

  // copy custom fonts into build directory
  gulp.task('fonts', ['clean'], function () {
    var fontFilter = $.filter('**/*.{eot,otf,svg,ttf,woff,woff2}', {restore: true});
    return gulp.src([config.appFontFiles])
      .pipe(fontFilter)
      .pipe(gulp.dest(config.buildFonts))
      .pipe(fontFilter.restore);
  });

  // copy optional favicon in app directory
  gulp.task('favicon', ['clean'], function () {
    return gulp.src(path.join(config.appDir, 'favicon.ico'))
      .pipe(gulp.dest(config.buildDir));
  });

  // copy and optimize images into build directory
  gulp.task('images', ['clean', 'favicon'], function () {
    return gulp.src(config.appImageFiles)
      .pipe($.if(isProd, $.imagemin()))
      .pipe(gulp.dest(config.buildImages));
  });

  // copy favicon.ico into build directory
  gulp.task('favicon', ['clean'], function () {
    return gulp.src(config.appDir + '/favicon.ico')
      .pipe(gulp.dest(config.buildDir));
  });

  gulp.task('copyTemplates', ['bowerInject'], function () {
    // always copy templates to testBuild directory
    var stream = $.streamqueue({objectMode: true});

    stream.queue(gulp.src([config.buildDirectiveTemplateFiles]));

    return stream.done()
      .pipe(gulp.dest(config.buildTestDirectiveTemplatesDir));
  });

  gulp.task('deleteTemplates', ['copyTemplates'], function (cb) {
    // only delete templates in production
    // the templates are injected into the app during prod build
    if (!isProd) {
      return cb();
    }

    gulp.src([config.buildDir + '**/*.html'])
      .pipe(gulp.dest('tmp/' + config.buildDir))
      .on('end', function () {
        $.del([
          config.buildDir + '*',
          '!' + config.buildCss,
          '!' + config.buildFonts,
          '!' + config.buildImages,
          '!' + config.buildJs,
          '!' + config.extDir,
          '!' + config.buildDir + 'index.html'
        ], {mark: true})
          .then(function () {
            cb();
          });
      });
  });

  gulp.task('readme', [], function() {
      return gulp.src([
          path.join(conf.paths.src, '/doc/partials/readme.md')
      ])
      .pipe($.rename("README.md"))
          .pipe(gulp.dest('./'));
  });

  gulp.task('build', ['deleteTemplates', 'bowerAssets', 'images', 'favicon', 'fonts']);
};


text:
{% extends "base.html" %}

{% load i18n sekizai_tags menu_tags verbatim storybase_tags compress %}

{% block head_title %}{{ storybase_explore_title }}{{ block.super }}{% endblock %}

{% block extrameta %}
<meta name="title" content="{{ storybase_explore_title }}" />
<meta name="description" content="{% blocktrans %}Browse and filter {{ storybase_site_name }} stories by topic, location, language, project and organization.{% endblocktrans %}">

{% url "explore_stories" as explore_url %}
<meta property="og:url" content="{% fullurl explore_url %}" />
<meta property="og:title" content="{{ storybase_explore_title }}" />
<meta property="og:description" content="{% blocktrans %}Browse and filter {{ storybase_site_name }} stories by topic, location, language, project and organization.{% endblocktrans %}" />
<meta property="og:image" content="{{ storybase_site_logo }}" />
{% endblock %}

{% block extrahead %}
{% comment %}
Handlebars templates for rendering Backbone views.
{% endcomment %}

{% verbatim %}

{% endverbatim %}
{% endblock %}

{% block body_class %}explorer{% endblock %}

{% block above_content %}
{% show_breadcrumb "breadcrumbs.html" %}
{% endblock %}

{% block base_content %}
{% addtoblock "css" %}<link rel="stylesheet" href="{{ STATIC_URL }}js/libs/leaflet/leaflet.css">{% endaddtoblock %}
{% addtoblock "css" %}<link rel="stylesheet" href="{{ STATIC_URL }}js/libs/select2/select2.css">{% endaddtoblock %}
{% addtoblock "css" %}<link rel="stylesheet" href="{{ STATIC_URL }}js/libs/tooltipster-2.1.4/css/tooltipster.css">{% endaddtoblock %}

{{ storybase_explore_title }}

{% addtoblock "js" %}

{% compress js %}

{% endcompress js %}

{% endaddtoblock %}
{% endblock %}


text:
package com.monitor.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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

import com.monitor.dao.UnitType_functionDAO;
import com.monitor.factory.UnitType_functionDAOFactory;

public class SearchUnitTypeServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public SearchUnitTypeServlet() {
		super();
	}

	/**
	 * Destruction of the servlet.

	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet.

	 *
	 * This method is called when a form has its tag value method equals to get.
	 *
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			doPost(request,response);
	}

	/**
	 * The doPost method of the servlet.

	 *
	 * This method is called when a form has its tag value method equals to post.
	 *
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//设置编码方式
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		UnitType_functionDAO UnitType_functionDAOImpl = UnitType_functionDAOFactory.createUnitType_functionDAOImplm();

		//从页面得到参数,并且访问数据库
		String unitTypeID = request.getParameter("unitTypeID");
		String unitTypeName = request.getParameter("unitTypeName");
		String[] str = UnitType_functionDAOImpl.searchUnitType(unitTypeID, unitTypeName);

		System.out.println(str);
		request.setAttribute("str",str);
		request.getRequestDispatcher("../jsp/unitType/showAllUnitType.jsp").forward(request, response);
	}

	/**
	 * Initialization of the servlet.

	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}


text:
package com.foregroundgalleryplugin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

/**
 * Class to search images from the memory card. Based on
 * http://mihaifonoage.blogspot.com/2009/11/displaying-images-from-sd-card-in.html
 * Thanks to the author.
 */
public class GalleryActivity extends Activity implements OnItemClickListener {

	private GridView sdcardImages;
	private ImageAdapter imageAdapter;
	private Display display;
	private LoadImagesFromSDCard load;
	private Map<Integer, Integer> sequencialImageID;

	/**
	 * Creates the content view, sets up the grid, the adapter, and the click
	 * listener.
	 *
	 * @param savedInstanceState
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Request progress bar
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.gallery);

		display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();

		setupViews();
		setProgressBarIndeterminateVisibility(true);
		loadImages();
	}

	/**
	 * Free up bitmap related resources.
	 */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		final GridView grid = sdcardImages;
		final int count = grid.getChildCount();
		ImageView v = null;
		for (int i = 0; i < count; i++) {
			v = (ImageView) grid.getChildAt(i);
			((BitmapDrawable) v.getDrawable()).setCallback(null);
		}
		if (load != null) {
			load.cancel(true);
		}
	}

	/**
	 * Setup the grid view.
	 */
	private void setupViews() {
		sdcardImages = (GridView) findViewById(R.id.sdcard);
		sdcardImages.setNumColumns(display.getWidth() / 95);
		sdcardImages.setClipToPadding(false);
		sdcardImages.setOnItemClickListener(GalleryActivity.this);
		imageAdapter = new ImageAdapter(getApplicationContext());
		sdcardImages.setAdapter(imageAdapter);
	}

	/**
	 * Load images.
	 */
	private void loadImages() {
		final Object data = getLastNonConfigurationInstance();
		if (data == null) {
			load = new LoadImagesFromSDCard();
			load.execute();
		} else {
			final LoadedImage[] photos = (LoadedImage[]) data;
			if (photos.length == 0) {
				load = new LoadImagesFromSDCard();
				load.execute();
			}
			for (LoadedImage photo : photos) {
				addImage(photo);
			}
		}
	}

	/**
	 * Add image(s) to the grid view adapter.
	 *
	 * @param value
	 *            Array of LoadedImages references
	 */
	private void addImage(LoadedImage... value) {
		for (LoadedImage image : value) {
			imageAdapter.addPhoto(image);
			imageAdapter.notifyDataSetChanged();
		}
	}

	/**
	 * Save bitmap images into a list and return that list.
	 *
	 * @return
	 * @see android.app.Activity#onRetainNonConfigurationInstance()
	 */
	@Override
	public Object onRetainNonConfigurationInstance() {
		final GridView grid = sdcardImages;
		final int count = grid.getChildCount();
		final LoadedImage[] list = new LoadedImage[count];

		for (int i = 0; i < count; i++) {
			final ImageView v = (ImageView) grid.getChildAt(i);
			list[i] = new LoadedImage(
					((BitmapDrawable) v.getDrawable()).getBitmap());
		}

		return list;
	}

	/**
	 * Async task for loading the images from the SD card.	 *
	 */
	class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Integer> {

		/**
		 * Load images from SD Card in the background, and display each image on
		 * the screen.
		 *
		 * @see android.os.AsyncTask#doInBackground(Params[])
		 */
		@Override
		protected Integer doInBackground(Object... params) {
			Bitmap bitmap = null;
			Bitmap newBitmap = null;
			sequencialImageID = new HashMap<Integer, Integer>();

			// Set up an array of the Thumbnail Image ID column we want
			String[] projection = { MediaStore.Images.Media._ID };
			// Create the cursor pointing to the SDCard
			Cursor cursor = managedQuery(
					MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, // Which
																				// columns
																				// to
																				// return
					null, // Return all rows
					null, MediaStore.Images.Media.DATE_TAKEN + " DESC");
			int columnIndex = cursor
					.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
			int size = cursor.getCount();
			// If size is 0, there are no images on the SD Card.
			if (size == 0) {
				return -1;
			}
			int imageID = 0;
			for (int i = 0; i < size; i++) {
				if (isCancelled() || cursor.isClosed()) {
					break;
				}
				cursor.moveToPosition(i);
				imageID = cursor.getInt(columnIndex);
				sequencialImageID.put(Integer.valueOf(i), imageID);

				bitmap = MediaStore.Images.Thumbnails.getThumbnail(
						getContentResolver(), imageID,
						MediaStore.Images.Thumbnails.MICRO_KIND, null);
				if (bitmap != null) {
					newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
					bitmap.recycle();
					if (newBitmap != null) {
						publishProgress(new LoadedImage(newBitmap));
					}
				}
			}
			cursor.close();
			return null;
		}

		/**
		 * Add a new LoadedImage in the images grid.
		 *
		 * @param value
		 *            The image.
		 */
		@Override
		public void onProgressUpdate(LoadedImage... value) {
			addImage(value);
		}

		/**
		 * Set the visibility of the progress bar to false.
		 *
		 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
		 */
		@Override
		protected void onPostExecute(Integer result) {
			if ((result != null) && (result == -1)) {
				AlertDialog.Builder dialog = new AlertDialog.Builder(
						sdcardImages.getContext());
				dialog.setTitle("Alert");
				dialog.setMessage("No images found!");
				dialog.setNeutralButton("OK", new OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						setResult(RESULT_CANCELED);
						finish();
					}
				});
				dialog.show();
			}

			setProgressBarIndeterminateVisibility(false);
		}
	}

	/**
	 * Adapter for our image files.
	 */
	class ImageAdapter extends BaseAdapter {

		private Context mContext;
		private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();

		public ImageAdapter(Context context) {
			mContext = context;
		}

		public void addPhoto(LoadedImage photo) {
			photos.add(photo);
		}

		public int getCount() {
			return photos.size();
		}

		public Object getItem(int position) {
			return photos.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final ImageView imageView;
			if (convertView == null) {
				imageView = new ImageView(mContext);
			} else {
				imageView = (ImageView) convertView;
			}
			imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
			imageView.setPadding(8, 8, 8, 8);
			imageView.setImageBitmap(photos.get(position).getBitmap());
			return imageView;
		}
	}

	/**
	 * A LoadedImage contains the Bitmap loaded for the image.
	 */
	private static class LoadedImage {
		Bitmap mBitmap;

		LoadedImage(Bitmap bitmap) {
			mBitmap = bitmap;
		}

		public Bitmap getBitmap() {
			return mBitmap;
		}
	}

	/**
	 * When an image is clicked, load that image as a puzzle.
	 *
	 * @param parent
	 * @param v
	 * @param position
	 * @param id
	 */
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

		Integer imageID = sequencialImageID.get(position);

		Uri uri = Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/"
				+ imageID);
		getIntent().setData(uri);
		setResult(RESULT_OK, getIntent());
		finish();
	}

}


text:
DEFAULT_OPENOFFICE_PORT = 8100

import sys
import os
import time

# Find OpenOffice.
_oopaths=(
        ('/usr/lib/openoffice/program',   '/usr/lib/openoffice/program'),
        ('/usr/lib64/ooo-2.0/program',   '/usr/lib64/ooo-2.0/program'),
        ('/opt/openoffice.org3/program', '/opt/openoffice.org/basis3.0/program'),
     )

for p in _oopaths:
    if os.path.exists(p[0]):
        OPENOFFICE_PATH    = p[0]
        OPENOFFICE_BIN     = os.path.join(OPENOFFICE_PATH, 'soffice')
        OPENOFFICE_LIBPATH = p[1]

        # Add to path so we can find uno.
        if sys.path.count(OPENOFFICE_LIBPATH) == 0:
            sys.path.insert(0, OPENOFFICE_LIBPATH)
        break

import uno
from os.path import abspath, isfile, splitext
from com.sun.star.beans import PropertyValue
from com.sun.star.task import ErrorCodeIOException
from com.sun.star.connection import NoConnectException

FAMILY_TEXT = "Text"
FAMILY_WEB = "Web"
FAMILY_SPREADSHEET = "Spreadsheet"
FAMILY_PRESENTATION = "Presentation"
FAMILY_DRAWING = "Drawing"

#---------------------#
# Configuration Start #
#---------------------#

# see http://wiki.services.openoffice.org/wiki/Framework/Article/Filter

# most formats are auto-detected; only those requiring options are defined here
IMPORT_FILTER_MAP = {
    "txt": {
        "FilterName": "Text (encoded)",
        "FilterOptions": "utf8"
    },
    "csv": {
        "FilterName": "Text - txt - csv (StarCalc)",
        "FilterOptions": "44,34,0"
    }
}

EXPORT_FILTER_MAP = {
    "pdf": {
        FAMILY_TEXT: { "FilterName": "writer_pdf_Export" },
        FAMILY_WEB: { "FilterName": "writer_web_pdf_Export" },
        FAMILY_SPREADSHEET: { "FilterName": "calc_pdf_Export" },
        FAMILY_PRESENTATION: { "FilterName": "impress_pdf_Export" },
        FAMILY_DRAWING: { "FilterName": "draw_pdf_Export" }
    },
    "html": {
        FAMILY_TEXT: { "FilterName": "HTML (StarWriter)" },
        FAMILY_SPREADSHEET: { "FilterName": "HTML (StarCalc)" },
        FAMILY_PRESENTATION: { "FilterName": "impress_html_Export" }
    },
    "odt": {
        FAMILY_TEXT: { "FilterName": "writer8" },
        FAMILY_WEB: { "FilterName": "writerweb8_writer" }
    },
    "doc": {
        FAMILY_TEXT: { "FilterName": "MS Word 97" }
    },
    "rtf": {
        FAMILY_TEXT: { "FilterName": "Rich Text Format" }
    },
    "txt": {
        FAMILY_TEXT: {
            "FilterName": "Text",
            "FilterOptions": "utf8"
        }
    },
    "ods": {
        FAMILY_SPREADSHEET: { "FilterName": "calc8" }
    },
    "xls": {
        FAMILY_SPREADSHEET: { "FilterName": "MS Excel 97" }
    },
    "csv": {
        FAMILY_SPREADSHEET: {
            "FilterName": "Text - txt - csv (StarCalc)",
            "FilterOptions": "44,34,0"
        }
    },
    "odp": {
        FAMILY_PRESENTATION: { "FilterName": "impress8" }
    },
    "ppt": {
        FAMILY_PRESENTATION: { "FilterName": "MS PowerPoint 97" }
    },
    "swf": {
        FAMILY_DRAWING: { "FilterName": "draw_flash_Export" },
        FAMILY_PRESENTATION: { "FilterName": "impress_flash_Export" }
    }
}

PAGE_STYLE_OVERRIDE_PROPERTIES = {
    FAMILY_SPREADSHEET: {
        #--- Scale options: uncomment 1 of the 3 ---
        # a) 'Reduce / enlarge printout': 'Scaling factor'
        "PageScale": 100,
        # b) 'Fit print range(s) to width / height': 'Width in pages' and 'Height in pages'
        #"ScaleToPagesX": 1, "ScaleToPagesY": 1000,
        # c) 'Fit print range(s) on number of pages': 'Fit print range(s) on number of pages'
        #"ScaleToPages": 1,
        "PrintGrid": False
    }
}

#-------------------#
# Configuration End #
#-------------------#

class OOService:
    """
    Start, stop, and connect to OpenOffice.
    """
    def __init__(self, port=DEFAULT_OPENOFFICE_PORT):
        """ Create OORunner that connects on the specified port. """
        self.port = port

    def connect(self, no_startup=False):
        """
        Connect to OpenOffice.
        If a connection cannot be established try to start OpenOffice.
        """
        localContext = uno.getComponentContext()
        resolver     = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
        context      = None

        n = 0
        while n < 6:
            try:
                context = resolver.resolve("uno:socket,host=localhost,port=%d;urp;StarOffice.ComponentContext" % self.port)
                break
            except NoConnectException:
                pass

            # If first connect failed then try starting OpenOffice.
            if n == 0:
                # Exit loop if startup not desired.
                if no_startup:
                     break
                self.startup()

            # Pause and try again to connect
            time.sleep(1)
            n += 1

        if not context:
            raise Exception, "Failed to connect to OpenOffice on port %d" % self.port

        desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)

        if not desktop:
            raise Exception, "Failed to create OpenOffice desktop on port %d" % self.port

        return desktop

    def startup(self):
        """
        Start a headless instance of OpenOffice.
        """
        args = [OPENOFFICE_BIN,
                '-accept=socket,host=localhost,port=%d;urp;StarOffice.ServiceManager' % self.port,
                '-norestore',
                '-nofirststartwizard',
                '-nologo',
                '-headless',
                ]
        env  = {'PATH'       : '/bin:/usr/bin:%s' % OPENOFFICE_PATH,
                'PYTHONPATH' : OPENOFFICE_LIBPATH,
                }

        try:
            pid = os.spawnve(os.P_NOWAIT, args[0], args, env)
        except Exception, e:
            raise Exception, "Failed to start OpenOffice on port %d: %s" % (self.port, e.message)

        if pid <= 0:
            raise Exception, "Failed to start OpenOffice on port %d" % self.port

    def shutdown(self):
        """
        Shutdown OpenOffice.
        """
        try:
            desktop = self.connect(True)
            if desktop:
                desktop.terminate()
        except Exception, e:
#            pass
            raise Exception, "Failed to shutdown the process: %s" % (e.message)

class DocumentConversionException(Exception):

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

    def __str__(self):
        return self.message

class DocumentConverter:

    def __init__(self, port=DEFAULT_OPENOFFICE_PORT):
        localContext = uno.getComponentContext()
        resolver = localContext.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext)
        try:
            context = resolver.resolve("uno:socket,host=localhost,port=%s;urp;StarOffice.ComponentContext" % port)
        except NoConnectException:
            raise DocumentConversionException, "failed to connect to OpenOffice.org on port %s" % port
        self.desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)

    def terminate(self):
	self.desktop.terminate()

    def convert(self, inputFile, outputFile):

        inputUrl = self._toFileUrl(inputFile)
        outputUrl = self._toFileUrl(outputFile)

        loadProperties = { "Hidden": True }
        inputExt = self._getFileExt(inputFile)
        if IMPORT_FILTER_MAP.has_key(inputExt):
            loadProperties.update(IMPORT_FILTER_MAP[inputExt])

        document = self.desktop.loadComponentFromURL(inputUrl, "_blank", 0, self._toProperties(loadProperties))
        try:
            document.refresh()
        except AttributeError:
            pass

        family = self._detectFamily(document)
        self._overridePageStyleProperties(document, family)

        outputExt = self._getFileExt(outputFile)
        storeProperties = self._getStoreProperties(document, outputExt)

        try:
            document.storeToURL(outputUrl, self._toProperties(storeProperties))
        finally:
            document.close(True)

    def _overridePageStyleProperties(self, document, family):
        if PAGE_STYLE_OVERRIDE_PROPERTIES.has_key(family):
            properties = PAGE_STYLE_OVERRIDE_PROPERTIES[family]
            pageStyles = document.getStyleFamilies().getByName('PageStyles')
            for styleName in pageStyles.getElementNames():
                pageStyle = pageStyles.getByName(styleName)
                for name, value in properties.items():
                    pageStyle.setPropertyValue(name, value)

    def _getStoreProperties(self, document, outputExt):
        family = self._detectFamily(document)
        try:
            propertiesByFamily = EXPORT_FILTER_MAP[outputExt]
        except KeyError:
            raise DocumentConversionException, "unknown output format: '%s'" % outputExt
        try:
            return propertiesByFamily[family]
        except KeyError:
            raise DocumentConversionException, "unsupported conversion: from '%s' to '%s'" % (family, outputExt)

    def _detectFamily(self, document):
        if document.supportsService("com.sun.star.text.WebDocument"):
            return FAMILY_WEB
        if document.supportsService("com.sun.star.text.GenericTextDocument"):
            # must be TextDocument or GlobalDocument
            return FAMILY_TEXT
        if document.supportsService("com.sun.star.sheet.SpreadsheetDocument"):
            return FAMILY_SPREADSHEET
        if document.supportsService("com.sun.star.presentation.PresentationDocument"):
            return FAMILY_PRESENTATION
        if document.supportsService("com.sun.star.drawing.DrawingDocument"):
            return FAMILY_DRAWING
        raise DocumentConversionException, "unknown document family: %s" % document

    def _getFileExt(self, path):
        ext = splitext(path)[1]
        if ext is not None:
            return ext[1:].lower()

    def _toFileUrl(self, path):
        return uno.systemPathToFileUrl(abspath(path))

    def _toProperties(self, dict):
        props = []
        for key in dict:
            prop = PropertyValue()
            prop.Name = key
            prop.Value = dict[key]
            props.append(prop)
        return tuple(props)

if __name__ == "__main__":
    from sys import argv, exit

    if argv[1] == "--daemon":
	try:
            service = OOService()
            service.startup()
	    exit(0)
	except ErrorCodeIOException, e:
	    print "Failed to start daemon process: %s" % e.message
	    exit(1)

    if argv[1] == "--shutdown":
	try:
            service = OOService()
            service.shutdown()
	    exit(0)
	except ErrorCodeIOException, e:
	    print "Failed to shut down daemon process: %s" % e.message
	    exit(1)

    if len(argv) < 3:
        print "USAGE: python %s <input-file> <output-file>" % argv[0]
        exit(255)
    elif not isfile(argv[1]):
        print "no such input file: %s" % argv[1]
        exit(1)
    try:
        converter = DocumentConverter()
        converter.convert(argv[1], argv[2])
    except DocumentConversionException, exception:
        print "ERROR! " + str(exception)
        exit(1)
    except ErrorCodeIOException, exception:
        print "ERROR! ErrorCodeIOException %d" % exception.ErrCode
        exit(1)


text:
//-----------------------------------------------------------------------
// <copyright file="VerifyCredentialsCommand.cs" company="Patrick 'Ricky' Smith">
//  This file is part of the Twitterizer library (http://www.twitterizer.net/)
//
//  Copyright (c) 2010, Patrick "Ricky" Smith (ricky@digitally-born.com)
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without modification, are
//  permitted provided that the following conditions are met:
//
//  - Redistributions of source code must retain the above copyright notice, this list
//    of conditions and the following disclaimer.
//  - Redistributions in binary form must reproduce the above copyright notice, this list
//    of conditions and the following disclaimer in the documentation and/or other
//    materials provided with the distribution.
//  - Neither the name of the Twitterizer nor the names of its contributors may be
//    used to endorse or promote products derived from this software without specific
//    prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
//  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
//  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
//  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
//  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
//  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//  POSSIBILITY OF SUCH DAMAGE.
// </copyright>
// <author>David Golden</author>
// <summary>The verify credentials optional parameters class.</summary>
//-----------------------------------------------------------------------
namespace Twitterizer.Commands
{
    using System;
    using Core;

    /// <summary>
    /// The verify credentials command class.
    /// </summary>
    [AuthorizedCommand]
#if !SILVERLIGHT
    [System.Serializable]
#endif
    internal class VerifyCredentialsCommand : TwitterCommand<TwitterUser>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="RateLimitStatusCommand"/> class.
        /// </summary>
        /// <param name="requestTokens">The request tokens.</param>
        /// <param name="options">The options.</param>
        public VerifyCredentialsCommand(OAuthTokens requestTokens, VerifyCredentialsOptions options)
            : base(HTTPVerb.GET, "account/verify_credentials.json", requestTokens, options)
        {
        }

        /// <summary>
        /// Initializes the command.
        /// </summary>
        public override void Init()
        {
            VerifyCredentialsOptions options = this.OptionalProperties as VerifyCredentialsOptions;

            if (options == null) return;

            if (options.IncludeEntities)
            {
                this.RequestParameters.Add("include_entities", "true");
            }
        }
    }
}


text:
'use strict';

describe('Controller: BuscarSemillasCtrl', function () {

  // load the controller's module
  beforeEach(module('frontApp'));

  var BuscarSemillasCtrl,
    scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    BuscarSemillasCtrl = $controller('BuscarSemillasCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings.length).toBe(3);
  });
});


text:
START_ATF_NAMESPACE
    typedef wchar_t *LPOLESTR;
END_ATF_NAMESPACE


text:
from realms.cards import CardFaction, CardTarget, CardAction
import pytest

@pytest.fixture
def viper(repo):
    return repo.new_viper()

def test_viper_properties(viper):
    assert viper.faction == CardFaction.UNALIGNED
    assert viper.cost == 0
    assert viper.base is False

def test_viper_effects_basic(viper):
    v_effect = viper.effects_basic[0]
    assert v_effect.target == CardTarget.OPPONENT
    assert v_effect.action == CardAction.ATTACK
    assert v_effect.value == 1

def test_viper_effects_number(viper):
    assert len(viper.effects_basic) == 1
    assert len(viper.effects_ally) == 0
    assert len(viper.effects_scrap) == 0

@pytest.fixture
def scout(repo):
    return repo.new_scout()

def test_scout_properties(scout):
    assert scout.faction == CardFaction.UNALIGNED
    assert scout.cost == 0
    assert scout.base is False

def test_scout_effects_basic(scout):
    s_effect = scout.effects_basic[0]
    assert s_effect.target == CardTarget.OWNER
    assert s_effect.action == CardAction.MONEY
    assert s_effect.value == 1

def test_scout_effects_number(scout):
    assert len(scout.effects_basic) == 1
    assert len(scout.effects_ally) == 0
    assert len(scout.effects_scrap) == 0

@pytest.fixture
def explorer(repo):
    return repo.new_explorer()

def test_explorer_properties(explorer):
    assert explorer.faction == CardFaction.UNALIGNED
    assert explorer.cost == 0
    assert explorer.base is False

def test_explorer_effects_basic(explorer):
    effect = explorer.effects_basic[0]
    assert effect.target == CardTarget.OWNER
    assert effect.action == CardAction.MONEY
    assert effect.value == 2

def test_explorer_effects_scrap(explorer):
    effect = explorer.effects_scrap[0]
    assert effect.target == CardTarget.OPPONENT
    assert effect.action == CardAction.ATTACK
    assert effect.value == 2

def test_explorer_effects_number(explorer):
    assert len(explorer.effects_basic) == 1
    assert len(explorer.effects_ally) == 0
    assert len(explorer.effects_scrap) == 1

@pytest.fixture
def main_deck_cards(repo):
    return repo.main_deck_cards()

def test_main_deck_cards_length(main_deck_cards):
    assert len(main_deck_cards) > 0

def test_main_deck_cards_does_not_contain_vipers(main_deck_cards):
    with pytest.raises(StopIteration):
        next(c for c in main_deck_cards if c.name == 'Viper')

def test_main_deck_cards_does_not_contain_scouts(main_deck_cards):
    with pytest.raises(StopIteration):
        next(c for c in main_deck_cards if c.name == 'Scout')

def test_main_deck_cards_does_not_contain_explorers(main_deck_cards):
    with pytest.raises(StopIteration):
        next(c for c in main_deck_cards if c.name == 'Explorer')

@pytest.fixture
def player_deck_cards(repo):
    return repo.player_deck_cards()

def test_player_deck_cards_length(player_deck_cards):
    assert len(player_deck_cards) == 10

def test_player_deck_cards_contains_only_vipers_and_scouts(player_deck_cards):
    with pytest.raises(StopIteration):
        next(c for c in player_deck_cards if (c.name != 'Viper') and (c.name != 'Scout'))

def test_player_deck_cards_viper_count(player_deck_cards):
    vipers = [c for c in player_deck_cards if c.name == 'Viper']
    assert len(vipers) == 2

def test_player_deck_cards_scout_count(player_deck_cards):
    scouts = [c for c in player_deck_cards if c.name == 'Scout']
    assert len(scouts) == 8


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Copyright 2012 MeetMe, Inc.

    Licensed 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.meetme.plugins.jira</groupId>
    <artifactId>gerrit-plugin</artifactId>
    <version>2.3-SNAPSHOT</version>

    <organization>
        <name>MeetMe, Inc.</name>
        <url>http://www.meetme.com/</url>
    </organization>

    <name>JIRA Gerrit Plugin</name>
    <description>Integrates Atlassian JIRA with Gerrit code review.</description>
    <issueManagement>
        <system>GitHub</system>
        <url>https://github.com/MeetMe/jira-gerrit-plugin/issues</url>
    </issueManagement>
    <inceptionYear>2012</inceptionYear>

    <packaging>atlassian-plugin</packaging>

    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>manual</distribution>
            <comments>A business-friendly OSS license</comments>
        </license>
    </licenses>

    <developers>
        <developer>
            <id>jhansche</id>
            <name>Joe Hansche</name>
            <email>jhansche@meetme.com</email>
            <organization>MeetMe, Inc.</organization>
            <organizationUrl>http://www.meetme.com/</organizationUrl>
            <roles>
                <role>developer</role>
                <role>maintainer</role>
            </roles>
            <timezone>-4</timezone>
        </developer>
    </developers>

    <dependencies>
        <!-- Base Atlassian requirements -->
        <dependency>
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-api</artifactId>
            <!--<artifactId>atlassian-jira</artifactId>-->
            <version>${jira.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- Add dependency on jira-core if you want access to JIRA implementation classes as well as the sanctioned API. -->
        <!-- This is not normally recommended, but may be required eg when migrating a plugin originally developed against JIRA 4.x -->
        <!-- <dependency>
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-core</artifactId>
            <version>${jira.version}</version>
            <scope>provided</scope>
            </dependency> -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-tests</artifactId>
            <version>${jira.test.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.atlassian.jira</groupId>
            <artifactId>jira-func-tests</artifactId>
            <version>${jira.test.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.9.5</version>
            <scope>test</scope>
        </dependency>

        <!-- Project Atlassian requirements -->
        <dependency>
            <groupId>com.atlassian.sal</groupId>
            <artifactId>sal-api</artifactId>
            <version>2.0.16</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.atlassian.templaterenderer</groupId>
            <artifactId>atlassian-template-renderer-api</artifactId>
            <version>${atlas.template.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <!-- Not automatically provided in <5.0 -->
            <groupId>com.atlassian.util.concurrent</groupId>
            <artifactId>atlassian-util-concurrent</artifactId>
            <version>${atlas.concurrent.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.atlassian.plugins.rest</groupId>
            <artifactId>atlassian-rest-common</artifactId>
            <version>${jira.rest.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.4</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>jsr311-api</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- Project dependencies -->
        <dependency>
            <!-- Using this for gerrit integration -->
            <groupId>com.sonyericsson.hudson.plugins.gerrit</groupId>
            <artifactId>gerrit-events</artifactId>
            <version>1.5.2</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>com.atlassian.maven.plugins</groupId>
                <artifactId>maven-jira-plugin</artifactId>
                <version>${amps.version}</version>
                <extensions>true</extensions>
                <configuration>
                    <productVersion>${jira.version}</productVersion>
                    <productDataVersion>${jira.version}</productDataVersion>
                    <log4jProperties>src/aps/resources/log4j.properties</log4jProperties>

                    <products>
                        <product>
                            <id>jira</id>
                            <version>${jira.version}</version>
                        </product>
                    </products>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <properties>
        <jira.version>5.0</jira.version>
        <jira.test.version>5.0</jira.test.version>
        <jira.data.version>5.0</jira.data.version>
        <jira.rest.version>1.0.2</jira.rest.version>
        <atlas.template.version>1.1.1</atlas.template.version>
        <atlas.concurrent.version>2.3.0</atlas.concurrent.version>
        <atlas.sal.version>2.0.16</atlas.sal.version>
        <amps.version>3.10.3</amps.version>
    </properties>

    <profiles>
        <profile>
            <id>jira5</id>
            <properties>
                <jira.version>5.0</jira.version>
                <skip.tests>true</skip.tests>
                <skip.func.tests>true</skip.func.tests>
            </properties>
        </profile>
        <profile>
            <id>release</id>
            <properties>
                <jira.version>5.0</jira.version>
                <skip.tests>true</skip.tests>
                <skip.func.tests>true</skip.func.tests>
            </properties>
        </profile>
        <profile>
            <id>jira6</id>
            <properties>
                <jira.version>6.4.5</jira.version>
                <jira.test.version>6.2-20131016.081905</jira.test.version>
                <jira.data.version>6.2-20131016.081905</jira.data.version>
                <jira.rest.version>2.9.0-REST-252-m01</jira.rest.version>
                <atlas.template.version>2.0.0-m4</atlas.template.version>
                <atlas.concurrent.version>2.4.1</atlas.concurrent.version>
                <atlas.sal.version>2.11.0-SAL-236-m03</atlas.sal.version>
                <amps.version>5.0.13</amps.version>
                <plugin.testrunner.version>1.1.2</plugin.testrunner.version>
                <skip.tests>true</skip.tests>
                <skip.func.tests>true</skip.func.tests>
            </properties>
        </profile>
    </profiles>

    <distributionManagement>
        <repository>
            <id>atlassian-contrib</id>
            <name>Atlassian Contrib Repository</name>
            <url>dav:https://maven.atlassian.com/contrib</url>
        </repository>
        <snapshotRepository>
            <id>atlassian-contrib-snapshot</id>
            <name>Atlassian Contrib Snapshot Repository</name>
            <url>dav:https://maven.atlassian.com/contrib-snapshot</url>
        </snapshotRepository>
    </distributionManagement>

    <scm>
        <connection>scm:git:git://github.com/MeetMe/jira-gerrit-plugin.git</connection>
        <developerConnection>scm:git:ssh://git@github.com/MeetMe/jira-gerrit-plugin.git</developerConnection>
        <url>https://github.com/MeetMe/jira-gerrit-plugin</url>
    </scm>

</project>


text:
1. What is wrong with this code example?

```coffee
df <- data.frame(id = c("Jason","Paul","Mary", "Robert","Toby","Nina","Robin","James"), x = 1:10, y = rnorm(10))
```

2. Fix each of the following common data frame subsetting errors:

```coffee
mtcars[mtcars$cyl = 4, ]
# Exclude only rows 1 through 4
mtcars[-1:4, ]
# Return only rows for cylinders less than 5
mtcars[mtcars$cyl <= 5]
# Return only rows for cylinders that are 4 or 6.
mtcars[mtcars$cyl == 4 | 6, ]
```

3. Why does `mtcars[1:20]` return a error? How does it differ from the similar `mtcars[1:20, ]`?

4. Load the `ggplot2` package. There should be a dataset called `diamonds`. You can verify that by typing in `data(diamonds)`

* How big is this dataset (number of rows and columns)?
* Create a new data frame called `small_diamonds` that only contains rows 1 through 9 and 19 through 23. You can do this in one or two steps.

5. Given a linear model

```coffee
mod <- lm(mpg ~ wt, data = mtcars)
```

extract the residual degrees of freedom.

----