text:
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import sys
import inspect
import os
from os import listdir, remove, makedirs
from shutil import copyfile
from os.path import isdir, join, exists, split, relpath, splitext
from subprocess import Popen, PIPE, STDOUT, call
import json
from collections import OrderedDict

def cmd(l, check=True, verbose=False, shell=False, cwd=None):
    text = l if shell else ' '.join(l)
    if verbose:
        print text
    rc = call(l, shell=shell, cwd=cwd)
    if check and rc != 0:
        raise Exception('ERROR %d: "%s"' % (rc, text))

def run_cmd(command, wd=None, redirect=False):
    assert is_cmd_valid(command[0])
    try:
        p = Popen(command, stdout=PIPE, stderr=STDOUT if redirect else PIPE, cwd=wd)
        _stdout, _stderr = p.communicate()
    except OSError as e:
        print "[OS ERROR] Command: "+(' '.join(command))
        raise

    return _stdout, _stderr, p.returncode

def run_cmd_ext(command):
    assert is_cmd_valid(command[0])
    p = Popen(command, stdout=PIPE, stderr=PIPE)
    _stdout, _stderr = p.communicate()
    return _stdout, _stderr, p.returncode

def is_cmd_valid(cmd):
    caller = get_caller_name()
    abspath = find_cmd_abspath(cmd)
    if not abspath:
        error("%s: Command '%s' can't be found" % (caller, cmd))
    if not is_exec(abspath):
        error("%s: Command '%s' resolves to file '%s' which is not executable" % (caller, cmd, abspath))
    return True

def is_exec(path):
    return os.access(path, os.X_OK) or os.access(path+'.exe', os.X_OK)

def find_cmd_abspath(cmd):
    """ Returns the absolute path to a command.
        None is returned if no absolute path was found.
    """
    if exists(cmd) or exists(cmd + '.exe'):
        return os.path.abspath(cmd)
    if not 'PATH' in os.environ:
        raise Exception("Can't find command path for current platform ('%s')" % sys.platform)
    PATH=os.environ['PATH']
    for path in PATH.split(os.pathsep):
        abspath = '%s/%s' % (path, cmd)
        if exists(abspath) or exists(abspath + '.exe'):
            return abspath

def mkdir(path):
    if not exists(path):
        makedirs(path)

def copy_file(src, dst):
    """ Implement the behaviour of "shutil.copy(src, dst)" without copying the
        permissions (this was causing errors with directories mounted with samba)
    """
    if isdir(dst):
        _, file = split(src)
        dst = join(dst, file)
    copyfile(src, dst)

def delete_dir_files(dir):
    if not exists(dir):
        return

    for f in listdir(dir):
        file = join(dir, f)
        if not isdir(file):
            remove(file)

def get_caller_name(steps=2):
    """
    When called inside a function, it returns the name
    of the caller of that function.
    """
    return inspect.stack()[steps][3]

def error(msg):
    print("ERROR: %s" % msg)
    sys.exit(1)

def rel_path(path, base, dot=False):
    p = relpath(path, base)
    if dot and not p.startswith('.'):
        p = './' + p
    return p

class ToolException(Exception):
    pass

class NotSupportedException(Exception):
    pass

def split_path(path):
    base, file = split(path)
    name, ext = splitext(file)
    return base, name, ext

def args_error(parser, message):
    print "\n\n%s\n\n" % message
    parser.print_help()
    sys.exit()

def construct_enum(**enums):
    """ Create your own pseudo-enums """
    return type('Enum', (), enums)

def check_required_modules(required_modules, verbose=True):
    """ Function checks for Python modules which should be "importable" (installed)
        before test suite can be used.
        @return returns True if all modules are installed already
    """
    import imp
    not_installed_modules = []
    for module_name in required_modules:
        try:
            imp.find_module(module_name)
        except ImportError as e:
            # We also test against a rare case: module is an egg file
            try:
                __import__(module_name)
            except ImportError as e:
                not_installed_modules.append(module_name)
                if verbose:
                    print "Error: %s" % e

    if verbose:
        if not_installed_modules:
            print "Warning: Module(s) %s not installed. Please install required module(s) before using this script."% (', '.join(not_installed_modules))

    if not_installed_modules:
        return False
    else:
        return True

# Utility function: traverse a dictionary and change all the strings in the dictionary to
# ASCII from Unicode. Useful when reading ASCII JSON data, because the JSON decoder always
# returns Unicode string.
# Based on http://stackoverflow.com/a/13105359
def dict_to_ascii(input):
    if isinstance(input, dict):
        return OrderedDict([(dict_to_ascii(key), dict_to_ascii(value)) for key, value in input.iteritems()])
    elif isinstance(input, list):
        return [dict_to_ascii(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('ascii')
    else:
        return input

# Read a JSON file and return its Python representation, transforming all the strings from Unicode
# to ASCII. The order of keys in the JSON file is preserved.
def json_file_to_dict(fname):
    with open(fname, "rt") as f:
        return dict_to_ascii(json.load(f, object_pairs_hook=OrderedDict))


text:
package com.anyi.report.entity;

import java.util.List;

public class DocApprove {

	private String approve_status;//--审签状态
	private String approve_person;//--审签人
	private String approve_time;//--审签时间
	private String now_time;//当前时间
	private List <DocApproveRecord> list;//记录ID

	public String getApprove_status() {
		return approve_status;
	}
	public void setApprove_status(String approve_status) {
		this.approve_status = approve_status;
	}
	public String getApprove_person() {
		return approve_person;
	}
	public void setApprove_person(String approve_person) {
		this.approve_person = approve_person;
	}
	public String getApprove_time() {
		return approve_time;
	}
	public void setApprove_time(String approve_time) {
		this.approve_time = approve_time;
	}
	public List<DocApproveRecord> getList() {
		return list;
	}
	public void setList(List<DocApproveRecord> list) {
		this.list = list;
	}
	public String getNow_time() {
		return now_time;
	}
	public void setNow_time(String now_time) {
		this.now_time = now_time;
	}

}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

namespace Microsoft.Common.Core.OS {
    public interface IRegistry {
        IRegistryKey OpenBaseKey(Win32.RegistryHive hive, Win32.RegistryView view);
    }
}


text:
AnimalMod.SoundUtils = {};
AnimalMod.Utils:inheritsFrom( AnimalMod );
-- to do: sound system: create a pool for sounds to be used during gameplay
-- we go use the pools to load sounds to the animals from out the AnimalMod/sound/animalType root.
-- idea is to also load sounds on animals where there is no sound defined on the animal.zip.
-- we go create a AnimalMod.soundUtils for handle sound creations, this i must see during development
-- the utils files will be evaluated

AnimalMod.animals.soundPools = {};
AnimalMod.animals.soundPoolsUsed = {};

function AnimalMod.SoundUtils.addSound(animalType, fileName, volume, isplaying )
    if(AnimalMod.animals.sounds[animalType] == nil) then
        AnimalMod.animals.sounds[animalType] = animalType;
    end;
end;

function AnimalMod.SoundUtils.createSpool(animalType, amount)
    local s = "soundPools";
    if(AnimalMod.animals[soundPools] == not nil)then
        print("AnimalMod ERROR: We already have a soundpool for this animalType.");
        return;
    end;

    if(AnimalMod.animals[soundPools][animalType] == nil)then
        AnimalMod.animals[soundPools][animalType] = animalType;
    else
        return false;
    end;
end;


text:
using content::BrowserThread;

namespace wallpaper_api_util {
namespace {

// Keeps in sync (same order) with WallpaperLayout enum in header file.
const char* const kWallpaperLayoutArrays[] = {
  "CENTER",
  "CENTER_CROPPED",
  "STRETCH",
  "TILE"
};

const int kWallpaperLayoutCount = arraysize(kWallpaperLayoutArrays);

}  // namespace

const char kCancelWallpaperMessage[] = "Set wallpaper was canceled.";

wallpaper::WallpaperLayout GetLayoutEnum(const std::string& layout) {
  for (int i = 0; i < kWallpaperLayoutCount; i++) {
    if (layout.compare(kWallpaperLayoutArrays[i]) == 0)
      return static_cast<wallpaper::WallpaperLayout>(i);
  }
  // Default to use CENTER layout.
  return wallpaper::WALLPAPER_LAYOUT_CENTER;
}

void RecordCustomWallpaperLayout(const wallpaper::WallpaperLayout& layout) {
  UMA_HISTOGRAM_ENUMERATION("Ash.Wallpaper.CustomLayout", layout,
                            wallpaper::NUM_WALLPAPER_LAYOUT);
}

}  // namespace wallpaper_api_util

class WallpaperFunctionBase::UnsafeWallpaperDecoder
    : public ImageDecoder::ImageRequest {
 public:
  explicit UnsafeWallpaperDecoder(scoped_refptr<WallpaperFunctionBase> function)
      : function_(function) {}

  void Start(const std::vector<char>& image_data) {
    DCHECK_CURRENTLY_ON(BrowserThread::UI);

    // This function can only be called after user login. It is fine to use
    // unsafe image decoder here. Before user login, a robust jpeg decoder will
    // be used.
    CHECK(chromeos::LoginState::Get()->IsUserLoggedIn());
    std::string image_data_str(image_data.begin(), image_data.end());
    ImageDecoder::StartWithOptions(this, image_data_str,
                                   ImageDecoder::DEFAULT_CODEC, true);
  }

  void Cancel() {
    cancel_flag_.Set();
  }

  void OnImageDecoded(const SkBitmap& decoded_image) override {
    // Make the SkBitmap immutable as we won't modify it. This is important
    // because otherwise it gets duplicated during painting, wasting memory.
    SkBitmap immutable(decoded_image);
    immutable.setImmutable();
    gfx::ImageSkia final_image = gfx::ImageSkia::CreateFrom1xBitmap(immutable);
    final_image.MakeThreadSafe();
    if (cancel_flag_.IsSet()) {
      function_->OnCancel();
      delete this;
      return;
    }
    function_->OnWallpaperDecoded(final_image);
    delete this;
  }

  void OnDecodeImageFailed() override {
    function_->OnFailure(
        l10n_util::GetStringUTF8(IDS_WALLPAPER_MANAGER_INVALID_WALLPAPER));
    delete this;
  }

 private:
  scoped_refptr<WallpaperFunctionBase> function_;
  base::CancellationFlag cancel_flag_;

  DISALLOW_COPY_AND_ASSIGN(UnsafeWallpaperDecoder);
};

WallpaperFunctionBase::UnsafeWallpaperDecoder*
    WallpaperFunctionBase::unsafe_wallpaper_decoder_;

WallpaperFunctionBase::WallpaperFunctionBase() {
}

WallpaperFunctionBase::~WallpaperFunctionBase() {
}

void WallpaperFunctionBase::StartDecode(const std::vector<char>& data) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);
  if (unsafe_wallpaper_decoder_)
    unsafe_wallpaper_decoder_->Cancel();
  unsafe_wallpaper_decoder_ = new UnsafeWallpaperDecoder(this);
  unsafe_wallpaper_decoder_->Start(data);
}

void WallpaperFunctionBase::OnCancel() {
  unsafe_wallpaper_decoder_ = NULL;
  SetError(wallpaper_api_util::kCancelWallpaperMessage);
  SendResponse(false);
}

void WallpaperFunctionBase::OnFailure(const std::string& error) {
  unsafe_wallpaper_decoder_ = NULL;
  SetError(error);
  SendResponse(false);
}


text:
var App = require('./start');
var Bootstrap = require('./bootstrap');
var Router = require('./routers/router');

$(document).ready(function() {

    // Init the application custom context
    Kiwapp("../config/kiwapp_config.js", function(){

        log('[App@init] : The application context is ready');

        Bootstrap.i18nLoader(function() {

            // Because we have a landscape app
            Kiwapp.driver().trigger('callApp', {call:'rotation', data:{
                "orientation" : 10
            }});

            App.Routers.Instances.router = new Router();

            Backbone.history.start();
            App.swiftclick = SwiftClick.attach(document.body);
        });
    });
});


text:
<?php

class testTechnique extends CI_Model
{

  public function getTestById($id_offre)
  {
		$query = $this->db->query('SELECT id_test FROM offres where id ='.$id_offre);
		return $query->row();
  }

  public function getQuestionsById($id_test)
  {
		$query = $this->db->query('SELECT * FROM questions where id_test ="'.$id_test.'"');
		return $query->result_array();

  }

  public function getReponsesById($id_question)
  {
		$query = $this->db->query('SELECT * FROM reponses where id_question ='.$id_question);
		return $query->result_array();

  }

  public function getReponsesCorrect($id_question)
  {

    $query = $this->db->select('*')
                ->from('reponses')
                ->where('id_question', $id_question)
                ->where('correct', 1);

    return $query->result_array();

  }

}


text:
using System;
using Microsoft.CognitiveServices.ContentModerator;
using Microsoft.CognitiveServices.ContentModerator.Models;
using System.Collections.Generic;
using ContentModeratorTests.Helpers;
using Newtonsoft.Json;
using System.Linq;
using System.Net;
using System.IO;
using Xunit;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Microsoft.Azure.Test.HttpRecorder;

namespace ContentModeratorTests
{
        public class ReviewAPIs : TestBase
    {
        ContentModeratorClient client = null;
        ReviewResponses results = new ReviewResponses();
        JobId Job = new JobId();
        IList<string> ReviewIds = new List<string>();
        static ReviewAPI api;
        static ReviewStatus rvwStatus;
        static Content content;

        public ReviewAPIs()
        {
            TestSetUpConfiguration();
        }

        public void TestCleanup()
        {
            TestCleanupConfiguration();
        }

        #region Jobs

        [Fact]
        public void CreateImageJob()
        {

            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    content = Content.IMAGE;
                    api = ReviewAPI.JOB_CREATE;
                    HttpMockServer.Initialize("ReviewAPIs", "CreateImageJob");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    results = Constants.GetReviewResponse(client, api, content, MIMETypes.JSON.GetDescription(), teamName, "Public", Workflow.IMAGE_WORKFLOW.GetDescription(), content.GetDescription() + " Review");

                    var job = results.CreateJob;
                    Assert.NotNull(job);
                    Assert.Equal(HttpStatusCode.OK, job.Response.StatusCode);
                    Job = job.Body;
                    Assert.NotNull(Job);
                    Assert.NotNull(Job.JobIdProperty);

                }
            }
            catch (Exception e)
            {

                throw e;
            }

        }

        [Fact]
        public void CreateTextJob()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {

                    content = Content.TEXT;
                    api = ReviewAPI.JOB_CREATE;
                    HttpMockServer.Initialize("ReviewAPIs", "CreateTextJob");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    results = Constants.GetReviewResponse(client, api, content, MIMETypes.JSON.GetDescription(), teamName, "Public", Workflow.TEXT_WORKFLOW.GetDescription(), content.GetDescription() + " Review");

                    var job = results.CreateJob;
                    Assert.NotNull(job);
                    Assert.Equal(HttpStatusCode.OK, job.Response.StatusCode);
                    Job = job.Body;
                    Assert.NotNull(Job);
                    Assert.NotNull(Job.JobIdProperty);

                }
            }
            catch (Exception e)
            {

                throw e;
            }

        }

        [Fact]
        public void GetImageJob()
        {

            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    //CreateImageJob();
                    //wait(2);
                    content = Content.IMAGE;
                    //string Jobid = Job.JobIdProperty;
                    api = ReviewAPI.JOB_GET;
                    HttpMockServer.Initialize("ReviewAPIs", "GetImageJob");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    //results = Constants.GetReviewResponse(client, api, content, MIMETypes.JSON.GetDescription(), teamName, null, null, null, Jobid);
                    results = Constants.GetReviewResponse(client, api, content, MIMETypes.JSON.GetDescription(), teamName, null, null, null, "201712471f16b6733748a69e3cf66126d337fb");

                    var jobdetails = results.GetJobDetails;
                    Assert.NotNull(jobdetails);
                    var job = jobdetails.Body;
                    Assert.Equal("201712471f16b6733748a69e3cf66126d337fb", job.Id);
                    //Assert.Equal(Jobid, job.Id);
                    Assert.True(Helpers.Utilities.VerifyJob(Content.IMAGE, job), " " + TestBase.ErrorMessage);

                }
            }
            catch (Exception e)
            {

                throw e;
            }

        }

        [Fact]
        public void GetTextJob()
        {

            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    //CreateTextJob();
                    wait(2);
                    content = Content.TEXT;
                    //string Jobid = Job.JobIdProperty;
                    api = ReviewAPI.JOB_GET;
                    HttpMockServer.Initialize("ReviewAPIs", "GetTextJob");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    //results = Constants.GetReviewResponse(client, api, content, MIMETypes.JSON.GetDescription(), teamName, null, null, null, Jobid);
                    results = Constants.GetReviewResponse(client, api, content, MIMETypes.JSON.GetDescription(), teamName, null, null, null, "201712b43444e4be70470b80bff6605a33e77d");

                    var jobdetails = results.GetJobDetails;
                    Assert.NotNull(jobdetails);
                    var job = jobdetails.Body;
                    Assert.Equal("201712b43444e4be70470b80bff6605a33e77d", job.Id);
                    //Assert.Equal(Jobid, job.Id);
                    Assert.True(Helpers.Utilities.VerifyJob(Content.TEXT, job), " " + TestBase.ErrorMessage);

                }
            }
            catch (Exception e)
            {

                throw e;
            }

        }

        #endregion

        #region Review

        [Fact]
        public void CreateImageReview()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    api = ReviewAPI.REVIEW_CREATE;
                    HttpMockServer.Initialize("ReviewAPIs", "CreateImageReview");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    results = Constants.GetReviewResponse(client, api, Content.IMAGE, MIMETypes.JSON.GetDescription(), teamName, null);

                    var review = results.CreateReview;
                    Assert.NotNull(review);
                    Assert.Equal(HttpStatusCode.OK, review.Response.StatusCode);
                    ReviewIds = review.Body.ToList();
                    Assert.True(ReviewIds.Count > 0, "Image Reviewid did not get generated");
                    Assert.NotNull(ReviewIds[0]);
                }
            }
            catch (Exception e)
            {

                throw e;
            }

        }

        [Fact]
        public void CreateTextReview()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    api = ReviewAPI.REVIEW_CREATE;
                    HttpMockServer.Initialize("ReviewAPIs", "CreateTextReview");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    results = Constants.GetReviewResponse(client, api, Content.TEXT, MIMETypes.JSON.GetDescription(), teamName, null);

                    var review = results.CreateReview;
                    Assert.NotNull(review);
                    Assert.Equal(HttpStatusCode.OK, review.Response.StatusCode);
                    ReviewIds = review.Body.ToList();
                    Assert.True(ReviewIds.Count > 0, "Text Reviewid did not get generated");
                    Assert.NotNull(ReviewIds[0]);
                }
            }
            catch (Exception e)
            {

                throw e;
            }

        }

        [Fact]
        public void CreateVideoReview()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    api = ReviewAPI.REVIEW_CREATE;
                    HttpMockServer.Initialize("ReviewAPIs", "CreateVideoReview");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    results = Constants.GetReviewResponse(client, api, Content.VIDEO, MIMETypes.JSON.GetDescription(), teamName, null, null, null, null, null, rvwStatus);

                    var review = results.CreateReview;
                    Assert.NotNull(review);
                    Assert.Equal(HttpStatusCode.OK, review.Response.StatusCode);
                    ReviewIds = review.Body.ToList();
                    Assert.True(ReviewIds.Count > 0, "Video Reviewid did not get generated");
                    Assert.NotNull(ReviewIds[0]);
                }
            }
            catch (Exception e)
            {

                throw e;
            }

        }

        [Fact]
        public void GetImageReview()
        {

            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    //CreateImageReview();
                    wait(2);
                    //string reviewid = ReviewIds.Count > 0 ? ReviewIds[0] : null;
                    api = ReviewAPI.REVIEW_GET;
                    HttpMockServer.Initialize("ReviewAPIs", "GetImageReview");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    //results = Constants.GetReviewResponse(client, api, Content.IMAGE, MIMETypes.JSON.GetDescription(), teamName, null, null, null, null, ReviewIds[0]);
                    results = Constants.GetReviewResponse(client, api, Content.IMAGE, MIMETypes.JSON.GetDescription(), teamName, null, null, null, null, "201712if012516997aa4d19befb3129c1082c48");
                    Review r = results.GetReview.Body;
                    Assert.NotNull(r);
                    Assert.Equal(HttpStatusCode.OK, results.GetReview.Response.StatusCode);
                    Assert.Equal("201712if012516997aa4d19befb3129c1082c48", r.ReviewId);
                    //Assert.Equal(reviewid, r.ReviewId);
                    Assert.True(Helpers.Utilities.VerifyReview(Content.IMAGE, r), " " + TestBase.ErrorMessage);

                }
            }
            catch (Exception e)
            {

                throw e;
            }

        }

        [Fact]
        public void GetTextReview()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {

                    //CreateTextReview();
                    wait(2);
                    //string reviewid = ReviewIds.Count > 0 ? ReviewIds[0] : null;
                    api = ReviewAPI.REVIEW_GET;
                    HttpMockServer.Initialize("ReviewAPIs", "GetTextReview");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    //results = Constants.GetReviewResponse(client, api, Content.TEXT, MIMETypes.JSON.GetDescription(), teamName, null, null, null, null, reviewid);
                    results = Constants.GetReviewResponse(client, api, Content.TEXT, MIMETypes.JSON.GetDescription(), teamName, null, null, null, null, "201712t9c7880135e834a939e4902ab82b5e97e");
                    Review r = results.GetReview.Body;
                    Assert.NotNull(r);
                    Assert.Equal(HttpStatusCode.OK, results.GetReview.Response.StatusCode);
                    Assert.Equal("201712t9c7880135e834a939e4902ab82b5e97e", r.ReviewId);
                    //Assert.Equal(reviewid, r.ReviewId);
                    Assert.True(Helpers.Utilities.VerifyReview(Content.TEXT, r), " " + TestBase.ErrorMessage);

                }
            }
            catch (Exception e)
            {

                throw e;
            }
        }

        [Fact]
        public void GetVideoReview()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {

                    //CreateVideoReview();
                    wait(2);
                    //string reviewid = ReviewIds.Count > 0 ? ReviewIds[0] : null;
                    api = ReviewAPI.REVIEW_GET;
                    HttpMockServer.Initialize("ReviewAPIs", "GetVideoReview");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    //results = Constants.GetReviewResponse(client, api, Content.VIDEO, MIMETypes.JSON.GetDescription(), teamName, null, null, null, null, reviewid);
                    results = Constants.GetReviewResponse(client, api, Content.VIDEO, MIMETypes.JSON.GetDescription(), teamName, null, null, null, null, "201712ve9d5eb16c9a247389ed371dbbf380b3c");
                    Review r = results.GetReview.Body;
                    Assert.NotNull(r);
                    Assert.Equal(HttpStatusCode.OK, results.GetReview.Response.StatusCode);
                    Assert.Equal("201712ve9d5eb16c9a247389ed371dbbf380b3c", r.ReviewId);
                    //Assert.Equal(reviewid, r.ReviewId);
                    Assert.True(Helpers.Utilities.VerifyReview(Content.VIDEO, r), " " + TestBase.ErrorMessage);

                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }
        #endregion

        #region VideoReview
        [Fact]
        public void AddURLFramesVideoReview()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    rvwStatus = ReviewStatus.UNPUBLISHED;
                    //CreateVideoReview();

                    api = ReviewAPI.FRAMES_ADD;
                    HttpMockServer.Initialize("ReviewAPIs", "AddURLFramesVideoReview");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    //results = Constants.GetVideoFramesReviewResponse(client, api, Content.VIDEO, MIMETypes.JSON.GetDescription(), teamName, ReviewIds[0]);
                    results = Constants.GetVideoFramesReviewResponse(client, api, Content.VIDEO, MIMETypes.JSON.GetDescription(), teamName, "201712v1f35675ed4d8457cbf84f4890ce59c58");

                    var review = results.AddFrames;
                    Assert.NotNull(review);
                    Assert.Equal(HttpStatusCode.NoContent, review.Response.StatusCode);
                }
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        [Fact]
        public void AddZipFramesVideoReview()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    rvwStatus = ReviewStatus.UNPUBLISHED;
                    //CreateVideoReview();
                    api = ReviewAPI.FRAMES_ADD;
                    HttpMockServer.Initialize("ReviewAPIs", "AddZipFramesVideoReview");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    //results = Constants.GetVideoFramesReviewResponse(client, api, Content.VIDEO, MIMETypes.MULTI_PART_FORM_DATA.GetDescription(), teamName, ReviewIds[0], false);
                    results = Constants.GetVideoFramesReviewResponse(client, api, Content.VIDEO, MIMETypes.MULTI_PART_FORM_DATA.GetDescription(), teamName, "201712vc779930a65dc4de993d25bc21f53f928", false);

                    var review = results.AddFrames;
                    Assert.NotNull(review);
                    Assert.Equal(HttpStatusCode.NoContent, review.Response.StatusCode);
                }
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        [Fact]
        public void GetFramesVideoReview()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    rvwStatus = ReviewStatus.UNPUBLISHED;
                    //CreateVideoReview();
                    api = ReviewAPI.FRAMES_GET;
                    HttpMockServer.Initialize("ReviewAPIs", "GetFramesVideoReview");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    //results = Constants.GetVideoFramesReviewResponse(client, api, Content.VIDEO, MIMETypes.JSON.GetDescription(), teamName, ReviewIds[0]);
                    results = Constants.GetVideoFramesReviewResponse(client, api, Content.VIDEO, MIMETypes.JSON.GetDescription(), teamName, "201712vbb90cbd620c0433dbecf70ad51e5563d");

                    var frames = results.GetFrames;
                    Assert.NotNull(frames);
                    Assert.Equal(HttpStatusCode.OK, frames.Response.StatusCode);
                    Assert.True(Helpers.Utilities.VerifyGetFrames(frames.Body), "Frames verification failed" + TestBase.ErrorMessage);
                }
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        [Fact]
        public void PublishVideo()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    rvwStatus = ReviewStatus.UNPUBLISHED;
                    //CreateVideoReview();
                    api = ReviewAPI.PUBLISH_VIDEO;
                    HttpMockServer.Initialize("ReviewAPIs", "PublishVideo");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    //results = Constants.GetReviewResponse(client, api, Content.VIDEO, MIMETypes.JSON.GetDescription(), teamName, null, null, null, null, ReviewIds[0]);
                    results = Constants.GetReviewResponse(client, api, Content.VIDEO, MIMETypes.JSON.GetDescription(), teamName, null, null, null, null, "201712v0e8053914c4a465c97fe401789364c71");
                    var review = results.PublishVideo;
                    Assert.NotNull(review);
                    Assert.Equal(HttpStatusCode.NoContent, review.Response.StatusCode);
                }
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        [Fact]
        public void AddTranscripts()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    rvwStatus = ReviewStatus.UNPUBLISHED;
                    //CreateVideoReview();

                    api = ReviewAPI.TRANSCRIPTS_ADD;
                    using (Stream s = new FileStream(currentExecutingDirectory + @"\TestDataSources\vttF.vtt", FileMode.Open, FileAccess.Read))
                    {
                        HttpMockServer.Initialize("ReviewAPIs", "AddTranscripts");
                        client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());

                        //results = Constants.GetTranscriptReviewResponse(client, api, Content.VIDEO, MIMETypes.TEXT_PLAIN.GetDescription(), teamName, ReviewIds[0], s);
                        results = Constants.GetTranscriptReviewResponse(client, api, Content.VIDEO, MIMETypes.TEXT_PLAIN.GetDescription(), teamName, "201712v67b52dea7aa94a669c766af506fd55d5", s);
                    }
                    var addTransacripts = results.AddTranscripts;
                    Assert.NotNull(addTransacripts);
                    Assert.Equal(HttpStatusCode.NoContent, addTransacripts.Response.StatusCode);
                }
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        [Fact]
        public void AddTranscriptsModerationResult()
        {
            try
            {
                using (MockContext context = MockContext.Start("ReviewAPIs"))
                {
                    rvwStatus = ReviewStatus.UNPUBLISHED;
                    //CreateVideoReview();
                    AddTranscripts();

                    api = ReviewAPI.TRANSCRIPTS_ADD_MODERATION_RESULT;
                    HttpMockServer.Initialize("ReviewAPIs", "AddTranscriptsModerationResult");
                    client = Constants.GenerateClient(api, HttpMockServer.CreateInstance());
                    //results = Constants.GetReviewResponse(client, api, Content.VIDEO, MIMETypes.JSON.GetDescription(), teamName, null, null, null, null, ReviewIds[0]);
                    results = Constants.GetReviewResponse(client, api, Content.VIDEO, MIMETypes.JSON.GetDescription(), teamName, null, null, null, null, "201712v67b52dea7aa94a669c766af506fd55d5");

                    var review = results.AddTranscriptsModerationResult;
                    Assert.NotNull(review);
                    Assert.Equal(HttpStatusCode.NoContent, review.Response.StatusCode);
                }
            }
            catch (Exception e)
            {
                throw e;
            }

        }

        #endregion

    }
}


text:
/* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
 *  (C) 2007 by Argonne National Laboratory.
 *      See COPYRIGHT in top-level directory.
 */
#include "mpi.h"
#include <stdio.h>
#include <string.h>
#include "mpitest.h"

/* Check that Comm_create detects the case where the group is not a subset of
   the group of the input communicator */

void abortMsg( const char *, int );

void abortMsg( const char *str, int code )
{
    char msg[MPI_MAX_ERROR_STRING];
    int class, resultLen;

    MPI_Error_class( code, &class );
    MPI_Error_string( code, msg, &resultLen );
    fprintf( stderr, "%s: errcode = %d, class = %d, msg = %s\n",
	     str, code, class, msg );
    MPI_Abort( MPI_COMM_WORLD, code );
}

int main( int argc, char *argv[] )
{
    MPI_Comm  evencomm, lowcomm, newcomm;
    int       wrank, wsize, gsize, err, errs = 0;
    int       ranges[1][3], mygrank;
    MPI_Group wGroup, godd, ghigh, geven;

    MTest_Init( &argc, &argv );

    MPI_Comm_set_errhandler( MPI_COMM_WORLD, MPI_ERRORS_RETURN );

    MPI_Comm_size( MPI_COMM_WORLD, &wsize );
    MPI_Comm_rank( MPI_COMM_WORLD, &wrank );

    /* Create some communicators */
    MPI_Comm_split( MPI_COMM_WORLD, wrank % 2, wrank, &evencomm );
    MPI_Comm_split( MPI_COMM_WORLD, wrank < wsize/2, wsize-wrank, &lowcomm );
    MPI_Comm_set_errhandler( evencomm, MPI_ERRORS_RETURN );
    MPI_Comm_set_errhandler( lowcomm, MPI_ERRORS_RETURN );

    /* Create some groups */
    MPI_Comm_group( MPI_COMM_WORLD, &wGroup );

    ranges[0][0] = 2*(wsize/2)-1;
    ranges[0][1] = 1;
    ranges[0][2] = -2;
    err = MPI_Group_range_incl( wGroup, 1, ranges, &godd );
    if (err) abortMsg( "Failed to create odd group: ", err );
    err = MPI_Group_size( godd, &gsize );
    if (err) abortMsg( "Failed to get size of odd group: ", err );
    if (gsize != wsize/2) {
	fprintf( stderr, "Group godd size is %d should be %d\n", gsize,
		 wsize/2 );
	errs++;
    }

    ranges[0][0] = wsize/4;
    ranges[0][1] = wsize-1;
    ranges[0][2] = 1;
    err = MPI_Group_range_incl( wGroup, 1, ranges, &ghigh );
    if (err) abortMsg( "Failed to create high group\n", err );
    ranges[0][0] = 0;
    ranges[0][1] = wsize-1;
    ranges[0][2] = 2;
    err = MPI_Group_range_incl( wGroup, 1, ranges, &geven );
    if (err) abortMsg( "Failed to create even group:", err );

    /* Check that a correct case returns success */
    if ( (wrank % 2) == 0) {
	err = MPI_Group_rank( geven, &mygrank );
	if (err) {
	    errs++;
	    fprintf( stderr, "Could not get rank from geven group\n" );
	}
	else if (mygrank == MPI_UNDEFINED) {
	    errs++;
	    fprintf( stderr, "mygrank should be %d but is undefined\n",
		     wrank/2);
	}
	err = MPI_Comm_create( evencomm, geven, &newcomm );
	/* printf( "Created new even comm\n" ); */
	if (err != MPI_SUCCESS) {
	    errs++;
	    fprintf( stderr, "Failed to allow creation from even group\n" );
	}
	else {
	    MPI_Comm_free( &newcomm );
	}
    }

    /* Now, test that these return errors when we try to use them to create
       groups */
    if ( (wrank % 2) == 0) {
	/* printf( "Even comm...\n" ); */
	/* evencomm is the comm of even-ranked processed in comm world */
	err = MPI_Comm_create( evencomm, godd, &newcomm );
	MPI_Group_rank( godd, &mygrank );
	if (err == MPI_SUCCESS) {
	    if (mygrank != MPI_UNDEFINED) {
		errs++;
		fprintf( stderr, "Did not detect group of odd ranks in even comm\n" );
	    }
	    MPI_Comm_free( &newcomm );
	}
    }
    if (wrank < wsize/2) {
	/* printf( "low comm...\n" ); */
	err = MPI_Comm_create( lowcomm, ghigh, &newcomm );
	MPI_Group_rank( ghigh, &mygrank );
	if (err == MPI_SUCCESS) {
	    if (mygrank != MPI_UNDEFINED) {
		errs++;
		fprintf( stderr, "Did not detect group of high ranks in low comm\n" );
	    }
	    MPI_Comm_free( &newcomm );
	}
    }

    MPI_Comm_free( &lowcomm );
    MPI_Comm_free( &evencomm );
    MPI_Group_free( &ghigh );
    MPI_Group_free( &godd );
    MPI_Group_free( &geven );
    MPI_Group_free( &wGroup );

    MTest_Finalize( errs );

    MPI_Finalize();
    return 0;
}


text:
/*===============================================================================================*/
// Copyright 2016 Kyle Finlay
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*===============================================================================================*/

/*===============================================================================================*/
//! TODO: Add module documentation.
/*===============================================================================================*/

// Modules
mod vec2;
mod vec3;
mod vec4;
mod vec_trait;

// Module imports
pub use self::vec2::{Vec2, Vec2f, Vec2i, Vec2u};
pub use self::vec3::{Vec3, Vec3f, Vec3i, Vec3u};
pub use self::vec4::{Vec4, Vec4f, Vec4i, Vec4u};
pub use self::vec_trait::{VecTrait, VecTraitF};


text:
package org.http4s
package client
package middleware

import cats.ApplicativeThrow
import cats.data.NonEmptyList
import cats.effect.kernel.Async
import cats.effect.kernel.MonadCancelThrow
import fs2.Pipe
import fs2.Pull
import fs2.Stream
import fs2.compression.Compression
import fs2.compression.DeflateParams
import fs2.io.compression._
import org.http4s.headers.`Accept-Encoding`
import org.http4s.headers.`Content-Encoding`
import org.typelevel.ci._

import scala.util.control.NoStackTrace

/** Client middleware for enabling gzip.
  */
object GZip {
  private val supportedCompressions =
    NonEmptyList.of(ContentCoding.gzip, ContentCoding.deflate)

  def apply[F[_]: MonadCancelThrow: Compression](
      bufferSize: Int = 32 * 1024
  )(client: Client[F]): Client[F] =
    Client[F] { req =>
      val reqWithEncoding = addHeaders(req)
      val responseResource = client.run(reqWithEncoding)

      responseResource.map { actualResponse =>
        decompress(bufferSize, actualResponse)
      }
    }

  @deprecated("Use overload with `Compression` constraint", "0.23.17")
  def apply[F[_]](bufferSize: Int, client: Client[F], F: Async[F]): Client[F] = {
    implicit val async = F
    apply(bufferSize)(client)
  }

  private def addHeaders[F[_]](req: Request[F]): Request[F] =
    req.headers.get[`Accept-Encoding`] match {
      case Some(_) =>
        req
      case _ =>
        req.putHeaders(`Accept-Encoding`(supportedCompressions))
    }

  private def decompress[F[_]: ApplicativeThrow: Compression](
      bufferSize: Int,
      response: Response[F],
  ): Response[F] =
    response.headers.get[`Content-Encoding`] match {
      case Some(header)
          if header.contentCoding == ContentCoding.gzip || header.contentCoding == ContentCoding.`x-gzip` =>
        val gunzip: Pipe[F, Byte, Byte] =
          _.through(Compression[F].gunzip(bufferSize)).flatMap(_.content)
        response
          .filterHeaders(nonCompressionHeader)
          .pipeBodyThrough(decompressWith(gunzip))

      case Some(header) if header.contentCoding == ContentCoding.deflate =>
        val deflate: Pipe[F, Byte, Byte] = Compression[F].deflate(DeflateParams(bufferSize))
        response
          .filterHeaders(nonCompressionHeader)
          .pipeBodyThrough(decompressWith(deflate))

      case _ =>
        response
    }

  private def decompressWith[F[_]: ApplicativeThrow](
      decompressor: Pipe[F, Byte, Byte]
  ): Pipe[F, Byte, Byte] =
    _.pull.peek1
      .flatMap {
        case None => Pull.raiseError(EmptyBodyException)
        case Some((_, fullStream)) => Pull.output1(fullStream)
      }
      .stream
      .flatten
      .through(decompressor)
      .handleErrorWith {
        case EmptyBodyException => Stream.empty
        case error => Stream.raiseError(error)
      }

  private def nonCompressionHeader(header: Header.Raw): Boolean =
    header.name != ci"Content-Encoding" &&
      header.name != ci"Content-Length"

  private object EmptyBodyException extends Throwable with NoStackTrace
}


text:
from dateutil.relativedelta import relativedelta
from nose.tools import eq_

from django.contrib.auth.models import User
from django.test import TestCase
from django.utils import timezone

from us_ignite.blog.models import Post
from us_ignite.blog.tests import fixtures
from us_ignite.profiles.tests.fixtures import get_user

class TestPostPublishedManager(TestCase):

    def tearDown(self):
        for model in [Post, User]:
            model.objects.all().delete()

    def test_published_post_is_returned(self):
        author = get_user('us-ignite')
        publication_date = timezone.now() - relativedelta(days=1)
        post = fixtures.get_post(
            author=author, status=Post.PUBLISHED,
            publication_date=publication_date)
        eq_(list(Post.published.all()), [post])

    def test_published_post_in_the_future_is_not_returned(self):
        author = get_user('us-ignite')
        publication_date = timezone.now() + relativedelta(days=1)
        post = fixtures.get_post(
            author=author, status=Post.PUBLISHED,
            publication_date=publication_date)
        eq_(list(Post.published.all()), [])

    def test_draft_post_is_not_returned(self):
        author = get_user('us-ignite')
        publication_date = timezone.now() - relativedelta(days=1)
        post = fixtures.get_post(
            author=author, status=Post.DRAFT,
            publication_date=publication_date)
        eq_(list(Post.published.all()), [])

    def test_removed_post_is_not_returned(self):
        author = get_user('us-ignite')
        publication_date = timezone.now() - relativedelta(days=1)
        post = fixtures.get_post(
            author=author, status=Post.REMOVED,
            publication_date=publication_date)
        eq_(list(Post.published.all()), [])


text:
$(document).ready(function() {

  var map = L.mapbox.map('map', 'jwatson.i4bh1ae1').setView([42.35872, -71.16568], 15);
  L.mapbox.featureLayer({
    type: 'Feature',
    geometry: {
      type: 'Point',
      coordinates: [-71.16568, 42.35872],
    },
    properties: {
      title: 'Harry Parker Boathouse',
      description: '20 Nonantum Rd. Brighton, MA',
      'marker-size': 'large',
      'marker-color': '#77c'
    }
  }).addTo(map);

  // Smooth scroll to the anchor target in the nav bar.
  $('header nav a[href *= #]').each(function scroll() {
      var targetAnchor = $('[name=' + this.hash.slice(1) + ']');
      var targetId = $(this.hash);

      if (targetId.length) {
        var targetOffset = targetId.offset().top;

        $(this).click(function onClick(event) {
          // Deselect the old link and select the new one.
          $('header nav a.selected').removeClass('selected');
          $(this).addClass('selected');

          $('html, body').animate({scrollTop: targetOffset}, 1000);
          return false;
        });
      }
  });

});


text:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let DataPointSchema = new Schema({
    variableName: { type: String },
    variableDescription: { type: String },
    variableUnit: { type: String },
    value: { type: Number },
    date: { type: Date }
});

let SiteDataSchema = new Schema({
    _id: { type: String, required: true, max: 15 },
    siteName: { type: String, required: true },
    siteId: { type: String, required: true, max: 15 },
    lastUpdated: { type: Date, required: true },
    minPrecip: { type: Number },
    minPrecipDate: { type: Date },
    maxPrecip: { type: Number },
    maxPrecipDate: { type: Date },
    minStreamFlow: { type: Number },
    minStreamFlowDate: { type: Date },
    maxStreamFlow: { type: Number },
    maxStreamFlowDate: { type: Date },
    minGageHeight: { type: Number },
    minGageHeightDate: { type: Date },
    maxGageHeight: { type: Number },
    maxGageHeightDate: { type: Date },
    data: {type: [DataPointSchema], default: undefined}
});

// Export the Model
module.exports = mongoose.model('SiteData', SiteDataSchema);


text:
#include <iostream>
using namespace std;

/*
* == equality test
* != not equal
* < less than
* > greater than
* <= less than or equal to
>= greater than or equal to
*/

int main(){

  int value1 = 7;
  int value2 = 4;

  bool condition1 = value2 != 8 && value1 == 10;
  bool condition2 = value1 < 10;

  if(condition1 || condition2){
    cout << "Condition 1: True" << endl;
  }
  else{
    cout << "Condition 1: False" << endl;
  }

  return 0;
}


text:
BIN_DIR ?= ./node_modules/.bin

help:
	@echo
	@echo "  \033[34mapi-server\033[0m  start dev server"

api-server:
	@$(BIN_DIR)/nodemon --ignore '*/frontend/**' api/runner.js

queue-server:
	@$(BIN_DIR)/nodemon api/queue-runner.js

app-server:
	@$(BIN_DIR)/nodemon --ignore app/frontend app/runner.js

app-dist: export NODE_ENV = production
app-dist:
	@$(BIN_DIR)/webpack --config ./app/webpack/prod.config.js --progress

admin-server:
	@$(BIN_DIR)/nodemon --ignore admin/frontend admin/runner.js

admin-dist: export NODE_ENV = production
admin-dist:
	@$(BIN_DIR)/webpack --config ./admin/webpack/prod.config.js --progress

dist: export NODE_ENV = production
dist:
	@$(BIN_DIR)/webpack --config ./admin/webpack/prod.config.js --progress && $(BIN_DIR)/webpack --config ./app/webpack/prod.config.js --progress

run-test:
	@$(BIN_DIR)/mocha


text:
'use strict';

app.controller('AdministrationCtrl', ['$scope', function ($scope) {

}]);


text:
package org.poorzerg.weixin.bean;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;

/**
 *
 * @author Poorzerg
 * @date 2014年4月22日 下午2:05:17
 */
public class FollwersInfo {
	public static class Data {
		private String[] openid;

		public String[] getOpenid() {
			return openid;
		}

		public void setOpenid(String[] openid) {
			this.openid = openid;
		}

		@Override
		public String toString() {
			return ReflectionToStringBuilder.toString(this);
		}
	}

	private long total;
	private long count;
	private Data data;

	private String next_openid;

	public long getCount() {
		return count;
	}

	public Data getData() {
		return data;
	}

	public String getNext_openid() {
		return next_openid;
	}

	public String[] getOpenids() {
		return data.openid;
	}

	public long getTotal() {
		return total;
	}

	public void setCount(long count) {
		this.count = count;
	}

	public void setData(Data data) {
		this.data = data;
	}

	public void setNext_openid(String next_openid) {
		this.next_openid = next_openid;
	}

	public void setTotal(long total) {
		this.total = total;
	}

	@Override
	public String toString() {
		return ReflectionToStringBuilder.toString(this);
	}
}


text:
/* $Id$ */
/*
 ** Copyright (C) 2003-2013 Sourcefire, Inc.
 **
 ** This program is free software; you can redistribute it and/or modify
 ** it under the terms of the GNU General Public License Version 2 as
 ** published by the Free Software Foundation.  You may not use, modify or
 ** distribute this program under any other version of the GNU General
 ** Public License.
 **
 ** This program is distributed in the hope that it will be useful,
 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 ** GNU General Public License for more details.
 **
 ** You should have received a copy of the GNU General Public License
 ** along with this program; if not, write to the Free Software
 ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
/*
   sfthreshold.c

   This file contains functions that glue the generic thresholding2 code to
   snort.

   dependent files:  sfthd sfxghash sfghash sflsq
                     util mstring

   Marc Norton

   2003-05-29:
     cmg: Added s_checked variable  --
       when this is 1, the sfthreshold_test will always return the same
       answer until
       sfthreshold_reset is called

   2003-11-3:
     man: cleaned up and added more startup printout.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include "mstring.h"
#include "util.h"
#include "parser.h"

#include "sfthd.h"
#include "sfthreshold.h"
#include "snort.h"

#ifndef WIN32
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#endif

#include <errno.h>

/* Data */
THD_STRUCT *thd_runtime = NULL;

static int thd_checked = 0;
static int thd_answer = 0;

typedef enum { PRINT_GLOBAL, PRINT_LOCAL, PRINT_SUPPRESS } PrintFormat;

ThresholdConfig * ThresholdConfigNew(void)
{
    ThresholdConfig *tc =
        (ThresholdConfig *)SnortAlloc(sizeof(ThresholdConfig));

    /* sfthd_objs_new will handle fatal */
    tc->thd_objs = sfthd_objs_new();
    tc->memcap = 1024 * 1024;
    tc->enabled = 1;

    return tc;
}

void ThresholdConfigFree(ThresholdConfig *tc)
{
    if (tc == NULL)
        return;

    if (tc->thd_objs != NULL)
    {
        sfthd_objs_free(tc->thd_objs);
        tc->thd_objs = NULL;
    }

    free(tc);
}

// prnMode = 0: init output format
// prnMode = 1: term output format (with header and count of filtered events)
// prnMode = 2: term output format (count only)
static int print_thd_node( THD_NODE *p , PrintFormat type, unsigned* prnMode )
{
    char buf[STD_BUF+1];
    memset(buf, 0, STD_BUF+1);

    switch( type )
    {
    case PRINT_GLOBAL:
           if(p->type == THD_TYPE_SUPPRESS ) return 0;
           if(p->sig_id != 0 ) return 0;
           break;

    case PRINT_LOCAL:
           if(p->type == THD_TYPE_SUPPRESS ) return 0;
           if(p->sig_id == 0 || p->gen_id == 0 ) return 0;
           break;

    case PRINT_SUPPRESS:
           if(p->type != THD_TYPE_SUPPRESS ) return 0;
           break;
    }

    /* SnortSnprintfAppend(buf, STD_BUF, "| thd-id=%d", p->thd_id ); */

    if ( *prnMode && !p->filtered )
        return 1;

    if( p->gen_id == 0 )
    {
        SnortSnprintfAppend(buf, STD_BUF, "| gen-id=global");
    }
    else
    {
        SnortSnprintfAppend(buf, STD_BUF, "| gen-id=%-6d", p->gen_id );
    }
    if( p->sig_id == 0 )
    {
        SnortSnprintfAppend(buf, STD_BUF, " sig-id=global" );
    }
    else
    {
        SnortSnprintfAppend(buf, STD_BUF, " sig-id=%-10d", p->sig_id );
    }

    switch ( p->type )
    {
        case THD_TYPE_LIMIT:
            SnortSnprintfAppend(buf, STD_BUF, " type=Limit    ");
            break;

        case THD_TYPE_THRESHOLD:
            SnortSnprintfAppend(buf, STD_BUF, " type=Threshold");
            break;

        case THD_TYPE_BOTH:
            SnortSnprintfAppend(buf, STD_BUF, " type=Both     ");
            break;

        case THD_TYPE_SUPPRESS:
            if ( *prnMode )
                SnortSnprintfAppend(buf, STD_BUF, " type=Suppress ");
            break;
    }

    switch ( p->tracking )
    {
        case THD_TRK_NONE:
            SnortSnprintfAppend(buf, STD_BUF, " tracking=none");
            break;

        case THD_TRK_SRC:
            SnortSnprintfAppend(buf, STD_BUF, " tracking=src");
            break;

        case THD_TRK_DST:
            SnortSnprintfAppend(buf, STD_BUF, " tracking=dst");
            break;
    }

    if( p->type == THD_TYPE_SUPPRESS )
    {
        if ( p->tracking != THD_TRK_NONE )
        {
            // TBD output suppress node ip addr set
            SnortSnprintfAppend(buf, STD_BUF, "-ip=%-16s", "<list>");
        }
    }
    else
    {
        SnortSnprintfAppend(buf, STD_BUF, " count=%-3d", p->count);
        SnortSnprintfAppend(buf, STD_BUF, " seconds=%-3d", p->seconds);
    }

    if ( *prnMode )
    {
        if ( *prnMode == 1 )
        {
            LogMessage("+-----------------------[filtered events]--------------------------------------\n");
            *prnMode = 2;
        }
        SnortSnprintfAppend(buf, STD_BUF, " filtered=" STDu64, p->filtered);
    }
    LogMessage("%s\n", buf);

    return 1;
}
/*
 *
 */
static int print_thd_local(ThresholdObjects *thd_objs, PrintFormat type, unsigned* prnMode)
{
    SFGHASH  * sfthd_hash;
    THD_ITEM * sfthd_item;
    THD_NODE * sfthd_node;
    int        gen_id;
    SFGHASH_NODE * item_hash_node;
    int        lcnt=0;
    tSfPolicyId policyId;

    for (policyId = 0; policyId < thd_objs->numPoliciesAllocated; policyId++)
    {
        for(gen_id=0;gen_id < THD_MAX_GENID ; gen_id++ )
        {
            sfthd_hash = thd_objs->sfthd_array[gen_id];
            if( !sfthd_hash )
            {
                continue;
            }

            for(item_hash_node  = sfghash_findfirst( sfthd_hash );
                    item_hash_node != 0;
                    item_hash_node  = sfghash_findnext( sfthd_hash ) )
            {
                /* Check for any Permanent sig_id objects for this gen_id */
                sfthd_item = (THD_ITEM*)item_hash_node->data;

                if (sfthd_item->policyId != policyId)
                {
                    continue;
                }

                for( sfthd_node  = (THD_NODE*)sflist_first(sfthd_item->sfthd_node_list);
                        sfthd_node != 0;
                        sfthd_node = (THD_NODE*)sflist_next(sfthd_item->sfthd_node_list) )
                {
                    if (print_thd_node(sfthd_node, type, prnMode) != 0)
                        lcnt++;
                }
            }
        }
    }

    if( !lcnt && !*prnMode )
        LogMessage("| none\n");

    return 0;
}

/*
 *  Startup/Shutdown Display Of Thresholding
 */
void print_thresholding(ThresholdConfig *thd_config, unsigned shutdown)
{
    int i;
    THD_NODE * thd;

    if (thd_config == NULL)
        return;

    if ( !shutdown )
    {
        LogMessage("\n");
        LogMessage("+-----------------------[event-filter-config]----------------------------------\n");
        LogMessage("| memory-cap : %d bytes\n",thd_config->memcap);
        LogMessage("+-----------------------[event-filter-global]----------------------------------\n");
    }

    if (thd_config->thd_objs == NULL)
    {
        if ( !shutdown )
            LogMessage("| none\n");
    }
    else
    {
        tSfPolicyId policyId;
        int gcnt=0;

        for (policyId = 0; policyId < thd_config->thd_objs->numPoliciesAllocated; policyId++)
        {
            if (thd_config->thd_objs->sfthd_garray[policyId] == NULL)
            {
                continue;
            }

            for(i=0;i<THD_MAX_GENID;i++)
            {
                thd = thd_config->thd_objs->sfthd_garray[policyId][i];
                if( !thd ) continue;
                gcnt++;
            }

            if( !gcnt )
            {
                if ( !shutdown )
                    LogMessage("| none\n");
            }
            /* display gen_id=global  and sig_id=global rules */
            if( gcnt )
            {
                for(i=0;i<THD_MAX_GENID;i++)
                {
                    thd = thd_config->thd_objs->sfthd_garray[policyId][i];
                    if( !thd ) continue;

                    if( thd->gen_id == 0 && thd->sig_id == 0 )
                    {
                        print_thd_node( thd, PRINT_GLOBAL, &shutdown );
                        break;
                    }
                }
            }

            /* display gen_id!=global and sig_id=global rules */
            if( gcnt )
            {
                for(i=0;i<THD_MAX_GENID;i++)
                {
                    thd = thd_config->thd_objs->sfthd_garray[policyId][i];
                    if( !thd ) continue;

                    if( thd->gen_id !=0 ||  thd->sig_id != 0 )
                    {
                        print_thd_node( thd, PRINT_GLOBAL, &shutdown );
                    }
                }
            }
        }
    }

    if ( !shutdown )
        LogMessage("+-----------------------[event-filter-local]-----------------------------------\n");
    if (thd_config->thd_objs == NULL)
    {
        if ( !shutdown )
            LogMessage("| none\n");
    }
    else
    {
        print_thd_local(thd_config->thd_objs, PRINT_LOCAL, &shutdown);
    }

    if ( !shutdown )
        LogMessage("+-----------------------[suppression]------------------------------------------\n");
    if (thd_config->thd_objs == NULL)
    {
        if ( !shutdown )
            LogMessage("| none\n");
    }
    else
    {
        print_thd_local(thd_config->thd_objs, PRINT_SUPPRESS, &shutdown);
    }

    if ( !shutdown )
        LogMessage("--------------------------------------------"
               "-----------------------------------\n");

}

void sfthreshold_free(void)
{
    if (thd_runtime != NULL)
        sfthd_free(thd_runtime);

    thd_runtime = NULL;
}

/*

    Create and Add a Thresholding Event Object

*/
int sfthreshold_create(ThresholdConfig *thd_config, THDX_STRUCT *thdx)
{
    if (thd_config == NULL)
        return -1;

    if (!thd_config->enabled)
        return 0;

    /* Auto init - memcap must be set 1st, which is not really a problem */
    if (thd_runtime == NULL)
    {
        thd_runtime = sfthd_new(thd_config->memcap, thd_config->memcap);
        if (thd_runtime == NULL)
            return -1;
    }

    /* print_thdx( thdx ); */

    /* Add the object to the table - */
    return sfthd_create_threshold(thd_config->thd_objs,
                                  thdx->gen_id,
                                  thdx->sig_id,
                                  thdx->tracking,
                                  thdx->type,
                                  thdx->priority,
                                  thdx->count,
                                  thdx->seconds,
                                  thdx->ip_address);
}

/*
    Test an event against the threshold object table
    to determine if it should be logged.

    It will always return the same answer until sfthreshold_reset is
    called

    gen_id:
    sig_id:
    sip:    host ordered sip
    dip:    host ordered dip
    curtime:

    2003-05-29 cmg:

     This code is in use in fpLogEvent, CallAlertFuncs, CallLogFuncs
     and the reset function is called in ProcessPacket

    returns 0 - log
           !0 - don't log
*/
int sfthreshold_test(
    unsigned gen_id, unsigned  sig_id,
    snort_ip_p sip, snort_ip_p dip,
    long curtime )
{
    if ((snort_conf->threshold_config == NULL) ||
        !snort_conf->threshold_config->enabled)
    {
        return 0;
    }

    if (!thd_checked)
    {
       thd_checked = 1;
       thd_answer = sfthd_test_threshold(snort_conf->threshold_config->thd_objs,
                                         thd_runtime, gen_id, sig_id, sip, dip, curtime);
    }

    return thd_answer;
}

/**
 * Reset the thresholding system so that subsequent calls to
 * sfthreshold_test will indeed try to alter the thresholding system
 *
 */
void sfthreshold_reset(void)
{
    thd_checked = 0;
}

/* empty out active entries */
void sfthreshold_reset_active(void)
{
    if (thd_runtime == NULL)
        return;

    if (thd_runtime->ip_nodes != NULL)
        sfxhash_make_empty(thd_runtime->ip_nodes);

    if (thd_runtime->ip_gnodes != NULL)
        sfxhash_make_empty(thd_runtime->ip_gnodes);
}


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

<TITLE>
Uses of Class org.hibernate.jdbc.ConnectionManager (Hibernate API Documentation)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../jdstyle.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.hibernate.jdbc.ConnectionManager

Packages that use ConnectionManager

org.hibernate.jdbc

	This package abstracts the mechanism for dispatching SQL statements
	to the database, and implements interaction with JDBC.

Uses of ConnectionManager in org.hibernate.jdbc

Methods in org.hibernate.jdbc that return ConnectionManager

 ConnectionManager
JDBCContext.getConnectionManager()

static ConnectionManager
ConnectionManager.deserialize(ObjectInputStream ois,
            SessionFactoryImplementor factory,
            Interceptor interceptor,
            ConnectionReleaseMode connectionReleaseMode,
            JDBCContext jdbcContext)

Methods in org.hibernate.jdbc with parameters of type ConnectionManager

 Batcher
NonBatchingBatcherFactory.createBatcher(ConnectionManager connectionManager,
              Interceptor interceptor)

static Connection
BorrowedConnectionProxy.generateProxy(ConnectionManager connectionManager)

 Batcher
BatchingBatcherFactory.createBatcher(ConnectionManager connectionManager,
              Interceptor interceptor)

 Batcher
BatcherFactory.createBatcher(ConnectionManager connectionManager,
              Interceptor interceptor)

Constructors in org.hibernate.jdbc with parameters of type ConnectionManager

NonBatchingBatcher(ConnectionManager connectionManager,
                   Interceptor interceptor)

BorrowedConnectionProxy(ConnectionManager connectionManager)

BatchingBatcher(ConnectionManager connectionManager,
                Interceptor interceptor)

AbstractBatcher(ConnectionManager connectionManager,
                Interceptor interceptor)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes


text:
module ActionView
  module Helpers
    module Tags # :nodoc:
      class MonthField < DatetimeField # :nodoc:
        private

          def format_date(value)
            value.try(:strftime, "%Y-%m")
          end
      end
    end
  end
end


text:
package Perf::Trace::Context;

use 5.010000;
use strict;
use warnings;

require Exporter;

our @ISA = qw(Exporter);

our %EXPORT_TAGS = ( 'all' => [ qw(
) ] );

our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );

our @EXPORT = qw(
	common_pc common_flags common_lock_depth
);

our $VERSION = '0.01';

require XSLoader;
XSLoader::load('Perf::Trace::Context', $VERSION);

1;
__END__
=head1 NAME

Perf::Trace::Context - Perl extension for accessing functions in perf.

=head1 SYNOPSIS

  use Perf::Trace::Context;

=head1 SEE ALSO

Perf (script) documentation

=head1 AUTHOR

Tom Zanussi, E<lt>tzanussi@gmail.com<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2009 by Tom Zanussi

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.10.0 or,
at your option, any later version of Perl 5 you may have available.

Alternatively, this software may be distributed under the terms of the
GNU General Public License ("GPL") version 2 as published by the Free
Software Foundation.

=cut


text:
        <link rel="stylesheet" type="text/css" href="../../../../asset/static/prettify.css" />
        <link rel="stylesheet" type="text/css" href="../../../../asset/static/style.css" />

                Zephir Documentation v1.0.1

                    <input class="search-box" placeholder="Search for a class or namespace " type="text" />

Home

Classes

Phalconry\Http\Client\Response

        Source

        Class

            Phalconry

            Http

            Client

Response

Methods

        setBody(variable  $body)

        getBody()

        parseHeaders(variable  $headerStr)

        getBodyDecoded()

Methods Details

                public

                function
setBody
(variable  $body)

                public

                function
getBody
()

                public

                function
parseHeaders
(variable  $headerStr)

                public

                function
getBodyDecoded
()


text: export { ObjectStorage20 as default } from "../../";


text:
using System;

namespace KataBowling
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ValidateArguments(args);
                var game = BowlingGameBootstrapper.Create();
                int result = game.CalculateScore(args[0]);
                Console.WriteLine("Result: " + result);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static void ValidateArguments(string[] args)
        {
            if (args.Length != 1)
            {
                throw new ArgumentException("Invalid usage. Provide the scorecard as a parameter.", "args");
            }
        }
    }
}


text:
package gov.nih.nci.cagrid.portal.domain.catalog;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;

/**
 * User: kherm
 *
 * @author kherm manav.kher@semanticbits.com
 */
@Entity
@DiscriminatorValue("tool_grid_data_service_endpoint")
public class GridDataServiceEndPointCatalogEntry extends GridServiceEndPointCatalogEntry {

}