text:
// HTMLParser Library $Name: v1_5 $ - A java-based parser for HTML
// http://sourceforge.org/projects/htmlparser
// Copyright (C) 2004 Derrick Oswald
//
// Revision Control Information
//
// $Source: /cvsroot/htmlparser/htmlparser/src/org/htmlparser/beans/StringBean.java,v $
// $Author: derrickoswald $
// $Date: 2005/05/15 11:49:03 $
// $Revision: 1.44 $
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//

package org.htmlparser.beans;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.Serializable;
import java.net.URLConnection;

import org.htmlparser.Parser;
import org.htmlparser.Text;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.Tag;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.EncodingChangeException;
import org.htmlparser.util.Translate;
import org.htmlparser.visitors.NodeVisitor;

/**
 * Extract strings from a URL.
 *
Text within <SCRIPT></SCRIPT> tags is removed.

 *
The text within <PRE></PRE> tags is not altered.

 *
The property Strings, which is the output property is null
 * until a URL is set. So a typical usage is:

 *

 *     StringBean sb = new StringBean ();
 *     sb.setLinks (false);
 *     sb.setReplaceNonBreakingSpaces (true);
 *     sb.setCollapse (true);
 *     sb.setURL ("http://www.netbeans.org"); // the HTTP is performed here
 *     String s = sb.getStrings ();
 *

 * You can also use the StringBean as a NodeVisitor on your own parser,
 * in which case you have to refetch your page if you change one of the
 * properties because it resets the Strings property:

 *

 *     StringBean sb = new StringBean ();
 *     Parser parser = new Parser ("http://cbc.ca");
 *     parser.visitAllNodesWith (sb);
 *     String s = sb.getStrings ();
 *     sb.setLinks (true);
 *     parser.reset ();
 *     parser.visitAllNodesWith (sb);
 *     String sl = sb.getStrings ();
 *

 * According to Nick Burch, who contributed the patch, this is handy if you
 * don't want StringBean to wander off and get the content itself, either
 * because you already have it, it's not on a website etc.
 */
public class StringBean extends NodeVisitor implements Serializable
{
    /**
     * Property name in event where the URL contents changes.
     */
    public static final String PROP_STRINGS_PROPERTY = "strings";

    /**
     * Property name in event where the 'embed links' state changes.
     */
    public static final String PROP_LINKS_PROPERTY = "links";

    /**
     * Property name in event where the URL changes.
     */
    public static final String PROP_URL_PROPERTY = "URL";

    /**
     * Property name in event where the 'replace non-breaking spaces'
     * state changes.
     */
    public static final String PROP_REPLACE_SPACE_PROPERTY =
        "replaceNonBreakingSpaces";

    /**
     * Property name in event where the 'collapse whitespace' state changes.
     */
    public static final String PROP_COLLAPSE_PROPERTY = "collapse";

    /**
     * Property name in event where the connection changes.
     */
    public static final String PROP_CONNECTION_PROPERTY = "connection";

    /**
     * A newline.
     */
    private static final String NEWLINE = System.getProperty ("line.separator");

    /**
     * The length of the NEWLINE.
     */
    private static final int NEWLINE_SIZE = NEWLINE.length ();

    /**
     * Bound property support.
     */
    protected PropertyChangeSupport mPropertySupport;

    /**
     * The parser used to extract strings.
     */
    protected Parser mParser;

    /**
     * The strings extracted from the URL.
     */
    protected String mStrings;

    /**
     * If true the link URLs are embedded in the text output.
     */
    protected boolean mLinks;

    /**
     * If true regular space characters are substituted for
     * non-breaking spaces in the text output.
     */
    protected boolean mReplaceSpace;

    /**
     * If true sequences of whitespace characters are replaced
     * with a single space character.
     */
    protected boolean mCollapse;

    /**
     * The buffer text is stored in while traversing the HTML.
     */
    protected StringBuffer mBuffer;

    /**
     * Set true when traversing a SCRIPT tag.
     */
    protected boolean mIsScript;

    /**
     * Set true when traversing a PRE tag.
     */
    protected boolean mIsPre;

    /**
     * Set true when traversing a STYLE tag.
     */
    protected boolean mIsStyle;

   /**
     * Create a StringBean object.
     * Default property values are set to 'do the right thing':
     *
Links is set false so text appears like a
     * browser would display it, albeit without the colour or underline clues
     * normally associated with a link.

     *
ReplaceNonBreakingSpaces is set true, so
     * that printing the text works, but the extra information regarding these
     * formatting marks is available if you set it false.

     *
Collapse is set true, so text appears
     * compact like a browser would display it.

     */
    public StringBean ()
    {
        super (true, true);
        mPropertySupport = new PropertyChangeSupport (this);
        mParser = new Parser ();
        mStrings = null;
        mLinks = false;
        mReplaceSpace = true;
        mCollapse = true;
        mBuffer = new StringBuffer (4096);
        mIsScript = false;
        mIsPre = false;
        mIsStyle = false;
    }

    //
    // internals
    //

    /**
     * Appends a newline to the buffer if there isn't one there already.
     * Except if the buffer is empty.
     */
    protected void carriageReturn ()
    {
        int length;

        length = mBuffer.length ();
        if ((0 != length) // don't append newlines to the beginning of a buffer
            && ((NEWLINE_SIZE <= length) // not enough chars to hold a NEWLINE
            && (!mBuffer.substring (
                length - NEWLINE_SIZE, length).equals (NEWLINE))))
            mBuffer.append (NEWLINE);
    }

    /**
     * Add the given text collapsing whitespace.
     * Use a little finite state machine:
     *

     * state 0: whitepace was last emitted character
     * state 1: in whitespace
     * state 2: in word
     * A whitespace character moves us to state 1 and any other character
     * moves us to state 2, except that state 0 stays in state 0 until
     * a non-whitespace and going from whitespace to word we emit a space
     * before the character:
     *    input:     whitespace   other-character
     * state\next
     *    0               0             2
     *    1               1        space then 2
     *    2               1             2
     *

     * @param buffer The buffer to append to.
     * @param string The string to append.
     */
    protected void collapse (StringBuffer buffer, String string)
    {
        int chars;
        int length;
        int state;
        char character;

        chars = string.length ();
        if (0 != chars)
        {
            length = buffer.length ();
            state = ((0 == length)
                || (buffer.charAt (length - 1) == ' ')
                || ((NEWLINE_SIZE <= length)
                    && buffer.substring (
                        length - NEWLINE_SIZE, length).equals (NEWLINE)))
                ? 0 : 1;
            for (int i = 0; i < chars; i++)
            {
                character = string.charAt (i);
                switch (character)
                {
                    // see HTML specification section 9.1 White space
                    // http://www.w3.org/TR/html4/struct/text.html#h-9.1
                    case '\u0020':
                    case '\u0009':
                    case '\u000C':
                    case '\u200B':
                    case '\r':
                    case '\n':
                        if (0 != state)
                            state = 1;
                        break;
                    default:
                        if (1 == state)
                            buffer.append (' ');
                        state = 2;
                        buffer.append (character);
                }
            }
        }
    }

    /**
     * Extract the text from a page.
     * @return The textual contents of the page.
     * @exception ParserException If a parse error occurs.
     */
    protected String extractStrings ()
        throws
            ParserException
    {
        String ret;

        mParser.visitAllNodesWith (this);
        ret = mBuffer.toString ();
        mBuffer = new StringBuffer(4096);

        return (ret);
    }

    /**
     * Assign the Strings property, firing the property change.
     * @param strings The new value of the Strings property.
     */
    protected void updateStrings (String strings)
    {
        String oldValue;

        if ((null == mStrings) || !mStrings.equals (strings))
        {
            oldValue = mStrings;
            mStrings = strings;
            mPropertySupport.firePropertyChange (
                PROP_STRINGS_PROPERTY, oldValue, strings);
        }
    }

    /**
     * Fetch the URL contents.
     * Only do work if there is a valid parser with it's URL set.
     */
    protected void setStrings ()
    {
        if (null != getURL ())
            try
            {
                try
                {
                    mParser.visitAllNodesWith (this);
                    updateStrings (mBuffer.toString ());
                }
                finally
                {
                    mBuffer = new StringBuffer (4096);
                }
            }
            catch (EncodingChangeException ece)
            {
                mIsPre = false;
                mIsScript = false;
                mIsStyle = false;
                try
                {   // try again with the encoding now in force
                    mParser.reset ();
                    mBuffer = new StringBuffer (4096);
                    mParser.visitAllNodesWith (this);
                    updateStrings (mBuffer.toString ());
                }
                catch (ParserException pe)
                {
                    updateStrings (pe.toString ());
                }
                finally
                {
                    mBuffer = new StringBuffer (4096);
                }
             }
            catch (ParserException pe)
            {
                updateStrings (pe.toString ());
            }
        else
        {
            // reset in case this StringBean is used as a visitor
            // on another parser, not it's own
            mStrings = null;
            mBuffer = new StringBuffer (4096);
        }
    }

    /**
     * Refetch the URL contents.
     * Only need to worry if there is already a valid parser and it's
     * been spent fetching the string contents.
     */
    private void resetStrings ()
    {
        if (null != mStrings)
            try
            {
                mParser.setURL (getURL ());
                setStrings ();
            }
            catch (ParserException pe)
            {
                updateStrings (pe.toString ());
            }
    }

    //
    // Property change support.
    //

    /**
     * Add a PropertyChangeListener to the listener list.
     * The listener is registered for all properties.
     * @param listener The PropertyChangeListener to be added.
     */
    public void addPropertyChangeListener (PropertyChangeListener listener)
    {
        mPropertySupport.addPropertyChangeListener (listener);
    }

    /**
     * Remove a PropertyChangeListener from the listener list.
     * This removes a registered PropertyChangeListener.
     * @param listener The PropertyChangeListener to be removed.
     */
    public void removePropertyChangeListener (PropertyChangeListener listener)
    {
        mPropertySupport.removePropertyChangeListener (listener);
    }

    //
    // Properties
    //

    /**
     * Return the textual contents of the URL.
     * This is the primary output of the bean.
     * @return The user visible (what would be seen in a browser) text.
     */
    public String getStrings ()
    {
        if (null == mStrings)
        if (0 == mBuffer.length ())
            setStrings ();
        else
            updateStrings (mBuffer.toString ());

        return (mStrings);
    }

    /**
     * Get the current 'include links' state.
     * @return true if link text is included in the text extracted
     * from the URL, false otherwise.
     */
    public boolean getLinks ()
    {
        return (mLinks);
    }

    /**
     * Set the 'include links' state.
     * If the setting is changed after the URL has been set, the text from the
     * URL will be reacquired, which is possibly expensive.
     * @param links Use true if link text is to be included in the
     * text extracted from the URL, false otherwise.
     */
    public void setLinks (boolean links)
    {
        boolean oldValue = mLinks;
        if (oldValue != links)
        {
            mLinks = links;
            mPropertySupport.firePropertyChange (
                PROP_LINKS_PROPERTY, oldValue, links);
            resetStrings ();
        }
    }

    /**
     * Get the current URL.
     * @return The URL from which text has been extracted, or null
     * if this property has not been set yet.
     */
    public String getURL ()
    {
         return ((null != mParser) ? mParser.getURL () : null);
    }

    /**
     * Set the URL to extract strings from.
     * The text from the URL will be fetched, which may be expensive, so this
     * property should be set last.
     * @param url The URL that text should be fetched from.
     */
    public void setURL (String url)
    {
        String old;
        URLConnection conn;

        old = getURL ();
        conn = getConnection ();
        if (((null == old) && (null != url)) || ((null != old)
            && !old.equals (url)))
        {
            try
            {
                if (null == mParser)
                    mParser = new Parser (url);
                else
                    mParser.setURL (url);
                mPropertySupport.firePropertyChange (
                    PROP_URL_PROPERTY, old, getURL ());
                mPropertySupport.firePropertyChange (
                    PROP_CONNECTION_PROPERTY, conn, mParser.getConnection ());
                setStrings ();
            }
            catch (ParserException pe)
            {
                updateStrings (pe.toString ());
            }
        }
    }

    /**
     * Get the current 'replace non breaking spaces' state.
     * @return true if non-breaking spaces (character '\u00a0',
     * numeric character reference &#160; or character entity
     * reference &nbsp;) are to be replaced with normal
     * spaces (character '\u0020').
     */
    public boolean getReplaceNonBreakingSpaces ()
    {
        return (mReplaceSpace);
    }

    /**
     * Set the 'replace non breaking spaces' state.
     * If the setting is changed after the URL has been set, the text from the
     * URL will be reacquired, which is possibly expensive.
     * @param replace true if non-breaking spaces
     * (character '\u00a0', numeric character reference &#160;
     * or character entity reference &nbsp;) are to be replaced with normal
     * spaces (character '\u0020').
     */
    public void setReplaceNonBreakingSpaces (boolean replace)
    {
        boolean oldValue = mReplaceSpace;
        if (oldValue != replace)
        {
            mReplaceSpace = replace;
            mPropertySupport.firePropertyChange (PROP_REPLACE_SPACE_PROPERTY,
                oldValue, replace);
            resetStrings ();
        }
    }

    /**
     * Get the current 'collapse whitespace' state.
     * If set to true this emulates the operation of browsers
     * in interpretting text where <quote>user agents should collapse input
     * white space sequences when producing output inter-word space</quote>.
     * See HTML specification section 9.1 White space
     *
     * http://www.w3.org/TR/html4/struct/text.html#h-9.1.
     * @return true if sequences of whitespace (space '\u0020',
     * tab '\u0009', form feed '\u000C', zero-width space '\u200B',
     * carriage-return '\r' and NEWLINE '\n') are to be replaced with a single
     * space.
     */
    public boolean getCollapse ()
    {
        return (mCollapse);
    }

    /**
     * Set the current 'collapse whitespace' state.
     * If the setting is changed after the URL has been set, the text from the
     * URL will be reacquired, which is possibly expensive.
     * @param collapse If true, sequences of whitespace
     * will be reduced to a single space.
     */
    public void setCollapse (boolean collapse)
    {
        boolean oldValue = mCollapse;
        if (oldValue != collapse)
        {
            mCollapse = collapse;
            mPropertySupport.firePropertyChange (
                    PROP_COLLAPSE_PROPERTY, oldValue, collapse);
            resetStrings ();
        }
    }

    /**
     * Get the current connection.
     * @return The connection that the parser has or null if it
     * hasn't been set or the parser hasn't been constructed yet.
     */
    public URLConnection getConnection ()
    {
        return ((null != mParser) ? mParser.getConnection () : null);
    }

    /**
     * Set the parser's connection.
     * The text from the URL will be fetched, which may be expensive, so this
     * property should be set last.
     * @param connection New value of property Connection.
     */
    public void setConnection (URLConnection connection)
    {
        String url;
        URLConnection conn;

        url = getURL ();
        conn = getConnection ();
        if (((null == conn) && (null != connection))
            || ((null != conn) && !conn.equals (connection)))
        {
            try
            {
                if (null == mParser)
                    mParser = new Parser (connection);
                else
                    mParser.setConnection (connection);
                mPropertySupport.firePropertyChange (
                    PROP_URL_PROPERTY, url, getURL ());
                mPropertySupport.firePropertyChange (
                    PROP_CONNECTION_PROPERTY, conn, mParser.getConnection ());
                setStrings ();
            }
            catch (ParserException pe)
            {
                updateStrings (pe.toString ());
            }
        }
    }

    //
    // NodeVisitor overrides
    //

    /**
     * Appends the text to the output.
     * @param string The text node.
     */
    public void visitStringNode (Text string)
    {
        if (!mIsScript && !mIsStyle)
        {
            String text = string.getText ();
            if (!mIsPre)
            {
                text = Translate.decode (text);
                if (getReplaceNonBreakingSpaces ())
                    text = text.replace ('\u00a0', ' ');
                if (getCollapse ())
                    collapse (mBuffer, text);
                else
                    mBuffer.append (text);
            }
            else
                mBuffer.append (text);
        }
    }

    /**
     * Appends a NEWLINE to the output if the tag breaks flow, and
     * possibly sets the state of the PRE and SCRIPT flags.
     * @param tag The tag to examine.
     */
    public void visitTag (Tag tag)
    {
        String name;

        if (tag instanceof LinkTag)
            if (getLinks ())
            { // appends the link as text between angle brackets to the output.
                mBuffer.append ("<");
                mBuffer.append (((LinkTag)tag).getLink ());
                mBuffer.append (">");
            }
        name = tag.getTagName ();
        if (name.equalsIgnoreCase ("PRE"))
            mIsPre = true;
        else if (name.equalsIgnoreCase ("SCRIPT"))
            mIsScript = true;
        else if (name.equalsIgnoreCase ("STYLE"))
            mIsStyle = true;
        if (tag.breaksFlow ())
            carriageReturn ();
    }

    /**
     * Resets the state of the PRE and SCRIPT flags.
     * @param tag The end tag to process.
     */
    public void visitEndTag (Tag tag)
    {
        String name;

        name = tag.getTagName ();
        if (name.equalsIgnoreCase ("PRE"))
            mIsPre = false;
        else if (name.equalsIgnoreCase ("SCRIPT"))
            mIsScript = false;
        else if (name.equalsIgnoreCase ("STYLE"))
            mIsStyle = false;
    }

    /**
     * Unit test.
     * @param args Pass arg[0] as the URL to process.
     */
    public static void main (String[] args)
    {
        if (0 >= args.length)
            System.out.println ("Usage: java -classpath htmlparser.jar"
                + " org.htmlparser.beans.StringBean <http://whatever_url>");
        else
        {
            StringBean sb = new StringBean ();
            sb.setLinks (false);
            sb.setReplaceNonBreakingSpaces (true);
            sb.setCollapse (true);
            sb.setURL (args[0]);
            System.out.println (sb.getStrings ());
        }
    }
}


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

<title>org.mitre.taxii.client.xml10 (java-taxii API)</title>
<meta name="date" content="2014-09-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.mitre.taxii.client.xml10

TAXII 1.0 version specific HTTP client classes.

See: Description

Class Summary

Class
Description

ResponseErrorHandler

This class handles generating StatusMessages for TAXII 1.0 when
 an error occurs while handling the response from the TAXII server.

Package org.mitre.taxii.client.xml10 Description

TAXII 1.0 version specific HTTP client classes.

See Also:

HttpClient

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

redpajama_set_name: RedPajamaGithub


text:
/**
 * General interface for nodes in the abstract syntax tree. Contains
 * only the method toString which is already inherited from Object,
 * so the interface doesn't add any functionality. It only provides
 * a common super type for all elements in the AST.
 */
interface AST {
  public String toString();   // already inherited from Object
}


text:
require 'optparse'

module Veewee
  module Command
    module Vagrant
      class Screenshot < ::Vagrant::Command::Base
        def execute
          options = {}

          opts = OptionParser.new do |opts|
            opts.banner = "Grab a screenshot of a running basebox"
            opts.separator ""
            opts.separator "Usage: vagrant basebox screenshot <boxname> <pngfile>"

            opts.on("-d", "--debug", "enable debugging") do |d|
              options['debug'] = d
            end

            opts.on("-f", "--force", "force overwrite") do |f|
              options['force'] = f
            end

          end

          # Parse the options
          argv = parse_options(opts)
          return if !argv
          raise ::Vagrant::Errors::CLIInvalidUsage, :help => opts.help.chomp if argv.length < 2

          begin
            venv=Veewee::Environment.new(options)
            venv.ui=@env.ui
            box_name=argv[0]
            pngfilename=argv[1]
            venv.providers["virtualbox"].get_box(box_name).screenshot(pngfilename)
          rescue Veewee::Error => ex
            venv.ui.error(ex,:prefix => false)
            exit -1
          end

        end
      end
    end
  end
end


text:
require File.expand_path('../any_value', __FILE__)
require File.expand_path('../string_value', __FILE__)
require File.expand_path('../text_value', __FILE__)
require File.expand_path('../integer_value', __FILE__)
require File.expand_path('../float_value', __FILE__)
require File.expand_path('../decimal_value', __FILE__)
require File.expand_path('../datetime_value', __FILE__)
require File.expand_path('../timestamp_value', __FILE__)
require File.expand_path('../time_value', __FILE__)
require File.expand_path('../date_value', __FILE__)
require File.expand_path('../binary_value', __FILE__)
require File.expand_path('../boolean_value', __FILE__)

require File.expand_path('../column', __FILE__)
require File.expand_path('../extend_at', __FILE__)


text:
<?php namespace Snapbuyer;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

/**
 * Snapbuyer\User
 *
 * @property integer $id
 * @property string $name
 * @property string $email
 * @property string $password
 * @property string $remember_token
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @method static \Illuminate\Database\Query\Builder|\Snapbuyer\User whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\Snapbuyer\User whereName($value)
 * @method static \Illuminate\Database\Query\Builder|\Snapbuyer\User whereEmail($value)
 * @method static \Illuminate\Database\Query\Builder|\Snapbuyer\User wherePassword($value)
 * @method static \Illuminate\Database\Query\Builder|\Snapbuyer\User whereRememberToken($value)
 * @method static \Illuminate\Database\Query\Builder|\Snapbuyer\User whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\Snapbuyer\User whereUpdatedAt($value)
 */
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

	use Authenticatable, CanResetPassword;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

	/**
	 * The attributes that are mass assignable.
	 *
	 * @var array
	 */
	protected $fillable = ['name', 'email', 'password'];

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = ['password', 'remember_token'];

}


text:
package com.google.gerrit.server.project;

import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.gerrit.extensions.restapi.AuthException;
import com.google.gerrit.extensions.restapi.BadRequestException;
import com.google.gerrit.extensions.restapi.IdString;
import com.google.gerrit.extensions.restapi.ResourceConflictException;
import com.google.gerrit.extensions.restapi.ResourceNotFoundException;
import com.google.gerrit.extensions.restapi.Response;
import com.google.gerrit.extensions.restapi.RestModifyView;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.IdentifiedUser;
import com.google.gerrit.server.git.MetaDataUpdate;
import com.google.gerrit.server.git.ProjectConfig;
import com.google.gerrit.server.project.DashboardsCollection.DashboardInfo;
import com.google.gerrit.server.project.SetDashboard.Input;
import com.google.inject.Inject;
import com.google.inject.Provider;

import org.eclipse.jgit.errors.ConfigInvalidException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.kohsuke.args4j.Option;

class SetDefaultDashboard implements RestModifyView<DashboardResource, Input> {
  private final ProjectCache cache;
  private final MetaDataUpdate.Server updateFactory;
  private final DashboardsCollection dashboards;
  private final Provider<GetDashboard> get;

  @Option(name = "--inherited", usage = "set dashboard inherited by children")
  private boolean inherited;

  @Inject
  SetDefaultDashboard(ProjectCache cache,
      MetaDataUpdate.Server updateFactory,
      DashboardsCollection dashboards,
      Provider<GetDashboard> get) {
    this.cache = cache;
    this.updateFactory = updateFactory;
    this.dashboards = dashboards;
    this.get = get;
  }

  @Override
  public Object apply(DashboardResource resource, Input input)
      throws AuthException, BadRequestException, ResourceConflictException,
      Exception {
    if (input == null) {
      input = new Input(); // Delete would set input to null.
    }
    input.id = Strings.emptyToNull(input.id);

    ProjectControl ctl = resource.getControl();
    IdentifiedUser user = (IdentifiedUser) ctl.getCurrentUser();
    if (!ctl.isOwner()) {
      throw new AuthException("not project owner");
    }

    DashboardResource target = null;
    if (input.id != null) {
      try {
        target = dashboards.parse(
            new ProjectResource(ctl),
            IdString.fromUrl(input.id));
      } catch (ResourceNotFoundException e) {
        throw new BadRequestException("dashboard " + input.id + " not found");
      }
    }

    try {
      MetaDataUpdate md = updateFactory.create(ctl.getProject().getNameKey());
      try {
        ProjectConfig config = ProjectConfig.read(md);
        Project project = config.getProject();
        if (inherited) {
          project.setDefaultDashboard(input.id);
        } else {
          project.setLocalDefaultDashboard(input.id);
        }

        String msg = Objects.firstNonNull(
          Strings.emptyToNull(input.commitMessage),
          input.id == null
            ? "Removed default dashboard.\n"
            : String.format("Changed default dashboard to %s.\n", input.id));
        if (!msg.endsWith("\n")) {
          msg += "\n";
        }
        md.setAuthor(user);
        md.setMessage(msg);
        config.commit(md);
        cache.evict(ctl.getProject());

        if (target != null) {
          DashboardInfo info = get.get().apply(target);
          info.isDefault = true;
          return info;
        }
        return Response.none();
      } finally {
        md.close();
      }
    } catch (RepositoryNotFoundException notFound) {
      throw new ResourceNotFoundException(ctl.getProject().getName());
    } catch (ConfigInvalidException e) {
      throw new ResourceConflictException(String.format(
          "invalid project.config: %s", e.getMessage()));
    }
  }

  static class CreateDefault implements
      RestModifyView<ProjectResource, SetDashboard.Input> {
    private final Provider<SetDefaultDashboard> setDefault;

    @Option(name = "--inherited", usage = "set dashboard inherited by children")
    private boolean inherited;

    @Inject
    CreateDefault(Provider<SetDefaultDashboard> setDefault) {
      this.setDefault = setDefault;
    }

    @Override
    public Object apply(ProjectResource resource, Input input)
        throws AuthException, BadRequestException, ResourceConflictException,
        Exception {
      SetDefaultDashboard set = setDefault.get();
      set.inherited = inherited;
      return Response.created(set.apply(
          DashboardResource.projectDefault(resource.getControl()),
          input));
    }
  }
}


text:
package org.apache.sqoop.submission.counter;

import org.apache.sqoop.classification.InterfaceAudience;
import org.apache.sqoop.classification.InterfaceStability;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 *
 */
@InterfaceAudience.Private
@InterfaceStability.Unstable
public class Counters implements Iterable<CounterGroup> {
  Map<String, CounterGroup> groups;

  public Counters() {
    this.groups = new HashMap<String, CounterGroup>();
  }

  public Counters addCounterGroup(CounterGroup group) {
    groups.put(group.getName(), group);
    return this;
  }

  public CounterGroup getCounterGroup(String name) {
    return groups.get(name);
  }

  @Override
  public Iterator<CounterGroup> iterator() {
    return groups.values().iterator();
  }

  public boolean isEmpty() {
    return groups.isEmpty();
  }
}


text:
using System;

namespace System.Windows.Input
{
    internal static class AngleUtil
    {
        /// <summary>
        ///     Method to convert from degrees to radians
        /// </summary>
        public static double DegreesToRadians(double degrees)
        {
            return degrees * Math.PI / 180.0;
        }

        /// <summary>
        ///     Method to convert from radians to degrees
        /// </summary>
        public static double RadiansToDegrees(double radians)
        {
            return radians * 180.0 / Math.PI;
        }
    }
}


text:
module Azure::Migrate::Mgmt::V2018_02_02
  module Models
    #
    # Defines values for ProvisioningState
    #
    module ProvisioningState
      Accepted = "Accepted"
      Creating = "Creating"
      Deleting = "Deleting"
      Failed = "Failed"
      Moving = "Moving"
      Succeeded = "Succeeded"
    end
  end
end


text:
import unittest

from pycard.param import params
from pycard.prop import from_string, props

class CategoryPropTestCase(unittest.TestCase):

    def test_1(self):
        Prop = props["CATEGORIES"]
        string = "CATEGORIES:Work,La Phase,Dynamo\r\n"
        obj = Prop(["Work", "La Phase", "Dynamo"])
        self.assertEqual(obj, from_string(string))
        self.assertEqual(obj.format(), string)

    def test_3(self):
        Prop = props["CATEGORIES"]
        string = "CATEGORIES:Work,A\, B\, and C\r\n"
        obj = Prop(["Work", "A, B, and C"])
        self.assertEqual(obj, from_string(string))
        self.assertEqual(obj.format(), string)

class DeliveryAddressPropTestCase(unittest.TestCase):

    def test_1(self):
        Prop = props["ADR"]
        string = "ADR;INTL;WORK:Albert;S S.A.R.L.;213 rue Martz;Mince;Papis;99999;Zut\r\n"
        obj = Prop( ["Albert","S S.A.R.L.","213 rue Martz", "Mince", "Papis", "99999", "Zut"],
                    [params["INTL"], params["WORK"]])
        self.assertEqual(obj, from_string(string))
        self.assertEqual(obj.format(), string)

class NameTestCase(unittest.TestCase):

    def test_1(self):
        Prop = props["N"]
        string = "N:;Albert;;Sir.;Jr.\r\n"
        obj = Prop( ["", "Albert", "", "Sir.", "Jr."])
        self.assertEqual(obj, from_string(string))
        self.assertEqual(obj.format(), string)


text:
require 'spec_helper_system'

describe 'mysql::server::backup class' do
  context 'should work with no errors' do
    pp = <<-EOS
      class { 'mysql::server': override_options => { 'root_password' => 'password' } }
      mysql::db { 'backup1':
        user     => 'backup',
        password => 'secret',
      }

      class { 'mysql::server::backup':
        backupuser     => 'myuser',
        backuppassword => 'mypassword',
        backupdir      => '/tmp/backups',
        backupcompress => true,
      }
    EOS

    context puppet_apply(pp) do
      its(:stderr) { should be_empty }
      its(:exit_code) { should_not == 1 }
      its(:refresh) { should be_nil }
      its(:stderr) { should be_empty }
      its(:exit_code) { should be_zero }
    end
  end

  describe 'mysqlbackup.sh' do
    context 'should run mysqlbackup.sh with no errors' do
      context shell("/usr/local/sbin/mysqlbackup.sh") do
        its(:exit_code) { should be_zero }
        its(:stderr) { should be_empty }
      end
    end

    context 'should dump all databases to single file' do
      describe command('ls /tmp/backups/ | grep -c "mysql_backup_[0-9][0-9]*-[0-9][0-9]*.sql.bz2"') do
        it { should return_stdout /1/ }
        it { should return_exit_status 0 }
      end
    end

    context 'should create one file per database per run' do
      context shell("/usr/local/sbin/mysqlbackup.sh") do
        its(:exit_code) { should be_zero }
        its(:stderr) { should be_empty }
      end

      describe command('ls /tmp/backups/ | grep -c "mysql_backup_backup1_[0-9][0-9]*-[0-9][0-9]*.sql.bz2"') do
        it { should return_stdout /2/ }
        it { should return_exit_status 0 }
      end
    end
  end
end


text:
package com.navercorp.pinpoint.profiler.util;

import java.lang.reflect.Method;

/**
 * @author emeroad
 */
public class ExcludeBindVariableFilter implements BindVariableFilter {

    private final String[] excludes;

    public ExcludeBindVariableFilter(String[] excludes) {
        if (excludes == null) {
            throw new NullPointerException("excludes must not be null");
        }
        this.excludes = excludes;
    }

    @Override
    public boolean filter(Method method) {
        if (method == null) {
            throw new NullPointerException("method must not be null");
        }
        for (String exclude : excludes) {
            if (method.getName().equals(exclude)) {
                return false;
            }
        }
        return true;
    }
}


text:
package com.amazonaws.services.opsworks.model;

import java.io.Serializable;

/**
 *

 * Contains the response to a DescribeCommands request.
 *

 */
public class DescribeCommandsResult implements Serializable, Cloneable {

    /**
     *

     * An array of Command objects that describe each of the
     * specified commands.
     *

     */
    private com.amazonaws.internal.SdkInternalList<Command> commands;

    /**
     *

     * An array of Command objects that describe each of the
     * specified commands.
     *

     *
     * @return An array of Command objects that describe each of
     *         the specified commands.
     */
    public java.util.List<Command> getCommands() {
        if (commands == null) {
            commands = new com.amazonaws.internal.SdkInternalList<Command>();
        }
        return commands;
    }

    /**
     *

     * An array of Command objects that describe each of the
     * specified commands.
     *

     *
     * @param commands
     *        An array of Command objects that describe each of the
     *        specified commands.
     */
    public void setCommands(java.util.Collection<Command> commands) {
        if (commands == null) {
            this.commands = null;
            return;
        }

        this.commands = new com.amazonaws.internal.SdkInternalList<Command>(
                commands);
    }

    /**
     *

     * An array of Command objects that describe each of the
     * specified commands.
     *

     *

     * NOTE: This method appends the values to the existing list (if
     * any). Use {@link #setCommands(java.util.Collection)} or
     * {@link #withCommands(java.util.Collection)} if you want to override the
     * existing values.
     *

     *
     * @param commands
     *        An array of Command objects that describe each of the
     *        specified commands.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DescribeCommandsResult withCommands(Command... commands) {
        if (this.commands == null) {
            setCommands(new com.amazonaws.internal.SdkInternalList<Command>(
                    commands.length));
        }
        for (Command ele : commands) {
            this.commands.add(ele);
        }
        return this;
    }

    /**
     *

     * An array of Command objects that describe each of the
     * specified commands.
     *

     *
     * @param commands
     *        An array of Command objects that describe each of the
     *        specified commands.
     * @return Returns a reference to this object so that method calls can be
     *         chained together.
     */
    public DescribeCommandsResult withCommands(
            java.util.Collection<Command> commands) {
        setCommands(commands);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getCommands() != null)
            sb.append("Commands: " + getCommands());
        sb.append("}");
        return sb.toString();
    }

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

        if (obj instanceof DescribeCommandsResult == false)
            return false;
        DescribeCommandsResult other = (DescribeCommandsResult) obj;
        if (other.getCommands() == null ^ this.getCommands() == null)
            return false;
        if (other.getCommands() != null
                && other.getCommands().equals(this.getCommands()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode
                + ((getCommands() == null) ? 0 : getCommands().hashCode());
        return hashCode;
    }

    @Override
    public DescribeCommandsResult clone() {
        try {
            return (DescribeCommandsResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException(
                    "Got a CloneNotSupportedException from Object.clone() "
                            + "even though we're Cloneable!", e);
        }
    }
}


text:
package lowlevel;// lowlevel/SerialNumberTest.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

public class SerialNumberTest {
  public static void main(String[] args) {
    SerialNumberChecker.test(new SerialNumbers());
  }
}
/* Output:
Duplicate: 148044
*/


text:
package org.eclipse.ceylon.javax.annotation.processing;

import org.eclipse.ceylon.javax.annotation.*;
import org.eclipse.ceylon.javax.annotation.processing.ProcessingEnvironment;
import org.eclipse.ceylon.javax.annotation.processing.RoundEnvironment;
import org.eclipse.ceylon.javax.lang.model.element.*;
import org.eclipse.ceylon.javax.tools.Diagnostic;

/**
 * A {@code Messager} provides the way for an annotation processor to
 * report error messages, warnings, and other notices.  Elements,
 * annotations, and annotation values can be passed to provide a
 * location hint for the message.  However, such location hints may be
 * unavailable or only approximate.
 *
 *
Printing a message with an {@linkplain
 * org.eclipse.ceylon.javax.tools.Diagnostic.Kind#ERROR error kind} will {@linkplain
 * RoundEnvironment#errorRaised raise an error}.
 *
 *
Note that the messages "printed" by methods in this
 * interface may or may not appear as textual output to a location
 * like {@link System#out} or {@link System#err}.  Implementations may
 * choose to present this information in a different fashion, such as
 * messages in a window.
 *
 * @author Joseph D. Darcy
 * @author Scott Seligman
 * @author Peter von der Ahé
 * @see ProcessingEnvironment#getLocale
 * @since 1.6
 */
public interface Messager {
    /**
     * Prints a message of the specified kind.
     *
     * @param kind the kind of message
     * @param msg  the message, or an empty string if none
     */
    void printMessage(Diagnostic.Kind kind, CharSequence msg);

    /**
     * Prints a message of the specified kind at the location of the
     * element.
     *
     * @param kind the kind of message
     * @param msg  the message, or an empty string if none
     * @param e    the element to use as a position hint
     */
    void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e);

    /**
     * Prints a message of the specified kind at the location of the
     * annotation mirror of the annotated element.
     *
     * @param kind the kind of message
     * @param msg  the message, or an empty string if none
     * @param e    the annotated element
     * @param a    the annotation to use as a position hint
     */
    void printMessage(Diagnostic.Kind kind, CharSequence msg, Element e, AnnotationMirror a);

    /**
     * Prints a message of the specified kind at the location of the
     * annotation value inside the annotation mirror of the annotated
     * element.
     *
     * @param kind the kind of message
     * @param msg  the message, or an empty string if none
     * @param e    the annotated element
     * @param a    the annotation containing the annotation value
     * @param v    the annotation value to use as a position hint
     */
    void printMessage(Diagnostic.Kind kind,
                      CharSequence msg,
                      Element e,
                      AnnotationMirror a,
                      AnnotationValue v);
}


text:
package com.microsoft.azure.management.compute.v2018_09_30;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The snapshots sku name. Can be Standard_LRS, Premium_LRS, or Standard_ZRS.
 */
public class SnapshotSku {
    /**
     * The sku name. Possible values include: 'Standard_LRS', 'Premium_LRS',
     * 'Standard_ZRS'.
     */
    @JsonProperty(value = "name")
    private SnapshotStorageAccountTypes name;

    /**
     * The sku tier.
     */
    @JsonProperty(value = "tier", access = JsonProperty.Access.WRITE_ONLY)
    private String tier;

    /**
     * Get the sku name. Possible values include: 'Standard_LRS', 'Premium_LRS', 'Standard_ZRS'.
     *
     * @return the name value
     */
    public SnapshotStorageAccountTypes name() {
        return this.name;
    }

    /**
     * Set the sku name. Possible values include: 'Standard_LRS', 'Premium_LRS', 'Standard_ZRS'.
     *
     * @param name the name value to set
     * @return the SnapshotSku object itself.
     */
    public SnapshotSku withName(SnapshotStorageAccountTypes name) {
        this.name = name;
        return this;
    }

    /**
     * Get the sku tier.
     *
     * @return the tier value
     */
    public String tier() {
        return this.tier;
    }

}


text:
/** @file
 * @brief First file
 */

/* This file needs to be kept the same as
   compound_includes_undocumented_files/First.h except for the above @file
   block. */

/**
@brief This namespace is contained in a single file

So it has only the global include and no per-entry includes, thus also no
detailed sections because there's only brief. (Unless the includes are disabled
globally or the file is not documented.)
*/
namespace Contained {

/** @brief An enum */
enum Enum {};

/** @brief A typedef */
typedef int Int;

/** @brief A variable */
constexpr const int Var = 3;

/** @brief A function */
void foo();

/** @{ @name A group */

/** @brief Flag in a group */
enum Flag {};

/** @brief Alias in a group */
using Main = void;

/** @brief Function in a group */
void bar();

/** @brief Variable in a group */
constexpr void* variable = nullptr;

/* Since 1.8.17, the original short-hand group closing doesn't work anymore.
   FFS. */
/**
 * @}
 */

}

/**
@brief This namespace is spread over two files

So it has no global include but per-entry includes, properly expanding the
brief-only docs into detailed ones. (Unless the includes are disabled globally
or the files are not documented.)
*/
namespace Spread {

/** @brief An enum */
enum Enum {};

/** @brief A typedef */
typedef int Int;

/** @brief A variable */
constexpr const int Var = 3;

/** @{ @name A group */

/** @brief Alias in a group */
using Main = void;

/** @brief Function in a group */
void bar();

/** @brief Variable in a group */
constexpr void* variable = nullptr;

/* Since 1.8.17, the original short-hand group closing doesn't work anymore.
   FFS. */
/**
 * @}
 */

}

/**
@brief A class

Global include information for this one. (Unless the includes are disabled
globally or the file is not documented.)
*/
class Class {
    public:
        /** @brief No include information for this one (and thus no details) */
        void foo();
};

/** @defgroup group A group
@brief Brief description. If this is not present, the detailed description gets interpreted as brief in 1.8.18. FFS.

All entries inside should have include information. (Unless the includes are disabled globally or the file is not documented.)
@{ */

/** @brief An enum */
enum Enum {};

/** @brief A typedef */
typedef int Int;

/** @brief A variable */
constexpr const int Var = 3;

/** @brief A function */
void foo();

/** @brief A define */
#define A_DEFINE

/* Since 1.8.17, the original short-hand group closing doesn't work anymore.
   FFS. */
/**
 * @}
 */

/**
@brief This namespace should not have a global include

Even though it's in a single file --- the contained namespace might or might
not be in the same file and that could be misleading.
*/
namespace ContainsNamespace {
    /**
     * @brief This namespace should not have a global include either
     *
     * Because it has a class inside.
     */
    namespace ContainsClass {
        /** @brief Union */
        union Union {};

        /** @brief This function should also have a local include */
        void foo();
    }

    /** @brief This function should have a local include */
    void foo();
}

/**
@brief This namespace should have a global include

Even though it has no members that could set the global include for it.
*/
namespace Empty {}

template <typename> struct SpreadClass;


text:
module Main where

import Text.XML.HXT.Core
import Data.Map (Map, fromList, toList)

class XmlPickler a where
  xpickle :: PU a

instance XmlPickler Season where
  xpickle = xpPersons

instance XmlPickler Season where
  xpickle = xpPerson

data Persons = Persons
  {
    persons :: [Person]
  }
  deriving (Show, Eq)

data Person = Person
  {
    name :: String
  , age :: Int
  }
  deriving (Show, Eq)

xpPersons :: PU Persons
xpPersons
 =  xpElem "data" $
    xpWrap ( fromList
          , toList
          ) $
    xpList $
    xpElem [] xpickle

xpPerson :: PU Person
xpPerson
  = xpElem "person" $
    xpWrap ( \ ((n,a)) -> Player n a
            , \ t -> (name n, age a)
          ) $
      xp2Tuple  (xpAttr "name" xpText)
                (xpAttr "age" xpText)

main :: IO()
main = do
  runX ( xunpickleDocument xpSeason
                                [ withValidate no
                                , withTrace 1
                                , withRemoveWS yes
                                , withPreserveComment no
                                ] "../data/sample.xml"
      )
  >>>
  processPersons
  >>>

processPersons :: IOSArrow Persons Persons
processPersons
  = arrIO ( \ x -> do { print x ; return x })


text:
import unittest
import os
from sandstone import settings
import sys

sandstone_suite = unittest.TestSuite()
for app in settings.INSTALLED_APPS:
    mod = __import__(app,fromlist=[''])
    app_dir = os.path.dirname(os.path.abspath(mod.__file__))
    test_dir = os.path.join(app_dir,'tests/python')
    try:
        app_suite = unittest.TestLoader().discover(test_dir)
        sandstone_suite.addTests(app_suite)
    except ImportError:
        print 'No tests found for {}'.format(app)

runner = unittest.TextTestRunner()
# runner.run(sandstone_suite)
ret = not runner.run(sandstone_suite).wasSuccessful()
sys.exit(ret)


text:
package main

import (
	"github.com/kataras/iris/v12/_examples/bootstrapper/bootstrap"
	"github.com/kataras/iris/v12/_examples/bootstrapper/middleware/identity"
	"github.com/kataras/iris/v12/_examples/bootstrapper/routes"
)

func newApp() *bootstrap.Bootstrapper {
	app := bootstrap.New("Awesome App", "kataras2006@hotmail.com")
	app.Bootstrap()
	app.Configure(identity.Configure, routes.Configure)
	return app
}

func main() {
	app := newApp()
	app.Listen(":8080")
}


text:
//=====================================================================
//
//File:      $RCSfile: IdAssigner.java,v $
//Version:   $Revision: 1.18 $
//Modified:  $Date: 2013/01/10 22:54:10 $
//
//(c) Copyright 2005-2014 by Mentor Graphics Corp. All rights reserved.
//
//=====================================================================
// 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.
//=====================================================================

package com.mentor.nucleus.bp.core.common;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.mentor.nucleus.bp.core.ComponentInstance_c;
import com.mentor.nucleus.bp.core.CorePlugin;

/**
 * This class serves as single place for all UUID related functions.
 */
public class IdAssigner
{
	private SecureRandom randomGenerator = null;

	public static final UUID MAX_UUID = new UUID(0xffffffffffffffffL, 0xffffffffffffffffL);
	public static final UUID NULL_UUID = new UUID(0, 0);

    /**
     * The instances of this class that been created so far.  This is here
     * because this class has methods that need to operate on all the
     * instances, such as seedForAllInstances().
     */
    private static List<IdAssigner> instances = new ArrayList<IdAssigner>();

    /**
     * The seed supplied to the last call made to seedForAllInstances(), to
     * be assigned to any future instances of this class that are created.
     */
    private static long seedForAllInstances = 0;

	public long seed = 0;

    /**
     * Constructor.
     */
    public IdAssigner()
    {
        instances.add(this);

        // if a seed for all instances has been set
        if (seedForAllInstances != 0) {
            // apply to this instance, as well
            setSeed(seedForAllInstances);
        }
    }

    public UUID createUUID(){
    	if(randomGenerator != null){
    		return new UUID(randomGenerator.nextLong(), randomGenerator.nextLong());
    	}
		return UUID.randomUUID();
	}

    /*
     * This method allows one to configure the IdAssigner such that
     * the randomness is removed.  It is used by creation of the state
     * machine identifiers as well as by unit tests.
     */
    public void setSeed(long seed){
		this.seed = seed;
    	if(seed == 0){
    		randomGenerator = null;
    	}else{
    		try {
				randomGenerator = SecureRandom.getInstance("SHA1PRNG");
			} catch (NoSuchAlgorithmException e) {
				CorePlugin.logError("Unable to locate SHA1PRNG algorithm.", e);
			}
			if(randomGenerator == null) {
				randomGenerator = new SecureRandom();
			}
    		randomGenerator.setSeed(seed);
    	}
    }

	public static UUID createRuntimeUUIDFromString(Object value, ComponentInstance_c ci) {
		// Runtime UUID's are created by Verifier. A remotely created UUID is one that
		// was created in raw java, or originated from a remote component. They are
		// stored as full UUID strings. Locally created UUID's have a particular format
		// starting with 'ideeda7a'.
		if (isUUID((String)value)) {
			// This is a remotely created UUID, convert and return it
			return UUID.fromString((String)value);
		}
		else {
			// This is a locally created UUID, synthesize it
			String id = String.format("%012x",Integer.parseInt((String)value));
			String comp_id = "00000000";
			if (ci != null) {
			  // Component Instance can be null when called from a bridge
			  comp_id = String.format("%08x",ci.Getenginenumber());
			}
			return UUID.fromString("1deeda7a-0000-" +
					         comp_id.substring(0,3) + "-" +
					         comp_id.substring(4) + "-" +
					         id);
		}
	}

	public static String convertFromRuntimeUUID(Object value, ComponentInstance_c ci) {
		if (value instanceof UUID) {
			String [] fields = ((UUID)value).toString().split("-");
			if (fields[0].equals("1deeda7a")) {
				// Its an xtUML originated UUID, parse it to see what to do
				// We have to ignore the most significant digit of field 2, else it won't fit in an
				// integer. A genuine xtUML originated UUID will never have these top bits set anyway.
				String field2 = fields[2].substring(1);
				int comp_id = Integer.parseInt(field2+fields[3], 16);
				if  (comp_id == 0 || comp_id == ci.Getenginenumber()) {
					// It's a UUID that originated from this running component
	                // or was passed out of a bridge call from any component. Turn
                    // it back into an integer
					return Integer.toString(Integer.parseInt(fields[4]));
			    }
			}
			// Either it's not an xtUML UUID, it's not local to this component and it didn't originate from a bridge
			return ((UUID)value).toString();
		}
		else {
			return null;
		}
	}

    public static final UUID createUUIDFromString(String id){
    	return createUUIDFromString(id, false);
    }

    public static final UUID createUUIDFromString(String id, boolean stripDomainCode){
    	if(isUUID(id)){
    		return UUID.fromString(id);
    	}else{
    		if (id == null) {
    			id = "0";
    		}
    		Long longval = 0L;
    		try {
    			longval = Long.parseLong(id);
    		} catch (NumberFormatException nfe) {
    			CorePlugin.logError(
    					"Expected a numeric UUID value and encountered a non-numeric.  This value is being changed to 0.",
    					nfe);
    		}

    		if(stripDomainCode){
        		return new UUID(0, longval & 0xfffffff);
    		}else{
        		return new UUID(0, longval);
    		}
    	}
    }

    public static final UUID preprocessUUID(UUID id){
    	if(NULL_UUID.equals(id)){
    		return NULL_UUID;
    	}
    	return id;
    }

    public static final boolean isUUID(String idString){
    	//  The format is: 00000000-0000-0000-0000-000000000000
    	return (idString != null && (idString.length() == 36 &&
    			   idString.charAt(8) == '-' &&
    			   idString.charAt(13) == '-' &&
    			   idString.charAt(18) == '-' &&
    			   idString.charAt(23) == '-' ));
    }

    public static final boolean isUUIDDummy(UUID id){
    	return (id.getMostSignificantBits() == 0);
    }

    /**
     * Sets the seed of all instances of this class that have been created,
     * which is required by test cases so they may have repeatable results.
     * Future instances of this class will also be started with the given
     * seed.
     */
    public static void setSeedOfAllInstances(long seed)
    {
        seedForAllInstances = seed;

        for (IdAssigner instance: instances) instance.setSeed(seed);
    }
    public static void setSeedOfAllInstances(long seed, boolean allocateHeterogeneousSeeds)
    {
    	if (allocateHeterogeneousSeeds) {
          seedForAllInstances = seed;
          for (IdAssigner instance: instances) instance.setSeed(seed++);
    	}
    	else {
    		setSeedOfAllInstances(seed);
    	}
    }
}


text:
<!--
 Copyright (c) Microsoft Corporation. All rights reserved.
 Licensed under the MIT License. See License.txt in the project root for
 license information.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.azure</groupId>
    <artifactId>azure-data-sdk-parent</artifactId>
    <version>1.3.0</version> <!-- {x-version-update;com.azure:azure-data-sdk-parent;current} -->
    <relativePath>../../parents/azure-data-sdk-parent</relativePath>
  </parent>

  <groupId>com.microsoft.azure</groupId>
  <artifactId>azure-batch</artifactId>
  <packaging>jar</packaging>
  <version>10.2.0-beta.1</version> <!-- {x-version-update;com.microsoft.azure:azure-batch;current} -->

  <name>Microsoft Azure Batch SDK Root</name>
  <description>This package contains the root module of Microsoft Azure Batch SDK.</description>
  <url>https://github.com/Azure/azure-sdk-for-java</url>

  <distributionManagement>
    <site>
      <id>azure-java-build-docs</id>
      <url>${site.url}/site/${project.artifactId}</url>
    </site>
  </distributionManagement>

  <scm>
    <url>https://github.com/Azure/azure-sdk-for-java</url>
  </scm>

  <dependencies>
    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure-client-runtime</artifactId>
      <version>1.7.14</version> <!-- {x-version-update;com.microsoft.azure:azure-client-runtime;external_dependency} -->
    </dependency>

    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>adal4j</artifactId>
      <version>1.6.5</version> <!-- {x-version-update;com.microsoft.azure:adal4j;external_dependency} -->
    </dependency>

    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.15</version> <!-- {x-version-update;commons-codec:commons-codec;external_dependency} -->
    </dependency>

    <!-- Test dependencies -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version> <!-- {x-version-update;junit:junit;external_dependency} -->
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure-storage</artifactId>
      <version>8.0.0</version> <!-- {x-version-update;com.microsoft.azure:azure-storage;external_dependency} -->
      <scope>test</scope>
    </dependency>

    <!-- Storage pulls in an old version of jackson-core; so we explicitly set it in test. -->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.13.4</version> <!-- {x-version-update;com.fasterxml.jackson.core:jackson-core;external_dependency} -->
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure</artifactId>
      <version>1.24.1</version> <!-- {x-version-update;com.microsoft.azure:azure;external_dependency} -->
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-core</artifactId>
      <version>1.34.0</version> <!-- {x-version-update;com.azure:azure-core;dependency} -->
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure-mgmt-network</artifactId>
      <version>1.33.0</version> <!-- {x-version-update;com.microsoft.azure:azure-mgmt-network;external_dependency} -->
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.11.0</version> <!-- {x-version-update;commons-io:commons-io;external_dependency} -->
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure-mgmt-resources</artifactId>
      <version>1.3.1-SNAPSHOT</version> <!-- {x-version-update;test_jar_com.microsoft.azure:azure-mgmt-resources;external_dependency} -->
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.microsoft.azure</groupId>
      <artifactId>azure-mgmt-resources</artifactId>
      <version>1.3.0</version> <!-- {x-version-update;com.microsoft.azure:azure-mgmt-resources;external_dependency} -->
      <scope>test</scope>
    </dependency>

  </dependencies>
  <build>
    <plugins>

      <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>9.4.33.v20201020</version> <!-- {x-version-update;org.eclipse.jetty:jetty-maven-plugin;external_dependency} -->
        <configuration>
          <scanIntervalSeconds>0</scanIntervalSeconds>
          <stopPort>11079</stopPort>
          <stopKey>stop-azure-batch</stopKey>
          <stopWait>20</stopWait>
          <waitForChild>false</waitForChild>
          <jettyXml>../../../jetty.xml</jettyXml>
          <supportedPackagings>jar</supportedPackagings>
        </configuration>
        <executions>
          <execution>
            <id>start-jetty</id>
            <phase>process-test-classes</phase>
            <goals>
              <goal>run-forked</goal>
            </goals>
          </execution>
          <execution>
            <id>stop-jetty</id>
            <phase>post-integration-test</phase>
            <goals>
              <goal>stop</goal>
            </goals>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.10.1</version> <!-- {x-version-update;org.apache.maven.plugins:maven-compiler-plugin;external_dependency} -->
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
          <showWarnings>true</showWarnings>
          <showDeprecation>true</showDeprecation>
        </configuration>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>3.3.0</version> <!-- {x-version-update;org.apache.maven.plugins:maven-resources-plugin;external_dependency} -->
        <configuration>
          <outputDirectory>${basedir}/target/test-classes/session-records</outputDirectory>
          <resources>
            <resource>
              <directory>${basedir}/src/test/resources/test-recordings</directory>
            </resource>
          </resources>
        </configuration>
      </plugin>

    </plugins>

  </build>
  <profiles>
    <profile>
      <id>java9plus</id>
      <activation>
        <jdk>[9,)</jdk>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M7</version><!-- {x-version-update;org.apache.maven.plugins:maven-surefire-plugin;external_dependency} -->
            <configuration>
              <reuseForks>false</reuseForks>
              <argLine>
                -Xmx4096m
                --add-exports com.azure.core/com.azure.core.implementation.http=ALL-UNNAMED
                --add-opens com.microsoft.azure.batch/com.microsoft.azure.batch=ALL-UNNAMED
                --add-opens java.base/java.util=ALL-UNNAMED
              </argLine>
            </configuration>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

</project>


text:
                        <input ng-model="model.username" required="" class="form-control" id="login" placeholder="Enter login" autofocus>

                        <input type="password" required="" ng-model="model.password" class="form-control" id="password" placeholder="Enter password">

                  Enter

            Enter with Facebook


text:
/*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>
*    @author Oppe Luis Sebastian
*    @Fecha 23/11/2013
*    @use Librerias de AJAX para inicio de sesion
*/
//inicializamos eventos y procesos desde el DOM
$(document).ready(function(){
	IniciarEventos();}
);

function IniciarEventos(){
	$('#ClienteDocumento').mask('99.999.999',{placeholder:" "});
	//icons GO
	$('.ui-state-default').hover(
			function(){ $(this).addClass('ui-state-hover'); },
			function(){ $(this).removeClass('ui-state-hover'); }
	);
	$('#buscar').click(function(){ reloadList(link,1) });
	//Una vez cargado los datos recargamos el link
	Ajaxcargarusuarios()
	showmessage()
}

function reloadList(rlink,tipofiltro){
	var serialize
	serialize=$('#filteruser').serialize()

	$('#cargandodatos').show(1)
	$.post(rlink,serialize,
			function(data) {
				$('#listusers').html(data);
				var divPaginationLinks = '#listusers'+" .pagination a,.sort a";
			    $(divPaginationLinks).click(function(){
			        var thisHref = $(this).attr("href");
			        reloadList(thisHref);
			        //recarmamos el proceso de carga
			        return false;
			    });
	}).always(function() {
		$('#cargandodatos').hide(1)
	});
}

//Permite cargar en el div el ajax
function loadPiece(href,divName) {
	//reloadList();
	$(divName).load(href, $('#filtros').serialize(), function(){
		//AjaxLinkOn(divName)
        var divPaginationLinks = divName+" .pagination a,.sort a";
        $(divPaginationLinks).click(function(){
            var thisHref = $(this).attr("href");
            loadPiece(thisHref,divName);
            //recarmamos el proceso de carga
            return false;
        });
    });
}

function Ajaxcargarusuarios(){
	reloadList(link,0)
}

function showmessage(){
	var message = $('#message').text();
	if(typeof(message) != 'undefined' && message.trim() != ''){
		$().toastmessage('showToast', {
				text     : message,
				sticky   : false,
				position : 'top-right',
				type     : 'success',
				closeText: '',
				close    : function () {

				}
			});
	}
}


text:
#import "APCStudyOverviewCollectionViewController.h"
#import "APCWebViewController.h"
#import "APCIntroVideoViewController.h"
#import "APCOnboardingManager.h"
#import "APCUser.h"
#import "APCLog.h"
#import "APCLocalization.h"

#import "UIColor+APCAppearance.h"
#import "UIFont+APCAppearance.h"

#import <ResearchKit/ResearchKit.h>

#import "APCAppDelegate.h"

static NSString *kConsentEmailSubject = @"Consent Document";

@interface APCStudyOverviewCollectionViewController () <ORKTaskViewControllerDelegate>

@property (weak, nonatomic) IBOutlet UIView *gradientCollectionView;
@property (weak, nonatomic) IBOutlet UIPageControl *pageControl;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *joinButtonLeadingConstraint;
@property (weak, nonatomic) IBOutlet UIButton *btnAlreadyParticipated;

@end

@implementation APCStudyOverviewCollectionViewController

#pragma mark - Lifecycle

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:APCUserDidDeclineConsentNotification object:nil];
    _collectionView.delegate = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.items = [NSMutableArray new];

    [self setUpAppearance];
    self.items = [self prepareContent];
    [self setUpPageView];
    [self setupCollectionView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];

    if (![((id<APCOnboardingManagerProvider>)[UIApplication sharedApplication].delegate).onboardingManager isSignInSupported]) {
        _loginButton.hidden = YES;
        _loginButton.enabled = NO;
    }

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(goBackToSignUpJoin:)
                                                 name:APCUserDidDeclineConsentNotification
                                               object:nil];
    APCLogViewControllerAppeared();
}

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)goBackToSignUpJoin:(NSNotification *)__unused notification {
    BOOL animated = (self.presentedViewController == nil);
    [self.navigationController popToRootViewControllerAnimated:animated];
}

- (NSArray *)prepareContent
{
    NSMutableArray *items = [NSMutableArray arrayWithArray:[self studyDetailsFromJSONFile:@"StudyOverview"]];

    if (self.showShareRow){

        APCTableViewStudyDetailsItem *shareStudyItem = [APCTableViewStudyDetailsItem new];
        shareStudyItem.caption = NSLocalizedStringWithDefaultValue(@"Share this Study", @"APCAppCore", APCBundle(), @"Share this Study", nil);
        shareStudyItem.iconImage = [UIImage imageNamed:@"share_icon"];
        shareStudyItem.tintColor = [UIColor appTertiaryGreenColor];

        APCTableViewRow *rowItem = [APCTableViewRow new];
        rowItem.item = shareStudyItem;
        rowItem.itemType = kAPCTableViewStudyItemTypeShare;

        APCTableViewSection *section = [items firstObject];
        NSMutableArray *rowItems = [NSMutableArray arrayWithArray:section.rows];
        [rowItems addObject:rowItem];
        section.rows = [NSArray arrayWithArray:rowItems];
    }

    if (self.showConsentRow) {

        APCTableViewStudyDetailsItem *reviewConsentItem = [APCTableViewStudyDetailsItem new];
        reviewConsentItem.caption = NSLocalizedStringWithDefaultValue(@"Review Consent", @"APCAppCore", APCBundle(), @"Review Consent", nil);
        reviewConsentItem.iconImage = [UIImage imageNamed:@"consent_icon"];
        reviewConsentItem.tintColor = [UIColor appTertiaryPurpleColor];

        APCTableViewRow *rowItem = [APCTableViewRow new];
        rowItem.item = reviewConsentItem;
        rowItem.itemType = kAPCTableViewStudyItemTypeReviewConsent;

        APCTableViewSection *section = [items firstObject];
        NSMutableArray *rowItems = [NSMutableArray arrayWithArray:section.rows];
        [rowItems addObject:rowItem];
        section.rows = [NSArray arrayWithArray:rowItems];
    }

    return [NSArray arrayWithArray:items];
}

- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];

    if ([self user].consented) {
        self.joinButtonLeadingConstraint.constant = CGRectGetWidth(self.view.frame)/2;
        [self.view layoutIfNeeded];
    }

}

- (void)setUpPageView
{
    APCTableViewSection *sectionItem = self.items.firstObject;
    self.pageControl.numberOfPages = sectionItem.rows.count;
}

- (void)setupCollectionView
{
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;

    [self.researchInstituteImageView setImage:[UIImage imageNamed:@"logo_disease_researchInstitute"]];
}

- (void)setUpAppearance
{
    self.diseaseNameLabel.font = [UIFont appMediumFontWithSize:19];
    self.diseaseNameLabel.textColor = [UIColor blackColor];
    self.diseaseNameLabel.adjustsFontSizeToFitWidth = YES;
    self.diseaseNameLabel.minimumScaleFactor = 0.5;

    self.dateRangeLabel.font = [UIFont appLightFontWithSize:16];
    self.dateRangeLabel.textColor = [UIColor appSecondaryColor3];

    self.btnAlreadyParticipated.tintColor = [UIColor appPrimaryColor];
    self.view.backgroundColor = [UIColor appPrimaryColor];
}

- (APCUser *)user
{
    return ((APCAppDelegate*) [UIApplication sharedApplication].delegate).dataSubstrate.currentUser;
}

#pragma mark - UICollectionViewDataSource methods

- (NSInteger) numberOfSectionsInCollectionView: (UICollectionView *) __unused collectionView
{
    return 1;
}

-(NSInteger) collectionView: (UICollectionView *) __unused collectionView
	 numberOfItemsInSection: (NSInteger) __unused section
{
    APCTableViewSection *sectionItem = self.items.firstObject;
    return sectionItem.rows.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell;
    APCTableViewStudyDetailsItem *studyDetails = [self itemForIndexPath:indexPath];

    if (indexPath.row == 0) {
        APCStudyLandingCollectionViewCell *landingCell = (APCStudyLandingCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kAPCStudyLandingCollectionViewCellIdentifier forIndexPath:indexPath];
        landingCell.delegate = self;
        landingCell.titleLabel.text = studyDetails.caption;
        landingCell.subTitleLabel.text = studyDetails.detailText;
        landingCell.readConsentButton.hidden = YES;
        landingCell.emailConsentButton.hidden = [((APCAppDelegate *)[UIApplication sharedApplication].delegate) hideEmailOnWelcomeScreen];

        if ([MFMailComposeViewController canSendMail]) {
            [landingCell.emailConsentButton setTitleColor:[UIColor appPrimaryColor] forState:UIControlStateNormal];
            [landingCell.emailConsentButton setUserInteractionEnabled:YES];
        } else {
            [landingCell.emailConsentButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [landingCell.emailConsentButton setUserInteractionEnabled:NO];
        }

        if (studyDetails.showsConsent) {
            landingCell.readConsentButton.hidden = NO;
        }
        cell = landingCell;

    } else if (studyDetails.videoName.length > 0) {

        APCStudyVideoCollectionViewCell *videoCell = (APCStudyVideoCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kAPCStudyVideoCollectionViewCellIdentifier forIndexPath:indexPath];
        videoCell.delegate = self;
        videoCell.titleLabel.text = studyDetails.caption;
        videoCell.videoMessageLabel.text = studyDetails.detailText;
        cell = videoCell;

    } else {
        APCStudyOverviewCollectionViewCell *webViewCell = (APCStudyOverviewCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:kAPCStudyOverviewCollectionViewCellIdentifier forIndexPath:indexPath];

        NSString *filePath = [[APCAppDelegate sharedAppDelegate] pathForResource: studyDetails.detailText ofType:@"html"];
        NSAssert(filePath, @"Expecting file \"%@.html\" to be present in Resources, but didn't find it", studyDetails.detailText);
        NSURL *targetURL = [NSURL URLWithString:filePath];
        NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
        [webViewCell.webView loadRequest:request];

        cell = webViewCell;
    }

    return cell;
}

- (CGSize) collectionView: (UICollectionView *) __unused collectionView
				   layout: (UICollectionViewLayout*) __unused collectionViewLayout
   sizeForItemAtIndexPath: (NSIndexPath *) __unused indexPath
{
    return self.collectionView.bounds.size;
}

#pragma mark - UIScrollViewDelegate methods

- (void) scrollViewDidEndDecelerating: (UIScrollView *) __unused scrollView
{
    CGFloat pageWidth = self.collectionView.frame.size.width;
    self.pageControl.currentPage = (self.collectionView.contentOffset.x + pageWidth / 2) / pageWidth;
}

#pragma mark - TaskViewController Delegate methods

- (void)taskViewController:(ORKTaskViewController *)taskViewController didFinishWithReason:(ORKTaskViewControllerFinishReason)reason error:(nullable NSError *)__unused error
{
    if (reason == ORKTaskViewControllerFinishReasonCompleted)
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        [taskViewController dismissViewControllerAnimated:YES completion:nil];
    }
}

#pragma mark - Public methods

- (NSArray *)studyDetailsFromJSONFile:(NSString *)jsonFileName
{
    NSParameterAssert(jsonFileName);
    NSString *filePath = [[APCAppDelegate sharedAppDelegate] pathForResource:jsonFileName ofType:@"json"];
    NSAssert(filePath, @"Must include file \"%@.json\" in bundle", jsonFileName);
    NSString *JSONString = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

    NSError *parseError;
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:[JSONString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&parseError];

    NSMutableArray *items = [NSMutableArray new];

    if (!parseError) {

        self.diseaseName = jsonDictionary[@"disease_name"];
        self.diseaseNameLabel.text = self.diseaseName;

        NSString *fromDate = jsonDictionary[@"from_date"];
        if (fromDate.length > 0) {
            self.dateRangeLabel.text = [fromDate stringByAppendingFormat:@" - %@", jsonDictionary[@"to_date"]];
        } else {
            self.dateRangeLabel.hidden = YES;
        }

        NSArray *questions = jsonDictionary[@"questions"];

        NSMutableArray *rowItems = [NSMutableArray new];

        for (NSDictionary *questionDict in questions) {

            APCTableViewStudyDetailsItem *studyDetails = [APCTableViewStudyDetailsItem new];
            studyDetails.caption = questionDict[@"title"];
            studyDetails.detailText = questionDict[@"details"];
            studyDetails.iconImage = [[UIImage imageNamed:questionDict[@"icon_image"]] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
            studyDetails.tintColor = [UIColor tertiaryColorForString:questionDict[@"tint_color"]];
            studyDetails.videoName = questionDict[@"video_name"];
            studyDetails.showsConsent = ((NSString *)questionDict[@"show_consent"]).length > 0;

            APCTableViewRow *row = [APCTableViewRow new];
            row.item = studyDetails;
            row.itemType = kAPCTableViewStudyItemTypeStudyDetails;
            [rowItems addObject:row];
        }

        APCTableViewSection *section = [APCTableViewSection new];
        section.rows = [NSArray arrayWithArray:rowItems];
        [items addObject:section];
    }

    return [NSArray arrayWithArray:items];
}

- (APCTableViewStudyDetailsItem *)itemForIndexPath:(NSIndexPath *)indexPath
{
    APCTableViewSection *sectionItem = self.items[indexPath.section];
    APCTableViewRow *rowItem = sectionItem.rows[indexPath.row];

    APCTableViewStudyDetailsItem *studyDetailsItem = (APCTableViewStudyDetailsItem *)rowItem.item;

    return studyDetailsItem;
}

- (APCTableViewStudyItemType)itemTypeForIndexPath:(NSIndexPath *)indexPath
{
    APCTableViewSection *sectionItem = self.items[indexPath.section];
    APCTableViewRow *rowItem = sectionItem.rows[indexPath.row];

    APCTableViewStudyItemType studyItemType = rowItem.itemType;

    return studyItemType;
}

- (void)signInTapped:(id)__unused sender {

    id <APCOnboardingManagerProvider> provider = (id<APCOnboardingManagerProvider>)[UIApplication sharedApplication].delegate;
    if ([provider respondsToSelector:@selector(didHandleSignInFromViewController:)] &&
        [provider didHandleSignInFromViewController:self]) {
        // If the custom handling is implemented then nothing else is required.
        return; // Exit
    }

    APCOnboardingManager *manager = [provider onboardingManager];
    [manager instantiateOnboardingForType:kAPCOnboardingTaskTypeSignIn];

    UIViewController *viewController = [manager.onboarding nextScene];
    NSAssert(viewController, @"Expecting the first scene's view controller for sign-in onboarding but got nothing");
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)signUpTapped:(id)__unused sender {

    id <APCOnboardingManagerProvider> provider = (id<APCOnboardingManagerProvider>)[UIApplication sharedApplication].delegate;
    if ([provider respondsToSelector:@selector(didHandleSignupFromViewController:)] &&
        [provider didHandleSignupFromViewController:self]) {
        // If the custom handling is implemented then nothing else is required.
        return; // Exit
    }

    APCOnboardingManager *manager = [provider onboardingManager];
    [manager instantiateOnboardingForType:kAPCOnboardingTaskTypeSignUp];

    UIViewController *viewController = [manager.onboarding nextScene];
    NSAssert(viewController, @"Expecting the first scene's view controller for sign-up onboarding but got nothing");
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (IBAction)pageClicked:(UIPageControl *)sender {
    NSInteger page = sender.currentPage;
    CGRect frame = self.collectionView.frame;
    CGFloat offset = frame.size.width * page;
    [self.collectionView setContentOffset:CGPointMake(offset, 0) animated:YES];
}

#pragma mark - APCStudyVideoCollectionViewCellDelegate methods

- (void)studyVideoCollectionViewCellWatchVideo:(APCStudyVideoCollectionViewCell *)cell
{
    APCTableViewStudyDetailsItem *studyDetails = (APCTableViewStudyDetailsItem *)[self itemForIndexPath:[self.collectionView indexPathForCell:cell]];

    NSURL *fileURL = [NSURL fileURLWithPath:[[APCAppDelegate sharedAppDelegate] pathForResource:studyDetails.videoName ofType:@"mp4"]];
    NSAssert(fileURL, @"Must include the consent video with filename \"%@.mp4\" in the app bundle", studyDetails.videoName);

    // Set the allowed orientation mask to allow landscape
    [[APCAppDelegate sharedAppDelegate] setPreferredOrientationMask:UIInterfaceOrientationMaskAllButUpsideDown];

    APCIntroVideoViewController *introVideoViewController = [[APCIntroVideoViewController alloc] initWithContentURL:fileURL];

    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:introVideoViewController];
    navController.navigationBarHidden = YES;
    [self presentViewController:navController animated:YES completion:nil];

}

- (void)studyVideoCollectionViewCellReadConsent:(APCStudyVideoCollectionViewCell *) __unused cell
{
    APCWebViewController *webViewController = [[UIStoryboard storyboardWithName:@"APCOnboarding" bundle:[NSBundle bundleForClass:[self class]]] instantiateViewControllerWithIdentifier:@"APCWebViewController"];
    [webViewController.webView setDataDetectorTypes:UIDataDetectorTypeAll];
    webViewController.title = NSLocalizedStringWithDefaultValue(@"Consent", @"APCAppCore", APCBundle(), @"Consent", @"Consent");

    UINavigationController *navController = [[UINavigationController alloc]initWithRootViewController:webViewController];
    [self.navigationController presentViewController:navController animated:YES completion:^{
        [webViewController.webView loadData:[self PDFDataOfConsent] MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:[NSURL URLWithString:@"http://"]];
    }];

}

- (void)studyVideoCollectionViewCellEmailConsent:(APCStudyVideoCollectionViewCell *) __unused cell
{
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *mailComposeVC = [[MFMailComposeViewController alloc] init];
        mailComposeVC.mailComposeDelegate = self;
        [mailComposeVC addAttachmentData:[self PDFDataOfConsent] mimeType:@"application/pdf" fileName:@"Consent"];

        [self presentViewController:mailComposeVC animated:YES completion:NULL];
    }
}

#pragma mark - MFMailComposeViewControllerDelegate method

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result) {
        case MFMailComposeResultCancelled:
            break;
        case MFMailComposeResultSaved:
            break;
        case MFMailComposeResultSent:
            break;
        case MFMailComposeResultFailed:
            APCLogError2(error);
            break;
        default:
            break;
    }
    controller.mailComposeDelegate = nil;
    [controller dismissViewControllerAnimated:YES completion:nil];
}

- (void)studyLandingCollectionViewCellEmailConsent:(APCStudyLandingCollectionViewCell *) __unused cell
{
    if ([MFMailComposeViewController canSendMail]) {
        MFMailComposeViewController *mailComposeVC = [[MFMailComposeViewController alloc] init];
        mailComposeVC.mailComposeDelegate = self;

        [mailComposeVC addAttachmentData:[self PDFDataOfConsent] mimeType:@"application/pdf" fileName:@"Consent"];
        [mailComposeVC setSubject:kConsentEmailSubject];
        [self presentViewController:mailComposeVC animated:YES completion:NULL];
    }
}

- (void)studyLandingCollectionViewCellReadConsent:(APCStudyLandingCollectionViewCell *) __unused cell
{
    APCWebViewController *webViewController = [[UIStoryboard storyboardWithName:@"APCOnboarding" bundle:[NSBundle bundleForClass:[self class]]] instantiateViewControllerWithIdentifier:@"APCWebViewController"];
    [webViewController.webView setDataDetectorTypes:UIDataDetectorTypeAll];
    webViewController.title = NSLocalizedStringWithDefaultValue(@"Consent", @"APCAppCore", APCBundle(), @"Consent", @"Consent");

    UINavigationController *navController = [[UINavigationController alloc]initWithRootViewController:webViewController];
    [self.navigationController presentViewController:navController animated:YES completion:^{
        [webViewController.webView loadData:[self PDFDataOfConsent] MIMEType:@"application/pdf" textEncodingName:@"utf-8" baseURL:[NSURL URLWithString:@"http://"]];
    }];
}

#pragma mark - Utilities

- (NSData *)PDFDataOfConsent
{
    NSString *filePath = [[APCAppDelegate sharedAppDelegate] pathForResource:@"consent" ofType:@"pdf"];
    NSAssert(filePath, @"Must include the consent PDF with filename \"consent.pdf\" in the app bundle");
    NSData *fileData = [NSData dataWithContentsOfFile:filePath];
    NSAssert(fileData, @"Failed to create an NSData representation of \"consent.pdf\"");
    return fileData;
}

@end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Skyfire.Service.Messager
{
    public partial class MsgForm : Form
    {
        public MsgForm()
        {
            InitializeComponent();
        }
    }
}


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Database\Driver\sqlite\Upsert.
 */

namespace Drupal\Core\Database\Driver\sqlite;

use Drupal\Core\Database\Query\Upsert as QueryUpsert;

/**
 * SQLite implementation of \Drupal\Core\Database\Query\Upsert.
 */
class Upsert extends QueryUpsert {

  /**
   * {@inheritdoc}
   */
  public function __toString() {
    // Create a sanitized comment string to prepend to the query.
    $comments = $this->connection->makeComment($this->comments);

    // Default fields are always placed first for consistency.
    $insert_fields = array_merge($this->defaultFields, $this->insertFields);

    $query = $comments . 'INSERT OR REPLACE INTO {' . $this->table . '} (' . implode(', ', $insert_fields) . ') VALUES ';

    $values = $this->getInsertPlaceholderFragment($this->insertValues, $this->defaultFields);
    $query .= implode(', ', $values);

    return $query;
  }

}


text:
<?php

declare(strict_types=1);

namespace Soluble\Japha\Bridge\Driver\Pjb62;

use Soluble\Japha\Bridge\Exception\ConnectionException;
use Soluble\Japha\Bridge\Socket\StreamSocket;

class SimpleHttpHandler extends SocketHandler
{
    public $headers;

    /**
     * @var array
     */
    public $cookies;

    /**
     * @var string
     */
    public $context;

    /**
     * @var string
     */
    public $ssl;

    /**
     * @var int
     */
    public $port;

    /**
     * @var string
     */
    public $host;

    /**
     * @var array
     */
    protected $cachedValues = [];

    /**
     * @var string
     */
    protected $java_servlet;

    /**
     * @var int
     */
    protected $java_recv_size;

    /**
     * @var int
     */
    protected $java_send_size;

    /**
     * @throws Exception\IllegalStateException on channel creation error
     *
     * @param Protocol $protocol
     * @param string   $ssl
     * @param string   $host
     * @param int      $port
     * @param string   $java_servlet
     * @param int      $java_recv_size
     * @param int      $java_send_size
     */
    public function __construct(Protocol $protocol, $ssl, $host, $port, $java_servlet, $java_recv_size, $java_send_size)
    {
        $this->cookies = [];
        $this->protocol = $protocol;
        $this->ssl = $ssl;
        $this->host = $host;
        $this->port = $port;
        $this->java_servlet = $java_servlet;

        $this->java_send_size = $java_send_size;
        $this->java_recv_size = $java_recv_size;

        $this->cachedValues = [
            'getContext' => null
        ];
        $this->createChannel();
    }

    /**
     * @throws Exception\IllegalStateException     on channel creation error
     * @throws Exception\BrokenConnectionException if all goes wrong
     */
    protected function createChannel()
    {
        $channelName = Pjb62Driver::getJavaBridgeHeader('X_JAVABRIDGE_REDIRECT', $_SERVER);
        $context = Pjb62Driver::getJavaBridgeHeader('X_JAVABRIDGE_CONTEXT', $_SERVER);
        $len = strlen($context);
        $len0 = PjbProxyClient::getInstance()->getCompatibilityOption($this->protocol->client);
        $len1 = chr($len & 0xFF);
        $len >>= 8;
        $len2 = chr($len & 0xFF);
        $this->channel = $this->getChannel($channelName);
        $this->protocol->setSocketHandler(new SocketHandler($this->protocol, $this->channel));
        $this->protocol->write("\177${len0}${len1}${len2}${context}");
        $this->context = sprintf("X_JAVABRIDGE_CONTEXT: %s\r\n", $context);
        $this->protocol->handler = $this->protocol->getSocketHandler();

        if ($this->protocol->client->sendBuffer !== null) {
            $ret = $this->protocol->handler->write($this->protocol->client->sendBuffer);
            if ($ret === null) {
                $this->protocol->handler->shutdownBrokenConnection('Broken local connection handle');
            }
            $this->protocol->client->sendBuffer = null;
            $this->protocol->handler->read(1);
        }
    }

    public function getContextFromCgiEnvironment(): string
    {
        return Pjb62Driver::getJavaBridgeHeader('X_JAVABRIDGE_CONTEXT', $_SERVER);
    }

    /**
     * @return string
     */
    public function getContext()
    {
        if (!array_key_exists('getContext', $this->cachedValues)) {
            $ctx = $this->getContextFromCgiEnvironment();
            if ($ctx) {
                $this->cachedValues['getContext'] = sprintf('X_JAVABRIDGE_CONTEXT: %s', $ctx);
            }
        }

        return $this->cachedValues['getContext'];
    }

    public function getWebAppInternal()
    {
        $context = $this->protocol->webContext;
        if (isset($context)) {
            return $context;
        }

        return ($this->java_servlet == 'User' &&
                array_key_exists('PHP_SELF', $_SERVER) &&
                array_key_exists('HTTP_HOST', $_SERVER)) ? $_SERVER['PHP_SELF'].'javabridge' : null;
    }

    public function getWebApp(): string
    {
        $context = $this->getWebAppInternal();
        if (null === $context) {
            $context = $this->java_servlet;
        }

        return $context;
    }

    /**
     * @throws Exception\BrokenConnectionException
     */
    public function write(string $data): ?int
    {
        return $this->protocol->getSocketHandler()->write($data);
    }

    public function doSetCookie($key, $val, $path)
    {
        $path = trim($path);
        $webapp = $this->getWebAppInternal();
        if (!$webapp) {
            $path = '/';
        }
        setcookie($key, $val, 0, $path);
    }

    /**
     * @throws Exception\BrokenConnectionException
     */
    public function read(int $size): string
    {
        return $this->protocol->getSocketHandler()->read($size);
    }

    /**
     * @param string $channelName generally the tcp port on which to connect
     *
     * @return SocketChannelP
     *
     * @throws Exception\ConnectException
     */
    public function getChannel(string $channelName): SocketChannelP
    {
        $persistent = $this->protocol->client->getParam(Client::PARAM_USE_PERSISTENT_CONNECTION);
        try {
            $streamSocket = new StreamSocket(
                $this->ssl === 'ssl://' ? StreamSocket::TRANSPORT_SSL : StreamSocket::TRANSPORT_TCP,
                $this->host.':'.$channelName,
                null,
                [],
                $persistent
            );
            $socket = $streamSocket->getSocket();
        } catch (\Throwable $e) {
            $logger = $this->protocol->getClient()->getLogger();
            $logger->critical(sprintf(
                '[soluble-japha] %s (%s)',
                $e->getMessage(),
                __METHOD__
            ));
            throw new ConnectionException($e->getMessage(), $e->getCode());
        }
        stream_set_timeout($socket, -1);

        return new SocketChannelP($socket, $this->host, $this->java_recv_size, $this->java_send_size);
    }

    public function keepAlive(): void
    {
        parent::keepAlive();
    }

    public function redirect(): void
    {
    }
}


text:
exports.TWITTER_CONSUMER_KEY = "foo";
exports.TWITTER_CONSUMER_SECRET = "bar";
exports.TWITTER_ACCESS_TOKEN = "baz";
exports.TWITTER_ACCESS_TOKEN_SECRET = "bam";


text:
'use strict';

module.exports = class BitbucketRepository {
	constructor({backend, repoUser, repoSlug}) {
		this.repoUser = repoUser;
		this.repoSlug = repoSlug;
		this._backend = backend;
	}

	pullRequest(id) {
		const BitbucketPullRequest = require('./pull-request');

		return new BitbucketPullRequest({
			backend       : this._backend,
			repository    : this,
			pullRequestId : id,
		});
	}
};