text:
using StudyBox.Core.Models;
using StudyBox.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using System.Net.Http.Headers;
using Windows.Storage;
using Windows.Storage.Streams;
using System.Diagnostics;

namespace StudyBox.Core.Services
{
    public class RestService : IRestService
    {
        private ResourceDictionary _resources = Application.Current.Resources;
        private readonly IDeserializeJsonService _deserializeJsonService;
        private readonly IAccountService _accountService;

        public RestService(IDeserializeJsonService deserializeJsonService, IAccountService accountService)
        {
            _deserializeJsonService = deserializeJsonService;
            _accountService = accountService;
        }

        #region public methods

        public async Task<List<Flashcard>> GetFlashcards(string deckId, CancellationTokenSource cts = null)
        {
            try
            {
                string url = String.Format(_resources["FlashcardGetAllUrl"].ToString(), deckId);
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<List<Flashcard>>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<List<Flashcard>> GetFlashcardsWithTipsCount(string deckId, CancellationTokenSource cts = null)
        {
            try
            {
                string url = String.Format(_resources["FlashcardWithTipsCountGetAllUrl"].ToString(), deckId);
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<List<Flashcard>>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<Flashcard> GetFlashcardById(string deckId, string flashcardId, CancellationTokenSource cts = null)
        {
            try
            {
                string url = String.Format(_resources["FlashcardGetByIdUrl"].ToString(), deckId, flashcardId);
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<Flashcard>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<Flashcard> CreateFlashcard(Flashcard flashcard, string deckId, CancellationTokenSource cts = null)
        {
            string url = String.Format(_resources["FlashcardCreateUrl"].ToString(), deckId);

            return await CreateHelper<Flashcard>(url,
                new { question = flashcard.Question, answer = flashcard.Answer, isHidden = flashcard.IsHidden },
                true,
                cts);
        }

        public async Task<bool> UpdateFlashcard(Flashcard flashcard, string deckId, CancellationTokenSource cts = null)
        {
            string url = String.Format(_resources["FlashcardUpdateUrl"].ToString(), deckId, flashcard.Id);

            return await UpdateHelper(url,
                new { question = flashcard.Question, answer = flashcard.Answer, isHidden = flashcard.IsHidden },
                cts);
        }

        public async Task<bool> RemoveFlashcard(string deckId, string flashcardId, CancellationTokenSource cts = null)
        {
            string url = String.Format(_resources["FlashcardRemoveUrl"].ToString(), deckId, flashcardId);
            return await RemoveHelper(url, cts);
        }

        public async Task<List<Deck>> GetDecks(CancellationTokenSource cts = null)
        {
            try
            {
                string url = _resources["DeckGetAllUrl"].ToString();
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<List<Deck>>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<List<Deck>> GetUserDecks(CancellationTokenSource cts = null)
        {
            try
            {
                string url = _resources["GetAllUserDecks"].ToString();
                string webPageSource = await GetWebPageSource(url, cts, true);

                return _deserializeJsonService.GetObjectFromJson<List<Deck>>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<Deck> GetDeckById(string deckId, CancellationTokenSource cts = null)
        {
            try
            {
                string url = String.Format(_resources["DeckGetByIdUrl"].ToString(), deckId);
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<Deck>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<List<Deck>> GetDecksByName(string name, CancellationTokenSource cts = null)
        {
            try
            {
                string url = String.Format(_resources["DeckGetAllByNameUrl"].ToString(), name);
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<List<Deck>>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<Deck> CreateDeck(Deck deck, CancellationTokenSource cts = null)
        {
            string url = _resources["DeckCreateUrl"].ToString();

            return await CreateHelper<Deck>(url,
                new { name = deck.Name, isPublic = deck.IsPublic },
                true,
                cts);
        }

        public async Task<bool> UpdateDeck(Deck deck, CancellationTokenSource cts = null)
        {
            string url = String.Format(_resources["DeckUpdateUrl"].ToString(), deck.ID);
            return await UpdateHelper(url,
                new { name = deck.Name, isPublic = deck.IsPublic },
                cts);
        }

        public async Task<bool> RemoveDeck(string deckId, CancellationTokenSource cts = null)
        {
            string url = String.Format(_resources["DeckRemoveUrl"].ToString(), deckId);
            return await RemoveHelper(url, cts);
        }

        public async Task<List<Deck>> GetAllDecks(bool authorize, bool includeOwn, bool flashcardsCount, string name, CancellationTokenSource cts = null)
        {
            try
            {
                string url = String.Format(_resources["GetAllDecksUrl"].ToString(), includeOwn.ToString(), flashcardsCount.ToString(), name);
                string webPageSource = await GetWebPageSource(url, cts, authorize);

                return _deserializeJsonService.GetObjectFromJson<List<Deck>>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<Deck> GetRandomDeck(CancellationTokenSource cts = null)
        {
            try
            {
                string url = _resources["GetRandomDeckUrl"].ToString();
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<Deck>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<List<Tip>> GetTips(string deckId, string flashcardId, CancellationTokenSource cts = null)
        {
            try
            {
                string url = String.Format(_resources["TipGetAllUrl"].ToString(), deckId, flashcardId);
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<List<Tip>>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<Tip> GetTipById(string deckId, string flashcardId, string tipId, CancellationTokenSource cts = null)
        {
            try
            {
                string url = String.Format(_resources["TipGetByIdUrl"].ToString(), deckId, flashcardId, tipId);
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<Tip>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<Tip> CreateTip(Tip tip, string deckId, string flashcardId, CancellationTokenSource cts = null)
        {
            string url = String.Format(_resources["TipCreateUrl"].ToString(), deckId, flashcardId);

            return await CreateHelper<Tip>(url,
                new { essence = tip.Essence, difficult = tip.Difficult },
                true,
                cts);
        }

        public async Task<bool> UpdateTip(Tip tip, string deckId, string flashcardId, CancellationTokenSource cts = null)
        {
            string url = String.Format(_resources["TipUpdateUrl"].ToString(), deckId, flashcardId, tip.ID);

            return await UpdateHelper(url,
                new { essence = tip.Essence, difficult = tip.Difficult },
                cts);
        }

        public async Task<bool> RemoveTip(string deckId, string flashcardId, string tipId, CancellationTokenSource cts = null)
        {
            string url = String.Format(_resources["TipRemoveUrl"].ToString(), deckId, flashcardId, tipId);
            return await RemoveHelper(url, cts);
        }

        public async Task<List<Tag>> GetTags(string deckId, CancellationTokenSource cts = null)
        {
            try
            {
                string url = String.Format(_resources["TagGetAllUrl"].ToString(), deckId);
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<List<Tag>>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<Tag> GetTagById(string deckId, string tagId, CancellationTokenSource cts = null)
        {
            try
            {
                string url = String.Format(_resources["TagGetByIdUrl"].ToString(), deckId, tagId);
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<Tag>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<Tag> CreateTag(Tag tag, string deckId, CancellationTokenSource cts = null)
        {
            string url = String.Format(_resources["TagCreateUrl"].ToString(), deckId);

            return await CreateHelper<Tag>(url,
                new { name = tag.Name },
                true,
                cts);
        }

        public async Task<bool> UpdateTag(Tag tag, string deckId, CancellationTokenSource cts = null)
        {
            string url = String.Format(_resources["TagUpdateUrl"].ToString(), deckId, tag.ID);

            return await UpdateHelper(url,
                new { name = tag.Name },
                cts);
        }

        public async Task<bool> RemoveTag(string deckId, string tagId, CancellationTokenSource cts = null)
        {
            string url = String.Format(_resources["TagRemoveUrl"].ToString(), deckId, tagId);
            return await RemoveHelper(url, cts);
        }

        public async Task<List<TestResult>> GetTestResults(string deckId, CancellationTokenSource cts = null)
        {
            try
            {
                string url = String.Format(_resources["TestResultsGetAllUrl"].ToString(), deckId);
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<List<TestResult>>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<bool> SaveTestResults(List<TestResult> testResults, string deckId, CancellationTokenSource cts = null)
        {
            string url = String.Format(_resources["TestResultsSaveUrl"].ToString(), deckId);

            try
            {
                using (var client = new HttpClient())
                {
                    HttpResponseMessage response;

                    if (cts != null)
                    {
                        response = await client.PostAsJsonAsync(url, testResults, cts.Token);
                    }
                    else
                    {
                        response = await client.PostAsJsonAsync(url, testResults);
                    }

                    if (response.StatusCode != System.Net.HttpStatusCode.Created && response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        return false;
                    }
                }
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

        public async Task<User> CreateUser(User user, CancellationTokenSource cts = null)
        {
            string url = _resources["UserCreateUrl"].ToString();

            return await CreateHelper<User>(url,
                new { email = user.Email, name = user.Email, password = user.Password },
                false,
                cts);
        }

        public async Task<User> GetLoggedUser(CancellationTokenSource cts = null)
        {
            try
            {
                string url = _resources["UserGetLoggedUrl"].ToString();
                string webPageSource = await GetWebPageSource(url, cts);

                return _deserializeJsonService.GetObjectFromJson<User>(webPageSource);
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public async Task<bool> UploadFile(StorageFile file, CancellationTokenSource cts = null)
        {
            string url;

            if (file.ContentType.Contains("image"))
                url = String.Format(_resources["FileUploadUrl"].ToString(), "image");
            else
                url = String.Format(_resources["FileUploadUrl"].ToString(), "text");

            try
            {
                byte[] byteArray = await GetFileBytesAsync(file);

                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(String.Format("{0}:{1}", _accountService.GetUserEmail(), _accountService.GetUserPassword()))));

                    MultipartFormDataContent form = new MultipartFormDataContent("---BOUNDARY");
                    HttpContent content = new ByteArrayContent(byteArray);
                    content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "file", FileName = file.Name };
                    content.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
                    form.Add(content);

                    HttpResponseMessage response;

                    if (cts != null)
                    {
                        response = await client.PostAsync(url, form, cts.Token);
                    }
                    else
                    {
                        response = await client.PostAsync(url, form);
                    }

                    if (response.StatusCode != System.Net.HttpStatusCode.Created)
                    {
                        return false;
                    }
                }
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

        public async Task<ResetPassword> ResetPassword(string email, CancellationTokenSource cts = null)
        {
            string url = _resources["ResetPasswordUrl"].ToString();

            return await CreateHelper<ResetPassword>(url,
                new { email = email },
                false,
                cts,
                true);
        }

        public async Task<bool> ChangePassword(User user, string token, CancellationTokenSource cts = null)
        {
            string url = _resources["ChangePasswordUrl"].ToString();

            return await CreateHelper<bool>(url,
                new { password = user.Password, token = token, email = user.Email },
                false, cts);
        }
        #endregion

        #region private methods

        private async Task<string> DecodeResponseContent(HttpResponseMessage response)
        {
            string jsonString = "";
            byte[] byteContent = await response.Content.ReadAsByteArrayAsync();

            try
            {
                string encoding = response.Content.Headers.ContentType.CharSet;
                jsonString = Encoding.GetEncoding(encoding).GetString(byteContent);
            }
            catch
            {
                jsonString = Encoding.UTF8.GetString(byteContent);
            }
            return jsonString;
        }

        private async Task<string> GetWebPageSource(string url, CancellationTokenSource cts, bool authorize = false)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                if (authorize)
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(String.Format("{0}:{1}", _accountService.GetUserEmail(), _accountService.GetUserPassword()))));
                }

                HttpResponseMessage response;
                if (cts == null)
                {
                    response = await httpClient.GetAsync(url);
                }
                else
                {
                    response = await httpClient.GetAsync(url, cts.Token);
                }

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    throw new HttpRequestException();
                }

                return await DecodeResponseContent(response);
            }
        }

        private async Task<T> CreateHelper<T>(string url, object apiCreateObject, bool authorize, CancellationTokenSource cts, bool decodeError = false)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    if (authorize)
                    {
                        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(String.Format("{0}:{1}", _accountService.GetUserEmail(), _accountService.GetUserPassword()))));
                    }

                    HttpResponseMessage response;
                    if (cts == null)
                    {
                        response = await client.PostAsJsonAsync(url, apiCreateObject);
                    }
                    else
                    {
                        response = await client.PostAsJsonAsync(url, apiCreateObject, cts.Token);
                    }

                    if (response.StatusCode != System.Net.HttpStatusCode.Created && response.StatusCode != System.Net.HttpStatusCode.OK)
                    {
                        if (!decodeError)
                            throw new HttpRequestException();
                        else
                        {
                            string errorDecode = await DecodeResponseContent(response);
                            return _deserializeJsonService.GetObjectFromJson<T>(errorDecode);
                        }
                    }

                    if (typeof(T) == typeof(bool))
                        return (T)(object)true;

                    string json = await DecodeResponseContent(response);
                    return _deserializeJsonService.GetObjectFromJson<T>(json);
                }
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return default(T);
            }
        }

        private async Task<bool> UpdateHelper(string url, object apiUpdateObject, CancellationTokenSource cts)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(String.Format("{0}:{1}", _accountService.GetUserEmail(), _accountService.GetUserPassword()))));

                    HttpResponseMessage response;
                    if (cts == null)
                    {
                        response = await client.PutAsJsonAsync(url, apiUpdateObject);
                    }
                    else
                    {
                        response = await client.PutAsJsonAsync(url, apiUpdateObject, cts.Token);
                    }

                    if (response.StatusCode != System.Net.HttpStatusCode.OK && response.StatusCode != System.Net.HttpStatusCode.NoContent)
                    {
                        throw new HttpRequestException();
                    }

                    return true;
                }
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private async Task<bool> RemoveHelper(string url, CancellationTokenSource cts)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(String.Format("{0}:{1}", _accountService.GetUserEmail(), _accountService.GetUserPassword()))));

                    HttpResponseMessage response;
                    if (cts == null)
                    {
                        response = await client.DeleteAsync(url);
                    }
                    else
                    {
                        response = await client.DeleteAsync(url, cts.Token);
                    }

                    if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.NoContent)
                    {
                        throw new HttpRequestException();
                    }

                    return true;
                }
            }
            catch (TaskCanceledException ex)
            {
                throw ex;
            }
            catch (Exception)
            {
                return false;
            }
        }

        private async Task<byte[]> GetFileBytesAsync(StorageFile file)
        {
            byte[] fileBytes = null;
            using (IRandomAccessStreamWithContentType stream = await file.OpenReadAsync())
            {
                fileBytes = new byte[stream.Size];
                using (DataReader reader = new DataReader(stream))
                {
                    await reader.LoadAsync((uint)stream.Size);
                    reader.ReadBytes(fileBytes);
                }
            }

            return fileBytes;
        }

        #endregion
    }
}


text:
<?php

require_once dirname(__FILE__).'/../lib/entitlement_packGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/entitlement_packGeneratorHelper.class.php';

/**
 * entitlement_pack actions.
 *
 * @package    sf_sandbox
 * @subpackage entitlement_pack
 * @author     gyufi@sztaki.hu
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class entitlement_packActions extends autoEntitlement_packActions
{
  public function executeNew(sfWebRequest $request)
  {
    $this->form = new ServEntitlementPackForm();
    $this->form->setDefault("service_id",$request->getParameter('id'));
    $this->entitlement_pack = $this->form->getObject();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->form = new ServEntitlementPackForm();
    $this->entitlement_pack = $this->form->getObject();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

  public function executeEdit(sfWebRequest $request)
  {
    $this->entitlement_pack = $this->getRoute()->getObject();
    $this->form = new ServEntitlementPackForm($this->entitlement_pack);
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $this->entitlement_pack = $this->getRoute()->getObject();
    $this->form = new ServEntitlementPackForm($this->entitlement_pack);

    $this->processForm($request, $this->form);

    $this->setTemplate('edit');
  }

  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $i18n = sfContext::getInstance()->getI18N();
    $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $notice = $form->getObject()->isNew() ? $i18n->__('The entitlement package has been created.') : $i18n->__('The entitlement package has been updated.');

      try {
        $entitlement_pack = $form->save();
      } catch (Doctrine_Validator_Exception $e) {

        $errorStack = $form->getObject()->getErrorStack();

        $message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ?  's' : null) . " with validation errors: ";
        foreach ($errorStack as $field => $errors) {
            $message .= "$field (" . implode(", ", $errors) . "), ";
        }
        $message = trim($message, ', ');

        $this->getUser()->setFlash('error', $message);
        return sfView::SUCCESS;
      }

      $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $entitlement_pack)));

      if ($request->hasParameter('_save_and_add'))
      {
        $this->getUser()->setFlash('notice', $notice.' You can add another one below.');

        $this->redirect('@entitlement_pack_new');
      }
      else
      {
        $this->getUser()->setFlash('notice', $notice);

        $this->redirect("show/index?id=".$form->getObject()->getServiceId());
      }
    }
    else
    {
      $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
    }
  }

  public function executeDeletea(sfWebRequest $request)
  {
    //$request->checkCSRFProtection();
    $i18n = sfContext::getInstance()->getI18N();
    $r = Doctrine::getTable('EntitlementPack')->find($request->getParameter('id'));
    $os = Doctrine::getTable('Organization')
			->createQuery('o')
                        ->leftJoin('o.OrganizationEntitlementPack oe')
                        ->where('oe.entitlement_pack_id = ?', $r->getId())->execute();
    $sid = $r->getServiceId();

    $this->checkIsMy($r);

    if ($request->getParameter("confirm") != $i18n->__("Yes, do as I say!"))
    {
      $this->getUser()->setFlash('notice', $i18n->__('The entitlement pack has not been deleted.'));
      $this->redirect('show/index?id='.$sid);
    }

    $this->dispatcher->notify(new sfEvent($this, 'admin.delete_object', array('object' => $r)));

    if ($r->delete())
    {
      //Frissítenünk kell a szervezetek szerepköreit, hogy kikerüljenek a már elérhetetlenné vált jogosultságok
      foreach($os as $o){
        foreach($o->getRole() as $role){
	  $role->updateEntitlements($o->getId());
        }
      }
      $this->getUser()->setFlash('notice', $i18n->__('The entitlement pack has been deleted successfully.'));

    $to=array();
    //Mail küldése
    foreach($os as $o){
      $to = $o->getManagersEmailArray();
    }
    $to += $r->getService()->getManagersEmailArray();

      $mail = $this->getMailer()->compose(ProjectConfiguration::$mail_from, $to, $i18n->__(ProjectConfiguration::$mail_tag.'Entitlement pack %ep% has been deleted from service %service%',array("%ep%"=>$r, "%service%"=>$s)));
      $html  = $this->getPartial('entitlement_pack/deleteEPHtml', array("s"=>$s, "ep"=>$r));
      $mail->setBody($html, 'text/html');

      $this->getMailer()->send($mail);

    }
    $this->redirect('show/index?id='.$sid);
  }

  private function checkIsMy($r)
  {
    $i18n = sfContext::getInstance()->getI18N();
    if (! $r->getService()->isMy())
    {
      $m=$i18n->__("You have no rights to access this organization.");
      $this->getUser()->setFlash('error',$m);
      $this->redirect("default/error");
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package models;

import contracts.IBunny;
import contracts.IGatherer;
import contracts.IResource;

public class GathererBunny
  extends BaseBunny implements IBunny, IGatherer{
  private int weight;

  public GathererBunny(int x, int y, int weight) {
    super(x, y);
    this.setWeight(weight);
  }

  public int getWeight() {
    return weight;
  }

  public void setWeight(int weight) {
    this.weight = weight;
  }

  @Override
  public void eat(IResource resource) {
    this.setWeight(this.getWeight() + resource.getQuantity());
  }

  @Override
  public int getSize() {
    return this.getWeight();
  }

  @Override
  public IResource gather(int hours) {
    return new Resource(hours * 2);
  }
}


text:
<?php
include_once 'functions.php';
sec_session_start();

// Desfaz todos os valores da sessão
$_SESSION = array();

// obtém os parâmetros da sessão
$params = session_get_cookie_params();

// Deleta o cookie em uso.
setcookie(session_name(),
          '', time() - 42000,
          $params["path"],
          $params["domain"],
          $params["secure"],
          $params["httponly"]);

// Destrói a sessão
session_destroy();
echo "<script type=text/javascript>window.location.href='../../index.php'</script>";
//header('Location: ../../ index.php');
?>


text:
package main

import (
	"fmt"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/route53"
	"io/ioutil"
	"net/http"
	"strings"
)

const (
	MAX_ITEMS_1   = "1"
	ACTION_UPSERT = "UPSERT"
)

type Updater interface {
	GetCurrentAddress() (*string, error)
	GetRecordSet() (*route53.ResourceRecordSet, error)
	GetRecordedAddress(recordSet *route53.ResourceRecordSet) (*string, error)
	UpdateRecordedAddress(recordSet *route53.ResourceRecordSet, currentAddress string) error
}

type Route53Updater struct {
	IpServiceUrl string
	svc          *route53.Route53
	HostedZoneId string
	RecordName   string
	RecordType   string
}

func (route53Updater Route53Updater) GetCurrentAddress() (*string, error) {
	resp, err := http.Get(route53Updater.IpServiceUrl)
	if err != nil {
		fmt.Errorf("Error getting response: %v", err)
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("Error reading response body: %v", err)
	}

	currentAddress := strings.TrimSpace(string(body))
	return &currentAddress, nil
}

func (route53Updater Route53Updater) GetRecordSet() (*route53.ResourceRecordSet, error) {
	params := &route53.ListResourceRecordSetsInput{
		HostedZoneId:    aws.String(route53Updater.HostedZoneId),
		MaxItems:        aws.String(MAX_ITEMS_1),
		StartRecordName: aws.String(route53Updater.RecordName),
		StartRecordType: aws.String(route53Updater.RecordType),
	}

	resp, err := route53Updater.svc.ListResourceRecordSets(params)
	if err != nil {
		return nil, fmt.Errorf("Error listing records: %v", err)
	}
	if len(resp.ResourceRecordSets) < 1 {
		return nil, fmt.Errorf("No records sets for: %v", params)
	}

	return resp.ResourceRecordSets[0], nil
}

func (route53Updater Route53Updater) GetRecordedAddress(recordSet *route53.ResourceRecordSet) (*string, error) {
	if len(recordSet.ResourceRecords) < 1 {
		return nil, fmt.Errorf("No records for set %v", recordSet)
	}

	recordedAddress := strings.TrimSpace(*recordSet.ResourceRecords[0].Value)
	return &recordedAddress, nil
}

func (route53Updater Route53Updater) UpdateRecordedAddress(recordSet *route53.ResourceRecordSet, currentAddress string) error {
	recordSet.ResourceRecords[0].Value = &currentAddress

	params := &route53.ChangeResourceRecordSetsInput{
		ChangeBatch: &route53.ChangeBatch{
			Changes: []*route53.Change{
				{
					Action:            aws.String(ACTION_UPSERT),
					ResourceRecordSet: recordSet,
				},
			},
		},
		HostedZoneId: aws.String(route53Updater.HostedZoneId),
	}
	_, err := route53Updater.svc.ChangeResourceRecordSets(params)
	if err != nil {
		return fmt.Errorf("Error applying changes: %v", params)
	}

	return nil
}


text:
package org.apache.lucene.queryparser.flexible.standard.processors;

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

import org.apache.lucene.queryparser.flexible.core.QueryNodeException;
import org.apache.lucene.queryparser.flexible.core.config.QueryConfigHandler;
import org.apache.lucene.queryparser.flexible.core.nodes.AndQueryNode;
import org.apache.lucene.queryparser.flexible.core.nodes.BooleanQueryNode;
import org.apache.lucene.queryparser.flexible.core.nodes.GroupQueryNode;
import org.apache.lucene.queryparser.flexible.core.nodes.ModifierQueryNode;
import org.apache.lucene.queryparser.flexible.core.nodes.OrQueryNode;
import org.apache.lucene.queryparser.flexible.core.nodes.QueryNode;
import org.apache.lucene.queryparser.flexible.core.nodes.ModifierQueryNode.Modifier;
import org.apache.lucene.queryparser.flexible.core.parser.SyntaxParser;
import org.apache.lucene.queryparser.flexible.core.processors.QueryNodeProcessor;
import org.apache.lucene.queryparser.flexible.standard.config.StandardQueryConfigHandler;
import org.apache.lucene.queryparser.flexible.standard.config.StandardQueryConfigHandler.ConfigurationKeys;
import org.apache.lucene.queryparser.flexible.standard.config.StandardQueryConfigHandler.Operator;
import org.apache.lucene.queryparser.flexible.standard.nodes.BooleanModifierNode;

/**
 * The {@link SyntaxParser}
 * generates query node trees that consider the boolean operator precedence, but
 * Lucene current syntax does not support boolean precedence, so this processor
 * remove all the precedence and apply the equivalent modifier according to the
 * boolean operation defined on an specific query node.

 *

 * If there is a {@link GroupQueryNode} in the query node tree, the query node
 * tree is not merged with the one above it.
 *
 * Example: TODO: describe a good example to show how this processor works
 *
 * @see org.apache.lucene.queryparser.flexible.standard.config.StandardQueryConfigHandler
 * @deprecated use {@link BooleanQuery2ModifierNodeProcessor} instead
 */
public class GroupQueryNodeProcessor implements QueryNodeProcessor {

  private ArrayList<QueryNode> queryNodeList;

  private boolean latestNodeVerified;

  private QueryConfigHandler queryConfig;

  private Boolean usingAnd = false;

  public GroupQueryNodeProcessor() {
    // empty constructor
  }

  @Override
  public QueryNode process(QueryNode queryTree) throws QueryNodeException {
    Operator defaultOperator = getQueryConfigHandler().get(ConfigurationKeys.DEFAULT_OPERATOR);

    if (defaultOperator == null) {
      throw new IllegalArgumentException(
          "DEFAULT_OPERATOR should be set on the QueryConfigHandler");
    }

    this.usingAnd = StandardQueryConfigHandler.Operator.AND == defaultOperator;

    if (queryTree instanceof GroupQueryNode) {
      queryTree = ((GroupQueryNode) queryTree).getChild();
    }

    this.queryNodeList = new ArrayList<>();
    this.latestNodeVerified = false;
    readTree(queryTree);

    List<QueryNode> actualQueryNodeList = this.queryNodeList;

    for (int i = 0; i < actualQueryNodeList.size(); i++) {
      QueryNode node = actualQueryNodeList.get(i);

      if (node instanceof GroupQueryNode) {
        actualQueryNodeList.set(i, process(node));
      }

    }

    this.usingAnd = false;

    if (queryTree instanceof BooleanQueryNode) {
      queryTree.set(actualQueryNodeList);

      return queryTree;

    } else {
      return new BooleanQueryNode(actualQueryNodeList);
    }

  }

  /**
   */
  private QueryNode applyModifier(QueryNode node, QueryNode parent) {

    if (this.usingAnd) {

      if (parent instanceof OrQueryNode) {

        if (node instanceof ModifierQueryNode) {

          ModifierQueryNode modNode = (ModifierQueryNode) node;

          if (modNode.getModifier() == Modifier.MOD_REQ) {
            return modNode.getChild();
          }

        }

      } else {

        if (node instanceof ModifierQueryNode) {

          ModifierQueryNode modNode = (ModifierQueryNode) node;

          if (modNode.getModifier() == Modifier.MOD_NONE) {
            return new BooleanModifierNode(modNode.getChild(), Modifier.MOD_REQ);
          }

        } else {
          return new BooleanModifierNode(node, Modifier.MOD_REQ);
        }

      }

    } else {

      if (node.getParent() instanceof AndQueryNode) {

        if (node instanceof ModifierQueryNode) {

          ModifierQueryNode modNode = (ModifierQueryNode) node;

          if (modNode.getModifier() == Modifier.MOD_NONE) {
            return new BooleanModifierNode(modNode.getChild(), Modifier.MOD_REQ);
          }

        } else {
          return new BooleanModifierNode(node, Modifier.MOD_REQ);
        }

      }

    }

    return node;

  }

  private void readTree(QueryNode node) {

    if (node instanceof BooleanQueryNode) {
      List<QueryNode> children = node.getChildren();

      if (children != null && children.size() > 0) {

        for (int i = 0; i < children.size() - 1; i++) {
          readTree(children.get(i));
        }

        processNode(node);
        readTree(children.get(children.size() - 1));

      } else {
        processNode(node);
      }

    } else {
      processNode(node);
    }

  }

  private void processNode(QueryNode node) {

    if (node instanceof AndQueryNode || node instanceof OrQueryNode) {

      if (!this.latestNodeVerified && !this.queryNodeList.isEmpty()) {
        this.queryNodeList.add(applyModifier(this.queryNodeList
            .remove(this.queryNodeList.size() - 1), node));
        this.latestNodeVerified = true;

      }

    } else if (!(node instanceof BooleanQueryNode)) {
      this.queryNodeList.add(applyModifier(node, node.getParent()));
      this.latestNodeVerified = false;

    }

  }

  @Override
  public QueryConfigHandler getQueryConfigHandler() {
    return this.queryConfig;
  }

  @Override
  public void setQueryConfigHandler(QueryConfigHandler queryConfigHandler) {
    this.queryConfig = queryConfigHandler;
  }

}


text:
using Hatfield.AnalyteManagement.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Hatfield.AnalyteManagement.GuidelineCalculation
{
    public class DependentDecider
    {
        public static bool Decide(
            ref GuidelineCalculationRequestViewModel data,
            IEnumerable<GuidelineCalculationRequestViewModel> dataset,
            DependentDecision decision,
            AnalyteGuideline guideline)
        {
            if (decision == DependentDecision.ExistingValue)
            {
                return true;
            }

            if (guideline.ValueType == Constants.EquationValueType)
            {
                foreach (var analyte in ExtractDependAnalyteNames(guideline.GuidelineValue))
                {
                    var result = FindDependValue(
                            ref data, dataset,
                            analyte,
                            dic[analyte]
                        );
                    if (!result)
                    {
                        return false;
                    }
                }

                return true;
            }

            return true;
        }

        private static Dictionary<string, Func<double, GuidelineCalculationRequestViewModel, GuidelineCalculationRequestViewModel>> dic = new Dictionary<string, Func<double, GuidelineCalculationRequestViewModel, GuidelineCalculationRequestViewModel>>
        {
            {
                Constants.MathE,
                (double value, GuidelineCalculationRequestViewModel point) => {
                    point.MathE = Math.E;
                    return point;
                }
            },
            {
                Constants.PH_AnalyteName,
                (double value, GuidelineCalculationRequestViewModel point) => {
                    point.PH = value;
                    return point;
                }
            },
            {
                Constants.Hardness_AnalyteName,
                (double value, GuidelineCalculationRequestViewModel point) => {
                    point.Hardness = value;
                    return point;
                }
            },
            {
                Constants.Chloride_AnalyteName,
                (double value, GuidelineCalculationRequestViewModel point) => {
                    point.Chloride = value;
                    return point;
                }
            },
        };

        private static bool FindDependValue(ref GuidelineCalculationRequestViewModel data,
            IEnumerable<GuidelineCalculationRequestViewModel> dataset,
            string dependAnalyteName, Func<double, GuidelineCalculationRequestViewModel, GuidelineCalculationRequestViewModel> callback)
        {
            if (dependAnalyteName == Constants.MathE)
            {
                data = callback(Math.E, data);
                return true;
            }

            var pointToMatch = data;

            if (dependAnalyteName == Constants.PH_AnalyteName)
            {
                return pointToMatch.PH.HasValue;
            }
            if (dependAnalyteName == Constants.Hardness_AnalyteName)
            {
                return pointToMatch.Hardness.HasValue;
            }
            if (dependAnalyteName == Constants.Chloride_AnalyteName)
            {
                return pointToMatch.Chloride.HasValue;
            }
            //var depend = dataset.FirstOrDefault(x => x.DateTime.Date == pointToMatch.DateTime.Date &&
            //                                        x.Site == pointToMatch.Site &&
            //                                        String.Compare(x.Analyte, dependAnalyteName, true) == 0);

            //if (depend == null || depend.Value == null)
            //{
            //    return false;
            //}
            //data = callback(depend.Value.Value, data);
            return true;
        }

        private static IEnumerable<string> ExtractDependAnalyteNames(string equation)
        {
            string pattern = @"\[(.*?)\]";
            var matches = Regex.Matches(equation, pattern, RegexOptions.IgnoreCase);

            var extractedAnalyteNames = new List<string>();
            foreach (Match match in matches)
            {
                extractedAnalyteNames.Add(match.Value.Substring(1, match.Value.Length - 2));
            }

            return extractedAnalyteNames.Distinct();
        }
    }
}


text:
/*!
 * Angular Material Design
 * https://github.com/angular/material
 * @license MIT
 * v1.0.3-master-e1c07ec
 */md-toolbar.md-THEME_NAME-theme:not(.md-menu-toolbar){background-color:'{{primary-color}}';color:'{{primary-contrast}}'}md-toolbar.md-THEME_NAME-theme:not(.md-menu-toolbar) md-icon{color:'{{primary-contrast}}'}md-toolbar.md-THEME_NAME-theme:not(.md-menu-toolbar).md-accent{background-color:'{{accent-color}}';color:'{{accent-contrast}}'}md-toolbar.md-THEME_NAME-theme:not(.md-menu-toolbar).md-warn{background-color:'{{warn-color}}';color:'{{warn-contrast}}'}


text:
package com.asakusafw.lang.compiler.analyzer.mock;

import com.asakusafw.vocabulary.flow.Export;
import com.asakusafw.vocabulary.flow.FlowDescription;
import com.asakusafw.vocabulary.flow.Import;
import com.asakusafw.vocabulary.flow.In;
import com.asakusafw.vocabulary.flow.JobFlow;
import com.asakusafw.vocabulary.flow.Out;

@SuppressWarnings("javadoc")
@JobFlow(name = "AbstractJobflow")
public abstract class AbstractJobflow extends FlowDescription {

    final In<String> in;

    final Out<String> out;

    public AbstractJobflow(
            @Import(name = "in", description = MockImporterDescription.class) In<String> in,
            @Export(name = "out", description = MockExporterDescription.class) Out<String> out) {
        this.in = in;
        this.out = out;
    }
}


text:
Genes

{{gene.nctIds.join(', ')}}

    	No Genes yet.


text:
using ZKWeb.Localize;
using ZKWebStandard.Web;

namespace ZKWeb.MVVMPlugins.MVVM.Common.Base.src.Components.Exceptions
{
    /// <summary>
    /// 请求参数有误的错误
    /// </summary>
    public class BadRequestException : HttpException
    {
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="message">错误消息</param>
        public BadRequestException(string message) : base(400, new T(message)) { }
    }
}


text:
package athenzutils

import "testing"

func TestExtractInstanceIdValid(test *testing.T) {

	tests := []struct {
		name       string
		certFile   string
		instanceId string
	}{
		{"nocn", "data/no_cn_x509.cert", "1001"},
		{"invalidemail", "data/invalid_email_x509.cert", "1001"},
		{"multiplemeail", "data/multiple_email_x509.cert", "1001"},
		{"noemail", "data/no_email_x509.cert", "1001"},
		{"uri", "data/athenz_instanceid_uri.cert", "id-001"},
	}
	for _, tt := range tests {
		test.Run(tt.name, func(t *testing.T) {
			x509Cert, _ := LoadX509Certificate(tt.certFile)
			instanceId, _ := ExtractInstanceId(*x509Cert)
			if instanceId != tt.instanceId {
				test.Errorf("invalid instance id %s from %s", instanceId, tt.certFile)
			}
		})
	}
}

func TestExtractInstanceIdInValid(test *testing.T) {

	tests := []struct {
		name      string
		certFile  string
	}{
		{"id1", "data/service_identity1.cert"},
		{"id2", "data/service_identity2.cert"},
		{"email", "data/valid_email_x509.cert"},
	}
	for _, tt := range tests {
		test.Run(tt.name, func(t *testing.T) {
			x509Cert, _ := LoadX509Certificate(tt.certFile)
			instanceId, err := ExtractInstanceId(*x509Cert)
			if err == nil {
				test.Errorf("no error from invalid file %s: %s", tt.certFile, instanceId)
			}
		})
	}
}


text:
/******************************************************************************
 *                    _   _____   __________                                  *
 *                   | | / / _ | / __/_  __/     Visibility                   *
 *                   | |/ / __ |_\ \  / /          Across                     *
 *                   |___/_/ |_/___/ /_/       Space and Time                 *
 *                                                                            *
 * This file is part of VAST. It is subject to the license terms in the       *
 * LICENSE file found in the top-level directory of this distribution and at  *
 * http://vast.io/license. No part of VAST, including this file, may be       *
 * copied, modified, propagated, or distributed except according to the terms *
 * contained in the LICENSE file.                                             *
 ******************************************************************************/

#pragma once

#include <caf/fwd.hpp>

namespace vast::detail {

/// Adds VAST's message type to a CAF actor system configuration.
/// @param cfg The actor system configuration to add VAST's types to.
void add_message_types(caf::actor_system_config& cfg);

} // namespace vast::detail


text:
<?php

namespace Aisel\AddressingBundle\Tests\Controller\Admin;

use Aisel\ResourceBundle\Tests\AbstractBackendWebTestCase;

/**
 * ApiCountryControllerTest
 *
 * @author Ivan Proskuryakov <volgodark@gmail.com>
 */
class ApiCountryControllerTest extends AbstractBackendWebTestCase
{

    public function setUp()
    {
        parent::setUp();
    }

    protected function tearDown()
    {
        parent::tearDown();
    }

    public function testGetCountriesAction()
    {
        $this->client->request(
            'GET',
            '/'. $this->api['backend'] . '/addressing/country/',
            [],
            [],
            ['CONTENT_TYPE' => 'application/json']
        );

        $response = $this->client->getResponse();
        $content = $response->getContent();
        $statusCode = $response->getStatusCode();

        $this->assertTrue(200 === $statusCode);
        $this->assertJson($content);
    }

    public function testPostCountryAction()
    {
        $data = array(
            'iso2' => 'AA',
            'iso3' => 'AAA',
            'short_name' => 'A',
            'long_name' => 'AA',
            'calling_code' => '123',
            'numcode' => '123',
        );

        $this->client->request(
            'POST',
            '/'. $this->api['backend'] . '/addressing/country/',
            [],
            [],
            ['CONTENT_TYPE' => 'application/json'],
            json_encode($data)
        );

        $response = $this->client->getResponse();
        $content = $response->getContent();
        $statusCode = $response->getStatusCode();
        $parts = explode('/', $response->headers->get('location'));
        $id = array_pop($parts);

        $country = $this
            ->dm
            ->getRepository('Aisel\AddressingBundle\Document\Country')
            ->find($id);

        $this->assertTrue(201 === $statusCode);
        $this->assertEmpty($content);
        $this->assertNotNull($country);
        $this->assertEquals($data['iso2'], $country->getIso2());
        $this->assertEquals($data['iso3'], $country->getIso3());
    }

    public function testGetCountryAction()
    {
        $country = $this
            ->dm
            ->getRepository('Aisel\AddressingBundle\Document\Country')
            ->findOneBy(['iso3' => 'AAA']);
        $id = $country->getId();

        $this->client->request(
            'GET',
            '/'. $this->api['backend'] . '/addressing/country/' . $id,
            [],
            [],
            ['CONTENT_TYPE' => 'application/json']
        );

        $response = $this->client->getResponse();
        $content = $response->getContent();
        $statusCode = $response->getStatusCode();
        $result = json_decode($content, true);

        $this->assertTrue(200 === $statusCode);
        $this->assertEquals($result['id'], $country->getId());
    }

    public function testPutCountryAction()
    {
        $country = $this
            ->dm
            ->getRepository('Aisel\AddressingBundle\Document\Country')
            ->findOneBy(['iso2' => 'AA']);
        $id = $country->getId();
        $data = array(
            'iso2' => 'ZZ',
        );

        $this->client->request(
            'PUT',
            '/'. $this->api['backend'] . '/addressing/country/' . $id,
            [],
            [],
            ['CONTENT_TYPE' => 'application/json'],
            json_encode($data)
        );

        $response = $this->client->getResponse();
        $content = $response->getContent();
        $statusCode = $response->getStatusCode();

        $this->dm->clear();

        $country = $this
            ->dm
            ->getRepository('Aisel\AddressingBundle\Document\Country')
            ->find($id);

        $this->assertTrue(204 === $statusCode);
        $this->assertEmpty($content);
        $this->assertEquals($data['iso2'], $country->getIso2());
    }

    public function testDeleteCountryAction()
    {
        $country = $this
            ->dm
            ->getRepository('Aisel\AddressingBundle\Document\Country')
            ->findOneBy(['iso3' => 'AAA']);
        $id = $country->getId();

        $this->client->request(
            'DELETE',
            '/'. $this->api['backend'] . '/addressing/country/'. $id,
            [],
            [],
            ['CONTENT_TYPE' => 'application/json']
        );

        $response = $this->client->getResponse();
        $content = $response->getContent();
        $statusCode = $response->getStatusCode();

        $this->dm->clear();

        $country = $this
            ->dm
            ->getRepository('Aisel\AddressingBundle\Document\Country')
            ->find($id);

        $this->assertTrue(204 === $statusCode);
        $this->assertEmpty($content);
        $this->assertEmpty($country);
    }

}


text:
/* these would be the practice neutral pics if we only had top 36  */
var neutral_pics = [
'boat.jpg',
'scooter.jpg',
'tennisracket.jpg',
'exercisemachine.jpg',
'bumpercar.jpg',
'airhockeytable.jpg'
]


text:
namespace mongocxx {
MONGOCXX_INLINE_NAMESPACE_BEGIN

cursor::cursor(void* cursor_ptr, bsoncxx::stdx::optional<cursor::type> cursor_type)
    : _impl(stdx::make_unique<impl>(static_cast<mongoc_cursor_t*>(cursor_ptr), cursor_type)) {}

cursor::cursor(cursor&&) noexcept = default;
cursor& cursor::operator=(cursor&&) noexcept = default;

cursor::~cursor() = default;

void cursor::iterator::operator++(int) {
    operator++();
}

cursor::iterator& cursor::iterator::operator++() {
    const bson_t* out;
    bson_error_t error;

    if (libmongoc::cursor_next(_cursor->_impl->cursor_t, &out)) {
        _cursor->_impl->doc = bsoncxx::document::view{bson_get_data(out), out->len};
    } else if (libmongoc::cursor_error(_cursor->_impl->cursor_t, &error)) {
        _cursor->_impl->mark_dead();
        throw_exception<query_exception>(error);
    } else {
        _cursor->_impl->mark_nothing_left();
    }
    return *this;
}

cursor::iterator cursor::begin() {
    if (_impl->is_dead()) {
        return end();
    }
    return iterator(this);
}

cursor::iterator cursor::end() {
    return iterator(nullptr);
}

cursor::iterator::iterator(cursor* cursor) : _cursor(cursor) {
    if (_cursor == nullptr || _cursor->_impl->has_started()) {
        return;
    }

    _cursor->_impl->mark_started();
    operator++();
}

//
// An iterator is exhausted if it is the end-iterator (_cursor == nullptr)
// or if the underlying _cursor is marked exhausted.
//
bool cursor::iterator::is_exhausted() const {
    return !_cursor || _cursor->_impl->is_exhausted();
}

const bsoncxx::document::view& cursor::iterator::operator*() const {
    return _cursor->_impl->doc;
}

const bsoncxx::document::view* cursor::iterator::operator->() const {
    return &_cursor->_impl->doc;
}

//
// Iterators are equal if they point to the same underlying _cursor or if they
// both are "at the end".  We check for exhaustion first because the most
// common check is `iter != cursor.end()`.
//
bool MONGOCXX_CALL operator==(const cursor::iterator& lhs, const cursor::iterator& rhs) {
    return ((rhs.is_exhausted() && lhs.is_exhausted()) || (lhs._cursor == rhs._cursor));
}

bool MONGOCXX_CALL operator!=(const cursor::iterator& lhs, const cursor::iterator& rhs) {
    return !(lhs == rhs);
}

MONGOCXX_INLINE_NAMESPACE_END
}  // namespace mongocxx


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from 'ionic-angular';
import { TranslateModule } from '@ngx-translate/core';
import { CoreComponentsModule } from '@components/components.module';
import { CoreCompileHtmlComponentModule } from '@core/compile/components/compile-html/compile-html.module';
import { CoreSitePluginsPluginContentComponent } from './plugin-content/plugin-content';
import { CoreSitePluginsModuleIndexComponent } from './module-index/module-index';
import { CoreSitePluginsCourseOptionComponent } from './course-option/course-option';
import { CoreSitePluginsCourseFormatComponent } from './course-format/course-format';
import { CoreSitePluginsUserProfileFieldComponent } from './user-profile-field/user-profile-field';
import { CoreSitePluginsQuestionComponent } from './question/question';
import { CoreSitePluginsQuestionBehaviourComponent } from './question-behaviour/question-behaviour';
import { CoreSitePluginsQuizAccessRuleComponent } from './quiz-access-rule/quiz-access-rule';
import { CoreSitePluginsAssignFeedbackComponent } from './assign-feedback/assign-feedback';
import { CoreSitePluginsAssignSubmissionComponent } from './assign-submission/assign-submission';
import { CoreSitePluginsWorkshopAssessmentStrategyComponent } from './workshop-assessment-strategy/workshop-assessment-strategy';
import { CoreSitePluginsBlockComponent } from '@core/siteplugins/components/block/block';
import { CoreSitePluginsOnlyTitleBlockComponent } from '@core/siteplugins/components/only-title-block/only-title-block';

@NgModule({
    declarations: [
        CoreSitePluginsPluginContentComponent,
        CoreSitePluginsModuleIndexComponent,
        CoreSitePluginsBlockComponent,
        CoreSitePluginsOnlyTitleBlockComponent,
        CoreSitePluginsCourseOptionComponent,
        CoreSitePluginsCourseFormatComponent,
        CoreSitePluginsUserProfileFieldComponent,
        CoreSitePluginsQuestionComponent,
        CoreSitePluginsQuestionBehaviourComponent,
        CoreSitePluginsQuizAccessRuleComponent,
        CoreSitePluginsAssignFeedbackComponent,
        CoreSitePluginsAssignSubmissionComponent,
        CoreSitePluginsWorkshopAssessmentStrategyComponent
    ],
    imports: [
        CommonModule,
        IonicModule,
        CoreComponentsModule,
        CoreCompileHtmlComponentModule,
        TranslateModule.forChild()
    ],
    providers: [
    ],
    exports: [
        CoreSitePluginsPluginContentComponent,
        CoreSitePluginsModuleIndexComponent,
        CoreSitePluginsBlockComponent,
        CoreSitePluginsOnlyTitleBlockComponent,
        CoreSitePluginsCourseOptionComponent,
        CoreSitePluginsCourseFormatComponent,
        CoreSitePluginsUserProfileFieldComponent,
        CoreSitePluginsQuestionComponent,
        CoreSitePluginsQuestionBehaviourComponent,
        CoreSitePluginsQuizAccessRuleComponent,
        CoreSitePluginsAssignFeedbackComponent,
        CoreSitePluginsAssignSubmissionComponent,
        CoreSitePluginsWorkshopAssessmentStrategyComponent
    ],
    entryComponents: [
        CoreSitePluginsModuleIndexComponent,
        CoreSitePluginsBlockComponent,
        CoreSitePluginsOnlyTitleBlockComponent,
        CoreSitePluginsCourseOptionComponent,
        CoreSitePluginsCourseFormatComponent,
        CoreSitePluginsUserProfileFieldComponent,
        CoreSitePluginsQuestionComponent,
        CoreSitePluginsQuestionBehaviourComponent,
        CoreSitePluginsQuizAccessRuleComponent,
        CoreSitePluginsAssignFeedbackComponent,
        CoreSitePluginsAssignSubmissionComponent,
        CoreSitePluginsWorkshopAssessmentStrategyComponent
    ]
})
export class CoreSitePluginsComponentsModule {}


text:
/* ----------------------------------------------------------------------
 * Project:      CMSIS DSP Library
 * Title:        arm_std_q15.c
 * Description:  Standard deviation of an array of Q15 vector
 *
 * $Date:        18. March 2019
 * $Revision:    V1.6.0
 *
 * Target Processor: Cortex-M cores
 * -------------------------------------------------------------------- */
/*
 * Copyright (C) 2010-2019 ARM Limited or its affiliates. All rights reserved.
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the License); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "arm_math.h"

/**
  @ingroup groupStats
 */

/**
  @addtogroup STD
  @{
 */

/**
  @brief         Standard deviation of the elements of a Q15 vector.
  @param[in]     pSrc       points to the input vector
  @param[in]     blockSize  number of samples in input vector
  @param[out]    pResult    standard deviation value returned here
  @return        none

  @par           Scaling and Overflow Behavior
                   The function is implemented using a 64-bit internal accumulator.
                   The input is represented in 1.15 format.
                   Intermediate multiplication yields a 2.30 format, and this
                   result is added without saturation to a 64-bit accumulator in 34.30 format.
                   With 33 guard bits in the accumulator, there is no risk of overflow, and the
                   full precision of the intermediate multiplication is preserved.
                   Finally, the 34.30 result is truncated to 34.15 format by discarding the lower
                   15 bits, and then saturated to yield a result in 1.15 format.
 */

void arm_std_q15(
  const q15_t * pSrc,
        uint32_t blockSize,
        q15_t * pResult)
{
        uint32_t blkCnt;                               /* Loop counter */
        q31_t sum = 0;                                 /* Accumulator */
        q31_t meanOfSquares, squareOfMean;             /* Square of mean and mean of square */
        q63_t sumOfSquares = 0;                        /* Sum of squares */
        q15_t in;                                      /* Temporary variable to store input value */

#if defined (ARM_MATH_LOOPUNROLL) && defined (ARM_MATH_DSP)
  q31_t in32;                                    /* Temporary variable to store input value */
#endif

  if (blockSize <= 1U)
  {
    *pResult = 0;
    return;
  }

#if defined (ARM_MATH_LOOPUNROLL)

  /* Loop unrolling: Compute 4 outputs at a time */
  blkCnt = blockSize >> 2U;

  while (blkCnt > 0U)
  {
    /* C = A[0] * A[0] + A[1] * A[1] + ... + A[blockSize-1] * A[blockSize-1] */
    /* C = A[0] + A[1] + ... + A[blockSize-1] */

    /* Compute sum of squares and store result in a temporary variable, sumOfSquares. */
    /* Compute sum and store result in a temporary variable, sum. */
#if defined (ARM_MATH_DSP)
    in32 = read_q15x2_ia ((q15_t **) &pSrc);
    sumOfSquares = __SMLALD(in32, in32, sumOfSquares);
    sum += ((in32 << 16U) >> 16U);
    sum +=  (in32 >> 16U);

    in32 = read_q15x2_ia ((q15_t **) &pSrc);
    sumOfSquares = __SMLALD(in32, in32, sumOfSquares);
    sum += ((in32 << 16U) >> 16U);
    sum +=  (in32 >> 16U);
#else
    in = *pSrc++;
    sumOfSquares += (in * in);
    sum += in;

    in = *pSrc++;
    sumOfSquares += (in * in);
    sum += in;

    in = *pSrc++;
    sumOfSquares += (in * in);
    sum += in;

    in = *pSrc++;
    sumOfSquares += (in * in);
    sum += in;
#endif /* #if defined (ARM_MATH_DSP) */

    /* Decrement loop counter */
    blkCnt--;
  }

  /* Loop unrolling: Compute remaining outputs */
  blkCnt = blockSize % 0x4U;

#else

  /* Initialize blkCnt with number of samples */
  blkCnt = blockSize;

#endif /* #if defined (ARM_MATH_LOOPUNROLL) */

  while (blkCnt > 0U)
  {
    /* C = A[0] * A[0] + A[1] * A[1] + ... + A[blockSize-1] * A[blockSize-1] */
    /* C = A[0] + A[1] + ... + A[blockSize-1] */

    in = *pSrc++;
    /* Compute sum of squares and store result in a temporary variable, sumOfSquares. */
    sumOfSquares += (in * in);
    /* Compute sum and store result in a temporary variable, sum. */
    sum += in;

    /* Decrement loop counter */
    blkCnt--;
  }

  /* Compute Mean of squares and store result in a temporary variable, meanOfSquares. */
  meanOfSquares = (q31_t) (sumOfSquares / (q63_t)(blockSize - 1U));

  /* Compute square of mean */
  squareOfMean = (q31_t) ((q63_t) sum * sum / (q63_t)(blockSize * (blockSize - 1U)));

  /* mean of squares minus the square of mean. */
  /* Compute standard deviation and store result in destination */
  arm_sqrt_q15(__SSAT((meanOfSquares - squareOfMean) >> 15U, 16U), pResult);
}

/**
  @} end of STD group
 */


text:
int qtc_QRadioButton_unSetHandler(void*,void*);
int qtc_QRadioButton_event_h(void*,void*);
int qtc_QRadioButton_setHandler1(void*,void*,void*,void*,void*);
void qtc_QRadioButton_mouseMoveEvent_h(void*,void*);
int qtc_QRadioButton_setHandler2(void*,void*,void*,void*,void*);
void qtc_QRadioButton_paintEvent_h(void*,void*);
void* qtc_QRadioButton_sizeHint_h(void*);
int qtc_QRadioButton_setHandler3(void*,void*,void*,void*,void*);
void* qtc_QRadioButton_sizeHint_qth_h(void*,int*,int*);
void qtc_QRadioButton_changeEvent_h(void*,void*);
void qtc_QRadioButton_focusInEvent_h(void*,void*);
void qtc_QRadioButton_focusOutEvent_h(void*,void*);
void qtc_QRadioButton_keyPressEvent_h(void*,void*);
void qtc_QRadioButton_keyReleaseEvent_h(void*,void*);
void qtc_QRadioButton_mousePressEvent_h(void*,void*);
void qtc_QRadioButton_mouseReleaseEvent_h(void*,void*);
void qtc_QRadioButton_actionEvent_h(void*,void*);
void qtc_QRadioButton_closeEvent_h(void*,void*);
void qtc_QRadioButton_contextMenuEvent_h(void*,void*);
int qtc_QRadioButton_devType_h(void*);
int qtc_QRadioButton_setHandler4(void*,void*,void*,void*,void*);
void qtc_QRadioButton_dragEnterEvent_h(void*,void*);
void qtc_QRadioButton_dragLeaveEvent_h(void*,void*);
void qtc_QRadioButton_dragMoveEvent_h(void*,void*);
void qtc_QRadioButton_dropEvent_h(void*,void*);
void qtc_QRadioButton_enterEvent_h(void*,void*);
int qtc_QRadioButton_heightForWidth_h(void*,int);
int qtc_QRadioButton_setHandler5(void*,void*,void*,void*,void*);
void qtc_QRadioButton_hideEvent_h(void*,void*);
void* qtc_QRadioButton_inputMethodQuery_h(void*,long);
int qtc_QRadioButton_setHandler6(void*,void*,void*,void*,void*);
void qtc_QRadioButton_leaveEvent_h(void*,void*);
void* qtc_QRadioButton_minimumSizeHint_h(void*);
void* qtc_QRadioButton_minimumSizeHint_qth_h(void*,int*,int*);
void qtc_QRadioButton_mouseDoubleClickEvent_h(void*,void*);
void qtc_QRadioButton_moveEvent_h(void*,void*);
void* qtc_QRadioButton_paintEngine_h(void*);
int qtc_QRadioButton_setHandler7(void*,void*,void*,void*,void*);
void qtc_QRadioButton_resizeEvent_h(void*,void*);
void qtc_QRadioButton_setVisible_h(void*,int);
int qtc_QRadioButton_setHandler8(void*,void*,void*,void*,void*);
void qtc_QRadioButton_showEvent_h(void*,void*);
void qtc_QRadioButton_tabletEvent_h(void*,void*);
void qtc_QRadioButton_wheelEvent_h(void*,void*);
int qtc_QRadioButton_eventFilter_h(void*,void*,void*);
int qtc_QRadioButton_setHandler9(void*,void*,void*,void*,void*);


text:
//
//  PhotoViewType.h
//  MEMobile
//
//  Created by LamTsanFeng on 2016/9/28.
//  Copyright © 2016年 GZMiracle. All rights reserved.
//

#ifndef PhotoViewType_h
#define PhotoViewType_h

typedef NS_ENUM(NSInteger, downLoadType) { // 加载类型
    downLoadTypeUnknown, // 未知
    downLoadTypeLocale, // 本地
    downLoadTypeNetWork, // 网络
    downLoadTypeImage, // 显示单张图片
    downLoadTypeFail = 9, // 下载失败
};

typedef NS_ENUM(NSInteger, MaskPosition) {//遮罩位置
    MaskPosition_None, //遮罩与图层一样大
    MaskPosition_LeftOrUp, //左边或者上边
    MaskPosition_Middle, //中间位置
    MaskPosition_RightOrDown,//右边或者下边
};

#endif /* PhotoViewType_h */


text:
<?php

namespace Akeeba\Engine\Postproc\Connector\S3v4\Exception;

// Protection against direct access
defined('AKEEBAENGINE') or die();

class CannotGetBucket extends \RuntimeException
{
}


text:
ecsHandle::ecsHandle(const char id[32])
{
	std::copy(&id[0], &id[32], &m_uuid[0]);
}

bool ecsHandle::operator==(const ecsHandle& other) const noexcept
{
	return bool(std::strncmp(m_uuid, other.m_uuid, 32ULL) == 0);
}

bool ecsHandle::operator<(const ecsHandle& other) const noexcept
{
	return bool(std::strncmp(m_uuid, other.m_uuid, 32ULL) < 0);
}

ecsHandle::operator bool() const noexcept
{
	static const ecsHandle empty;
	return !bool((*this) == empty);
}

bool ecsHandle::isValid() const noexcept
{
	static const ecsHandle empty;
	return !bool((*this) == empty);
}

EntityHandle::EntityHandle(const ecsHandle& handle) noexcept
	: ecsHandle(handle)
{
}

ComponentHandle::ComponentHandle(const ecsHandle& handle) noexcept
	: ecsHandle(handle)
{
}


text:
package com.xebia.xtime.test.shared.model;

import android.os.Parcel;

import com.xebia.xtime.shared.model.DayOverview;
import com.xebia.xtime.shared.model.Project;
import com.xebia.xtime.shared.model.TimeSheetEntry;

import junit.framework.TestCase;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class DayOverviewTest extends TestCase {

    private DayOverview mOverview;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        List<Project> projects = Arrays.asList(new Project("project id", "project name"));
        mOverview = new DayOverview(new Date(1234), projects, true);
        mOverview.setTotalHours(42);
        mOverview.setTimeSheetEntries(new ArrayList<TimeSheetEntry>());
    }

    public void testEquals() {
        List<Project> projects = Arrays.asList(new Project("project id", "project name"));
        DayOverview compare = new DayOverview(new Date(1234), projects, true);
        compare.setTotalHours(42);
        compare.setTimeSheetEntries(new ArrayList<TimeSheetEntry>());
        assertTrue(mOverview.equals(compare));

        compare.setTotalHours(13);
        assertFalse(mOverview.equals(compare));
        compare.setTotalHours(42);
        assertTrue(mOverview.equals(compare));

        compare.getTimeSheetEntries().add(new TimeSheetEntry(null, null, null, null));
        assertFalse(mOverview.equals(compare));
        compare.getTimeSheetEntries().clear();
        assertTrue(mOverview.equals(compare));

        compare.setEditable(false);
        assertFalse(mOverview.equals(compare));
        compare.setEditable(true);
        assertTrue(mOverview.equals(compare));

        DayOverview shouldNotEqual = new DayOverview(new Date(1234), new ArrayList<Project>(),
                true);
        shouldNotEqual.setTotalHours(42);
        shouldNotEqual.setTimeSheetEntries(new ArrayList<TimeSheetEntry>());
        assertFalse(mOverview.equals(shouldNotEqual));
    }

    public void testParcelable() {
        Parcel in = Parcel.obtain();
        Parcel out = Parcel.obtain();
        DayOverview result = null;
        try {
            in.writeParcelable(mOverview, 0);
            byte[] bytes = in.marshall();
            out.unmarshall(bytes, 0, bytes.length);
            out.setDataPosition(0);
            result = out.readParcelable(DayOverview.class.getClassLoader());
        } finally {
            in.recycle();
            out.recycle();
        }

        assertNotNull(result);
        assertEquals(mOverview, result);
    }
}


text:
from . import db
from sqlalchemy import ForeignKey
from sqlalchemy import Table, Column, Integer, ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

# Application models
ROLE_STUDENT = 0
ROLE_ADMIN = 1

user_focus = db.Table('user_focus',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('focus_id', db.Integer, db.ForeignKey('focus.id'))
)

org_focus = db.Table('org_focus',
    db.Column('org_id', db.Integer, db.ForeignKey('organisation.id')),
    db.Column('focus_id', db.Integer, db.ForeignKey('focus.id'))
)

user_org = db.Table('user_org',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('org_id', db.Integer, db.ForeignKey('organisation.id'))
)

class User(db.Model):
    """ `User` is any entity which uses the application. User will
    have a valid facebook account to access the application.
    """
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(255), nullable=False)
    last_name = db.Column(db.String(255),nullable=False)
    date_of_birth = db.Column(db.Integer)
    college=db.Column(db.String(255),nullable=False)
    year_of_study = db.Column(db.Integer,nullable=False)
    branch = db.Column(db.String(60),nullable=False)
    blood_group=db.Column(db.String(5),nullable=False)
    email = db.Column(db.String(255),index = True,unique = True)
    news=db.Column(db.Boolean)
    phone = db.Column(db.Integer,nullable=False,unique=True)
    address=db.Column(db.String(255),nullable=False)
    facebook=db.Column(db.String(255),unique=True)
    linkedin=db.Column(db.String(255),unique=True)
    twitter=db.Column(db.Integer(255),unique=True)
    google=db.Column(db.Integer(255),unique=True)
    pintrest=db.Column(db.String(255),unique=True)
    role = db.Column(db.String(255),default = ROLE_STUDENT)
    blood = db.Column(db.Boolean)
    organ = db.Column(db.Boolean)
    disaster = db.Column(db.Boolean)
    focus = db.relationship('FocusAreas', secondary=user_focus)
    orgs = db.relationship('Organisation', secondary=user_org)
    def __repr__(self):
        return "<User:%d:%s:%s:%s>" % (self.id , self.first_name,self.email,self.last_name)

class Organisation(db.Model):
    """Organisation` is any entity which uses the application."""
    __tablename__ = "organisation"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False)
    yer_es=db.Column(db.Integer(255),nullable=True)
    about=db.Column(db.String(255),nullable=True)
    reg_adr=db.Column(db.String(255),nullable=True)
    cor_adr=db.Column(db.String(255),nullable=True)
    contact_name=db.Column(db.String(255),nullable=True)
    contact_des=db.Column(db.String(255),nullable=True)
    icare_phone=db.Column(db.Integer,nullable=True)
    icare_mobile=db.Column(db.Integer,nullable=True)
    icare_fax=db.Column(db.Integer,nullable=True)
    website = db.Column(db.String(255),nullable=True)
    icare_email = db.Column(db.String(255),nullable=True)
    social = db.Column(db.Boolean)
    skills_based = db.Column(db.Boolean)
    micro = db.Column(db.Boolean)
    areaofwork = db.Column(db.String(255))
    community=db.Column(db.Boolean)
    intl_camp=db.Column(db.Boolean)
    dis_hr=db.Column(db.Boolean)
    dis_stationary=db.Column(db.Boolean)
    dis_software=db.Column(db.Boolean)
    dis_hardware=db.Column(db.Boolean)
    focus = db.relationship('FocusAreas', secondary=org_focus)

    def __repr__(self):
        return "<Organisation:%d:%s:%s:%s>" % (self.id , self.name,self.website,self.email)

class FocusAreas(db.Model):
    """'Focus Areas' is an entity which has focus areas as fields"""
    __tablename__ = "focus"
    id = db.Column(db.Integer,primary_key=True)
    interest_name=db.Column(db.String(255),nullable=False)

    def __repr__(self):
          return "<FocusAreas:%r:%r>" % (self.id,self.interest_name)


text:
'use strict';
/**
 * Contains `lookupFiles`, which takes some globs/dirs/options and returns a list of files.
 * @module
 * @private
 */

var fs = require('fs');
var path = require('path');
var glob = require('glob');
var errors = require('../errors');
var createNoFilesMatchPatternError = errors.createNoFilesMatchPatternError;
var createMissingArgumentError = errors.createMissingArgumentError;
const debug = require('debug')('mocha:cli:lookup-files');

/**
 * Determines if pathname would be a "hidden" file (or directory) on UN*X.
 *
 * @description
 * On UN*X, pathnames beginning with a full stop (aka dot) are hidden during
 * typical usage. Dotfiles, plain-text configuration files, are prime examples.
 *
 * @see {@link http://xahlee.info/UnixResource_dir/writ/unix_origin_of_dot_filename.html|Origin of Dot File Names}
 *
 * @private
 * @param {string} pathname - Pathname to check for match.
 * @return {boolean} whether pathname would be considered a hidden file.
 * @example
 * isHiddenOnUnix('.profile'); // => true
 */
const isHiddenOnUnix = pathname => path.basename(pathname).startsWith('.');

/**
 * Determines if pathname has a matching file extension.
 *
 * Supports multi-part extensions.
 *
 * @private
 * @param {string} pathname - Pathname to check for match.
 * @param {string[]} exts - List of file extensions, w/-or-w/o leading period
 * @return {boolean} `true` if file extension matches.
 * @example
 * hasMatchingExtname('foo.html', ['js', 'css']); // false
 * hasMatchingExtname('foo.js', ['.js']); // true
 * hasMatchingExtname('foo.js', ['js']); // ture
 */
const hasMatchingExtname = (pathname, exts = []) =>
  exts
    .map(ext => (ext.startsWith('.') ? ext : `.${ext}`))
    .some(ext => pathname.endsWith(ext));

/**
 * Lookup file names at the given `path`.
 *
 * @description
 * Filenames are returned in _traversal_ order by the OS/filesystem.
 * **Make no assumption that the names will be sorted in any fashion.**
 *
 * @public
 * @alias module:lib/cli.lookupFiles
 * @param {string} filepath - Base path to start searching from.
 * @param {string[]} [extensions=[]] - File extensions to look for.
 * @param {boolean} [recursive=false] - Whether to recurse into subdirectories.
 * @return {string[]} An array of paths.
 * @throws {Error} if no files match pattern.
 * @throws {TypeError} if `filepath` is directory and `extensions` not provided.
 */
module.exports = function lookupFiles(
  filepath,
  extensions = [],
  recursive = false
) {
  const files = [];
  let stat;

  if (!fs.existsSync(filepath)) {
    let pattern;
    if (glob.hasMagic(filepath)) {
      // Handle glob as is without extensions
      pattern = filepath;
    } else {
      // glob pattern e.g. 'filepath+(.js|.ts)'
      const strExtensions = extensions
        .map(ext => (ext.startsWith('.') ? ext : `.${ext}`))
        .join('|');
      pattern = `${filepath}+(${strExtensions})`;
      debug('looking for files using glob pattern: %s', pattern);
    }
    files.push(...glob.sync(pattern, {nodir: true}));
    if (!files.length) {
      throw createNoFilesMatchPatternError(
        `Cannot find any files matching pattern "${filepath}"`,
        filepath
      );
    }
    return files;
  }

  // Handle file
  try {
    stat = fs.statSync(filepath);
    if (stat.isFile()) {
      return filepath;
    }
  } catch (err) {
    // ignore error
    return;
  }

  // Handle directory
  fs.readdirSync(filepath).forEach(dirent => {
    const pathname = path.join(filepath, dirent);
    let stat;

    try {
      stat = fs.statSync(pathname);
      if (stat.isDirectory()) {
        if (recursive) {
          files.push(...lookupFiles(pathname, extensions, recursive));
        }
        return;
      }
    } catch (ignored) {
      return;
    }
    if (!extensions.length) {
      throw createMissingArgumentError(
        `Argument '${extensions}' required when argument '${filepath}' is a directory`,
        'extensions',
        'array'
      );
    }

    if (
      !stat.isFile() ||
      !hasMatchingExtname(pathname, extensions) ||
      isHiddenOnUnix(pathname)
    ) {
      return;
    }
    files.push(pathname);
  });

  return files;
};


text:
#ifndef HTTPSERVER_H
#define HTTPSERVER_H

#include <QtCore>
#include <QtNetwork>

class GlobalSettings;
class SkinManager;

class HttpServer : public QTcpServer
{
    Q_OBJECT
    Q_PROPERTY(QString address READ address NOTIFY addressChanged)
    Q_PROPERTY(int port READ port NOTIFY portChanged)

public:
    HttpServer(GlobalSettings *settings, quint16 port, QObject* parent = 0);

    void incomingConnection(qintptr socket);

    QString address() const { return m_address; }
    int port() const { return serverPort(); }

signals:
    void addressChanged();
    void portChanged();

private:
    QString getAddress();

    GlobalSettings *m_settings;
    QString m_base;
    QString m_address;
    SkinManager* m_skinManager;
};

#endif // HTTPSERVER_H


text:
package com.facebook.rebound;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * BaseSpringSystem maintains the set of springs within an Application context. It is responsible for
 * Running the spring integration loop and maintains a registry of all the Springs it solves for.
 * In addition to listening to physics events on the individual Springs in the system, listeners
 * can be added to the BaseSpringSystem itself to provide pre and post integration setup.
 */
public class BaseSpringSystem {

  private final Map<String, Spring> mSpringRegistry = new HashMap<String, Spring>();
  private final Set<Spring> mActiveSprings = new CopyOnWriteArraySet<Spring>();
  private final SpringLooper mSpringLooper;
  private final CopyOnWriteArraySet<SpringSystemListener> mListeners = new CopyOnWriteArraySet<SpringSystemListener>();
  private boolean mIdle = true;

  /**
   * create a new BaseSpringSystem
   * @param springLooper parameterized springLooper to allow testability of the
   *        physics loop
   */
  public BaseSpringSystem(SpringLooper springLooper) {
    if (springLooper == null) {
      throw new IllegalArgumentException("springLooper is required");
    }
    mSpringLooper = springLooper;
    mSpringLooper.setSpringSystem(this);
  }

  /**
   * check if the system is idle
   * @return is the system idle
   */
  public boolean getIsIdle() {
    return mIdle;
  }

  /**
   * create a spring with a random uuid for its name.
   * @return the spring
   */
  public Spring createSpring() {
    Spring spring = new Spring(this);
    registerSpring(spring);
    return spring;
  }

  /**
   * get a spring by name
   * @param id id of the spring to retrieve
   * @return Spring with the specified key
   */
  public Spring getSpringById(String id) {
    if (id == null) {
      throw new IllegalArgumentException("id is required");
    }
    return mSpringRegistry.get(id);
  }

  /**
   * return all the springs in the simulator
   * @return all the springs
   */
  public List<Spring> getAllSprings() {
    Collection<Spring> collection = mSpringRegistry.values();
    List<Spring> list;
    if (collection instanceof List) {
      list = (List<Spring>)collection;
    } else {
      list = new ArrayList<Spring>(collection);
    }
    return Collections.unmodifiableList(list);
  }

  /**
   * Registers a Spring to this BaseSpringSystem so it can be iterated if active.
   * @param spring the Spring to register
   */
  void registerSpring(Spring spring) {
    if (spring == null) {
      throw new IllegalArgumentException("spring is required");
    }
    if (mSpringRegistry.containsKey(spring.getId())) {
      throw new IllegalArgumentException("spring is already registered"); }
    mSpringRegistry.put(spring.getId(), spring);
  }

  /**
   * Deregisters a Spring from this BaseSpringSystem, so it won't be iterated anymore. The Spring should
   * not be used anymore after doing this.
   *
   * @param spring the Spring to deregister
   */
  void deregisterSpring(Spring spring) {
    if (spring == null) {
      throw new IllegalArgumentException("spring is required");
    }
    mActiveSprings.remove(spring);
    mSpringRegistry.remove(spring.getId());
  }

  /**
   * update the springs in the system
   * @param deltaTime delta since last update in millis
   */
  void advance(double deltaTime) {
    for (Spring spring : mActiveSprings) {
      // advance time in seconds
      if (spring.systemShouldAdvance()) {
        spring.advance(deltaTime / 1000.0);
      } else {
        mActiveSprings.remove(spring);
      }
    }
  }

  /**
   * loop the system until idle
   */
  public void loop(double ellapsedMillis) {
    for (SpringSystemListener listener : mListeners) {
      listener.onBeforeIntegrate(this);
    }
    advance(ellapsedMillis);
    if (mActiveSprings.isEmpty()) {
      mIdle = true;
    }
    for (SpringSystemListener listener : mListeners) {
      listener.onAfterIntegrate(this);
    }
    if (mIdle) {
      mSpringLooper.stop();
    }
  }

  /**
   * This is used internally by the {@link Spring}s created by this {@link BaseSpringSystem} to notify
   * it has reached a state where it needs to be iterated. This will add the spring to the list of
   * active springs on this system and start the iteration if the system was idle before this call.
   * @param springId the id of the Spring to be activated
   */
  void activateSpring(String springId) {
    Spring spring = mSpringRegistry.get(springId);
    if (spring == null) {
      throw new IllegalArgumentException("springId " + springId + " does not reference a registered spring");
    }
    mActiveSprings.add(spring);
    if (getIsIdle()) {
      mIdle = false;
      mSpringLooper.start();
    }
  }

  /** listeners **/

  public void addListener(SpringSystemListener newListener) {
    if (newListener == null) {
      throw new IllegalArgumentException("newListener is required");
    }
    mListeners.add(newListener);
  }

  public void removeListener(SpringSystemListener listenerToRemove) {
    if (listenerToRemove == null) {
      throw new IllegalArgumentException("listenerToRemove is required");
    }
    mListeners.remove(listenerToRemove);
  }

  public void removeAllListeners() {
    mListeners.clear();
  }
}


text:
typedef unsigned short uint16;

extern void uint16_pack(char *,uint16);
extern void uint16_pack_big(char *,uint16);
extern void uint16_unpack(const char *,uint16 *);
extern void uint16_unpack_big(const char *,uint16 *);

#endif