text:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
using System.Collections.Generic;
using ModularFramework.Core;
using ModularFramework.Helpers;
using TMPro;

using System;
using EA4S;

namespace EA4S.DancingDots
{
    public enum DiacriticEnum { None, Sokoun, Fatha, Dameh, Kasrah };

    public class DancingDotsGame : MiniGame
    {

        public IntroductionGameState IntroductionState { get; private set; }
        public QuestionGameState QuestionState { get; private set; }
        public PlayGameState PlayState { get; private set; }
        public ResultGameState ResultState { get; private set; }

        protected override void OnInitialize(IGameContext context)
        {
            IntroductionState = new IntroductionGameState(this);
            QuestionState = new QuestionGameState(this);
            PlayState = new PlayGameState(this);
            ResultState = new ResultGameState(this);
        }

        protected override IGameState GetInitialState()
        {
            return IntroductionState;
        }

        protected override IGameConfiguration GetConfiguration()
        {
            return DancingDotsConfiguration.Instance;
        }

        public static DancingDotsGame instance;
        public Canvas endGameCanvas;
//        public StarFlowers starFlowers;

        public const string DANCING_DOTS = "DancingDots_DotZone";
        public const string DANCING_DIACRITICS = "DancingDots_Diacritic";

        public bool disableInput;
        public float gameDuration = 60f;
        public DancingDotsLivingLetter dancingDotsLL;
        public GameObject antura;
        public float anturaMinDelay = 3f;
        public float anturaMaxDelay = 10f;
        public float anturaMinScreenTime = 1f;
        public float anturaMaxScreenTime = 2f;
        public GameObject[] diacritics;
        public DancingDotsDiacriticPosition activeDiacritic;

        [HideInInspector]
        public DancingDotsQuestionsManager questionsManager;

		[HideInInspector]
		public DiacriticEnum letterDiacritic;

        DancingDotsTutorial tutorial;

        public bool isTutRound
        {
            get
            {
                if (numberOfRoundsPlayed == 0)
                    return true;
                else
                    return false;
            }
        }

        public string currentLetter = "";
        private int _dotsCount;
        public int dotsCount
        {
            get
            {
                return _dotsCount;
            }
            set
            {
                _dotsCount = value;
                foreach (DancingDotsDraggableDot dd in dragableDots)
                {
                    dd.isNeeded = dd.dots == _dotsCount;
                }
            }
        }

        public GameObject splatPrefab;
        public Transform splatParent;

        [Range(0, 255)]
        public byte dotHintAlpha = 60;
        [Range(0, 255)]
        public byte diacriticHintAlpha = 60;

        public float hintDotDuration = 2.5f;
        public float hintDiacriticDuration = 3f;

        public GameObject poofPrefab;

        [Range(0, 1)]
        public float pedagogicalLevel = 0;

        public int numberOfRounds = 6;

        public int allowedFailedMoves = 3;

        public DancingDotsDraggableDot[] dragableDots;
        public DancingDotsDraggableDot[] dragableDiacritics;
        public DancingDotsDropZone[] dropZones;

        private bool isCorrectDot = false;
        private bool isCorrectDiacritic = false;

        public int currStarsNum = 0;
        public int numberOfRoundsWon = 0;
        private int numberOfRoundsPlayed = -1;
        private int numberOfFailedMoves = 0;

        enum Level { Level1, Level2, Level3, Level4, Level5, Level6 };

        private Level currentLevel = Level.Level4;
        private List<DancingDotsSplat> splats;
        private bool isPlaying = false;

        protected override void Awake()
        {
            base.Awake();
            instance = this;
        }

        protected override void Start()
        {

            base.Start();
            tutorial = GetComponent<DancingDotsTutorial>();

            AppManager.I.InitTeacherForPlayer();
            AppManager.I.CurrentGameManagerGO = gameObject;
            SceneTransitioner.Close();

            AudioManager.I.PlayMusic(Music.MainTheme);
            //			DancingDotsConfiguration.Instance.Context.GetAudioManager().PlayMusic(Music.MainTheme);

            questionsManager = new DancingDotsQuestionsManager();

            splats = new List<DancingDotsSplat>();

			foreach (DancingDotsDraggableDot dDots in dragableDots) dDots.gameObject.SetActive(false);
			foreach (DancingDotsDraggableDot dDiacritic in dragableDiacritics) dDiacritic.gameObject.SetActive(false);

            //StartRound();

            isPlaying = true;

            //			StartCoroutine(AnimateAntura());

        }

        public Color32 SetAlpha(Color32 color, byte alpha)
        {
            if (alpha >= 0 && alpha <= 255)
            {
                return new Color32(color.r, color.g, color.b, alpha);
            }
            else
            {
                return color;
            }
        }

        IEnumerator AnimateAntura()
        {
            Vector3 pos = antura.transform.position;
            // Move antura off screen because SetActive is reseting the animation to running
            antura.transform.position = new Vector3(-50, pos.y, pos.z);
            do
            {
                yield return new WaitForSeconds(UnityEngine.Random.Range(anturaMinDelay, anturaMaxDelay));
                CreatePoof(pos, 2f, false);
                yield return new WaitForSeconds(0.4f);
                antura.transform.position = pos;
                antura.GetComponent<AnturaAnimationController>().DoSniff();
                yield return new WaitForSeconds(UnityEngine.Random.Range(anturaMinScreenTime, anturaMaxScreenTime));
                CreatePoof(pos, 2f, false);
                antura.transform.position = new Vector3(-50, pos.y, pos.z);
            } while (isPlaying);

        }

        private void SetLevel(Level level)
        {
            foreach (DancingDotsDraggableDot dDots in dragableDots) dDots.gameObject.SetActive(false);
            foreach (DancingDotsDraggableDot dDiacritic in dragableDiacritics) dDiacritic.gameObject.SetActive(false);
            foreach (GameObject go in diacritics) go.SetActive(false);
			isCorrectDiacritic = true;

			foreach (DancingDotsDraggableDot dDots in dragableDots) dDots.Reset();
			isCorrectDot = false;

            switch (level)
            {
			case Level.Level1: // Dots alone with visual aid
				gameDuration = 120;
				StartCoroutine(RemoveHintDot());
				break;

			case Level.Level2: // Diacritics alone with visual aid
				gameDuration = 110;

				StartCoroutine(RemoveHintDot());
				break;

			case Level.Level3: // Dots and diacritics with visual aid
				gameDuration = 100;

				StartCoroutine(RemoveHintDot());
				break;

			case Level.Level4: // Dots alone without visual aid
				gameDuration = 90;
				dancingDotsLL.HideText(dancingDotsLL.hintText);
				break;

			case Level.Level5: // Diacritics alone without visual aid
				gameDuration = 90;
				dancingDotsLL.HideText(dancingDotsLL.hintText);
				break;

			case Level.Level6: // Dots and diacritics without visual aid
				gameDuration = 80;
				dancingDotsLL.HideText(dancingDotsLL.hintText);
				break;

			default:
				SetLevel(Level.Level1);
				break;

            }
        }

        public void StartRound()
        {

            numberOfRoundsPlayed++;

            dancingDotsLL.letterObjectView.SetDancingSpeed(1f);

            if(splats != null)
                splats.Clear();

            dancingDotsLL.HideRainbow();

            Debug.Log("[Dancing Dots] Round: " + numberOfRoundsPlayed);
            numberOfFailedMoves = 0;

            if (pedagogicalLevel == 0f) // TODO for testing only each round increment Level. Remove later!
            {
                switch (numberOfRoundsPlayed)
                {
                    case 1:
                    case 2:
                        currentLevel = Level.Level1;
                        break;
                    case 3:
                        currentLevel = Level.Level4;
                        break;
                    case 4:
                        currentLevel = Level.Level2;
                        break;
                    case 5:
                    case 6:
                        currentLevel = Level.Level3;
                        break;
                    default:
                        currentLevel = Level.Level3;
                        break;
                }
            }
            else
            {
                // TODO Move later to Start method
                var numberOfLevels = Enum.GetNames(typeof(Level)).Length;
				pedagogicalLevel = DancingDotsConfiguration.Instance.Difficulty;
                currentLevel = (Level)Mathf.Clamp((int)Mathf.Floor(pedagogicalLevel * numberOfLevels), 0, numberOfLevels - 1);
            }

            Debug.Log("[Dancing Dots] pedagogicalLevel: " + pedagogicalLevel + " Game Level: " + currentLevel);
            SetLevel(currentLevel);

			startUI();

			dancingDotsLL.Reset();

            tutorial.doTutorial();

        }

        private void CreatePoof(Vector3 position, float duration, bool withSound)
        {
            if (withSound) AudioManager.I.PlaySfx(Sfx.BalloonPop);
            GameObject poof = Instantiate(poofPrefab, position, Quaternion.identity) as GameObject;
            Destroy(poof, duration);
        }

        IEnumerator RemoveHintDot()
        {
            yield return new WaitForSeconds(hintDotDuration);
            if (!isCorrectDot)
            {
                // find dot postion
                Vector3 poofPosition = Vector3.zero;
                foreach (DancingDotsDropZone dz in dropZones)
                {
                    if (dz.letters.Contains(currentLetter))
                    {
                        poofPosition = new Vector3(dz.transform.position.x, dz.transform.position.y, -8);
                        break;
                    }
                }
                CreatePoof(poofPosition, 2f, true);
                dancingDotsLL.HideText(dancingDotsLL.hintText);
            }
        }

        IEnumerator RemoveHintDiacritic()
        {
			if (letterDiacritic != DiacriticEnum.None)
			{
				yield return new WaitForSeconds(hintDiacriticDuration);
				if (!isCorrectDiacritic)
				{
					CreatePoof(activeDiacritic.transform.position, 2f, true);
					activeDiacritic.Hide();
				}
			}
        }

        public IEnumerator SetupDiacritic()
        {
			if (letterDiacritic != DiacriticEnum.None)
			{
				foreach (DancingDotsDraggableDot dDots in dragableDiacritics)
				{
					dDots.Reset();
				}
				isCorrectDiacritic = false;

				foreach (GameObject go in diacritics)
				{
					go.SetActive(true);
					if (go.GetComponent<DancingDotsDiacriticPosition>().diacritic == letterDiacritic)
					{
						activeDiacritic = go.GetComponent<DancingDotsDiacriticPosition>();
					}
					go.SetActive(false);
					go.GetComponent<DancingDotsDiacriticPosition>().Hide();
				}

				Debug.Log(activeDiacritic.diacritic);

				//            int random = UnityEngine.Random.Range(0, diacritics.Length);
				//            activeDiacritic = diacritics[random].GetComponent<DancingDotsDiacriticPosition>();

				activeDiacritic.gameObject.SetActive(true);

				foreach (DancingDotsDraggableDot dd in dragableDiacritics)
				{
					dd.isNeeded = activeDiacritic.diacritic == dd.diacritic;
				}

				// wait for end of frame to get correct values for meshes
				yield return new WaitForEndOfFrame();
				activeDiacritic.CheckPosition();

				// Level checked in SetDiacritic instead of SetLevel due to frame delay
				if (currentLevel != Level.Level5 && currentLevel != Level.Level6)
				{
					activeDiacritic.Show();
					StartCoroutine(RemoveHintDiacritic());
				}
			}
        }

        IEnumerator CorrectMove(bool roundWon)
        {
            //AudioManager.I.PlayDialog("comment_welldone");
            AudioManager.I.PlayDialog("Keeper_Good_" + UnityEngine.Random.Range(1, 13));
            dancingDotsLL.ShowRainbow();
            dancingDotsLL.letterObjectView.SetDancingSpeed(1f);

            if (roundWon)
            {
                StartCoroutine(RoundWon());
            }
            else
            {
                dancingDotsLL.letterObjectView.DoHorray(); // ("Jump");
                yield return new WaitForSeconds(1f);
                dancingDotsLL.HideRainbow();
                //                yield return new WaitForSeconds(1f);
                tutorial.doTutorial();
                //startUI();

            }
        }

        IEnumerator PoofOthers(DancingDotsDraggableDot[] draggables)
        {
            foreach (DancingDotsDraggableDot dd in draggables)
            {
                if (dd.gameObject.activeSelf)
                {
                    yield return new WaitForSeconds(0.25f);
                    dd.gameObject.SetActive(false);
                    CreatePoof(dd.transform.position, 2f, true);
                }

            }
        }

        public void CorrectDot()
        {
            // Change font or show correct character
            isCorrectDot = true;
            dancingDotsLL.fullTextGO.SetActive(true);
            StartCoroutine(PoofOthers(dragableDots));
            StartCoroutine(CorrectMove(isCorrectDiacritic));
        }

        public void CorrectDiacritic()
        {
            isCorrectDiacritic = true;
            activeDiacritic.GetComponent<TextMeshPro>().color = new Color32(0, 0, 0, 255);
            StartCoroutine(PoofOthers(dragableDiacritics));
            StartCoroutine(CorrectMove(isCorrectDot));
        }

        public void WrongMove(Vector3 pos)
        {

            AudioManager.I.PlayDialog("Keeper_Bad_" + UnityEngine.Random.Range(1, 6));
            numberOfFailedMoves++;
            dancingDotsLL.letterObjectView.SetDancingSpeed(1f - numberOfFailedMoves * 0.25f);
            GameObject splat = (GameObject)Instantiate(splatPrefab);
            splat.transform.parent = splatParent;
            splat.transform.localScale = new Vector3(1f, 1f, 1f);
            splat.transform.localRotation = Quaternion.Euler(0f, 0f, 0f);
            splat.transform.position = pos;
            splat.transform.localPosition = new Vector3(splat.transform.localPosition.x, splat.transform.localPosition.y, 0f);

            splats.Add(splat.GetComponent<DancingDotsSplat>());

            if (numberOfFailedMoves >= allowedFailedMoves)
            {
                StartCoroutine(RoundLost());
            }

        }

        IEnumerator CheckNewRound()
        {
            dancingDotsLL.letterObjectView.SetDancingSpeed(1f);

            if (numberOfRoundsPlayed >= numberOfRounds)
            {
                DancingDotsEndGame();
            }
            else
            {

                dancingDotsLL.letterObjectView.DoTwirl(null);
                foreach (DancingDotsSplat splat in splats) splat.CleanSplat();
                yield return new WaitForSeconds(1f);
                StartRound();
                dancingDotsLL.letterObjectView.ToggleDance();

            }
        }

        IEnumerator RoundLost()
        {
            yield return new WaitForSeconds(0.5f);
            AudioManager.I.PlaySfx(Sfx.Lose);

            StartCoroutine(PoofOthers(dragableDots));
            StartCoroutine(PoofOthers(dragableDiacritics));
            dancingDotsLL.letterObjectView.SetDancingSpeed(1f);
            dancingDotsLL.letterObjectView.DoDancingLose();
            yield return new WaitForSeconds(1.5f);
            dancingDotsLL.letterObjectView.DoSmallJump();
            dancingDotsLL.letterObjectView.ToggleDance();
            StartCoroutine(CheckNewRound());
        }

        IEnumerator RoundWon()
        {
            if (!isTutRound)
            {
                numberOfRoundsWon++;
                currStarsNum = numberOfRoundsWon / 2;
				Context.GetOverlayWidget().SetStarsScore(numberOfRoundsWon);
            }

            yield return new WaitForSeconds(0.25f);
            AudioManager.I.PlaySfx(Sfx.Win);
            yield return new WaitForSeconds(1f);

            StartCoroutine(CheckNewRound());
        }

        public void DancingDotsEndGame()
        {
            dancingDotsLL.letterObjectView.DoDancingWin();
            isPlaying = false;
            dancingDotsLL.letterObjectView.SetState(LLAnimationStates.LL_idle);
			// Stop danger clock if rounds finish and it is running
			AudioManager.I.StopSfx(Sfx.DangerClockLong);
            this.SetCurrentState(this.ResultState);
            //StartCoroutine(EndGame_Coroutine());
        }

		void startUI()
		{
			if (numberOfRoundsPlayed != 1)
			{
				return;
			}
			Debug.Log("UI Started");
			Context.GetOverlayWidget().Initialize(true, true, false);
			Context.GetOverlayWidget().SetClockDuration(gameDuration);
			Context.GetOverlayWidget().SetStarsThresholds(2,3,6);
			Context.GetOverlayWidget().SetStarsScore(0);
		}

	}
}


text:
package edu.duke.cabig.c3pr.web.study;

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

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import edu.duke.cabig.c3pr.constants.CoordinatingCenterStudyStatus;
import edu.duke.cabig.c3pr.dao.StudyDao;
import edu.duke.cabig.c3pr.domain.LocalStudy;
import edu.duke.cabig.c3pr.domain.Study;
import edu.duke.cabig.c3pr.domain.SystemAssignedIdentifier;
import edu.duke.cabig.c3pr.utils.ConfigurationProperty;
import edu.duke.cabig.c3pr.utils.Lov;
import edu.duke.cabig.c3pr.utils.StringUtils;
import edu.duke.cabig.c3pr.utils.web.WebUtils;
import edu.duke.cabig.c3pr.web.SearchCommand;
import edu.duke.cabig.c3pr.web.ajax.StudyAjaxFacade;

public class SearchStudyController extends SimpleFormController {

    private static Log log = LogFactory.getLog(SearchStudyController.class);

    private ConfigurationProperty configurationProperty;

    private StudyDao studyDao;

    private StudyAjaxFacade studyAjaxFacade;

    @Override
    protected boolean isFormSubmission(HttpServletRequest request) {
        if (request.getParameter("test") != null) return true;
        return super.isFormSubmission(request);
    }

    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response,
                                    Object oCommand, BindException errors) throws Exception {
        SearchCommand searchStudyCommand = (SearchCommand) oCommand;
        Study study = new LocalStudy(true);
        String type = searchStudyCommand.getSearchType();

        String searchtext = "";
        String statusSearchText = "";
        if(!StringUtils.isBlank(searchStudyCommand.getSearchText())){
        	searchtext = searchStudyCommand.getSearchText().trim();
        }
        if(!StringUtils.isBlank(searchStudyCommand.getStatusSearchText())){
        	statusSearchText = searchStudyCommand.getStatusSearchText().trim();
        }

        log.debug("search string = " + searchtext + "; type = " + type);
        if ("id".equals(type)) {
            SystemAssignedIdentifier id = new SystemAssignedIdentifier();
            id.setValue(searchtext.trim());
            study.addIdentifier(id);
        } else if ("shortTitle".equals(type)) {
            study.setShortTitleText(searchtext);
        }

        if (WebUtils.hasSubmitParameter(request, "fromRegistration")) {
        	 study.setCoordinatingCenterStudyStatus(CoordinatingCenterStudyStatus.OPEN);
            if (request.getParameter("standaloneOnly").toString().equalsIgnoreCase("true")) {
                study.setStandaloneIndicator(true);
            }
        }

        List<Study> exampleStudies = new ArrayList<Study>();
        List<Study> studies = new ArrayList<Study>();
        if ("status".equalsIgnoreCase(type)) {
        	exampleStudies = studyDao.searchByStatus(study, statusSearchText, true);
        } else if (WebUtils.hasSubmitParameter(request, "fromStudyRegistrations")) {
        	if (WebUtils.hasSubmitParameter(request, "studyId")){
        		Integer studyId = Integer.parseInt((request.getParameter("studyId")));
        		exampleStudies.add(studyDao.getById(studyId));
            }
        }else {
        	exampleStudies = studyDao.searchByExample(study, true);
        }

        log.debug("Search results size " + studies.size());
        Map<String, List<Lov>> configMap = configurationProperty.getMap();

        Map map = errors.getModel();
        map.put("studyResults", exampleStudies);
        map.put("searchTypeRefData", configMap.get("studySearchType"));
        map.put("studyStatus", configMap.get("statusRefData"));
        Object viewData = studyAjaxFacade.getTableForExport(map, request);
        request.setAttribute("studies", viewData);
        if (WebUtils.hasSubmitParameter(request, "async")) {
            return new ModelAndView("/registration/studyResultsAsync", map);
        }
        ModelAndView modelAndView = new ModelAndView(getSuccessView(), map);
        return modelAndView;
    }

    protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception {
        Map<String, Object> refdata = new HashMap<String, Object>();
        Map<String, List<Lov>> configMap = configurationProperty.getMap();
        refdata.put("searchTypeRefData", configMap.get("studySearchType"));
        refdata.put("studyStatus", configMap.get("statusRefData"));
        return refdata;
    }

    public ConfigurationProperty getConfigurationProperty() {
        return configurationProperty;
    }

    public void setConfigurationProperty(ConfigurationProperty configurationProperty) {
        this.configurationProperty = configurationProperty;
    }

    public StudyDao getStudyDao() {
        return studyDao;
    }

    public void setStudyDao(StudyDao studyDao) {
        this.studyDao = studyDao;
    }

    public StudyAjaxFacade getStudyAjaxFacade() {
        return studyAjaxFacade;
    }

    public void setStudyAjaxFacade(StudyAjaxFacade studyAjaxFacade) {
        this.studyAjaxFacade = studyAjaxFacade;
    }

}

redpajama_set_name: RedPajamaGithub


text:
layout: post
date:	2009-04-24 05:37:00
title:  Heres wishing You, <lj user=yathin>
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
To Y, of Y!, who is, today, probably at Y (Yosemite).....

And of course, happy birthday to William Shakespeare as well! :)...and my Sambandhi, D's mother, LS, too. Now, that's an amazing lady if you like...she was a math major in college, and after her sons were born, went back to college to study architecture, and qualified in a tough 9-part exam to get her licence to practice in Maine! I think my daughter's very lucky to have found such a great family.

I am awaiting two deliveries...one, of the GD, and two, of the NMLC (New MLC)....neither seems to be in a hurry to arrive...so there is a sense of "What on earth am I doing here?" and I spent a little time playing around with editing and text on Photobucket!

The visit to the gynaecologist took practically the entire day...I was joking that since A had spent so long in the hospital, she might as well have the baby and come back.


text:
unsigned char buffer[LEN];
struct tcpheader {
 uint16_t srcport;
 uint16_t destport;
 unsigned int seqnum;
 unsigned int acknum;
 unsigned char offset:4,reserved:4;
 uint8_t flags;
 uint16_t win;
 uint16_t chksum;
 uint16_t urgptr;
 }*t_head;
unsigned char *buf,*dest_ip;

unsigned short csum(unsigned short *buf, int nwords)
{
    unsigned long sum;
    for(sum=0; nwords>0; nwords--) sum += *buf++;
    sum = (sum >> 16) + (sum &0xffff);
    sum += (sum >> 16);
    return (unsigned short)(~sum);
}

void TCP_header()
{
    t_head=(struct tcpheader *)malloc(sizeof(struct tcpheader));
    t_head->srcport=PORTNO;
    t_head->destport=PORTNO;
    t_head->offset=5;
    t_head->reserved=0;
    t_head->urgptr=0;
    t_head->seqnum=rand()%1024;
    t_head->acknum=0;
    t_head->win=2048;
    t_head->flags=2;
    t_head->chksum=0;
}

void TCP_header_init()
{
    struct tcpheader *tcp_head=(struct tcpheader *)buffer;
    tcp_head->srcport=t_head->srcport;
    tcp_head->destport=t_head->destport;
    tcp_head->offset=t_head->offset;
    tcp_head->reserved=0;
    tcp_head->urgptr=0;
    tcp_head->seqnum=t_head->seqnum;
    tcp_head->acknum=t_head->acknum;
    tcp_head->win=2048;
    tcp_head->flags=t_head->flags;
    tcp_head->chksum=0;
    tcp_head->chksum=csum((unsigned short *)buffer, sizeof(struct tcpheader));
}

int recvtimeout(int s, char *buf, int len, int timeout)
{
    fd_set fds;
    int n;
    struct timeval tv;

    // set up the file descriptor set
    FD_ZERO(&fds);
    FD_SET(s, &fds);

    // set up the struct timeval for the timeout
    tv.tv_sec = timeout;
    tv.tv_usec = 0;

    // wait until timeout or data received
    n = select(s+1, &fds, NULL, NULL, &tv);
    if (n == 0) return -2; // timeout!
    if (n == -1) return -1; // error

    // data must be here, so do a normal recv()
    return recv(s, buf, len, 0);
}

void send_init(unsigned char *add)
{
    int s=sizeof(struct tcpheader);
    struct sockaddr_in senaddr,recaddr;
    struct tcpheader *res=malloc(sizeof(struct tcpheader));
    unsigned char *r=(unsigned char *)res;
    int socksd,sendsd,dl,length;
    TCP_header();
    buf=(unsigned char *)t_head;
    socksd=socket(AF_INET,SOCK_STREAM,0);
    memset(&senaddr,0,sizeof(struct sockaddr_in));
    senaddr.sin_family=AF_INET;
    senaddr.sin_port=htons(PORTNO);
    inet_pton(AF_INET,add,&senaddr.sin_addr);
    bind(socksd,(struct sockaddr *)&senaddr,sizeof(struct sockaddr_in));
    connect(socksd,(struct sockaddr *)&senaddr,sizeof(struct sockaddr_in));
    if(send(socksd,buf,s,0))
    printf("SYN sent\n");       //SYN
    bzero(r, sizeof(r));
    dl=recvtimeout(socksd,r,s,2);

    if(dl==-1)
    {
        printf("SYN + ACK error\n");
        exit(-1);
    }
    else if(dl==-2)
    {
        printf("SYN + ACK Timeout\n");
        exit(-1);
    }
    else if(res->acknum==t_head->seqnum+1 && res->flags==18)
    printf("SYN + ACK received\n");
    else
    {
        printf("Connection ERROR\n");
        exit(-1);
    }
    res->acknum=res->seqnum+1;
    res->flags-=2;
    if(send(socksd,r,s,0))
    printf("ACK sent\n");

    shutdown(socksd,2);
    close(socksd);
    t_head->seqnum+=1;
    t_head->flags=0;

    FILE *in,*out;
    in = fopen("application_out","r");
    if(!in)
    {
        printf("Input file error\n");
        exit(-1);
    }
    unsigned char * data = (unsigned char *)(sizeof(struct tcpheader)+buffer);
    int total = fread(data,1,LEN-s,in);
    TCP_header_init();

    total+=s;
    out = fopen("transport_out","wb");
    if(!out)
    {
        printf("Output file error\n");
        exit(-1);
    }
    fwrite(buffer,1,total,out);
    fclose(in);
    fclose(out);
}

void receive_init()
{

    int length=sizeof(struct sockaddr_in);
    struct tcpheader *rec=malloc(sizeof(struct tcpheader));
    unsigned char *r=(unsigned char *)rec;
    int nwords=sizeof(struct tcpheader);
    struct sockaddr_in recaddr,sendaddr;
    int recsd,sendsd,dl,seq;
    recsd=socket(AF_INET,SOCK_STREAM,0);
    memset(&recaddr,0,sizeof(struct sockaddr_in));
    recaddr.sin_family=AF_INET;
    recaddr.sin_port=htons(PORTNO);
    bind(recsd,(struct sockaddr *)&recaddr,sizeof(struct sockaddr_in));
    listen(recsd,1);

    sendsd=accept(recsd,(struct sockaddr *)&sendaddr,&length);
    dl=recvtimeout(sendsd,r,nwords,2);     //SYN
    if(dl==-1 || dl==0)
    {
        printf("SYN error\n");
        exit(-1);
    }
    else if(dl==-2)
    {
        printf("SYN Timeout\n");
        exit(-1);
    }
    else if(rec->flags==2)
    printf("SYN received\n");
    else
    {
        printf("Connection ERROR\n");
        exit(-1);
    }
    rec->acknum=rec->seqnum+1;
    rec->seqnum=rand()%1024;
    rec->flags=18;
    seq=rec->seqnum;
    if(send(sendsd,r,nwords,10))     //SYN + ACK
    printf("SYN + ACK sent\n");
    dl=recvtimeout(sendsd,r,nwords,2);     //ACK

    if(dl==-1 || dl==0)
    {
        printf("ACK error\n");
        exit(-1);
    }
    else if(dl==-2)
    {
        printf("ACK Timeout\n");
        exit(-1);
    }
    else if(rec->flags==16 && rec->acknum==seq+1)
    printf("ACK received\n3 way handshake established\n");
    else
    {
        printf("Connection ERROR\n");
        exit(-1);
    }
    shutdown(recsd,2);
    close(recsd);
}

void receiver()
{
    printf("Removing TCP header..\n");
    memset(buffer, 0, LEN);
    FILE *in, *out;
    out = fopen("application_in","wb");
    in = fopen("transport_in","r");
    unsigned char * data = (unsigned char *)(sizeof(struct tcpheader)+buffer);
    int total = fread(buffer, 1, LEN, in);
    total -= sizeof(struct tcpheader);

    if(csum((unsigned short*)buffer, sizeof(struct tcpheader))==0)
    {
        fwrite(data,1,total,out);
    }
    else
    {
        printf("TCP Header Error - CheckSum..!!\n");
        exit(-1);
    }

    fclose(in);
    fclose(out);
}

int main(int argc, char * argv[])
{
    srand(time(NULL));
    printf("Transport Layer ...\n");
    dest_ip = argv[2];
    if(argv[1][0]=='1') send_init(argv[2]);
    else if(argv[1][0]=='3') receive_init();
    else if(argv[1][0]=='2')receiver();
    else {printf("Wrong Agruments.....!!\nAborting....!!\n");exit(-1);}
    printf("Transport Layer exiting....!!\n");
    return 0;
}


text:
package com.consol.citrus.message;

import com.consol.citrus.TestAction;
import com.consol.citrus.endpoint.Endpoint;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Christoph Deppisch
 * @since 2.6.2
 */
public class DefaultMessageStore extends ConcurrentHashMap<String, Message> implements MessageStore {

    @Override
    public Message getMessage(String id) {
        return super.get(id);
    }

    @Override
    public void storeMessage(String id, Message message) {
        super.put(id, message);
    }

    @Override
    public String constructMessageName(TestAction action, Endpoint endpoint) {
        return action.getName() + "(" + endpoint.getName() + ")";
    }
}


text:
#import "UIButton+WebCache.h"
#import "objc/runtime.h"
#import "UIView+WebCacheOperation.h"

static char imageURLStorageKey;

@implementation UIButton (WebCache)

- (NSURL *)kf5_currentImageURL {
    NSURL *url = self.imageURLStorage[@(self.state)];

    if (!url) {
        url = self.imageURLStorage[@(UIControlStateNormal)];
    }

    return url;
}

- (NSURL *)kf5_imageURLForState:(UIControlState)state {
    return self.imageURLStorage[@(state)];
}

- (void)kf5_setImageWithURL:(NSURL *)url forState:(UIControlState)state {
    [self kf5_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
}

- (void)kf5_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
    [self kf5_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
}

- (void)kf5_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
    [self kf5_setImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
}

- (void)kf5_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock {
    [self kf5_setImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
}

- (void)kf5_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
    [self kf5_setImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
}

- (void)kf5_setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {

    [self setImage:placeholder forState:state];
    [self kf5_cancelImageLoadForState:state];

    if (!url) {
        [self.imageURLStorage removeObjectForKey:@(state)];

        dispatch_main_async_safe(^{
            if (completedBlock) {
                NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
                completedBlock(nil, error, SDImageCacheTypeNone, url);
            }
        });

        return;
    }

    self.imageURLStorage[@(state)] = url;

    __weak __typeof(self)wself = self;
    id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        if (!wself) return;
        dispatch_main_sync_safe(^{
            __strong UIButton *sself = wself;
            if (!sself) return;
            if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock)
            {
                completedBlock(image, error, cacheType, url);
                return;
            }
            else if (image) {
                [sself setImage:image forState:state];
            }
            if (completedBlock && finished) {
                completedBlock(image, error, cacheType, url);
            }
        });
    }];
    [self kf5_setImageLoadOperation:operation forState:state];
}

- (void)kf5_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state {
    [self kf5_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
}

- (void)kf5_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder {
    [self kf5_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:nil];
}

- (void)kf5_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options {
    [self kf5_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:options completed:nil];
}

- (void)kf5_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletionBlock)completedBlock {
    [self kf5_setBackgroundImageWithURL:url forState:state placeholderImage:nil options:0 completed:completedBlock];
}

- (void)kf5_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock {
    [self kf5_setBackgroundImageWithURL:url forState:state placeholderImage:placeholder options:0 completed:completedBlock];
}

- (void)kf5_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock {
    [self kf5_cancelBackgroundImageLoadForState:state];

    [self setBackgroundImage:placeholder forState:state];

    if (url) {
        __weak __typeof(self)wself = self;
        id <SDWebImageOperation> operation = [SDWebImageManager.sharedManager downloadImageWithURL:url options:options progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            if (!wself) return;
            dispatch_main_sync_safe(^{
                __strong UIButton *sself = wself;
                if (!sself) return;
                if (image && (options & SDWebImageAvoidAutoSetImage) && completedBlock)
                {
                    completedBlock(image, error, cacheType, url);
                    return;
                }
                else if (image) {
                    [sself setBackgroundImage:image forState:state];
                }
                if (completedBlock && finished) {
                    completedBlock(image, error, cacheType, url);
                }
            });
        }];
        [self kf5_setBackgroundImageLoadOperation:operation forState:state];
    } else {
        dispatch_main_async_safe(^{
            NSError *error = [NSError errorWithDomain:SDWebImageErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"Trying to load a nil url"}];
            if (completedBlock) {
                completedBlock(nil, error, SDImageCacheTypeNone, url);
            }
        });
    }
}

- (void)kf5_setImageLoadOperation:(id<SDWebImageOperation>)operation forState:(UIControlState)state {
    [self kf5_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]];
}

- (void)kf5_cancelImageLoadForState:(UIControlState)state {
    [self kf5_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonImageOperation%@", @(state)]];
}

- (void)kf5_setBackgroundImageLoadOperation:(id<SDWebImageOperation>)operation forState:(UIControlState)state {
    [self kf5_setImageLoadOperation:operation forKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]];
}

- (void)kf5_cancelBackgroundImageLoadForState:(UIControlState)state {
    [self kf5_cancelImageLoadOperationWithKey:[NSString stringWithFormat:@"UIButtonBackgroundImageOperation%@", @(state)]];
}

- (NSMutableDictionary *)imageURLStorage {
    NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey);
    if (!storage)
    {
        storage = [NSMutableDictionary dictionary];
        objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }

    return storage;
}

@end


text:
/* Game namespace */
var game = {

	// an object where to store game information
	data : {
		// score
		minimap: "",
		score: 0,
		enemyBaseHealth: 10,
		playerBaseHealth: 10,
		enemyCreepHealth: 3,
		playerHealth: 10,
		playerAttack: 1,
		playerTimer: 1000,
		enemyCreepAttack: 1,
		playerCreepAttack: 1,
		creepAttackTimer: 1000,
		playerMoveSpeed: 5,
		creepMoveSpeed: 3,
		gameManager: "",
		GameTimerManager: "",
		HeroDeathManager: "",
		spearTimer: 6000,
		player: "",
		playerCreep: "",
		exp: 0,
		gold: 0,
		exp1: 0,
		exp2: 0,
		exp3: 0,
		exp4: 0,
		exp5: 0,
		exp6: 0,
		ability1: 0,
		ability2: 0,
		ability3: 0,
		skill1: 0,
		skill2: 0,
		skill3: 0,
		win: "",
		PausePos: "",
		buyscreen: "",
		buytext: "",
		pausetext: "",
		miniPlayer: "",

	},

	// Run on page load.
	"onload" : function () {
	// Initialize the video.
	if (!me.video.init("screen",  me.video.CANVAS, 1067, 600, true, '1.0')) { //sets screen dimensions
		alert("Your browser does not support HTML5 canvas.");
		return;
	}

	// add "#debug" to the URL to enable the debug Panel
	if (document.location.hash === "#debug") {
		window.onReady(function () {
			me.plugin.register.defer(this, debugPanel, "debug");
		});
	}

	me.save.add({exp: 0, exp1: 0, exp2: 0, exp3: 0, exp4: 0,});

	me.state.SPENDEXP = 112; //112 represents the screen for SPENDEXP
	me.state.LOAD = 113;
	me.state.NEW = 114;

	// Initialize the audio.
	me.audio.init("mp3,ogg");

	// Set a callback to run when loading is complete.
	me.loader.onload = this.loaded.bind(this);

	// Load the resources.
	me.loader.preload(game.resources);

	// Initialize melonJS and display a loading screen.
	me.state.change(me.state.LOADING);
},

	// Run on game resources loaded.
	"loaded" : function () {
		me.pool.register("player", game.PlayerEntity, true); //adding the player to the pool of objects that can be accessed
		me.pool.register("PlayerBase", game.PlayerBaseEntity);
		me.pool.register("EnemyBase", game.EnemyBaseEntity);
		me.pool.register("EnemyCreep", game.EnemyCreep, true);
		me.pool.register("PlayerCreep", game.PlayerCreep, true);
		me.pool.register("GameTimerManager", game.GameTimerManager);
		me.pool.register("HeroDeathManager", game.HeroDeathManager);
		me.pool.register("ExperienceManager", game.ExperienceManager);
		me.pool.register("SpendGold", game.SpendGold);
		me.pool.register("spear", game.SpearThrow, true);
		me.pool.register("PauseScreen", game.PauseScreen);
		me.pool.register("minimap", game.MiniMap, true);
		me.pool.register("miniplayer", game.MiniPlayerLocation, true);

		me.state.set(me.state.MENU, new game.TitleScreen());
		me.state.set(me.state.PLAY, new game.PlayScreen());
		me.state.set(me.state.SPENDEXP, new game.SpendExp());
		me.state.set(me.state.NEW, new game.NewProfile());
		me.state.set(me.state.LOAD, new game.LoadProfile());

		// Start the game.
		me.state.change(me.state.MENU); //when the game is loaded, it starts at the menu screen
	}
};


text:
<?php

namespace com\listBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class listBundle extends Bundle
{
}


text:
<?php

namespace Omines\Tests\Semver\Expressions;

use Omines\Semver\Expression;
use Omines\Semver\Expressions\PrimitiveGenerator;
use Omines\Semver\Version;

/**
 * ExpressionTest.
 *
 * @author Niels Keurentjes <niels.keurentjes@omines.com>
 */
class ExpressionTest extends \PHPUnit\Framework\TestCase
{
    /**
     * @dataProvider variousRangesProvider
     * @param string $string
     */
    public function testExpressionParser($string)
    {
        $expression = Expression::fromString($string);
        $version = Version::fromString('6.8.4-alpha');

        $this->assertEquals($string, $expression->getOriginalString());
        $this->assertEquals($expression->matches($version), $version->matches($expression));
    }

    public function variousRangesProvider()
    {
        $expressions = [
            '^0.0.0',
            '^0.0.1',
            '^0.1.1',
            '~0.0.0',
            '~0.0.1',
            '~0.1.1',
            '=1.2.3',
            '>2.3.4',
            '<3.4.5',
            '!=4.5.6',
            '<>5.6.7',
            '>=4.5.6',
            '<=5.6.7',
            '~6.7.8',
            '^7.8.9',
            '1.2.3 - 2.3.4',
            '1.2 - 2.3',
            '1.2.x',
            '1.*',
            '2.X',
            '*',
            '1.2.3|2.3.4',
            ' 1.2.3 || 2.3.4',
            '1 - 2 | 4 - 5   ',
            '^1.2 | ~2.3 | ~3.4 | ^4.5',
            '^1.2 | ~2.3 | 3.4 - 3.5 | ^4.5',
        ];
        return array_combine($expressions, array_map(function ($item) {
            return [$item];
        }, $expressions));
    }

    /**
     * @dataProvider expressionDataProvider
     *
     * @param string $string
     * @param string $type
     * @param Version $version
     */
    public function testExpression($string, $type, $version)
    {
        $expression = Expression::fromString($string);
        switch ($type) {
            case 'match':
                $this->assertTrue($expression->matches($version));
                break;
            case 'fail':
                $this->assertFalse($expression->matches($version));
                break;
            default:
                // TODO: Implement lt/gt
                $this->markTestSkipped('Expressions with GT/LT are not being tested right now');
                break;
        }
    }

    public function expressionDataProvider()
    {
        $data = json_decode(file_get_contents(FIXTURES_PATH . '/Expressions/ExpressionMatches.json'), JSON_OBJECT_AS_ARRAY);
        foreach ($data as $expression => $tests) {
            foreach ($tests as $type => $versions) {
                foreach ($versions as $version) {
                    yield "$expression $type $version" => [$expression, $type, Version::fromString($version)];
                }
            }
        }
    }

    /**
     * @dataProvider normalizedExpressionDataProvider
     *
     * @param string $input
     * @param string $expected
     */
    public function testExpressionNormalization($input, $expected)
    {
        $this->assertEquals($expected, $expression = Expression::fromString($input));
        $this->assertEquals($expected, Expression::fromString($expression)->getNormalizedString());
    }

    public function normalizedExpressionDataProvider()
    {
        $data = json_decode(file_get_contents(FIXTURES_PATH . '/Expressions/NormalizedExpressions.json'), JSON_OBJECT_AS_ARRAY);
        foreach ($data as $key => $value) {
            yield $value => [$key, $value];
        }
    }

    /**
     * @expectedException \Omines\Semver\Exception\SemverException
     * @expectedExceptionMessage Unknown operator "^="
     */
    public function testPrimitiveGeneratorThrowsOnInvalidOperator()
    {
        PrimitiveGenerator::getInstance()->generate('^=', []);
    }
}


text:
<?php

namespace Swaggest\GoCodeBuilder\Templates\Type;

use Swaggest\GoCodeBuilder\Exception;
use Swaggest\GoCodeBuilder\Templates\Func\FuncDef;
use Swaggest\GoCodeBuilder\Templates\GoTemplate;

class FuncType extends GoTemplate implements AnyType
{
    private $func;

    public function __construct(FuncDef $func)
    {
        $this->func = $func;
    }

    protected function toString()
    {
        // func({$data->iteratorResultGoType}, error) bool
        $res = 'func(';
        if ($this->func->getArguments() !== null) {
            $res .= $this->func->getArguments()->toTypesString();
        }
        $res .= ') ';
        if ($this->func->getResult() !== null) {
            $res .= $this->func->getResult()->toTypesString();
        }
        return trim($res);
    }

    public function getTypeString()
    {
        throw new Exception('TypeString rendering for func is not implemented');
    }

}


text:
<?php

namespace GetOlympus\Zeus\Configuration\Configs\Cleaners\Plugins;

/**
 * Clean Google Tag Manager for WordPress Plugin helper
 *
 * @package    OlympusZeusCore
 * @subpackage Configuration\Configs\Cleaners\Plugins
 * @author     Achraf Chouk <achrafchouk@gmail.com>
 * @since      2.0.10
 * @see        https://wordpress.org/plugins/duracelltomi-google-tag-manager/
 *
 */

class GoogleTagManagerPlugin
{
    /**
     * @var array
     */
    protected $available = [
        'enqueue_scripts',
    ];

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

    /**
     * Constructor.
     *
     * @param  array   $settings
     */
    public function __construct($settings)
    {
        if (empty($settings)) {
            return;
        }

        $this->settings = $settings;

        // Initialize
        $this->init();
    }

    /**
     * Initialize main functions.
     */
    protected function init() : void
    {
        // Special case
        if (is_bool($this->settings) && $this->settings) {
            $this->settings = $this->available;
        }

        // Iterate
        foreach ($this->settings as $key) {
            $key = strtolower($key);

            if (!in_array($key, $this->available)) {
                continue;
            }

            if ('enqueue_scripts' === $key && !OL_ZEUS_ISADMIN) {
                add_filter('gtm4wp_event-outbound', '__return_true');
                add_filter('gtm4wp_event-form-move', '__return_true');
                add_filter('gtm4wp_event-social', '__return_true');
                add_filter('gtm4wp_event-email-clicks', '__return_true');
                add_filter('gtm4wp_event-downloads', '__return_true');
                add_filter('gtm4wp_scroller-enabled', '__return_true');

                if (function_exists('gtm4wp_wp_footer')) {
                    remove_action('wp_footer', 'gtm4wp_wp_footer');
                    add_action('wp_footer', 'gtm4wp_wp_footer', 999);
                }

                if (function_exists('gtm4wp_woocommerce_wp_footer')) {
                    remove_action('wp_footer', 'gtm4wp_woocommerce_wp_footer');
                    add_action('wp_footer', 'gtm4wp_woocommerce_wp_footer', 500);
                }

                continue;
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<ti:app xmlns:ti="http://ti.appcelerator.org">
    <id>com.fayettevillekigs.bandgclub</id>
    <name>the Club</name>
    <version>1.1.3</version>
    <publisher>mcore</publisher>
    <url>http://</url>
    <description>Boys and Girls Club (Sports Edition) of Fayetteville Ar. </description>
    <copyright>2015 theClub</copyright>
    <icon>appicon.png</icon>
    <fullscreen>false</fullscreen>
    <navbar-hidden>false</navbar-hidden>
    <analytics>false</analytics>
    <guid>ad6f0cfe-ef87-47d8-9a17-cc86c7b73a39</guid>
    <property name="ti.ui.defaultunit" type="string">dp</property>
    <ios>
        <plist>
            <dict>
                <key>UISupportedInterfaceOrientations~iphone</key>
                <array>
                    <string>UIInterfaceOrientationPortrait</string>
                </array>
                <key>UISupportedInterfaceOrientations~ipad</key>
                <array>
                    <string>UIInterfaceOrientationPortrait</string>
                    <string>UIInterfaceOrientationPortraitUpsideDown</string>
                    <string>UIInterfaceOrientationLandscapeLeft</string>
                    <string>UIInterfaceOrientationLandscapeRight</string>
                </array>
                <key>UIRequiresPersistentWiFi</key>
                <false/>
                <key>UIPrerenderedIcon</key>
                <false/>
                <key>UIStatusBarHidden</key>
                <false/>
                <key>UIStatusBarStyle</key>
                <string>UIStatusBarStyleDefault</string>
            </dict>
        </plist>
    </ios>
    <property name="ti.android.fastdev" type="bool">false</property>
    <android xmlns:android="http://schemas.android.com/apk/res/android">
        <uses-sdk android:minSdkVersion="14"/>
        <manifest>
            <supports-screens android:anyDensity="false"/>
            <uses-permission android:name="android.permission.INTERNET"/>
            <uses-permission android:name="android.permission.READ_CALENDAR"/>
            <uses-permission android:name="android.permission.WRITE_CALENDAR"/>
        </manifest>
    </android>
    <mobileweb>
        <precache/>
        <splash>
            <enabled>true</enabled>
            <inline-css-images>true</inline-css-images>
        </splash>
        <theme>default</theme>
    </mobileweb>
    <modules>
        <module platform="android">ti.urbanairship</module>
        <module platform="iphone">ti.urbanairship</module>
    </modules>
    <deployment-targets>
        <target device="android">true</target>
        <target device="blackberry">false</target>
        <target device="ipad">false</target>
        <target device="iphone">true</target>
        <target device="mobileweb">false</target>
    </deployment-targets>
    <sdk-version>3.5.0.GA</sdk-version>
    <plugins>
        <plugin version="1.0">ti.alloy</plugin>
    </plugins>
</ti:app>


text:
/* $This file is distributed under the terms of the license in /doc/license.txt$ */

package edu.cornell.mannlib.vitro.webapp.utils.dataGetter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;

import com.hp.hpl.jena.rdf.model.Model;

import edu.cornell.mannlib.vitro.webapp.beans.VClass;
import edu.cornell.mannlib.vitro.webapp.beans.VClassGroup;
import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest;
import edu.cornell.mannlib.vitro.webapp.controller.freemarker.UrlBuilder;
import edu.cornell.mannlib.vitro.webapp.dao.DisplayVocabulary;
import edu.cornell.mannlib.vitro.webapp.dao.VClassGroupsForRequest;
import edu.cornell.mannlib.vitro.webapp.dao.jena.VClassGroupCache;
import edu.cornell.mannlib.vitro.webapp.web.templatemodels.VClassGroupTemplateModel;

/**
 * This will pass these variables to the template:
 * classGroupUri: uri of the classgroup associated with this page.
 * vClassGroup: a data structure that is the classgroup associated with this page.
 */
public class ClassGroupPageData extends DataGetterBase implements DataGetter{

    private static final Log log = LogFactory.getLog(ClassGroupPageData.class);
    String dataGetterURI;
    String classGroupUri;
    VitroRequest vreq;
    ServletContext context;

    /**
     * Constructor with display model and data getter URI that will be called by reflection.
     */
    public ClassGroupPageData(VitroRequest vreq, Model displayModel, String dataGetterURI){
        this.configure(vreq, displayModel,dataGetterURI);
    }

    /**
     * Configure this instance based on the URI and display model.
     */
    protected void configure(VitroRequest vreq, Model displayModel, String dataGetterURI) {
    	if( vreq == null )
    		throw new IllegalArgumentException("VitroRequest  may not be null.");
        if( displayModel == null )
            throw new IllegalArgumentException("Display Model may not be null.");
        if( dataGetterURI == null )
            throw new IllegalArgumentException("PageUri may not be null.");

        this.vreq = vreq;
        this.context = vreq.getSession().getServletContext();
        this.dataGetterURI = dataGetterURI;
        this.classGroupUri = 	DataGetterUtils.getClassGroupForDataGetter(displayModel, dataGetterURI);
    }

    @Override
    public Map<String, Object> getData(Map<String, Object> pageData) {
    	  HashMap<String, Object> data = new HashMap<String,Object>();
          data.put("classGroupUri", this.classGroupUri);

          VClassGroupsForRequest vcgc = VClassGroupCache.getVClassGroups(vreq);
          List<VClassGroup> vcgList = vcgc.getGroups();
          VClassGroup group = null;
          for( VClassGroup vcg : vcgList){
              if( vcg.getURI() != null && vcg.getURI().equals(classGroupUri)){
                  group = vcg;
                  break;
              }
          }
          if( classGroupUri != null && !classGroupUri.isEmpty() && group == null ){
              /*This could be for two reasons: one is that the classgroup doesn't exist
               * The other is that there are no individuals in any of the classgroup's classes */
              group = vreq.getWebappDaoFactory().getVClassGroupDao().getGroupByURI(classGroupUri);
              if( group != null ){
                  List<VClassGroup> vcgFullList = vreq.getWebappDaoFactory().getVClassGroupDao()
                      .getPublicGroupsWithVClasses(false, true, false);
                  for( VClassGroup vcg : vcgFullList ){
                      if( classGroupUri.equals(vcg.getURI()) ){
                          group = vcg;
                          break;
                      }
                  }

                  setAllClassCountsToZero(group);

                  log.debug("Retrieved class group " + group.getURI()
                        + " and returning to template");
                  if (log.isDebugEnabled()) {
                      List<VClass> groupClasses = group.getVitroClassList();
                      for (VClass v : groupClasses) {
                        log.debug("Class " + v.getName() + " - " + v.getURI()
                                + " has " + v.getEntityCount() + " entities");
                      }
                  }
              }else{
                  throw new RuntimeException("classgroup " + classGroupUri + " does not exist in the system");
              }
          }

          data.put("vClassGroup", group);  //may put null

          // WheatVIVO addition
	  // We have override this Java class to put the class group label and URI in the data map
	  // because Freemarker is apparently a dumb piece of garbage that assumes that because
	  // an object implements a collections interface (e.g. the group) it can't possibly also
	  // have other methods we might like to call in addition
          data.put("vClassGroupURI", group.getURI());
	  data.put("vClassGroupPublicName", group.getPublicName());

          //This page level data getters tries to set its own template,
          // not all of the data getters need to do this.
          data.put("bodyTemplate", "page-classgroup.ftl");

          //Also add data service url
          //Hardcoding for now, need a more dynamic way of doing this
          data.put("dataServiceUrlIndividualsByVClass", this.getDataServiceUrl());
          return data;
    }

    public static VClassGroupTemplateModel getClassGroup(String classGroupUri, ServletContext context, VitroRequest vreq){

        VClassGroupsForRequest vcgc = VClassGroupCache.getVClassGroups(vreq);
        List<VClassGroup> vcgList = vcgc.getGroups();
        VClassGroup group = null;
        for( VClassGroup vcg : vcgList){
            if( vcg.getURI() != null && vcg.getURI().equals(classGroupUri)){
                group = vcg;
                break;
            }
        }

        if( classGroupUri != null && !classGroupUri.isEmpty() && group == null ){
            /*This could be for two reasons: one is that the classgroup doesn't exist
             * The other is that there are no individuals in any of the classgroup's classes */
            group = vreq.getWebappDaoFactory().getVClassGroupDao().getGroupByURI(classGroupUri);
            if( group != null ){
                List<VClassGroup> vcgFullList = vreq.getWebappDaoFactory().getVClassGroupDao()
                    .getPublicGroupsWithVClasses(false, true, false);
                for( VClassGroup vcg : vcgFullList ){
                    if( classGroupUri.equals(vcg.getURI()) ){
                        group = vcg;
                        break;
                    }
                }
                if( group == null ){
                    log.error("Cannot get classgroup '" + classGroupUri + "'");
                    return null;
                }else{
                    setAllClassCountsToZero(group);
                }
            }else{
                log.error("classgroup " + classGroupUri + " does not exist in the system");
                return null;
            }
        }

        return new VClassGroupTemplateModel(group);
    }

  //Get data servuice
    public String getDataServiceUrl() {
    	return UrlBuilder.getUrl("/dataservice?getRenderedSearchIndividualsByVClass=1&vclassId=");
    }

    /**
     * Query to get the definition of the ClassGroupDataGetter for a given data getter URI - specifically
     * the class group uri
     */
    private static final String forClassGroupURI = "<" + DisplayVocabulary.FOR_CLASSGROUP + ">";
    private static final String dataGetterQuery =
        "PREFIX display: <" + DisplayVocabulary.DISPLAY_NS +"> \n" +
        "SELECT ?classGroupUri WHERE { \n" +
        "  ?dataGetterUri "+forClassGroupURI+" ?classGroupUri . \n" +
        "}";

    /**
     * For processing of JSONObject
     */
    //Currently empty, TODO: Review requirements
    public JSONObject convertToJSON(Map<String, Object> dataMap, VitroRequest vreq) {
    	JSONObject rObj = null;
    	return rObj;
    }
    protected static void setAllClassCountsToZero(VClassGroup vcg){
        for(VClass vc : vcg){
            vc.setEntityCount(0);
        }
    }
}


text:
using System;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using System.Collections;
using System.IO;
using System.Threading;

namespace System.Runtime.Remoting.Channels.Tcp
{
	internal class TcpClientTransportSink : IClientChannelSink
	{
		string _host;
		int _port;

		public TcpClientTransportSink (string url)
		{
			string objectUri;
			_host = TcpChannel.ParseTcpURL (url, out objectUri, out _port);
		}

		public IDictionary Properties
		{
			get
			{
				return null;
			}
		}

		public IClientChannelSink NextChannelSink
		{
			get
			{
				// we are the last one
				return null;
			}
		}

		public void AsyncProcessRequest (IClientChannelSinkStack sinkStack, IMessage msg,
			ITransportHeaders headers, Stream requestStream)
		{
			TcpConnection connection = null;
			bool isOneWay = RemotingServices.IsOneWay (((IMethodMessage)msg).MethodBase);

			try
			{
				if (headers == null) headers = new TransportHeaders();
				headers [CommonTransportKeys.RequestUri] = ((IMethodMessage)msg).Uri;

				// Sends the stream using a connection from the pool
				// and creates a WorkItem that will wait for the
				// response of the server

				connection = TcpConnectionPool.GetConnection (_host, _port);
				TcpMessageIO.SendMessageStream (connection.Stream, requestStream, headers, connection.Buffer);
				connection.Stream.Flush ();

				if (!isOneWay)
				{
					sinkStack.Push (this, connection);
					ThreadPool.QueueUserWorkItem (new WaitCallback(ReadAsyncTcpMessage), sinkStack);
				}
				else
					connection.Release();
			}
			catch
			{
				if (connection != null) connection.Release();
				if (!isOneWay) throw;
			}
		}

		private void ReadAsyncTcpMessage(object data)
		{
			// This method is called by a new thread to asynchronously
			// read the response to a request

			// The stack was provided as state data in QueueUserWorkItem
			IClientChannelSinkStack stack = (IClientChannelSinkStack)data;

			// The first sink in the stack is this sink. Pop it and
			// get the status data, which is the TcpConnection used to send
			// the request
			TcpConnection connection = (TcpConnection)stack.Pop(this);

			try
			{
				ITransportHeaders responseHeaders;

				// Read the response, blocking if necessary
				MessageStatus status = TcpMessageIO.ReceiveMessageStatus (connection.Stream, connection.Buffer);

				if (status != MessageStatus.MethodMessage)
					throw new RemotingException ("Unknown response message from server");

				Stream responseStream = TcpMessageIO.ReceiveMessageStream (connection.Stream, out responseHeaders, connection.Buffer);

				// Free the connection, so it can be reused
				connection.Release();
				connection = null;

				// Ok, proceed with the other sinks
				stack.AsyncProcessResponse (responseHeaders, responseStream);
			}
			catch
			{
				if (connection != null) connection.Release();
				throw;
			}
		}

		public void AsyncProcessResponse (IClientResponseChannelSinkStack sinkStack,
			object state, ITransportHeaders headers,
			Stream stream)
		{
			// Should never be called
			throw new NotSupportedException();
		}

		public Stream GetRequestStream (IMessage msg, ITransportHeaders headers)
		{
			return null;
		}

		public void ProcessMessage (IMessage msg,
			ITransportHeaders requestHeaders,
			Stream requestStream,
			out ITransportHeaders responseHeaders,
			out Stream responseStream)
		{
			TcpConnection connection = null;
			try
			{
				if (requestHeaders == null) requestHeaders = new TransportHeaders();
				requestHeaders [CommonTransportKeys.RequestUri] = ((IMethodMessage)msg).Uri;

				// Sends the message
				connection = TcpConnectionPool.GetConnection (_host, _port);
				TcpMessageIO.SendMessageStream (connection.Stream, requestStream, requestHeaders, connection.Buffer);
				connection.Stream.Flush ();

				// Reads the response
				MessageStatus status = TcpMessageIO.ReceiveMessageStatus (connection.Stream, connection.Buffer);

				if (status != MessageStatus.MethodMessage)
					throw new RemotingException ("Unknown response message from server");

				responseStream = TcpMessageIO.ReceiveMessageStream (connection.Stream, out responseHeaders, connection.Buffer);
			}
			finally
			{
				if (connection != null)
					connection.Release();
			}
		}

	}

}


text:
package com.cezarykluczynski.stapi.model.animal.repository;

import com.cezarykluczynski.stapi.model.animal.dto.AnimalRequestDTO;
import com.cezarykluczynski.stapi.model.animal.entity.Animal;
import com.cezarykluczynski.stapi.model.animal.entity.Animal_;
import com.cezarykluczynski.stapi.model.animal.query.AnimalQueryBuilderFactory;
import com.cezarykluczynski.stapi.model.common.query.QueryBuilder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;

@Repository
public class AnimalRepositoryImpl implements AnimalRepositoryCustom {

	private final AnimalQueryBuilderFactory animalQueryBuilderFactory;

	public AnimalRepositoryImpl(AnimalQueryBuilderFactory animalQueryBuilderFactory) {
		this.animalQueryBuilderFactory = animalQueryBuilderFactory;
	}

	@Override
	public Page<Animal> findMatching(AnimalRequestDTO criteria, Pageable pageable) {
		QueryBuilder<Animal> animalQueryBuilder = animalQueryBuilderFactory.createQueryBuilder(pageable);

		animalQueryBuilder.equal(Animal_.uid, criteria.getUid());
		animalQueryBuilder.like(Animal_.name, criteria.getName());
		animalQueryBuilder.equal(Animal_.earthAnimal, criteria.getEarthAnimal());
		animalQueryBuilder.equal(Animal_.earthInsect, criteria.getEarthInsect());
		animalQueryBuilder.equal(Animal_.avian, criteria.getAvian());
		animalQueryBuilder.equal(Animal_.canine, criteria.getCanine());
		animalQueryBuilder.equal(Animal_.feline, criteria.getFeline());
		animalQueryBuilder.setSort(criteria.getSort());

		return animalQueryBuilder.findPage();
	}

}


text:
package org.openrdf.repository.object.codegen;

import org.openrdf.repository.object.base.CodeGenTestCase;

public class Base64BinaryTest extends CodeGenTestCase {

	public void testOneOf() throws Exception {
		addRdfSource("/ontologies/xsd-datatypes.rdf");
		addRdfSource("/ontologies/rdfs-schema.rdf");
		addRdfSource("/ontologies/owl-schema.rdf");
		addRdfSource("/ontologies/binary-ontology.owl");
		createJar("binary.jar");
	}

}


text:
```php
$comment = $commentableResource->comments()->index();
```

## Show a comment

```php
$comment = $commentableResource->comments()->show($id);
```

## Create a new comment

```php
$comment = $commentableResource->comments()->store('Hello!');
```

## Update a comment

```php
$comment->update('Bye!');

// Or update with ID.
$commentableResource->comments()->update($id, 'Bye!');
```

## Delete a comment

```php
$comment->destroy();

// Or destroy with ID.
$commentableResource->comments()->destroy($id);
```


text:
package org.dasein.cloud.platform;

import org.dasein.cloud.CloudException;
import org.dasein.cloud.CloudProvider;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.OperationNotSupportedException;
import org.dasein.util.uom.time.Second;
import org.dasein.util.uom.time.TimePeriod;

import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;

/**
 * Creation options for creating message queues.
 *
Created by George Reese: 7/24/13 4:50 AM

 * @author George Reese
 * @version 2013.07 initial version (issue #76)
 * @since 2013.07
 */
public class MQCreateOptions {
    /**
     * Provides a basic set of options for creating a message queue with the specified name and description. The options
     * will support a default visibility timeout of 15 seconds.
     * @param name the name for the message queue to be created
     * @param description the description for the message queue to be created
     * @return options for creating the desired message queue
     */
    static public @Nonnull MQCreateOptions getInstance(@Nonnull String name, @Nonnull String description) {
        MQCreateOptions options = new MQCreateOptions();

        options.name= name;
        options.description = description;
        options.visibilityTimeout = new TimePeriod<Second>(15, TimePeriod.SECOND);
        return options;
    }

    private String             description;
    private Map<String,String> metaData;
    private String             name;
    private TimePeriod<Second> visibilityTimeout;

    private MQCreateOptions() { }

    /**
     * Creates a message queue in the specified cloud based on the contents of this options object.
     * @param provider the provider object for the cloud in which the message queue should be created
     * @return the ID of the newly created message queue
     * @throws CloudException an error occurred with the cloud provider while making the snapshot
     * @throws InternalException an error occurred within the Dasein Cloud implementation
     * @throws OperationNotSupportedException snapshots are not supported in this cloud
     */
    public @Nonnull String build(@Nonnull CloudProvider provider) throws CloudException, InternalException {
        PlatformServices services = provider.getPlatformServices();

        if( services == null ) {
            throw new OperationNotSupportedException(provider.getCloudName() + " does not support platform services");
        }
        MQSupport support = services.getMessageQueueSupport();

        if( support == null ) {
            throw new OperationNotSupportedException(provider.getCloudName() + " does not support message queues");
        }
        return support.createMessageQueue(this);
    }

    /**
     * @return a description of the message queue
     */
    public @Nonnull String getDescription() {
        return description;
    }

    /**
     * @return any extra meta-data to assign to the message queue
     */
    public @Nonnull Map<String,String> getMetaData() {
        return (metaData == null ? new HashMap<String, String>() : metaData);
    }

    /**
     * @return a name for the message queue
     */
    public @Nonnull String getName() {
        return name;
    }

    /**
     * @return the length of time that a message received from a queue will be invisible to other receiving components when they ask to receive messages
     */
    public @Nonnull TimePeriod<Second> getVisibilityTimeout() {
        return visibilityTimeout;
    }

    /**
     * Specifies any meta-data to be associated with the message queue when created. This method is
     * accretive, meaning that it adds to any existing meta-data (or replaces an existing key).
     * @param key the key of the meta-data entry
     * @param value the value for the meta-data entry
     * @return this
     */
    public @Nonnull MQCreateOptions withMetaData(@Nonnull String key, @Nonnull String value) {
        if( metaData == null ) {
            metaData = new HashMap<String, String>();
        }
        metaData.put(key, value);
        return this;
    }

    /**
     * Specifies meta-data to add onto any existing meta-data being associated with this message queue when created.
     * This method is accretive, meaning that it adds to any existing meta-data (or replaces an existing keys).
     * @param metaData the meta-data to be set for the new firewall
     * @return this
     */
    public @Nonnull MQCreateOptions withMetaData(@Nonnull Map<String,String> metaData) {
        if( this.metaData == null ) {
            this.metaData = new HashMap<String, String>();
        }
        this.metaData.putAll(metaData);
        return this;
    }

    @Override
    public @Nonnull String toString() {
        return ("[create -> " + name + " with timeout=" + visibilityTimeout + "]");
    }
}


text:
import ast
import os
import sys

from setuptools import (
    find_packages,
    setup,
)

def get_version():
    path = os.path.join(os.path.dirname(__file__), 'threema', 'gateway', '__init__.py')
    with open(path) as file:
        for line in file:
            if line.startswith('__version__'):
                _, value = line.split('=', maxsplit=1)
                return ast.literal_eval(value.strip())
        else:
            raise Exception('Version not found in {}'.format(path))

def read(file):
    return open(os.path.join(os.path.dirname(__file__), file)).read().strip()

# Allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

# Import long description
long_description = '\n\n'.join((read('README.rst'), read('CHANGELOG.rst')))

# Check python version
py_version = sys.version_info[:3]
if py_version < (3, 7, 0):
    raise Exception("threema.gateway requires Python >= 3.7")

# Test requirements
# Note: These are just tools that aren't required, so a version range
#       is not necessary here.
tests_require = [
    'pytest>=7.1..2,<8',
    'pytest-asyncio>=0.18.3,<0.19',
    'pytest-cov>=3.0.0,<4',
    'flake8==4.0.1',
    'isort==5.10.1',
    'collective.checkdocs>=0.2,<0.3',
    'Pygments>=2.12.0',  # required by checkdocs
    'mypy==0.961',
]

setup(
    name='threema.gateway',
    version=get_version(),
    packages=find_packages(include=["threema.*"]),
    install_requires=[
        'logbook>=1.1.0,<2',
        'libnacl>=1.5.2,<2',
        'click>=8,<9',
        'aiohttp>=3.7.3,<4',
        'wrapt>=1.10.10,<2',
    ],
    tests_require=tests_require,
    extras_require={
        'dev': tests_require,
        'uvloop': ['uvloop>=0.8.0,<2'],
    },
    include_package_data=True,
    entry_points={
        'console_scripts': [
            'threema-gateway = threema.gateway.bin.gateway_client:main',
        ],
    },

    # PyPI metadata
    author='Lennart Grahl',
    author_email='lennart.grahl@gmail.com',
    description=('An API for the Threema gateway service to send and receive '
                 'messages including text, images, files and delivery reports.'),
    long_description=long_description,
    license='MIT License',
    keywords='threema gateway service sdk api',
    url='https://gateway.threema.ch/',
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'Intended Audience :: System Administrators',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Operating System :: OS Independent',
        'Programming Language :: Python :: 3 :: Only',
        'Topic :: Communications :: Chat',
        'Topic :: Internet :: WWW/HTTP',
        'Topic :: Security',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: System :: Logging',
    ],
)


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v10/common/criteria.proto

package com.google.ads.googleads.v10.common;

public interface HotelCountryRegionInfoOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v10.common.HotelCountryRegionInfo)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * The Geo Target Constant resource name.
   *

   *
   * optional string country_region_criterion = 2;
   * @return Whether the countryRegionCriterion field is set.
   */
  boolean hasCountryRegionCriterion();
  /**
   *

   * The Geo Target Constant resource name.
   *

   *
   * optional string country_region_criterion = 2;
   * @return The countryRegionCriterion.
   */
  java.lang.String getCountryRegionCriterion();
  /**
   *

   * The Geo Target Constant resource name.
   *

   *
   * optional string country_region_criterion = 2;
   * @return The bytes for countryRegionCriterion.
   */
  com.google.protobuf.ByteString
      getCountryRegionCriterionBytes();
}


text:
using System;
using Adaptive.Arp.Api;

namespace Adaptive.Arp.Api.Impl
{

     /**
        Interface for Managing the Network reachability operations
        Auto-generated implementation of INetworkReachability specification.
     */
     public class NetworkReachabilityDelegate : BaseCommunicationDelegate, INetworkReachability
     {

          /**
             Default Constructor.
          */
          public NetworkReachabilityDelegate() : base()
          {
          }

          /**
             Whether there is connectivity to a host, via domain name or ip address, or not.

             @param host     domain name or ip address of host.
             @param callback Callback called at the end.
             @since v2.0
          */
          public void IsNetworkReachable(string host, INetworkReachabilityCallback callback) {
               // TODO: Not implemented.
               throw new NotSupportedException("NetworkReachabilityDelegate:isNetworkReachable");
          }

          /**
             Whether there is connectivity to an url of a service or not.

             @param url      to look for
             @param callback Callback called at the end
             @since v2.0
          */
          public void IsNetworkServiceReachable(string url, INetworkReachabilityCallback callback) {
               // TODO: Not implemented.
               throw new NotSupportedException("NetworkReachabilityDelegate:isNetworkServiceReachable");
          }

     }
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/


text:
<?php
namespace rockunit;

use rock\validate\Validate;

class OddTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @dataProvider providerValid
     */
    public function testValid($input)
    {
        $v = Validate::odd();
        $this->assertTrue($v->validate($input));
    }

    /**
     * @dataProvider providerInvalid
     */
    public function testInvalid($input)
    {
        $v = Validate::odd();
        $this->assertFalse($v->validate($input));
    }

    public function providerValid()
    {
        return [
            [''],
            [-5],
            [-1],
            [1],
            [13],
        ];
    }

    public function providerInvalid()
    {
        return [
            [-2],
            [-0],
            [0],
            [32],
        ];
    }
}


text:
require 'spec_helper'

describe UserAnnouncements::MiscHelper do

  describe '#ua_bootstrap?' do
    before { @_config = UserAnnouncements[:bootstrap] }
    after  { UserAnnouncements.config.bootstrap = @_config }

    it "true if params[:bootstrap] is true" do
      UserAnnouncements.config.bootstrap = false
      helper.stub(params: {bootstrap: 'true'})
      helper.should be_ua_bootstrap

      helper.stub(params: {bootstrap: 'false'})
      helper.should_not be_ua_bootstrap
    end

    it "true if config true" do
      UserAnnouncements.config.bootstrap = true
      helper.should be_ua_bootstrap

      UserAnnouncements.config.bootstrap = false
      helper.should_not be_ua_bootstrap
    end
  end

  describe '#ua_bootstrap_datetime_picker?' do
    before { @_config_bs = UserAnnouncements[:bootstrap_datetime_picker] }
    after  { UserAnnouncements.config.bootstrap = @_config_bs }

    before { @_config_dtp = UserAnnouncements[:bootstrap_datetime_picker] }
    after  { UserAnnouncements.config.bootstrap = @_config_dtp }

    it "true if params[:bootstrap] is true" do
      UserAnnouncements.config.bootstrap = false
      UserAnnouncements.config.bootstrap_datetime_picker = false
      helper.stub(params: {bootstrap: 'true'})
      helper.should be_ua_bootstrap_datetime_picker

      helper.stub(params: {bootstrap: 'false'})
      helper.should_not be_ua_bootstrap_datetime_picker
    end

    it "true if config true" do
      UserAnnouncements.config.bootstrap = true
      UserAnnouncements.config.bootstrap_datetime_picker = true
      helper.should be_ua_bootstrap_datetime_picker
    end

    it "false if config false" do
      UserAnnouncements.config.bootstrap_datetime_picker = false
      helper.should_not be_ua_bootstrap_datetime_picker
    end

    it "false if bootstrap false" do
      UserAnnouncements.config.bootstrap = false
      UserAnnouncements.config.bootstrap_datetime_picker = true
      helper.should_not be_ua_bootstrap_datetime_picker
    end
  end

end


text:
use std::fmt::{self};

use header;

/// The `Access-Control-Request-Headers` request header,
/// part of [CORS](http://www.w3.org/TR/cors/).
///
/// > The `Access-Control-Request-Headers` header indicates which headers will
/// > be used in the actual request as part of the preflight request.
///
/// Spec: www.w3.org/TR/cors/#access-control-request-headers-request-header
#[derive(Clone, PartialEq, Debug)]
pub struct AccessControlRequestHeaders(pub Vec<String>);

impl header::Header for AccessControlRequestHeaders {
    #[inline]
    fn header_name() -> &'static str {
        "Access-Control-Request-Headers"
    }

    fn parse_header(raw: &[Vec<u8>]) -> Option<AccessControlRequestHeaders> {
        header::parsing::from_comma_delimited(raw).map(AccessControlRequestHeaders)
    }
}

impl header::HeaderFormat for AccessControlRequestHeaders {
    fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let AccessControlRequestHeaders(ref parts) = *self;
        header::parsing::fmt_comma_delimited(f, parts.as_slice())
    }
}


text:
namespace carve {
namespace geom3d {

struct hash_vector_ptr {
  size_t operator()(const Vector* const& v) const { return (size_t)v; }
  size_t operator()(const std::pair<const Vector*, const Vector*>& v) const {
    size_t r = (size_t)v.first;
    size_t s = (size_t)v.second;
    return r ^ ((s >> 16) | (s << 16));
  }
};

struct vec_adapt_ident {
  const Vector& operator()(const Vector& v) const { return v; }
  Vector& operator()(Vector& v) const { return v; }
};

struct vec_adapt_ptr {
  const Vector& operator()(const Vector* const& v) const { return *v; }
  Vector& operator()(Vector*& v) const { return *v; }
};

struct vec_adapt_pair_first {
  template <typename pair_t>
  const Vector& operator()(const pair_t& v) const {
    return v.first;
  }
  template <typename pair_t>
  Vector& operator()(pair_t& v) const {
    return v.first;
  }
};

struct vec_adapt_pair_second {
  template <typename pair_t>
  const Vector& operator()(const pair_t& v) const {
    return v.second;
  }
  template <typename pair_t>
  Vector& operator()(pair_t& v) const {
    return v.second;
  }
};

template <typename adapt_t>
struct vec_cmp_lt_x {
  adapt_t adapt;
  vec_cmp_lt_x(adapt_t _adapt = adapt_t()) : adapt(_adapt) {}
  template <typename input_t>
  bool operator()(const input_t& a, const input_t& b) const {
    return adapt(a).x < adapt(b).x;
  }
};
template <typename adapt_t>
vec_cmp_lt_x<adapt_t> vec_lt_x(adapt_t& adapt) {
  return vec_cmp_lt_x<adapt_t>(adapt);
}

template <typename adapt_t>
struct vec_cmp_lt_y {
  adapt_t adapt;
  vec_cmp_lt_y(adapt_t _adapt = adapt_t()) : adapt(_adapt) {}
  template <typename input_t>
  bool operator()(const input_t& a, const input_t& b) const {
    return adapt(a).y < adapt(b).y;
  }
};
template <typename adapt_t>
vec_cmp_lt_y<adapt_t> vec_lt_y(adapt_t& adapt) {
  return vec_cmp_lt_y<adapt_t>(adapt);
}

template <typename adapt_t>
struct vec_cmp_lt_z {
  adapt_t adapt;
  vec_cmp_lt_z(adapt_t _adapt = adapt_t()) : adapt(_adapt) {}
  template <typename input_t>
  bool operator()(const input_t& a, const input_t& b) const {
    return adapt(a).z < adapt(b).z;
  }
};
template <typename adapt_t>
vec_cmp_lt_z<adapt_t> vec_lt_z(adapt_t& adapt) {
  return vec_cmp_lt_z<adapt_t>(adapt);
}

template <typename adapt_t>
struct vec_cmp_gt_x {
  adapt_t adapt;
  vec_cmp_gt_x(adapt_t _adapt = adapt_t()) : adapt(_adapt) {}
  template <typename input_t>
  bool operator()(const input_t& a, const input_t& b) const {
    return adapt(a).x > adapt(b).x;
  }
};
template <typename adapt_t>
vec_cmp_gt_x<adapt_t> vec_gt_x(adapt_t& adapt) {
  return vec_cmp_gt_x<adapt_t>(adapt);
}

template <typename adapt_t>
struct vec_cmp_gt_y {
  adapt_t adapt;
  vec_cmp_gt_y(adapt_t _adapt = adapt_t()) : adapt(_adapt) {}
  template <typename input_t>
  bool operator()(const input_t& a, const input_t& b) const {
    return adapt(a).y > adapt(b).y;
  }
};
template <typename adapt_t>
vec_cmp_gt_y<adapt_t> vec_gt_y(adapt_t& adapt) {
  return vec_cmp_gt_y<adapt_t>(adapt);
}

template <typename adapt_t>
struct vec_cmp_gt_z {
  adapt_t adapt;
  vec_cmp_gt_z(adapt_t _adapt = adapt_t()) : adapt(_adapt) {}
  template <typename input_t>
  bool operator()(const input_t& a, const input_t& b) const {
    return adapt(a).z > adapt(b).z;
  }
};
template <typename adapt_t>
vec_cmp_gt_z<adapt_t> vec_gt_z(adapt_t& adapt) {
  return vec_cmp_gt_z<adapt_t>(adapt);
}

template <typename iter_t, typename adapt_t>
void sortInDirectionOfRay(const Vector& ray_dir, iter_t begin, iter_t end,
                          adapt_t adapt) {
  switch (carve::geom::largestAxis(ray_dir)) {
    case 0:
      if (ray_dir.x > 0) {
        std::sort(begin, end, vec_lt_x(adapt));
      } else {
        std::sort(begin, end, vec_gt_x(adapt));
      }
      break;
    case 1:
      if (ray_dir.y > 0) {
        std::sort(begin, end, vec_lt_y(adapt));
      } else {
        std::sort(begin, end, vec_gt_y(adapt));
      }
      break;
    case 2:
      if (ray_dir.z > 0) {
        std::sort(begin, end, vec_lt_z(adapt));
      } else {
        std::sort(begin, end, vec_gt_z(adapt));
      }
      break;
  }
}
}  // namespace geom3d
}  // namespace carve


text:
Release history
===============

0.12.1
------

* Issue #25: Complex python files could cause an "maximum recursion depth exceeded"
  exception due to using stack-based recursion to walk the module AST.

0.12
----

* Added 'modulegraph.modulegraph.InvalidSourceModule'. This graph node is
  used for Python source modules that cannot be compiled (for example because
  they contain syntax errors).

  This is primarily useful for being able to create a graph for packages
  that have python 2.x or python 3.x compatibility in separate modules that
  contain code that isn't valid in the "other" python version.

* Added 'modulegraph.modulegraph.InvalidCompiledModule'. This graph node
  is used for Python bytecode modules that cannot be loaded.

* Added 'modulegraph.modulegraph.NamespacePackage'.

  Patch by bitbucket user htgoebel.

* No longer add a MissingModule node to the graph for 'collections.defaultdict'
  when using 'from collections import defaultdict' ('collections.defaultdict'
  is an attribute of 'collections', not a submodule).

* Fixed typo in ModuleGraph.getReferences()

* Added ModuleGraph.getReferers(tonode). This methods yields the
  nodes that are referencing *tonode* (the reverse of getReferences)

* The graph will no longer contain MissingModule nodes when using 'from ... import name' to
  import a global variable in a python module.

  There will still be MissingModule nodes for global variables in C extentions, and
  for 'from missing import name' when 'missing' is itself a MissingModule.

* Issue #18: Don't assume that a PEP 302 loader object has a ``path`` attribute. That
  attribute is not documented and is not always present.

0.11.2
------

*

0.11.1
------

* Issue #145: Don't exclude the platform specific 'path' modules (like ntpath)

0.11
----

This is a feature release

Features
........

* Hardcode knowlegde about the compatibility aliases in the email
  module (for python 2.5 upto 3.0).

  This makes it possible to remove a heavy-handed recipe from py2app.

* Added ``modegraph.zipio.getmode`` to fetch the Unix file mode
  for a file.

* Added some handy methods to ``modulegraph.modulegraph.ModuleGraph``.

0.10.5
------

This is a bugfix release

* Don't look at the file extension to determine the file type
  in modulegraph.find_modules.parse_mf_results, but use the
  class of the item.

* Issue #13: Improved handing of bad relative imports
  ("from .foo import bar"), these tended to raise confusing errors and
  are now handled like any other failed import.

0.10.4
------

This is a bugfix release

* There were no 'classifiers' in the package metadata due to a bug
  in setup.py.

0.10.3
------

This is a bugfix release

Bugfixes
........

* ``modulegraph.find.modules.parse_mf_results`` failed when the main script of
  a py2app module didn't have a file name ending in '.py'.

0.10.2
------

This is a bugfix release

Bugfixes
........

* Issue #12: modulegraph would sometimes find the wrong package *__init__*
  module due to using the wrong search method. One easy way to reproduce the
  problem was to have a toplevel module named *__init__*.

  Reported by Kentzo.

0.10.1
------

This is a bugfix release

Bugfixes
........

* Issue #11: creating xrefs and dotty graphs from modulegraphs (the --xref
  and --graph options of py2app) didn't work with python 3 due to use of
  APIs that aren't available in that version of python.

  Reported by Andrew Barnert.

0.10
----

This is a minor feature release

Features
........

* ``modulegraph.find_modules.find_needed_modules`` claimed to automaticly
  include subpackages for the "packages" argument as well, but that code
  didn't work at all.

* Issue #9: The modulegraph script is deprecated, use
  "python -mmodulegraph" instead.

* Issue #10: Ensure that the result of "zipio.open" can be used
  in a with statement (that is, ``with zipio.open(...) as fp``.

* No longer use "2to3" to support Python 3.

  Because of this modulegraph now supports Python 2.6
  and later.

* Slightly improved HTML output, which makes it easier
  to manipulate the generated HTML using JavaScript.

  Patch by anatoly techtonik.

* Ensure modulegraph works with changes introduced after
  Python 3.3b1.

* Implement support for PEP 420 ("Implicit namespace packages")
  in Python 3.3.

* ``modulegraph.util.imp_walk`` is deprecated and will be
  removed in the next release of this package.

Bugfixes
........

* The module graph was incomplete, and generated incorrect warnings
  along the way, when a subpackage contained import statements for
  submodules.

  An example of this is ``sqlalchemy.util``, the ``__init__.py`` file
  for this package contains imports of modules in that modules using
  the classic relative import syntax (that is ``import compat`` to
  import ``sqlalchemy.util.compat``). Until this release modulegraph
  searched the wrong path to locate these modules (and hence failed
  to find them).

0.9.2
-----

This is a bugfix release

Bugfixes
........

* The 'packages' option to modulegraph.find_modules.find_modules ignored
  the search path argument but always used the default search path.

* The 'imp_find_modules' function in modulegraph.util has an argument 'path',
  this was a string in previous release and can now also be a sequence.

* Don't crash when a module on the 'includes' list doesn't exist, but warn
  just like for missing 'packages' (modulegraph.find_modules.find_modules)

0.9.1
-----

This is a bugfix release

Bug fixes
.........

- Fixed the name of nodes imports in packages where the first element of
  a dotted name can be found but the rest cannot. This used to create
  a MissingModule node for the dotted name in the global namespace instead
  of relative to the package.

  That is, given a package "pkg" with submodule "sub" if the "__init__.py"
  of "pkg" contains "import sub.nomod" we now create a MissingModule node
  for "pkg.sub.nomod" instead of "sub.nomod".

  This fixes an issue with including the crcmod package in application
  bundles, first reported on the pythonmac-sig mailinglist by
  Brendan Simon.

0.9
---

This is a minor feature release

Features:

- Documentation is now generated using `sphinx <http://pypi.python.org/pypi/sphinx>`_
  and can be viewed at <http://packages.python.org/modulegraph>.

  The documention is very rough at this moment and in need of reorganisation and
  language cleanup. I've basiclly writting the current version by reading the code
  and documenting what it does, the order in which classes and methods are document
  is therefore not necessarily the most useful.

- The repository has moved to bitbucket

- Renamed ``modulegraph.modulegraph.AddPackagePath`` to ``addPackagePath``,
  likewise ``ReplacePackage`` is now ``replacePackage``. The old name is still
  available, but is deprecated and will be removed before the 1.0 release.

- ``modulegraph.modulegraph`` contains two node types that are unused and
  have unclear semantics: ``FlatPackage`` and ``ArchiveModule``. These node
  types are deprecated and will be removed before 1.0 is released.

- Added a simple commandline tool (``modulegraph``) that will print information
  about the dependency graph of a script.

- Added a module (``zipio``) for dealing with paths that may refer to entries
  inside zipfiles (such as source paths referring to modules in zipped eggfiles).

  With this addition ``modulegraph.modulegraph.os_listdir`` is deprecated and
  it will be removed before the 1.0 release.

Bug fixes:

- The ``__cmp__`` method of a Node no longer causes an exception
  when the compared-to object is not a Node. Patch by Ivan Kozik.

- Issue #1: The initialiser for ``modulegraph.ModuleGraph`` caused an exception
  when an entry on the path (``sys.path``) doesn't actually exist.

  Fix by "skurylo", testcase by Ronald.

- The code no longer worked with python 2.5, this release fixes that.

- Due to the switch to mercurial setuptools will no longer include
  all required files. Fixed by adding a MANIFEST.in file

- The method for printing a ``.dot`` representation of a ``ModuleGraph``
  works again.

0.8.1
-----

This is a minor feature release

Features:

- ``from __future__ import absolute_import`` is now supported

- Relative imports (``from . import module``) are now supported

- Add support for namespace packages when those are installed
  using option ``--single-version-externally-managed`` (part
  of setuptools/distribute)

0.8
---

This is a minor feature release

Features:

- Initial support for Python 3.x

- It is now possible to run the test suite
  using ``python setup.py test``.

  (The actual test suite is still fairly minimal though)


text:
package com.example.android.models;

import android.os.Parcel;
import android.os.Parcelable;

import com.google.gson.annotations.Expose;

public class Profile implements Parcelable {

    @Expose
    private String id;
    @Expose
    private String email;
    @Expose
    private String firstName;
    @Expose
    private String lastName;

    /**
     *
     * @return
     * The id
     */
    public String getId() {
        return id;
    }

    /**
     *
     * @param id
     * The id
     */
    public void setId(String id) {
        this.id = id;
    }

    /**
     *
     * @return
     * The email
     */
    public String getEmail() {
        return email;
    }

    /**
     *
     * @param email
     * The email
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     *
     * @return
     * The firstName
     */
    public String getFirstName() {
        return firstName;
    }

    /**
     *
     * @param firstName
     * The firstName
     */
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    /**
     *
     * @return
     * The lastName
     */
    public String getLastName() {
        return lastName;
    }

    /**
     *
     * @param lastName
     * The lastName
     */
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    protected Profile(Parcel in) {
        id = in.readString();
        email = in.readString();
        firstName = in.readString();
        lastName = in.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(id);
        dest.writeString(email);
        dest.writeString(firstName);
        dest.writeString(lastName);
    }

    @SuppressWarnings("unused")
    public static final Parcelable.Creator<Profile> CREATOR = new Parcelable.Creator<Profile>() {
        @Override
        public Profile createFromParcel(Parcel in) {
            return new Profile(in);
        }

        @Override
        public Profile[] newArray(int size) {
            return new Profile[size];
        }
    };
}


text:
require 'msgpack'

module Cannon
  # Response object responsible for sending all response data for a request
  class Response
    extend Forwardable
    include Views

    attr_reader :delegated_response
    attr_accessor :status, :app

    delegate content: :delegated_response
    delegate :content= => :delegated_response
    delegate headers: :delegated_response
    delegate header: :delegated_response
    delegate cookies: :delegated_response

    HTTP_STATUS = {
      continue:                      100,
      switching_protocols:           101,
      ok:                            200,
      created:                       201,
      accepted:                      202,
      non_authoritative_information: 203,
      no_content:                    204,
      reset_content:                 205,
      partial_content:               206,
      multiple_choices:              300,
      moved_permanently:             301,
      found:                         302,
      see_other:                     303,
      not_modified:                  304,
      use_proxy:                     305,
      temporary_redirect:            307,
      bad_request:                   400,
      unauthorized:                  401,
      payment_required:              402,
      forbidden:                     403,
      not_found:                     404,
      method_not_allowed:            405,
      not_acceptable:                406,
      proxy_authentication_required: 407,
      request_timeout:               408,
      conflict:                      409,
      gone:                          410,
      length_required:               411,
      precondition_failed:           412,
      request_entity_too_large:      413,
      request_uri_too_long:          414,
      unsupported_media_type:        415,
      requested_range_not_satisfied: 416,
      expectation_failed:            417,
      internal_server_error:         500,
      not_implemented:               501,
      bad_gateway:                   502,
      service_unavailable:           503,
      gateway_timeout:               504,
      http_version_not_supported:    505
    }.freeze

    def initialize(delegated_response)
      @delegated_response = delegated_response
      self.status = :ok
    end

    def flushed?
      delegated_response.flushed?
    end

    def send(content, status: self.status)
      self.content ||= ''
      self.status = status
      delegated_response.status = converted_status(status)
      delegated_response.content += content
    end

    def flush
      return if delegated_response.flushed?

      headers['Content-Type'] = 'text/plain' unless headers['Content-Type']
      delegated_response.flush
    end

    def location_header(location)
      header('Location', location)
    end

    def permanent_redirect(location)
      location_header(location)
      self.status = :moved_permanently
      flush
    end

    def temporary_redirect(location)
      location_header(location)
      self.status = :found
      flush
    end

    def internal_server_error(title:, content:)
      html = "<title>Internal Server Error: #{title}</title>" \
             "
#{title}

#{content}
"
      header('Content-Type', 'text/html')
      send(html, status: :internal_server_error)
    end

    def not_found
      send('Not Found', status: :not_found)
      flush
    end

    private

    def converted_status(status)
      status.is_a?(Integer) ? status : (HTTP_STATUS[status] || status.to_s)
    end
  end
end