text:
package org.bits_waves.waves2017.activities;

/**
 * Created by Keshav on 17-Oct-17.
 */

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import org.bits_waves.waves2017.adapters.Category_adapter;
import org.bits_waves.waves2017.listitems.EventItem;
import org.bits_waves.waves2017.R;

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

public class Category extends AppCompatActivity {
    private String heading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category);

        TextView tv_heading = findViewById(R.id.category_title);

        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycle_catogory);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        List<EventItem> listItems = new ArrayList<>();
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        RecyclerView.Adapter adapter = new Category_adapter(listItems, getApplicationContext());

        recyclerView.setAdapter(adapter);
//
//
//        if(catogory_button==null)
//        {
//            Toast.makeText(getApplicationContext(),"Image BUtton Null",Toast.LENGTH_LONG).show();
//        }

        Bundle b=getIntent().getExtras();
        heading =b.getString("category_heading");
        if("Dance".equals(heading))
        {
//
//            test.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    Toast.makeText(getApplicationContext(),"sdff",Toast.LENGTH_LONG).show();
//                }
//            });

            //catogory_button.setVisibility(View.INVISIBLE);
            tv_heading.setText("Dance");
            EventItem listItem3 = new EventItem("Sizzle","","http://bits-waves.org/static/main/images1/events/sizzle.jpg","23:00","C-301","Dance");
            listItems.add(listItem3);
            //Day1
            EventItem listItem1 = new EventItem("Dancing Duo","","http://bits-waves.org/static/main/images1/events/dancingduo.jpg","09:00","Outdoor Stage","Dance");
            listItems.add(listItem1);
            EventItem listItem19 = new EventItem("Natyanjali","","http://bits-waves.org/static/main/images1/events/natyanjali.JPG","00:00","CC","Dance");
            listItems.add(listItem19);
            //day2
            //day3
        }
        else if("Drama".equals(heading))
        {
            tv_heading.setText("Drama");
            //day1
            EventItem listItem = new EventItem("Rangmanch","","http://bits-waves.org/static/main/images1/events/rangmanch.jpg","09:00","Auditorium","Drama");
            listItems.add(listItem);
            EventItem listItem6 = new EventItem("Nukkad Natak","","http://bits-waves.org/static/main/images1/events/nukkadnatak.jpg","10:00","LT1,2Lawns","Drama");
            listItems.add(listItem6);
            //day3
            EventItem listItem5 = new EventItem("Skime","",
                    "http://bits-waves.org/static/main/images1/events/skime.JPG",
                    "09:00","Auditorium","Drama");
            listItems.add(listItem5);
        }
        else if("Specials".equals(heading))
        {
            tv_heading.setText("Specials");
            //day0
            EventItem listItem = new EventItem("Inaugration","","http://bits-waves.org/static/main/images1/events/skime.JPG","17:00","Auditorium","Specials");
            listItems.add(listItem);
            EventItem listItem5 = new EventItem("Strangely Familiar","","http://bits-waves.org/static/main/images1/events/sf.JPG","23:00","C-306","Specials");
            listItems.add(listItem5);
            EventItem listItem6 = new EventItem("FashP","","http://bits-waves.org/static/main/images1/events/fashp.jpg","23:00","CC","Specials");
            listItems.add(listItem6);
            EventItem listItem8 = new EventItem("Show Me The Funny","","http://bits-waves.org/static/main/images1/events/smtf.JPG","23:00","C-302","Specials");
            listItems.add(listItem8);
            //day1
            EventItem listItem20 = new EventItem("Mr and Ms Waves","","http://bits-waves.org/static/main/images1/events/mr_waves.jpg","00:00","C-301,C-302","Specials");
            listItems.add(listItem20);
            //day2
            EventItem listItem211 = new EventItem("Moot Court","","http://bits-waves.org/static/main/images1/events/moot.JPG","09:00","A & C Block","Specials");
            listItems.add(listItem211);
            EventItem listItem12 = new EventItem("Hogathon","","http://bits-waves.org/static/main/images1/events/rangmanch.jpg","11:00","MarketingPavilion","Specials");
            listItems.add(listItem12);
            EventItem listItem201 = new EventItem("Waves Ball","","http://bits-waves.org/static/main/images1/events/rangmanch.jpg","00:00","LT3,4Lawns","Specials");
            listItems.add(listItem201);
            EventItem listItem21 = new EventItem("All Night Treasure Hunt","","http://bits-waves.org/static/main/images1/events/rangmanch.jpg","0100","MarketingPavilion","Specials");
            listItems.add(listItem21);
            //da3
            EventItem listItem51 = new EventItem("Premier League","","http://bits-waves.org/static/main/images1/events/moot.JPG","09:00","C-307","Specials");
            listItems.add(listItem51);

        }
        else if("Music".equals(heading))
        {
            tv_heading.setText("Music");
            //day0
            EventItem listItem1 = new EventItem("Spin Off","","http://bits-waves.org/static/main/images1/events/spinoff.JPG","22:00","Outdoor Stage","Music");
            listItems.add(listItem1);
            EventItem listItem2 = new EventItem("Searock","","http://bits-waves.org/static/main/images1/events/searock.JPG","23:00","Auditorium","Music");
            listItems.add(listItem2);
            EventItem listItem4 = new EventItem("Jukebox","","http://bits-waves.org/static/main/images1/events/jokebox.JPG","23:00","LT 1/2 lawns","Music");
            listItems.add(listItem4);
            //day1
            //day2
            EventItem listItem47 = new EventItem("Solonote","",
                    "http://bits-waves.org/static/main/images1/events/solonote.jpg",
                    "09:00","LT3,4Lawns","Music");
            listItems.add(listItem47);
            EventItem listItem7 = new EventItem("Silence Of The Amps","","http://bits-waves.org/static/main/images1/events/rangmanch.jpg","09:30","LT 1,2 Lawns","Music");
            listItems.add(listItem7);
            EventItem listItem8 = new EventItem("Alaap","",
                    "http://bits-waves.org/static/main/images1/events/alaap.jpg","09:30",
                    "C-303","Music");
            listItems.add(listItem8);
            EventItem listItem19 = new EventItem("Indian Rock","",
                    "http://bits-waves.org/static/main/images1/events/indian_rock.jpg",
                    "00:00","Auditorium","Music");
            listItems.add(listItem19);
            //day3
            EventItem listItem1677 = new EventItem("Coffee Cats- Jazz","","http://bits-waves.org/static/main/images1/events/culturalgauntlet.JPG","00:00","Auditorium","Music");
            listItems.add(listItem1677);

        }
        else if("Literary".equals(heading))
        {
            tv_heading.setText("Literary");
            //day1
            EventItem listItem3 = new EventItem("Contention","","http://bits-waves.org/static/main/images1/events/Contention.JPG","09:00","A & C Block","Literary");
            listItems.add(listItem3);
            EventItem listItem4 = new EventItem("Carpedictum","","http://bits-waves.org/static/main/images1/events/culturalgauntlet.JPG","09:00","C-303","Literary");
            listItems.add(listItem4);
            //day2
            EventItem listItem18 = new EventItem("Inverse","",
                    "http://bits-waves.org/static/main/images1/events/culturalgauntlet.JPG","13:30","C-301","Literary");
            listItems.add(listItem18);
            //day3
            EventItem listItem7 = new EventItem("Spell Bee","","http://bits-waves.org/static/main/images1/events/moot.JPG","10:00","LT-1","Literary");
            listItems.add(listItem7);
            EventItem listItem9 = new EventItem("Irshaad","","http://bits-waves.org/static/main/images1/events/culturalgauntlet.JPG","12:00","Oustdoor Stage","Literary");
            listItems.add(listItem9);

        }
        else if("Quiz".equals(heading))
        {
            tv_heading.setText("Quiz");
            //day1
            EventItem listItem5 = new EventItem("Vice Quiz","","http://bits-waves.org/static/main/images1/events/artathon.jpg","10:00","LT-1","Quiz");
            listItems.add(listItem5);
            //day2
            EventItem listItem10 = new EventItem("Waves Open","","http://bits-waves.org/static/main/images1/events/rangmanch.jpg","10:00","LT-1","Quiz");
            listItems.add(listItem10);
            EventItem listItem15 = new EventItem("Quiz In Two Shades","","http://bits-waves.org/static/main/images1/events/rangmanch.jpg","14:00","LT-1","Quiz");
            listItems.add(listItem15);
            //day3
            EventItem listItem11 = new EventItem("WIPRO Quiz","","http://bits-waves.org/static/main/images1/events/culturalgauntlet.JPG","10:30","LT-4","Quiz");
            listItems.add(listItem11);

        }
        else if("Workshop".equals(heading))
        {
            tv_heading.setText("Workshop");
            //day3
            EventItem listItem12 = new EventItem("SAM Workshop","","http://bits-waves.org/static/main/images1/events/natyanjali.JPG","11:30","C-403","Workshop");
            listItems.add(listItem12);
            EventItem listItem127 = new EventItem("Kala Workshop","","http://bits-waves.org/static/main/images1/events/artathon.jpg","12:00","Kalaroom","Workshop");
            listItems.add(listItem127);

        }
        else if("Design".equals(heading))
        {
            tv_heading.setText("Design");
            //day1
            EventItem listItem7 = new EventItem("Artathon","Round 1","http://bits-waves.org/static/main/images1/events/artathon.jpg","10:00","LT-4","Design");
            listItems.add(listItem7);
            EventItem listItem8 = new EventItem("Blind Art","","http://bits-waves.org/static/main/images1/events/blindart.JPG","10:00","KalaRoom","Design");
            listItems.add(listItem8);
            EventItem listItem9 = new EventItem("Fashion Design","","http://bits-waves.org/static/main/images1/events/artathon.jpg","10:00","C-304","Design");
            listItems.add(listItem9);
            EventItem listItem11 = new EventItem("AAROH","","http://bits-waves.org/static/main/images1/events/artathon.jpg","12:00","LT-4","Design");
            listItems.add(listItem11);
            //day2
            EventItem listItem5 = new EventItem("Portaiture","",
                    "http://bits-waves.org/static/main/images1/events/portraiture.JPG",
                    "09:00","C-302","Design");
            listItems.add(listItem5);
            EventItem listItem87 = new EventItem("Poster Design","","http://bits-waves.org/static/main/images1/events/artathon.jpg","10:00","C-301","Design");
            listItems.add(listItem87);

        }
        else if("Carpedictum".equals(heading))
        {
            tv_heading.setText("Carpedictum");
            EventItem listItem18 = new EventItem("Inverse","",
                    "http://bits-waves.org/static/main/images1/events/culturalgauntlet.JPG","13:30","C-301","Literary");
            listItems.add(listItem18);

        }
        else if("BeauVista".equals(heading))
        {
            tv_heading.setText("Beau Vista");
            EventItem listItem7 = new EventItem("Artathon","Round 1","http://bits-waves.org/static/main/images1/events/artathon.jpg","10:00","LT-4","Design");
            listItems.add(listItem7);
            EventItem listItem5 = new EventItem("Portaiture","",
                    "http://bits-waves.org/static/main/images1/events/portraiture.JPG",
                    "09:00","C-302","Design");
            listItems.add(listItem5);
            EventItem listItem8 = new EventItem("Blind Art","","http://bits-waves.org/static/main/images1/events/blindart.JPG","10:00","KalaRoom","Design");
            listItems.add(listItem8);

        }
        else if("Florence".equals(heading))
        {
            tv_heading.setText("Florence");
            //dance
            EventItem listItem3 = new EventItem("Sizzle","","http://bits-waves.org/static/main/images1/events/sizzle.jpg","23:00","C-301","Dance");
            listItems.add(listItem3);
            EventItem listItem1 = new EventItem("Dancing Duo","","http://bits-waves.org/static/main/images1/events/dancingduo.jpg","09:00","Outdoor Stage","Dance");
            listItems.add(listItem1);
            EventItem listItem19 = new EventItem("Natyanjali","","http://bits-waves.org/static/main/images1/events/natyanjali.JPG","00:00","CC","Dance");
            listItems.add(listItem19);

            //drama
            EventItem listItem = new EventItem("Rangmanch","","http://bits-waves.org/static/main/images1/events/rangmanch.jpg","09:00","Auditorium","Drama");
            listItems.add(listItem);
            EventItem listItem6 = new EventItem("Nukkad Natak","","http://bits-waves.org/static/main/images1/events/nukkadnatak.jpg","10:00","LT1,2Lawns","Drama");
            listItems.add(listItem6);
            EventItem listItem5 = new EventItem("Skime","",
                    "http://bits-waves.org/static/main/images1/events/skime.JPG",
                    "09:00","Auditorium","Drama");
            listItems.add(listItem5);

            //music
            EventItem listItem4 = new EventItem("Jukebox","","http://bits-waves.org/static/main/images1/events/jokebox.JPG","23:00","LT 1/2 lawns","Music");
            listItems.add(listItem4);
            EventItem listItem47 = new EventItem("Solonote","",
                    "http://bits-waves.org/static/main/images1/events/solonote.jpg",
                    "09:00","LT3,4Lawns","Music");
            listItems.add(listItem47);
            EventItem listItem7 = new EventItem("Silence Of The Amps","","http://bits-waves.org/static/main/images1/events/rangmanch.jpg","09:30","LT 1,2 Lawns","Music");
            listItems.add(listItem7);
            EventItem listItem8 = new EventItem("Alaap","",
                    "http://bits-waves.org/static/main/images1/events/alaap.jpg","09:30",
                    "C-303","Music");
            listItems.add(listItem8);
            EventItem listItem197 = new EventItem("Indian Rock","",
                    "http://bits-waves.org/static/main/images1/events/indian_rock.jpg",
                    "00:00","Auditorium","Music");
            listItems.add(listItem197);

        }

        ImageButton back = findViewById(R.id.back_button_category);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(heading.equals("Florence") || heading.equals("BeauVista") || heading.equals("Carpedictum")) {

                    Intent it = new Intent(Category.this, Mini_fest.class);
                    startActivity(it);
                }
                else
                {

                    Intent it = new Intent(Category.this, Category_home_page.class);
                    startActivity(it);
                }
            }
        });

    }
}


text:
package jcurry.util.function;

import java.util.function.IntBinaryOperator;

public interface CurryingIntBinaryOperator extends IntBinaryOperator {

    default CurryingIntUnaryOperator curry(int i) {
        return (i2) -> this.applyAsInt(i, i2);
    }

    default CurryingIntSupplier curry(int i, int i2) {
        return () -> this.applyAsInt(i, i2);
    }

    default CurryingIntBinaryOperator flip() {
        return (i2, i) -> this.applyAsInt(i, i2);
    }

}

redpajama_set_name: RedPajamaGithub


text:
module Robot (Robot, initialState, mkRobot, resetName, robotName) where

import Control.Monad.State (StateT)

data Robot = Dummy1
data RunState = Dummy2

initialState :: RunState
initialState = error "You need to implement this function"

mkRobot :: StateT RunState IO Robot
mkRobot = error "You need to implement this function."

resetName :: Robot -> StateT RunState IO ()
resetName robot = error "You need to implement this function."

robotName :: Robot -> IO String
robotName robot = error "You need to implement this function."


text:
<!doctype html>

    {% capture lchar %}{{page.url | slice: -1, 1}}{% endcapture %}
    {% capture url %}{% if lchar == "/" %}{{page.url}}index.html{% else %}{{ page.url | default: 'index.html' }}{% endif %}{% endcapture %}
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <title>{{ site.title | default: site.github.repository_name }} by {{ site.github.owner_name }}</title>

    <link rel="stylesheet" href="{{ '/assets/css/style.css?v=' | append: site.github.build_revision | relative_url }}">

    {% if site.custom_head %}
        {% include head.html %}
    {% endif %}

    <meta name="viewport" content="width=device-width">

{{ site.title | default: site.github.repository_name }}

{{ site.description | default: site.github.project_tagline }}

        {% if site.github.is_user_page %}

View My GitHub Profile

        {% endif %}

        {% if site.show_downloads %}

Download ZIP File

Download TAR Ball

View On GitHub

        {% endif %}

      {% if site.custom_sidebar %}
          {% include sidebar.html %}
      {% endif %}

        {{page.relative_path}}
        {% if site.use_github_wiki %}
          Edit
          History
          Source
        {% else %}
          Edit
          {% if site.use_prose_io %}
          Edit with Prose.io
          {% endif %}
          History
          Source
        {% endif %}

        {% if site.google_cse_token %}

          <gcse:search></gcse:search>
        {% else %}
          <form method="GET" action="{{ site.github.repository_url }}/search">
            {% if site.use_github_wiki %}
              <input type="hidden" name="type" value="Wikis">
            {% endif %}
            <input type="text" name="q" placeholder="Text to search"><input type="submit" value="Search">
          </form>
        {% endif %}

        {{ content }}

      {% if site.comments %}
          {% include comments.html %}
      {% endif %}

        {% if site.custom_footer %}
            {% include footer.html %}
        {% endif %}

        {% if site.github.is_project_page %}

This project is maintained by {{ site.github.owner_name }}

        {% endif %}

Hosted on GitHub Pages — Powered by Git-Wiki

        {% if site.github.is_project_page %}

View the Project on GitHub {{ github_name }}

        {% endif %}

    {% if site.google_analytics %}

    {% endif %}


text:
module RGallery
  autoload :Photos,       'rails-gallery/rgallery/photos'
  autoload :Pages,        'rails-gallery/rgallery/pages'
  autoload :Page,         'rails-gallery/rgallery/page'
  autoload :Photo,        'rails-gallery/rgallery/photo'
  autoload :PhotoConfig,  'rails-gallery/rgallery/photo_config'
end


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

        <meta content="text/html; charset=iso-8859-1" http-equiv="content-type">
        <title>Downslope index</title>
        <link rel="stylesheet" type="text/css" href="Help.css">

Downslope index

This tool can be used to calculate the downslope index described
            by Hjerdt et al. (2004). The downslope index is a measure of the
            slope gradient between a grid cell and some downslope location (along the
            flowpath passing through the upslope grid cell) that represents a specified
            vertical drop (i.e. a potential head drop). The index has been shown to be
            useful for hydrological, geomorphological, and biogeochemical applications.

The user must specify the name of a flow pointer grid derived using the
            D8 flow algorithm. This grid should be
            derived from a digital elevation model that has been pre-processed to remove
            artifact topographic depressions and flat areas. The user must also specify
            the name of the digital elevaton model (DEM) from which the flow pointer grid
            has been derived, the head potential drop (d), and the output type. The
            output type can be either 'tangent', 'degrees', 'radians', or 'distance'. If
            'distance' is selected as the output type, the output grid actually represents
            the downslope flowpath length required to drop d meters
            from each grid cell. Linear interpolation is used when the specified drop value
            is encountered between two adjacent grid cells along a flowpath traverse.

Notice that this algorithm is affected by edge contamination. That is, for
            some grid cells, the edge of the grid will be encountered along a flowpath
            traverse before the specified vertical drop occurs. In these cases, the
            value of the downslope index is approximated by replacing
            d with the actual elevation drop observed along the flowpath. To avoid
            this problem, the entire watershed containing an area of interest should be
            contained in the DEM.

Grid cells containing NoData values in any of the input images
            are assigned the NoData value in the output raster. The output
            raster is of the float data type and continuous data scale.

Reference:

Hjerdt, K.N., McDonnell, J.J., Seibert, J. Rodhe, A. (2004) A new topographic
            index to quantify downslope controls on local drainage, Water Resources
                Research, 40, W05602, doi:10.1029/2004WR003130.

See Also:

D8 flow algorithm

Scripting:

The following is an example of a Python script that uses this tool:

                wd = pluginHost.getWorkingDirectory()

                pointerFile = wd + "D8 pointer.dep"

                demFile = wd + "DEM.dep"

                outputFile = wd + "output.dep"

                verticalDrop = "10.0"

                outputType = "tangent"

                args = [pointerFile, demFile, outputFile, verticalDrop, outputType]

                pluginHost.runPlugin("DownslopeIndex", args, False)

This is a Groovy script also using this tool:

                def wd = pluginHost.getWorkingDirectory()

                def pointerFile = wd + "D8 pointer.dep"

                def demFile = wd + "DEM.dep"

                def outputFile = wd + "output.dep"

                def verticalDrop = "10.0"

                def outputType = "degrees"

                String[] args = [pointerFile, demFile, outputFile, verticalDrop, outputType]

                pluginHost.runPlugin("DownslopeIndex", args, false)

Credits:

John Lindsay (2013) email: jlindsay@uoguelph.ca


text:
package com.tlswe.awsmock.ec2.model;

import java.io.Serializable;
import java.util.Random;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeSet;
import java.util.UUID;

import com.tlswe.awsmock.common.exception.AwsMockException;
import com.tlswe.awsmock.common.util.Constants;
import com.tlswe.awsmock.common.util.PropertiesUtils;

/**
 * Generic class for mock ec2 instance, with basic simulation of behaviors and states of genuine ec2 instances' life
 * cycle. Any extra implementation of more customized ec2 mock instances should extend this class (and override the
 * events) and be defined as "ec2.instance.class" in aws-mock.properties (or if not overridden, as defined in
 * aws-mock-default.properties). To simulate actual ec2 instances, we have an internal timer in each object of mock ec2
 * instance that continuously check and set the states of it, within the life cycle of
 * start-pending-running-stopping-stopped-terminated for a single ec2 instance, and with random time deviations (e.g.
 * random boot/shutdown time within predefined values).
 *
 * @author xma
 *
 */
public abstract class AbstractMockEc2Instance implements Serializable {

    /**
     * Default serial version ID for this class which implements {@link Serializable}.
     *
     * @see Serializable
     */
    private static final long serialVersionUID = 1L;

    /**
     * Length of generated postfix of instance ID.
     */
    protected static final short INSTANCE_ID_POSTFIX_LENGTH = 7;

    /**
     * Prefix for generated random public dnsname.
     */
    protected static final String MOCK_PUBDNS_PREFIX = "mock-ec2-";

    /**
     * Postfix for generated random public dnsname.
     */
    protected static final String MOCK_PUBDNS_POSTFIX = ".amazon.com";

    /**
     * Enumeration of all allowed instance types.
     *
     * @author xma
     *
     */
    public static enum InstanceType {
        /**
         * t1.micro.
         */
        T1_MICRO("t1.micro"),
        /**
         * m1.small.
         */
        M1_SMALL("m1.small"),
        /**
         * m1.medium.
         */
        M1_MEDIUM("m1.medium"),
        /**
         * m1.large.
         */
        M1_LARGE("m1.large"),
        /**
         * m1.xlarge.
         */
        M1_XLARGE("m1.xlarge"),
        /**
         * m2.xlarge.
         */
        M2_XLARGE("m2.xlarge"),
        /**
         * m2.2xlarge.
         */
        M2_2XLARGE("m2.2xlarge"),
        /**
         * m2.4xlarge.
         */
        M2_4XLARGE("m2.4xlarge"),
        /**
         * c1.medium.
         */
        C1_MEDIUM("c1.medium"),
        /**
         * c1.xlarge.
         */
        C1_XLARGE("c1.xlarge"),
        /**
         * cc1.4xlarge.
         */
        CC1_4XLARGE("cc1.4xlarge"),
        /**
         * cc2.8xlarge.
         */
        CC2_8XLARGE("cc2.8xlarge"),
        /**
         * cg1.4xlarge.
         */
        CG1_4XLARGE("cg1.4xlarge"),
        /**
         * hi1.4xlarge.
         */
        HI1_4XLARGE("hi1.4xlarge");

        /**
         * Name of instacne type.
         */
        private String name;

        /**
         * Private constructor for the enums of instance types defined above.
         *
         * @param typeName
         *            name of instance type
         *
         */
        private InstanceType(final String typeName) {
            this.name = typeName;
        }

        /**
         * Get the instance type name.
         *
         * @return the instance type name of the enum.
         */
        public String getName() {
            return this.name;
        }

        /**
         * Tests if an instance type of the given name exists as among all the defined instance types.
         *
         * @param name
         *            instance type name
         * @return true for existing and false for not existing
         */
        public static boolean containsByName(final String name) {
            InstanceType[] values = InstanceType.values();
            for (InstanceType value : values) {
                if (value.getName().equals(name)) {
                    return true;
                }
            }
            return false;
        }

        /**
         * Get enum of an instance type of the given name exists as among all the defined instance types.
         *
         * @param name
         *            instance type name
         * @return object of instance type, null will be returned in case that not found
         */
        public static InstanceType getByName(final String name) {
            InstanceType[] values = InstanceType.values();
            for (InstanceType value : values) {
                if (value.getName().equals(name)) {
                    return value;
                }
            }
            return null;
        }

    }

    /**
     * Enumeration of all instance states.
     *
     * @author xma
     *
     */
    public static enum InstanceState {

        /**
         * pending.
         */
        PENDING(0, "pending"),
        /**
         * running.
         */
        RUNNING(16, "running"),
        /**
         * shutting-down.
         */
        SHUTTING_DOWN(32, "shutting-down"),
        /**
         * terminated.
         */
        TERMINATED(48, "terminated"),
        /**
         * stopping.
         */
        STOPPING(64, "stopping"),
        /**
         * stopped.
         */
        STOPPED(80, "stopped");

        /**
         * Code of instance state.
         */
        private int code;

        /**
         * Name of instance state.
         */
        private String name;

        /**
         * Private constructor for the enums of instance states defined above.
         *
         * @param stateCode
         *            code of instance state
         * @param stateName
         *            name of instance stateO
         */
        private InstanceState(final int stateCode, final String stateName) {
            this.code = stateCode;
            this.name = stateName;
        }

        /**
         * Get the instance state code.
         *
         * @return instance state code
         */
        public int getCode() {
            return code;
        }

        /**
         * Get the instance state name.
         *
         * @return instance state name
         */
        public String getName() {
            return name;
        }

    }

    /**
     * We define {@link Serializable} {@link Timer} here because all members in {@link AbstractMockEc2Instance} need to
     * be save to binary file as for persistence.
     *
     * @author xma
     *
     */
    public class SerializableTimer extends Timer implements Serializable {

        /**
         * Default serial version ID for this class which implements {@link Serializable}.
         *
         * @see Serializable
         */
        private static final long serialVersionUID = 1L;

        /**
         * Constructor from superclass.
         */
        public SerializableTimer() {
            super();
        }

        /**
         * Constructor from superclass.
         *
         * @param isDaemon
         *            true if the associated thread should run as a daemon
         */
        public SerializableTimer(final boolean isDaemon) {
            super(isDaemon);
        }

    }

    /**
     * Interval for the internal timer thread that triggered for state chacking and changing - we set it for 10 seconds.
     */
    public static final int TIMER_INTERVAL_MILLIS = 10 * 1000;

    /**
     * Utility random object for getting random numbers.
     */
    private static Random random = new Random();

    /**
     * Minimal boot time.
     */
    public static final long MIN_BOOT_TIME_MILLS = Integer
            .parseInt(PropertiesUtils
                    .getProperty(Constants.PROP_NAME_INSTANCE_MIN_BOOT_TIME_SECONDS)) * 1000L;

    /**
     * Maximum boot time.
     */
    protected static final long MAX_BOOT_TIME_MILLS = Integer
            .parseInt(PropertiesUtils
                    .getProperty(Constants.PROP_NAME_INSTANCE_MAX_BOOT_TIME_SECONDS)) * 1000L;

    /**
     * Minimal shutdown time.
     */
    protected static final long MIN_SHUTDOWN_TIME_MILLS = Integer
            .parseInt(PropertiesUtils
                    .getProperty(Constants.PROP_NAME_INSTANCE_MIN_SHUTDOWN_TIME_SECONDS)) * 1000L;

    /**
     * maximum shutdown time.
     */
    protected static final long MAX_SHUTDOWN_TIME_MILLS = Integer
            .parseInt(PropertiesUtils
                    .getProperty(Constants.PROP_NAME_INSTANCE_MAX_SHUTDOWN_TIME_SECONDS)) * 1000L;

    /**
     * instance ID, randomly assigned on creating.
     */
    private String instanceID = null;

    /**
     * AMI for this ec2 instance.
     */
    private String imageId = null;

    /**
     * Instance type, by default is "m1.small".
     */
    private InstanceType instanceType = InstanceType.M1_SMALL;

    /**
     * Security groups for this ec2 instance.
     */
    private Set<String> securityGroups = new TreeSet<String>();

    /**
     * Flag that indicates whether internal timer of this mock ec2 instance has been started (on instance start()).
     */
    private boolean internalTimerInitialized = false;

    /**
     * Flag that indicates whether this is ec2 instance is booting (pending).
     */
    private boolean booting = false;

    /**
     * Flag that indicates whether this is ec2 instance is running (started).
     */
    private boolean running = false;

    /**
     * Flag that indicates whether this is ec2 instance is stopping (shutting-down).
     */
    private boolean stopping = false;

    /**
     * Flag that indicates whether this is ec2 instance is terminated.
     */
    private boolean terminated = false;

    /**
     * Randomly assigned public dns name for this ec2 instance (dns name is assigned each time instance is started).
     */
    private String pubDns = null;

    /**
     * Internal timer for simulating the behaviors and states of this mock ec2 instance.
     */
    private SerializableTimer timer = null;

    /**
     * On constructing, an instance ID is assigned.
     */
    public AbstractMockEc2Instance() {
        if (null == this.instanceID) {
            this.instanceID = "i-"
                    + UUID.randomUUID().toString()
                            .substring(0, INSTANCE_ID_POSTFIX_LENGTH);
        }
    }

    /**
     * Get ID of this mock ec2 instance.
     *
     * @return ID of this mock ec2 instance
     */
    public final String getInstanceID() {
        return instanceID;
    }

    /**
     * Test if this mock ec2 instance is during booting phase (pending).
     *
     * @return this mock ec2 instance is booting or not
     */
    public final boolean isBooting() {
        return booting;
    }

    /**
     * Test if this mock ec2 instance is running (started/power-on).
     *
     * @return this mock ec2 instance is running or not
     */
    public final boolean isRunning() {
        return running;
    }

    /**
     * Get public DNS of this mock ec2 instance.
     *
     * @return public DNS of this mock ec2 instance
     */
    public final String getPubDns() {
        return pubDns;
    }

    /**
     * Test if this mock ec2 instance is during stopping phase.
     *
     * @return this mock ec2 instance is stopping or not
     */
    public final boolean isStopping() {
        return stopping;
    }

    /**
     * Test if this mock ec2 instance is terminated.
     *
     * @return this mock ec2 instance is terminated or not
     */
    public final boolean isTerminated() {
        return terminated;
    }

    /**
     * Start scheduling the internal timer that controls the behaviors and states of this mock ec2 instance.
     */
    public final void initializeInternalTimer() {
        // if it is the first the instance is started, we initialize the
        // internal timer thread
        if (!internalTimerInitialized) {

            TimerTask internalTimerTask = new TimerTask() {

                /**
                 * this method is triggered every TIMER_INTERVAL_MILLIS
                 */
                @Override
                public void run() {

                    if (terminated) {
                        running = false;
                        booting = false;
                        stopping = false;
                        pubDns = null;
                        this.cancel();
                        onTerminated();
                        return;
                    }

                    if (running) {

                        if (booting) {

                            // delay a random 'boot time'
                            try {
                                Thread.sleep(MIN_BOOT_TIME_MILLS
                                        + random.nextInt((int) (MAX_BOOT_TIME_MILLS - MIN_BOOT_TIME_MILLS)));
                            } catch (InterruptedException e) {
                                throw new AwsMockException(
                                        "InterruptedException caught when delaying a mock random 'boot time'",
                                        e);
                            }

                            // booted, assign a mock pub dns name
                            pubDns = generatePubDns();

                            booting = false;

                            onBooted();

                        } else if (stopping) {

                            // delay a random 'shutdown time'
                            try {
                                Thread.sleep(MIN_SHUTDOWN_TIME_MILLS
                                        + random.nextInt((int) (MAX_SHUTDOWN_TIME_MILLS
                                                - MIN_SHUTDOWN_TIME_MILLS)));
                            } catch (InterruptedException e) {
                                throw new AwsMockException(
                                        "InterruptedException caught when delaying a mock random 'shutdown time'",
                                        e);
                            }

                            // unset pub dns name
                            pubDns = null;

                            stopping = false;

                            running = false;

                            onStopped();

                        }

                        onInternalTimer();

                    }

                }
            };
            timer = new SerializableTimer(true);
            timer.schedule(internalTimerTask, 0L, TIMER_INTERVAL_MILLIS);

            internalTimerInitialized = true;
        }
    }

    /**
     * Cancel the internal timer of this mock ec2 instance so that it stops its lifecycle-emulation.
     */
    public final void destroyInternalTimer() {
        timer.cancel();
        timer = null;
        internalTimerInitialized = false;
    }

    /**
     * Start a stopped mock ec2 instance.
     *
     * @return true for successfully started and false for nothing changed by this action
     */
    public final boolean start() {

        if (running || booting || stopping || terminated) {
            // do nothing if this instance is not stopped
            return false;
        } else {
            // mark this instance started
            booting = true;
            running = true;

            onStarted();

            return true;
        }
    }

    /**
     * Stop this ec2 instance.
     *
     * @return true for successfully turned into 'stopping' and false for nothing changed
     */
    public final boolean stop() {

        if (booting || running) {
            stopping = true;
            booting = false;
            onStopping();
            return true;
        } else {
            return false;
        }

    }

    /**
     * Terminate this ec2 instance.
     *
     * @return true for successfully terminated and false for nothing changed
     */
    public final boolean terminate() {

        if (!terminated) {
            onTerminating();
            terminated = true;
            return true;
        } else {
            return false;
        }

    }

    /**
     * Get state of this mock ec2 instance.
     *
     * @return state of this mock ec2 instance, should be one of the instance states defined in {@link InstanceState}
     */
    public final InstanceState getInstanceState() {
        return isTerminated() ? InstanceState.TERMINATED
                : (isBooting() ? InstanceState.PENDING
                        : (isStopping() ? InstanceState.STOPPING
                                : (isRunning() ? InstanceState.RUNNING
                                        : InstanceState.STOPPED)));
    }

    /**
     * Get the AMI this mock ec2 instance started from.
     *
     * @return the AMI
     */
    public final String getImageId() {
        return imageId;
    }

    /**
     * Set the AMI this mock ec2 instance starts from.
     *
     * @param newImageID
     *            the AMI
     */
    public final void setImageId(final String newImageID) {
        this.imageId = newImageID;
    }

    /**
     * Get type of this mock ec2 instance.
     *
     * @return type of this mock ec2 instance
     */
    public final InstanceType getInstanceType() {
        return instanceType;
    }

    /**
     * Set type of this mock ec2 instance.
     *
     * @param newInstanceType
     *            type of this mock ec2 instance, should be one of the instance types defined in {@link InstanceType}
     */
    public final void setInstanceType(final InstanceType newInstanceType) {
        this.instanceType = newInstanceType;
    }

    /**
     * Get the security groups used by this mock ec2 instance.
     *
     * @return a list of security groups
     */
    public final Set<String> getSecurityGroups() {
        return securityGroups;
    }

    /**
     * Get the security groups used by this mock ec2 instance.
     *
     * @param newSecurityGroups
     *            a list of security groups
     */
    public final void setSecurityGroups(final Set<String> newSecurityGroups) {
        if (null != newSecurityGroups) {
            this.securityGroups = newSecurityGroups;
        }
    }

    /**
     * Generate a random public dns name for a mock EC2 instance.
     *
     * @return a random public dns name
     */
    private String generatePubDns() {

        return MOCK_PUBDNS_PREFIX
                + UUID.randomUUID().toString()
                        .toLowerCase() + MOCK_PUBDNS_POSTFIX;
    }

    /**
     * Triggered right after the 'instance' is 'powered-on'.
     */
    public abstract void onStarted();

    /**
     * Triggered after the 'instance' boots into 'OS'.
     */
    public abstract void onBooted();

    /**
     * Triggered on 'instance' entering the process of shutdown.
     */
    public abstract void onStopping();

    /**
     * Triggered right after the 'instance' is 'powered-off'.
     */
    public abstract void onStopped();

    /**
     * Triggered on 'instance' entering the process of termination.
     */
    public abstract void onTerminating();

    /**
     * Triggered right after the 'instance' is terminated.
     */
    public abstract void onTerminated();

    /**
     * Triggered on arriving interval of the internal timer of mock ec2 instance. <br>
     * Note that if this method does things that take a long time, the interval would be prolonged and consequent
     * events/state changing would always be delayed.
     *
     * @see #TIMER_INTERVAL_MILLIS
     */
    public abstract void onInternalTimer();

}


text:
import os

print(os.system('ls .'))

fname = 'helloshell.py'

print(os.system('file %s' % fname ))
print(open(fname).read())
print(os.popen('ls .').readlines())
print(os.popen('python3 helloshell.py').read())


text:
import { IResponse, IContext } from '../../types';

export interface IDeleteNodeApiRequest {
  kubernetes_cluster_id: string;
  node_pool_id: string;
  node_id: string;
  drain_node?: boolean;
  replace_node?: boolean;
}

export type DeleteNodeResponse = IResponse<void>;

export const deleteNode = ({
  httpClient,
}: IContext) => ({
  kubernetes_cluster_id,
  node_pool_id,
  node_id,
  drain_node = true,
  replace_node = false,
}: IDeleteNodeApiRequest): Promise<Readonly<DeleteNodeResponse>> => {
  const path = '/kubernetes/clusters';
  const url = `${path}/${kubernetes_cluster_id}/node_pools/${node_pool_id}/nodes/${node_id}`;
  const query_params = {
    replace: replace_node ? 1 : 0,
    skip_drain: drain_node ? 0 : 1,
  };

  return httpClient.delete(url, {params: query_params});
};


text:
layout: post
title: How to set-up GIT for Mac Os?
author: FX
---

At the heart of GitHub is an open source version control system (VCS) called [Git](https://git-scm.com/). Git is responsible for everything GitHub-related that happens locally on your computer.

To use Git on the command line, you'll need to download, install, and configure Git on your computer. [Homebrew](https://brew.sh/) is the missing packages manager for MacOS. I'll assume that you have it installed and running on your computer. If not just head over to their website and follow the installation instructions.

The first step is to install GIT locally.

Enter the following command:

```brew install git```

In order to maximise security it is highly recommended to connect either through the HTTPS method or via SSH.

If you have enabled double factor authentication it might be difficult to configure. In that case use the SSH config.

After you've checked for existing SSH keys, you can generate a new SSH key to use for authentication, then add it to the ssh-agent and to your Git account.


text:
var P = require('fstream').DirReader
var tar = require('tar')
function f (entry) {
  return entry.basename !== '.git'
}

new P({ path: './', type: 'Directory', Directory: true, filter: f })
  .on('package', function (p) {
    console.error('package', p)
  })
  .on('ignoreFile', function (e) {
    console.error('ignoreFile', e)
  })
  .on('entry', function (e) {
    console.error(e.constructor.name, e.path.substr(e.root.path.length + 1))
  })
  .pipe(tar.Pack())
  .pipe(process.stdout)


text:
package org.ry8.external.activeandroid.content;

import android.app.Application;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.util.SparseArray;
import org.ry8.external.activeandroid.ActiveAndroid;
import org.ry8.external.activeandroid.Cache;
import org.ry8.external.activeandroid.Model;
import org.ry8.external.activeandroid.TableInfo;

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

public class ContentProvider extends android.content.ContentProvider {
	//////////////////////////////////////////////////////////////////////////////////////
	// PRIVATE CONSTANTS
	//////////////////////////////////////////////////////////////////////////////////////

	private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
	private static final SparseArray<Class<? extends Model>> TYPE_CODES = new SparseArray<Class<? extends Model>>();

	//////////////////////////////////////////////////////////////////////////////////////
	// PRIVATE MEMBERS
	//////////////////////////////////////////////////////////////////////////////////////

	private String mAuthority;

	//////////////////////////////////////////////////////////////////////////////////////
	// PUBLIC METHODS
	//////////////////////////////////////////////////////////////////////////////////////

	@Override
	public boolean onCreate() {
	    mAuthority = getContext().getPackageName();
		ActiveAndroid.initialize((Application) getContext().getApplicationContext());

		List<TableInfo> tableInfos = new ArrayList<TableInfo>(Cache.getTableInfos());
		for (int i = 0; i < tableInfos.size(); i++) {
			TableInfo tableInfo = tableInfos.get(i);

			URI_MATCHER.addURI(mAuthority, tableInfo.getTableName().toLowerCase(), i);
			TYPE_CODES.put(i, tableInfo.getType());
		}

		return true;
	}

	@Override
	public String getType(Uri uri) {
		return null;
	}

	// SQLite methods

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		Class<? extends Model> type = getModelType(uri);
		Long id = Cache.openDatabase().insert(Cache.getTableName(type), null, values);

		if (id != null && id > 0) {
			Uri retUri = createUri(type, id);
			notifyChange(retUri);

			return retUri;
		}

		return null;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		Class<? extends Model> type = getModelType(uri);
		int count = Cache.openDatabase().update(Cache.getTableName(type), values, selection, selectionArgs);

		notifyChange(uri);

		return count;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		Class<? extends Model> type = getModelType(uri);
		int count = Cache.openDatabase().delete(Cache.getTableName(type), selection, selectionArgs);

		notifyChange(uri);

		return count;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		Class<? extends Model> type = getModelType(uri);
		return Cache.openDatabase().query(Cache.getTableName(type), projection, selection, selectionArgs, null, null,
				sortOrder);
	}

	//////////////////////////////////////////////////////////////////////////////////////
	// PRIVATE METHODS
	//////////////////////////////////////////////////////////////////////////////////////

	private Class<? extends Model> getModelType(Uri uri) {
		int code = URI_MATCHER.match(uri);
		if (code != UriMatcher.NO_MATCH) {
			return TYPE_CODES.get(code);
		}

		return null;
	}

	private Uri createUri(Class<? extends Model> type, Long id) {
		return Uri.parse("content://" + mAuthority + "/" + Cache.getTableName(type).toLowerCase() + "/" + id);
	}

	private void notifyChange(Uri uri) {
		getContext().getContentResolver().notifyChange(uri, null);
	}
}


text:
title: django.contrib.auth.hashers make_password Python Code Examples
category: page
slug: django-contrib-auth-hashers-make-password-examples
sortorder: 500012210
toc: False
sidebartitle: django.contrib.auth.hashers make_password
meta: Python code examples for the Django function make_password from the django.contrib.auth.hashers module.

[Django](/django.html)'s
[make_password](https://docs.djangoproject.com/en/dev/topics/auth/passwords/#django.contrib.auth.hashers.make_password)
([source code](https://github.com/django/django/blob/master/django/contrib/auth/hashers.py))
function converts a plain-text password into a hash that is appropriate
for storing in a [persistent database](/databases.html).

You definitely do not want to try to roll your own encryption and hashing
functions for storing passwords when this function already exists.

## Example 1 from gadget-board
[gadget-board](https://github.com/mik4el/gadget-board) is a
[Django](/django.html),
[Django REST Framework (DRF)](/django-rest-framework-drf.html) and
[Angular](/angular.html) web application that is open source under the
[Apache2 license](https://github.com/mik4el/gadget-board/blob/master/LICENSE).

[**gadget-board / web / authentication / views.py**](https://github.com/mik4el/gadget-board/blob/master/web/authentication/views.py)

```python
from rest_framework import permissions, viewsets, status
from rest_framework.response import Response
from rest_framework_jwt.settings import api_settings
~~from django.contrib.auth.hashers import make_password

from .models import Account
from .permissions import IsAccountOwner
from .serializers import AccountSerializer

class AccountViewSet(viewsets.ModelViewSet):
    lookup_field = 'username'
    queryset = Account.objects.all()
    serializer_class = AccountSerializer

    def get_permissions(self):
        if self.request.method in permissions.SAFE_METHODS:
            # only logged in users can see accounts
            return (permissions.IsAuthenticated(),)

        if self.request.method == 'POST':
            return (permissions.AllowAny(),)

        return (permissions.IsAuthenticated(), IsAccountOwner(),)

    def create(self, request):
        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():
            if 'password' not in serializer.validated_data:
                return Response({
                    'error': 'Password required for creating account.'
                }, status=status.HTTP_400_BAD_REQUEST)

            account = Account.objects.\
                create_account(**serializer.validated_data)

            # add JWT token to response
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

            payload = jwt_payload_handler(account)
            token = jwt_encode_handler(payload)

            serializer.validated_data['token'] = token

            return Response(serializer.validated_data,
                            status=status.HTTP_201_CREATED)

        return Response({
            'error': 'Account could not be created with received data.'
        }, status=status.HTTP_400_BAD_REQUEST)

    def perform_create(self, serializer):
        # Hash password but passwords are not required
        if ('password' in self.request.data):
~~            password = make_password(self.request.data['password'])
            serializer.save(password=password)
        else:
            serializer.save()

    def perform_update(self, serializer):
        # Hash password but passwords are not required
        if ('password' in self.request.data):
~~            password = make_password(self.request.data['password'])
            serializer.save(password=password)
        else:
            serializer.save()
```


text:
module Ardes
  module ResourcesController
    # extension for any module that is used as an Actions module.
    #
    # After extending the module (say 'MyActions'), instead of doing this:
    #   self.include ActionsModule
    # do this:
    #   ActionsModule.include_actions(self, <:only or :except options>)
    #
    # RC extends any actions module with this automatically, so you don't need to know about it.
    #
    # However, if you ahve any special behaviour in your actions module that is sensitive to
    # :only and :except, you can define your own include_actions method on that module
    # to effect this special behaviour.
    module IncludeActions
      def include_actions(controller, options = {})
        options.assert_valid_keys(:only, :except)
        raise ArgumentError, "you can only specify either :except or :only, not both" if options[:only] && options[:except]
        mixin = self.clone
        action_methods_to_remove(options).each {|a| mixin.remove_action_method(a) }
        controller.send :include, mixin
      end

      def remove_action_method(action)
        undef_method action
      end

      def action_methods_to_remove(options = {})
        if options[:only]
          instance_methods - Array(options[:only]).map(&:to_s)
        elsif options[:except]
          Array(options[:except]).map(&:to_s) & instance_methods
        else
          []
        end
      end
    end
  end
end


text:
package me.aymen.castle;

import java.io.IOException;
import me.aymen.castle.role.SuperRole;
import me.aymen.castle.user.Users;

/**
 * Represents a library for Authentication and Authorization
 * @author Aymen Alquaiti
 * @Date 30/08/2014
 */
public interface Castle
{
    /**
     * Provides access to Users repository
     * @return Users object
     */
    public Users Users();

    /**
     * Provides access to SuperRole
     * @return SuperRole object
     */
    public SuperRole Roles();

    /**
     * Commits or save changes to Castle System
     * @throws IOException if commit failed
     */
    public void commit() throws IOException;

    /**
     * Set Implementation dependent options to be considered when committing
     * @param options Committing options
     */
    public void setOptions(String options);

    /**
     * Retrieve Implementation dependent committing options
     * @return String of committing options
     */
    public String getOptions();
}


text:
<?php

namespace Google\Service\Integrations;

class GoogleCloudConnectorsV1ConnectionStatus extends \Google\Model
{
  /**
   * @var string
   */
  public $description;
  /**
   * @var string
   */
  public $state;
  /**
   * @var string
   */
  public $status;

  /**
   * @param string
   */
  public function setDescription($description)
  {
    $this->description = $description;
  }
  /**
   * @return string
   */
  public function getDescription()
  {
    return $this->description;
  }
  /**
   * @param string
   */
  public function setState($state)
  {
    $this->state = $state;
  }
  /**
   * @return string
   */
  public function getState()
  {
    return $this->state;
  }
  /**
   * @param string
   */
  public function setStatus($status)
  {
    $this->status = $status;
  }
  /**
   * @return string
   */
  public function getStatus()
  {
    return $this->status;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudConnectorsV1ConnectionStatus::class, 'Google_Service_Integrations_GoogleCloudConnectorsV1ConnectionStatus');


text:
package eu.leads.processor.core;

/**
 * Created by vagvaz on 8/6/14.
 */
public enum ActionCategory {
  REQUEST, ACTION, OPERATOR
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using ServiceStack.Common.Utils;
using ServiceStack.Common.Web;
using ServiceStack.Logging;
using ServiceStack.ServiceHost;
using ServiceStack.Text;

namespace ServiceStack.WebHost.Endpoints.Extensions
{
	/**
	 *
		 Input: http://localhost:96/Cambia3/Temp/Test.aspx/path/info?q=item#fragment

		Some HttpRequest path and URL properties:
		Request.ApplicationPath:	/Cambia3
		Request.CurrentExecutionFilePath:	/Cambia3/Temp/Test.aspx
		Request.FilePath:			/Cambia3/Temp/Test.aspx
		Request.Path:				/Cambia3/Temp/Test.aspx/path/info
		Request.PathInfo:			/path/info
		Request.PhysicalApplicationPath:	D:\Inetpub\wwwroot\CambiaWeb\Cambia3\
		Request.QueryString:		/Cambia3/Temp/Test.aspx/path/info?query=arg
		Request.Url.AbsolutePath:	/Cambia3/Temp/Test.aspx/path/info
		Request.Url.AbsoluteUri:	http://localhost:96/Cambia3/Temp/Test.aspx/path/info?query=arg
		Request.Url.Fragment:
		Request.Url.Host:			localhost
		Request.Url.LocalPath:		/Cambia3/Temp/Test.aspx/path/info
		Request.Url.PathAndQuery:	/Cambia3/Temp/Test.aspx/path/info?query=arg
		Request.Url.Port:			96
		Request.Url.Query:			?query=arg
		Request.Url.Scheme:			http
		Request.Url.Segments:		/
									Cambia3/
									Temp/
									Test.aspx/
									path/
									info
	 * */
	public static class HttpRequestExtensions
	{
		private static readonly ILog Log = LogManager.GetLogger(typeof(HttpRequestExtensions));

		private static string WebHostDirectoryName = "";

		static HttpRequestExtensions()
		{
			WebHostDirectoryName = Path.GetFileName("~".MapHostAbsolutePath());
		}

		public static string GetOperationName(this HttpRequest request)
		{
			var pathInfo = request.GetLastPathInfo();
			return GetOperationNameFromLastPathInfo(pathInfo);
		}

		public static string GetOperationNameFromLastPathInfo(string lastPathInfo)
		{
			if (string.IsNullOrEmpty(lastPathInfo)) return null;

			var operationName = lastPathInfo.Substring("/".Length);

			return operationName;
		}

		private static string GetLastPathInfoFromRawUrl(string rawUrl)
		{
			var pathInfo = rawUrl.IndexOf("?") != -1
				? rawUrl.Substring(0, rawUrl.IndexOf("?"))
				: rawUrl;

			pathInfo = pathInfo.Substring(pathInfo.LastIndexOf("/"));

			return pathInfo;
		}

		public static string GetLastPathInfo(this HttpRequest request)
		{
			var pathInfo = request.PathInfo;
			if (string.IsNullOrEmpty(pathInfo))
			{
				pathInfo = GetLastPathInfoFromRawUrl(request.RawUrl);
			}

			//Log.DebugFormat("Request.PathInfo: {0}, Request.RawUrl: {1}, pathInfo:{2}",
			//    request.PathInfo, request.RawUrl, pathInfo);

			return pathInfo;
		}

		public static string GetUrlHostName(this HttpRequest request)
		{
			//TODO: Fix bug in mono fastcgi, when trying to get 'Request.Url.Host'
			try
			{
				return request.Url.Host;
			}
			catch (Exception ex)
			{
				Log.ErrorFormat("Error trying to get 'Request.Url.Host'", ex);

				return request.UserHostName;
			}
		}

		// http://localhost/ServiceStack.Examples.Host.Web/Public/Public/Soap12/Wsdl =>
		// http://localhost/ServiceStack.Examples.Host.Web/Public/Soap12/
		public static string GetParentBaseUrl(this HttpRequest request)
		{
			var rawUrl = request.RawUrl; // /Cambia3/Temp/Test.aspx/path/info
			var endpointsPath = rawUrl.Substring(0, rawUrl.LastIndexOf('/') + 1);  // /Cambia3/Temp/Test.aspx/path
			return GetAuthority(request) + endpointsPath;
		}

		public static string GetBaseUrl(this HttpRequest request)
		{
			return GetAuthority(request) + request.RawUrl;
		}

		//=> http://localhost:96 ?? ex=> http://localhost
		private static string GetAuthority(HttpRequest request)
		{
			try
			{
				return request.Url.GetLeftPart(UriPartial.Authority);
			}
			catch (Exception ex)
			{
				Log.Error("Error trying to get: request.Url.GetLeftPart(UriPartial.Authority): " + ex.Message, ex);
				return "http://" + request.UserHostName;
			}
		}

		public static string GetOperationName(this HttpListenerRequest request)
		{
			return request.Url.Segments[request.Url.Segments.Length - 1];
		}

		public static string GetLastPathInfo(this HttpListenerRequest request)
		{
			return GetLastPathInfoFromRawUrl(request.RawUrl);
		}

		public static string GetPathInfo(this HttpRequest request)
		{
			if (!string.IsNullOrEmpty(request.PathInfo)) return request.PathInfo.TrimEnd('/');

			var mode = EndpointHost.Config.ServiceStackHandlerFactoryPath;
			var appPath = string.IsNullOrEmpty(request.ApplicationPath)
			              ? WebHostDirectoryName
			              : request.ApplicationPath.TrimStart('/');

			//mod_mono: /CustomPath35/api//default.htm
			var path = Env.IsMono ? request.Path.Replace("//", "/") : request.Path;
			return GetPathInfo(path, mode, appPath);
		}

		public static string GetPathInfo(string fullPath, string mode, string appPath)
		{
			var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
			if (!string.IsNullOrEmpty(pathInfo)) return pathInfo;

			//Wildcard mode relies on this to find work out the handlerPath
			pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
			if (!string.IsNullOrEmpty(pathInfo)) return pathInfo;

			return fullPath;
		}

		public static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
		{
			var sbPathInfo = new StringBuilder();
			var fullPathParts = fullPath.Split('/');
			var pathRootFound = false;
			foreach (var fullPathPart in fullPathParts)
			{
				if (pathRootFound)
				{
					sbPathInfo.Append("/" + fullPathPart);
				}
				else
				{
					pathRootFound = string.Equals(fullPathPart, mappedPathRoot, StringComparison.InvariantCultureIgnoreCase);
				}
			}
			if (!pathRootFound) return null;

			var path = sbPathInfo.ToString();
			return path.Length > 1 ? path.TrimEnd('/') : "/";
		}

		public static bool IsContentType(this IHttpRequest request, string contentType)
		{
			return request.ContentType.StartsWith(contentType, StringComparison.InvariantCultureIgnoreCase);
		}

		public static bool HasAnyOfContentTypes(this IHttpRequest request, params string[] contentTypes)
		{
			if (contentTypes == null || request.ContentType == null) return false;
			foreach (var contentType in contentTypes)
			{
				if (IsContentType(request, contentType)) return true;
			}
			return false;
		}

		public static IHttpRequest GetHttpRequest(this HttpRequest request)
		{
			return new HttpRequestWrapper(null, request);
		}

		public static IHttpRequest GetHttpRequest(this HttpListenerRequest request)
		{
			return new HttpListenerRequestWrapper(null, request);
		}

		public static Dictionary<string, string> GetRequestParams(this IHttpRequest request)
		{
			var map = new Dictionary<string, string>();

			foreach (var name in request.QueryString.AllKeys)
			{
				if (name == null) continue; //thank you ASP.NET
				map[name] = request.QueryString[name];
			}

			if ((request.HttpMethod == HttpMethods.Post || request.HttpMethod == HttpMethods.Put)
				&& request.FormData != null)
			{
				foreach (var name in request.FormData.AllKeys)
				{
					if (name == null) continue; //thank you ASP.NET
					map[name] = request.FormData[name];
				}
			}

			return map;
		}

		public static string GetQueryStringContentType(this IHttpRequest httpReq)
		{
			var callback = httpReq.QueryString["callback"];
			if (!string.IsNullOrEmpty(callback)) return ContentType.Json;

			var format = httpReq.QueryString["format"];
			if (format == null)
			{
				const int formatMaxLength = 4;
				var pi = httpReq.PathInfo;
				if (pi == null || pi.Length <= formatMaxLength) return null;
				if (pi[0] == '/') pi = pi.Substring(1);
				format = pi.SplitOnFirst('/')[0];
				if (format.Length > formatMaxLength) return null;
			}

			format = format.SplitOnFirst('.')[0].ToLower();
			if (format.Contains("json")) return ContentType.Json;
			if (format.Contains("xml")) return ContentType.Xml;
			if (format.Contains("jsv")) return ContentType.Jsv;

			string contentType;
			EndpointHost.ContentTypeFilter.ContentTypeFormats.TryGetValue(format, out contentType);

			return contentType;
		}

		public static string[] PreferredContentTypes = new[] {
			ContentType.Html, ContentType.Json, ContentType.Xml, ContentType.Jsv
		};

		/// <summary>
		/// Use this to treat Request.Items[] as a cache by returning pre-computed items to save
		/// calculating them multiple times.
		/// </summary>
		public static object ResolveItem(this IHttpRequest httpReq,
			string itemKey, Func<IHttpRequest, object> resolveFn)
		{
			object cachedItem;
			if (httpReq.Items.TryGetValue(itemKey, out cachedItem))
				return cachedItem;

			var item = resolveFn(httpReq);
			httpReq.Items[itemKey] = item;

			return item;
		}

		public static string GetResponseContentType(this IHttpRequest httpReq)
		{
			var specifiedContentType = GetQueryStringContentType(httpReq);
			if (!string.IsNullOrEmpty(specifiedContentType)) return specifiedContentType;

			var acceptContentTypes = httpReq.AcceptTypes;
			var defaultContentType = httpReq.ContentType;
			if (httpReq.HasAnyOfContentTypes(ContentType.FormUrlEncoded, ContentType.MultiPartFormData))
			{
				defaultContentType = EndpointHost.Config.DefaultContentType;
			}

			var customContentTypes = EndpointHost.ContentTypeFilter.ContentTypeFormats.Values;

			var acceptsAnything = false;
			var hasDefaultContentType = !string.IsNullOrEmpty(defaultContentType);
			if (acceptContentTypes != null)
			{
				var hasPreferredContentTypes = new bool[PreferredContentTypes.Length];
				foreach (var contentType in acceptContentTypes)
				{
					acceptsAnything = acceptsAnything || contentType == "*/*";

					for (var i = 0; i < PreferredContentTypes.Length; i++)
					{
						if (hasPreferredContentTypes[i]) continue;
						var preferredContentType = PreferredContentTypes[i];
						hasPreferredContentTypes[i] = contentType.StartsWith(preferredContentType);

						//Prefer Request.ContentType if it is also a preferredContentType
						if (hasPreferredContentTypes[i] && preferredContentType == defaultContentType)
							return preferredContentType;
					}
				}
				for (var i = 0; i < PreferredContentTypes.Length; i++)
				{
					if (hasPreferredContentTypes[i]) return PreferredContentTypes[i];
				}
				if (acceptsAnything && hasDefaultContentType) return defaultContentType;

				foreach (var contentType in acceptContentTypes)
				{
					foreach (var customContentType in customContentTypes)
					{
						if (contentType.StartsWith(customContentType)) return customContentType;
					}
				}
			}

			//We could also send a '406 Not Acceptable', but this is allowed also
			return EndpointHost.Config.DefaultContentType;
		}

	}

}


text:
import logging
import telegram
import random
import json
from giphypop import translate

with open('quotes.json') as data_file:
	quotes = json.load(data_file)
	rick = quotes["Rick"]
	morty = quotes["Morty"]
	beth = quotes["Beth"]
	jerry = quotes["Jerry"]
	summer = quotes["Summer"]
	extra = quotes["Extra"]

def main():
    logging.basicConfig(
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    bot = telegram.Bot(token='HERE GOES THE TOKEN!')

    try:
        LAST_UPDATE_ID = bot.getUpdates()[-1].update_id
    except IndexError:
        LAST_UPDATE_ID = None

    while True:
        for update in bot.getUpdates(offset=LAST_UPDATE_ID, timeout=5):
            text = update.message.text
            chat_id = update.message.chat.id
            update_id = update.update_id

            if '/start' in text:
                custom_keyboard = [["/quote", "/gif"]]
                reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard, resize_keyboard=True)
                bot.sendMessage(chat_id=chat_id,
                                text="I'm Mr. Meeseeks! Look at me!!",
                                reply_markup=reply_markup)
                LAST_UPDATE_ID = update_id + 1

            elif '/quote' in text:
                answer = quote()
                bot.sendMessage(chat_id=chat_id,
                                text=answer)
                LAST_UPDATE_ID = update_id + 1

            elif '/gif' in text:
                bot.sendMessage(chat_id=chat_id,
                                text="Ooohhh can do. ")
                img = translate('rick and morty')
                bot.sendDocument(chat_id=chat_id,
                                 document=img.fixed_height.url)
                print "Enviar Gif " + img.fixed_height.url
                LAST_UPDATE_ID = update_id + 1

def quote():
	character = random.randint(0, 5)

	if character == 0:
		return "Rick: " + random.choice(rick)
	elif character == 1:
		return "Morty: "  + random.choice(morty)
	elif character == 2:
		return "Beth: "  + random.choice(beth)
	elif character == 3:
		return "Jerry: "  + random.choice(jerry)
	elif character == 4:
		return "Summer: "  + random.choice(summer)
	else:
		return random.choice(extra)

if __name__ == '__main__':
    main()


text:
package mocks

import apperrors "github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors"

import mock "github.com/stretchr/testify/mock"
import model "github.com/kyma-project/kyma/components/central-application-gateway/internal/metadata/model"

// ServiceDefinitionService is an autogenerated mock type for the ServiceDefinitionService type
type ServiceDefinitionService struct {
	mock.Mock
}

// GetAPIByEntryName provides a mock function with given fields: appName, serviceName, entryName
func (_m *ServiceDefinitionService) GetAPIByEntryName(appName string, serviceName string, entryName string) (*model.API, apperrors.AppError) {
	ret := _m.Called(appName, serviceName, entryName)

	var r0 *model.API
	if rf, ok := ret.Get(0).(func(string, string, string) *model.API); ok {
		r0 = rf(appName, serviceName, entryName)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.API)
		}
	}

	var r1 apperrors.AppError
	if rf, ok := ret.Get(1).(func(string, string, string) apperrors.AppError); ok {
		r1 = rf(appName, serviceName, entryName)
	} else {
		if ret.Get(1) != nil {
			r1 = ret.Get(1).(apperrors.AppError)
		}
	}

	return r0, r1
}

// GetAPIByServiceName provides a mock function with given fields: appName, serviceName
func (_m *ServiceDefinitionService) GetAPIByServiceName(appName string, serviceName string) (*model.API, apperrors.AppError) {
	ret := _m.Called(appName, serviceName)

	var r0 *model.API
	if rf, ok := ret.Get(0).(func(string, string) *model.API); ok {
		r0 = rf(appName, serviceName)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.API)
		}
	}

	var r1 apperrors.AppError
	if rf, ok := ret.Get(1).(func(string, string) apperrors.AppError); ok {
		r1 = rf(appName, serviceName)
	} else {
		if ret.Get(1) != nil {
			r1 = ret.Get(1).(apperrors.AppError)
		}
	}

	return r0, r1
}


text:
namespace scm {
namespace gl {
namespace wm {
namespace util {

inline
std::string win32_error_message()
{
    char* error_msg;

    if (0 == FormatMessage(    FORMAT_MESSAGE_IGNORE_INSERTS
                             | FORMAT_MESSAGE_FROM_SYSTEM
                             | FORMAT_MESSAGE_ALLOCATE_BUFFER,
                             0,
                             GetLastError(),
                             MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                             (LPTSTR)&error_msg,
                             0,
                             0)) {
        return (std::string("FormatMessage failed (" + boost::lexical_cast<std::string>(GetLastError())));
    }

    std::string msg(error_msg);
    LocalFree(error_msg);

    return (msg);
}

} // namespace util
} // namespace wm
} // namepspace gl
} // namepspace scm

#endif // SCM_PLATFORM == SCM_PLATFORM_WINDOWS
#endif // SCM_GL_CORE_WM_WIN32_ERROR_WIN32_H_INCLUDED


text:
from __future__ import division, print_function, absolute_import
from collections import defaultdict, namedtuple
import json
import sqlite3
from contextlib import contextmanager

class Transaction(object):
    def __init__(self, connection):
        self.connection = connection
        self.cursor = self.connection.cursor()

    def __enter__(self):
        return self.cursor

    def __exit__(self, *args, **kwargs):
        try:
            self.connection.commit()
        except:
            self.connection.rollback()
            raise

EventEntry = namedtuple('EventEntry', ['timestamp', 'event_id'])

class Database(object):
    tablenames = ['address', 'host', 'event']

    def __init__(self, dbname):
        self.dbname = dbname
        self.connection = sqlite3.connect(self.dbname)

    def cursor(self):
        return Transaction(self.connection)

    def clear_db(self):
        with self.cursor() as cursor:
            for name in self.tablenames:
                cursor.execute('drop table if exists {}'.format(name))
        return self

    def initialise_db(self):
        with self.cursor() as cursor:
            cursor.execute('''
                           CREATE TABLE event (
                           id INTEGER NOT NULL,
                           timestamp INTEGER NOT NULL,
                           PRIMARY KEY (id));
                           ''')

            cursor.execute('''
                           CREATE TABLE host (
                           id INTEGER NOT NULL,
                           hostname VARCHAR NOT NULL,
                           event_id INTEGER,
                           PRIMARY KEY (id),
                           FOREIGN KEY(event_id) REFERENCES event (id));
                           ''')

            cursor.execute('''
                           CREATE TABLE address (
                           id INTEGER NOT NULL,
                           type VARCHAR NOT NULL,
                           address VARCHAR NOT NULL,
                           host_id INTEGER,
                           PRIMARY KEY (id),
                           FOREIGN KEY(host_id) REFERENCES host (id));
                           ''')
        return self

    def add_event(self, timestamp):
        with self.cursor() as cursor:
            cursor.execute('insert into event (timestamp) values (?)',
                           (timestamp, ))
            return cursor.lastrowid

    def add_host(self, hostname, event_id):
        with self.cursor() as cursor:
            cursor.execute(
                'insert into host (hostname, event_id) values (?, ?)',
                (hostname, event_id))

    def add_address(self, address, type, host_id):
        with self.cursor() as cursor:
            cursor.execute(
                'insert into address (address, type, host_id) values (?, ?, ?)',
                (address, type, host_id))

    def unique_hosts(self):
        with self.cursor() as cursor:
            cursor.execute('select distinct hostname from host')
            return { row[0] for row in cursor.fetchall() }

    def get_events(self):
        with self.cursor() as cursor:
            cursor.execute(
                'select id, timestamp from event order by timestamp')
            for (event_id, timestamp) in cursor:
                yield EventEntry(event_id=event_id, timestamp=timestamp)

    def get_hosts(self, event):
        with self.cursor() as cursor:
            cursor.execute(
                '''select hostname from host
                where event_id = ?''',
                (event.event_id, ))
            for hostname, in cursor:
                yield hostname


text:
package main

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestPiPhoneHome(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "PiPhoneHome Suite")
}


text:
'use strict';

/**
 * Server helpers & dependencies
 */
const $$ = require('../config/helpers');
const settings = $$.loadSettings(require('../config/build-config.json'));

const express = require('express');
const compression = require('compression');
const logger = require('morgan');
const bodyParser = require('body-parser');
const path = require('path');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const webpackConfig = require($$.root('./config/webpack.config'));

const server = express();
server.use(compression());
server.use(logger('dev'));

/**
 * HMR support
 */
const conf = webpackConfig({
    env: 'playground',
}, $$.root, settings);
const compiler = webpack(conf);

server.use(webpackDevMiddleware(compiler, {
    noInfo: true,
    publicPath: conf.output.publicPath,
    stats: {
        colors: true
    }
}));
server.use(webpackHotMiddleware(compiler, {
    log: console.log
}));

/**
 * Parsers for POST data
 */
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended: false}));

/**
 * Point static path to `public`
 */
server.use('/', express.static('public', {index: false}));

/**
 * Catch all routes and return the `index.html`
 */
server.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '../public/index.html'));
});

/**
 * Error handlers
 */
// development error handler
// will print stacktrace
if (server.get('env') === 'development') {
    server.use(function(err, req, res) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
server.use(function(err, req, res) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

/**
 * Port & host settings
 */
const PORT = process.env.PORT || 1337;
const HOST = process.env.BASE_URL || 'localhost';
const baseUrl = `http://${HOST}:${PORT}`;

server.set('port', PORT);

/**
 * Begin listening
 */
server.listen(server.get('port'), () => {
    console.log(`Express server listening on ${baseUrl}`);
});

module.exports = server;


text:
package onlysaviorcommon.util;

import onlysaviorcommon.Constants;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 14-4-25
 * Time: 下午4:23
 * To change this template use File | Settings | File Templates.
 */
public class Data {

    /**
     * The length of an integer value.
     */
    public static final int LENGTH_INT = 4;

    /**
     * The length of a long value.
     */
    private static final int LENGTH_LONG = 8;

    private static final int INT_0_15 = 32;
    private static final int LONG_0_7 = 48;
    private static final int DECIMAL_0_1 = 56;
    private static final int DECIMAL_SMALL_0 = 58;
    private static final int DECIMAL_SMALL = 59;
    private static final int DOUBLE_0_1 = 60;
    private static final int FLOAT_0_1 = 62;
    private static final int BOOLEAN_FALSE = 64;
    private static final int BOOLEAN_TRUE = 65;
    private static final int INT_NEG = 66;
    private static final int LONG_NEG = 67;
    private static final int STRING_0_31 = 68;
    private static final int BYTES_0_31 = 100;
    private static final int LOCAL_TIME = 132;
    private static final int LOCAL_DATE = 133;
    private static final int LOCAL_TIMESTAMP = 134;

    private static final long MILLIS_PER_MINUTE = 1000 * 60;

    /**
     * The data itself.
     */
    private byte[] data;

    /**
     * The current write or read position.
     */
    private int pos;

    /**
     * The data handler responsible for lob objects.
     */

    private Data(byte[] data) {
        this.data = data;
    }

    /**
     * Update an integer at the given position.
     * The current position is not change.
     *
     * @param pos the position
     * @param x the value
     */
    public void setInt(int pos, int x) {
        byte[] buff = data;
        buff[pos] = (byte) (x >> 24);
        buff[pos + 1] = (byte) (x >> 16);
        buff[pos + 2] = (byte) (x >> 8);
        buff[pos + 3] = (byte) x;
    }

    /**
     * Write an integer at the current position.
     * The current position is incremented.
     *
     * @param x the value
     */
    public void writeInt(int x) {
        byte[] buff = data;
        buff[pos] = (byte) (x >> 24);
        buff[pos + 1] = (byte) (x >> 16);
        buff[pos + 2] = (byte) (x >> 8);
        buff[pos + 3] = (byte) x;
        pos += 4;
    }

    /**
     * Read an integer at the current position.
     * The current position is incremented.
     *
     * @return the value
     */
    public int readInt() {
        byte[] buff = data;
        int x = (buff[pos] << 24) + ((buff[pos+1] & 0xff) << 16) + ((buff[pos+2] & 0xff) << 8) + (buff[pos+3] & 0xff);
        pos += 4;
        return x;
    }

    /**
     * Get the length of a String. This includes the bytes required to encode
     * the length.
     *
     * @param s the string
     * @return the number of bytes required
     */
    public static int getStringLen(String s) {
        int len = s.length();
        return getStringWithoutLengthLen(s, len) + getVarIntLen(len);
    }

    /**
     * Calculate the length of String, excluding the bytes required to encode
     * the length.
     *

     * For performance reasons the internal representation of a String is
     * similar to UTF-8, but not exactly UTF-8.
     *
     * @param s the string
     * @param len the length of the string
     * @return the number of bytes required
     */
    private static int getStringWithoutLengthLen(String s, int len) {
        int plus = 0;
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            if (c >= 0x800) {
                plus += 2;
            } else if (c >= 0x80) {
                plus++;
            }
        }
        return len + plus;
    }

    /**
     * Read a String value.
     * The current position is incremented.
     *
     * @return the value
     */
    public String readString() {
        int len = readVarInt();
        return readString(len);
    }

    /**
     * Read a String from the byte array.
     *

     * For performance reasons the internal representation of a String is
     * similar to UTF-8, but not exactly UTF-8.
     *
     * @param len the length of the resulting string
     * @return the String
     */
    private String readString(int len) {
        byte[] buff = data;
        int p = pos;
        char[] chars = new char[len];
        for (int i = 0; i < len; i++) {
            int x = buff[p++] & 0xff;
            if (x < 0x80) {
                chars[i] = (char) x;
            } else if (x >= 0xe0) {
                chars[i] = (char) (((x & 0xf) << 12) + ((buff[p++] & 0x3f) << 6) + (buff[p++] & 0x3f));
            } else {
                chars[i] = (char) (((x & 0x1f) << 6) + (buff[p++] & 0x3f));
            }
        }
        pos = p;
        return new String(chars);
    }

    /**
     * Write a String.
     * The current position is incremented.
     *
     * @param s the value
     */
    public void writeString(String s) {
        int len = s.length();
        writeVarInt(len);
        writeStringWithoutLength(s, len);
    }

    /**
     * Write a String.
     *

     * For performance reasons the internal representation of a String is
     * similar to UTF-8, but not exactly UTF-8.
     *
     * @param s the string
     * @param len the number of characters to write
     */
    private void writeStringWithoutLength(String s, int len) {
        int p = pos;
        byte[] buff = data;
        for (int i = 0; i < len; i++) {
            int c = s.charAt(i);
            if (c < 0x80) {
                buff[p++] = (byte) c;
            } else if (c >= 0x800) {
                buff[p++] = (byte) (0xe0 | (c >> 12));
                buff[p++] = (byte) (((c >> 6) & 0x3f));
                buff[p++] = (byte) (c & 0x3f);
            } else {
                buff[p++] = (byte) (0xc0 | (c >> 6));
                buff[p++] = (byte) (c & 0x3f);
            }
        }
        pos = p;
    }

    private void writeStringWithoutLength(char[] chars, int len) {
        int p = pos;
        byte[] buff = data;
        for (int i = 0; i < len; i++) {
            int c = chars[i];
            if (c < 0x80) {
                buff[p++] = (byte) c;
            } else if (c >= 0x800) {
                buff[p++] = (byte) (0xe0 | (c >> 12));
                buff[p++] = (byte) (((c >> 6) & 0x3f));
                buff[p++] = (byte) (c & 0x3f);
            } else {
                buff[p++] = (byte) (0xc0 | (c >> 6));
                buff[p++] = (byte) (c & 0x3f);
            }
        }
        pos = p;
    }

    /**
     * Create a new buffer for the given handler. The
     * handler will decide what type of buffer is created.
     *
     * @param handler the data handler
     * @param capacity the initial capacity of the buffer
     * @return the buffer
     */
    public static Data create(int capacity) {
        return new Data(new byte[capacity]);
    }

    /**
     * Create a new buffer using the given data for the given handler. The
     * handler will decide what type of buffer is created.
     *
     * @param handler the data handler
     * @param buff the data
     * @return the buffer
     */
    public static Data create( byte[] buff) {
        return new Data(buff);
    }

    /**
     * Get the current write position of this buffer, which is the current
     * length.
     *
     * @return the length
     */
    public int length() {
        return pos;
    }

    /**
     * Get the byte array used for this page.
     *
     * @return the byte array
     */
    public byte[] getBytes() {
        return data;
    }

    /**
     * Set the position to 0.
     */
    public void reset() {
        pos = 0;
    }

    /**
     * Append a number of bytes to this buffer.
     *
     * @param buff the data
     * @param off the offset in the data
     * @param len the length in bytes
     */
    public void write(byte[] buff, int off, int len) {
        System.arraycopy(buff, off, data, pos, len);
        pos += len;
    }

    /**
     * Copy a number of bytes to the given buffer from the current position. The
     * current position is incremented accordingly.
     *
     * @param buff the output buffer
     * @param off the offset in the output buffer
     * @param len the number of bytes to copy
     */
    public void read(byte[] buff, int off, int len) {
        System.arraycopy(data, pos, buff, off, len);
        pos += len;
    }

    /**
     * Append one single byte.
     *
     * @param x the value
     */
    public void writeByte(byte x) {
        data[pos++] = x;
    }

    /**
     * Read one single byte.
     *
     * @return the value
     */
    public byte readByte() {
        return data[pos++];
    }

    /**
     * Read a long value. This method reads two int values and combines them.
     *
     * @return the long value
     */
    public long readLong() {
        return ((long) (readInt()) << 32) + (readInt() & 0xffffffffL);
    }

    /**
     * Append a long value. This method writes two int values.
     *
     * @param x the value
     */
    public void writeLong(long x) {
        writeInt((int) (x >>> 32));
        writeInt((int) x);
    }

    /**
     * Set the current read / write position.
     *
     * @param pos the new position
     */
    public void setPos(int pos) {
        this.pos = pos;
    }

    /**
     * Write a short integer at the current position.
     * The current position is incremented.
     *
     * @param x the value
     */
    public void writeShortInt(int x) {
        byte[] buff = data;
        buff[pos++] = (byte) (x >> 8);
        buff[pos++] = (byte) x;
    }

    /**
     * Read an short integer at the current position.
     * The current position is incremented.
     *
     * @return the value
     */
    public short readShortInt() {
        byte[] buff = data;
        return (short) (((buff[pos++] & 0xff) << 8) + (buff[pos++] & 0xff));
    }

    /**
     * Shrink the array to this size.
     *
     * @param size the new size
     */
    public void truncate(int size) {
        if (pos > size) {
            byte[] buff = new byte[size];
            System.arraycopy(data, 0, buff, 0, size);
            this.pos = size;
            data = buff;
        }
    }

    /**
     * The number of bytes required for a variable size int.
     *
     * @param x the value
     * @return the len
     */
    private static int getVarIntLen(int x) {
        if ((x & (-1 << 7)) == 0) {
            return 1;
        } else if ((x & (-1 << 14)) == 0) {
            return 2;
        } else if ((x & (-1 << 21)) == 0) {
            return 3;
        } else if ((x & (-1 << 28)) == 0) {
            return 4;
        }
        return 5;
    }

    /**
     * Write a variable size int.
     *
     * @param x the value
     */
    public void writeVarInt(int x) {
        while ((x & ~0x7f) != 0) {
            data[pos++] = (byte) (0x80 | (x & 0x7f));
            x >>>= 7;
        }
        data[pos++] = (byte) x;
    }

    /**
     * Read a variable size int.
     *
     * @return the value
     */
    public int readVarInt() {
        int b = data[pos];
        if (b >= 0) {
            pos++;
            return b;
        }
        // a separate function so that this one can be inlined
        return readVarIntRest(b);
    }

    private int readVarIntRest(int b) {
        int x = b & 0x7f;
        b = data[pos + 1];
        if (b >= 0) {
            pos += 2;
            return x | (b << 7);
        }
        x |= (b & 0x7f) << 7;
        b = data[pos + 2];
        if (b >= 0) {
            pos += 3;
            return x | (b << 14);
        }
        x |= (b & 0x7f) << 14;
        b = data[pos + 3];
        if (b >= 0) {
            pos += 4;
            return x | b << 21;
        }
        x |= ((b & 0x7f) << 21) | (data[pos + 4] << 28);
        pos += 5;
        return x;
    }

    /**
     * The number of bytes required for a variable size long.
     *
     * @param x the value
     * @return the len
     */
    public static int getVarLongLen(long x) {
        int i = 1;
        while (true) {
            x >>>= 7;
            if (x == 0) {
                return i;
            }
            i++;
        }
    }

    /**
     * Write a variable size long.
     *
     * @param x the value
     */
    public void writeVarLong(long x) {
        while ((x & ~0x7f) != 0) {
            data[pos++] = (byte) ((x & 0x7f) | 0x80);
            x >>>= 7;
        }
        data[pos++] = (byte) x;
    }

    /**
     * Read a variable size long.
     *
     * @return the value
     */
    public long readVarLong() {
        long x = data[pos++];
        if (x >= 0) {
            return x;
        }
        x &= 0x7f;
        for (int s = 7;; s += 7) {
            long b = data[pos++];
            x |= (b & 0x7f) << s;
            if (b >= 0) {
                return x;
            }
        }
    }

    /**
     * Check if there is still enough capacity in the buffer.
     * This method extends the buffer if required.
     *
     * @param plus the number of additional bytes required
     */
    public void checkCapacity(int plus) {
        if (pos + plus >= data.length) {
            // a separate method to simplify inlining
            expand(plus);
        }
    }

    private void expand(int plus) {
        byte[] d = new byte[(data.length + plus) * 2];
        // must copy everything, because pos could be 0 and data may be
        // still required
        System.arraycopy(data, 0, d, 0, data.length);
        data = d;
    }

    /**
     * Fill up the buffer with empty space and an (initially empty) checksum
     * until the size is a multiple of Constants.FILE_BLOCK_SIZE.
     */
    public void fillAligned() {
        // 0..6 > 8, 7..14 > 16, 15..22 > 24, ...
        int len = MathUtils.roundUpInt(pos + 2, Constants.FILE_BLOCK_SIZE);
        pos = len;
        if (data.length < len) {
            checkCapacity(len - data.length);
        }
    }

    /**
     * Copy a String from a reader to an output stream.
     *
     * @param source the reader
     * @param target the output stream
     */
    public static void copyString(Reader source, OutputStream target) throws IOException
    {
        char[] buff = new char[Constants.IO_BUFFER_SIZE];
        Data d = new Data(new byte[3 * Constants.IO_BUFFER_SIZE]);
        while (true) {
            int l = source.read(buff);
            if (l < 0) {
                break;
            }
            d.writeStringWithoutLength(buff, l);
            target.write(d.data, 0, d.pos);
            d.reset();
        }
    }
}


text:
$output.java($WebValidation, "JpaUniqueValidator")##

$output.requireStatic("javax.faces.application.FacesMessage.SEVERITY_ERROR")##
$output.requireStatic("org.apache.commons.lang.StringUtils.isBlank")##
$output.require("javax.enterprise.context.RequestScoped")##
$output.require("javax.faces.application.FacesMessage")##
$output.require("javax.faces.component.UIComponent")##
$output.require("javax.faces.context.FacesContext")##
$output.require("javax.faces.validator.FacesValidator")##
$output.require("javax.faces.validator.Validator")##
$output.require("javax.faces.validator.ValidatorException")##
$output.require("javax.inject.Inject")##
$output.require("javax.inject.Named")##
$output.require("com.jaxio.jpa.querybyexample.JpaUniqueUtil")##
$output.require("com.jaxio.jpa.querybyexample.Identifiable")##
$output.require($Util, "ResourcesUtil")##

@Named
@RequestScoped
@FacesValidator(value = "jpaUniqueValidator")
public class $output.currentClass implements Validator {

    @Inject
    private JpaUniqueUtil jpaUniqueUtil;
    @Inject
    private ResourcesUtil resourcesUtil;

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
        if (ConditionalValidatorUtil.doValidation(context)) {
            if (entity == null && isBlank(property)) {
                return;
            }

            String errorCode = jpaUniqueUtil.validateSimpleUnique(entity, property, value);
            if (errorCode != null) {
                FacesMessage fm = new FacesMessage(resourcesUtil.getProperty(errorCode));
                fm.setSeverity(SEVERITY_ERROR);
                throw new ValidatorException(fm);
            }
        }
    }

    private Identifiable<?> entity;
    private String property;

    public void setEntity(Identifiable<?> entity) {
        this.entity = entity;
    }

    public Identifiable<?> getEntity() {
        return entity;
    }

    public void setProperty(String property) {
        this.property = property;
    }

    public String getProperty() {
        return property;
    }
}


text:
namespace base {
class TimeDelta;
}

namespace net {

// Simple class to wait until a TCP server is accepting connections.
class TCPPinger {
 public:
  explicit TCPPinger(const net::AddressList& addr)
    : io_thread_("TCPPinger"),
      worker_(new Worker(addr)) {
    worker_->AddRef();
    // Start up a throwaway IO thread just for this.
    // TODO(dkegel): use some existing thread pool instead?
    base::Thread::Options options;
    options.message_loop_type = MessageLoop::TYPE_IO;
    io_thread_.StartWithOptions(options);
  }

  ~TCPPinger() {
    io_thread_.message_loop()->ReleaseSoon(FROM_HERE, worker_);
  }

  int Ping() {
    // Default is 10 tries, each with a timeout of 1000ms,
    // for a total max timeout of 10 seconds.
    return Ping(base::TimeDelta::FromMilliseconds(1000), 10);
  }

  int Ping(base::TimeDelta tryTimeout, int nTries) {
    int err = ERR_IO_PENDING;
    // Post a request to do the connect on that thread.
    for (int i = 0; i < nTries; i++) {
      io_thread_.message_loop()->PostTask(FROM_HERE,
        NewRunnableMethod(worker_,
        &net::TCPPinger::Worker::DoConnect));
      // Timeout here in case remote host offline
      err = worker_->TimedWaitForResult(tryTimeout);
      if (err == net::OK)
        break;
      PlatformThread::Sleep(static_cast<int>(tryTimeout.InMilliseconds()));

      // Cancel leftover activity, if any
      io_thread_.message_loop()->PostTask(FROM_HERE,
        NewRunnableMethod(worker_,
        &net::TCPPinger::Worker::DoDisconnect));
      worker_->WaitForResult();
    }
    return err;
  }

 private:

  // Inner class to handle all actual socket calls.
  // This makes the outer interface simpler,
  // and helps us obey the "all socket calls
  // must be on same thread" restriction.
  class Worker : public base::RefCountedThreadSafe<Worker> {
   public:
    explicit Worker(const net::AddressList& addr)
      : event_(false, false),
        net_error_(ERR_IO_PENDING),
        addr_(addr),
        ALLOW_THIS_IN_INITIALIZER_LIST(connect_callback_(this,
            &net::TCPPinger::Worker::ConnectDone)) {
    }

    void DoConnect() {
      sock_.reset(new TCPClientSocket(addr_));
      int rv = sock_->Connect(&connect_callback_);
      // Regardless of success or failure, if we're done now,
      // signal the customer.
      if (rv != ERR_IO_PENDING)
        ConnectDone(rv);
    }

    void DoDisconnect() {
      sock_.reset();
      event_.Signal();
    }

    void ConnectDone(int rv) {
      sock_.reset();
      net_error_ = rv;
      event_.Signal();
    }

    int TimedWaitForResult(base::TimeDelta tryTimeout) {
      event_.TimedWait(tryTimeout);
      return net_error_;
    }

    int WaitForResult() {
      event_.Wait();
      return net_error_;
    }

   private:
    base::WaitableEvent event_;
    int net_error_;
    net::AddressList addr_;
    scoped_ptr<TCPClientSocket> sock_;
    net::CompletionCallbackImpl<Worker> connect_callback_;
  };

  base::Thread io_thread_;
  Worker* worker_;
  DISALLOW_COPY_AND_ASSIGN(TCPPinger);
};

}  // namespace net

#endif  // NET_SOCKET_TCP_PINGER_H_


text:
extern volatile float beta;				// algorithm gain
//extern volatile float q0, q1, q2, q3;	// quaternion of sensor frame relative to auxiliary frame

//---------------------------------------------------------------------------------------------------
// Function declarations

void MadgwickAHRSupdate(float gx, float gy, float gz, float ax, float ay, float az, float mx, float my, float mz, float sampleFreq, float *q);
void MadgwickAHRSupdateIMU(float gx, float gy, float gz, float ax, float ay, float az, float sampleFreq, float *q);

#endif
//=====================================================================================================
// End of file
//=====================================================================================================