text:
package com.greengrocer.freshmarket.web.servlet.admin;

import java.io.IOException;

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

import com.greengrocer.freshmarket.domain.Commodity;
import com.greengrocer.freshmarket.domain.PageBean;
import com.greengrocer.freshmarket.service.CommodityService;
import com.greengrocer.freshmarket.utils.WebUtils;
import com.greengrocer.freshmarket.web.formbean.CommodityForm;
import com.greengrocer.freshmarket.web.servlet.BaseServlet;

public class AdminCommodityServlet extends BaseServlet {

	private CommodityService service = new CommodityService();

	/**
	 * 添加商品信息实体
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public String addCommodity(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//调用工具类,把上传的表单封装成一个bean对象
		CommodityForm commodityForm = WebUtils.uploadForm2Bean(request, CommodityForm.class);
		Commodity commodity = service.findCommodityByName(commodityForm.getCommodityName());

		if(commodity!=null && commodity.getCommodityName()==null){
			//添加商品信息实体
			service.addCommodity(commodityForm);
			//重定向到展示的列表(先查询所有的商品信息再重定向)
			return "r:/AdminCommodityServlet?method=findAllCommodity";
		}else{

			request.setAttribute("message", "该商品名称存在,添加失败!");
			return "/message.jsp";
		}
	}

	/**
	 * 查询所有商品信息实体(分页查询)
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findAllCommodity(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获得url
		String url = getUrl(request);
		//获取页面传递过来的当前页码数
		int pageCode = getPageCode(request);
		//给pageSize,每页的记录数赋值
		int pageSize = 10;
		//得到商品信息实体集合
		PageBean<Commodity> pb = service.findAllCommodity(pageCode,pageSize);
		//设置url
		pb.setUrl(url);
		//存入request域中
		request.setAttribute("pb", pb);
		//跳转到显示商品信息页面
		return "/adminjsps/admin/commodity/list.jsp";

	}

	/**
	 * 获取url信息
	 * @param request
	 * @return
	 */
	private String getUrl(HttpServletRequest request) {
		String url = request.getQueryString();
		 //url中有可能导游pageCode,需要把它截取掉
		int index = url.lastIndexOf("&pageCode=");
		if(index == -1) {
			return url;
		}
		return url.substring(0, index);
	}

	/**
	 * 获取当前页码数
	 * @param request
	 * @return
	 */
	private int getPageCode(HttpServletRequest request) {
		/*
		 * 1. 得到PageCode
		 *   如果PageCode参数不存在,说明PageCode=1
		 *   如果PageCode参数存在,需要转换成int类型即可
		 */
		String value = request.getParameter("pageCode");
		if(value == null || value.trim().isEmpty()) {
			return 1;
		}
		return Integer.parseInt(value);
	}

	/**
	 * 根据商品编号删除该商品信息实体
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String deleteCommodity(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//得到删除的商品编号
		String commodityID = request.getParameter("commodityID");
		//进行删除操作
		service.deleteCommodity(commodityID);
		//重定向到展示的列表(先查询所有的商品信息再重定向)
		return "r:/AdminCommodityServlet?method=findAllCommodity";
	}

	/**
	 * 根据商品id查询
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public String findCommodity(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//得到修改的商品编号
		String commodityID = request.getParameter("commodityID");
		//查询该商品信息
		Commodity commodity = service.findCommodity(commodityID);
		request.setAttribute("commodity", commodity);
		//转发到展示的列表
		return "/adminjsps/admin/commodity/showCommodity.jsp";
	}

	/**
	 * 根据商品编号查询该商品信息返回给修改页面
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String update(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//得到修改的商品编号
		String commodityID = request.getParameter("commodityID");
		//查询该商品信息
		Commodity commodity = service.findCommodity(commodityID);
		request.setAttribute("commodity", commodity);
		//转发向到修改的列表
		return "/adminjsps/admin/commodity/update.jsp";
	}

	/**
	 * 修改商品信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String updateCommodity(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//调用工具类,把上传的表单封装成一个bean对象
		CommodityForm commodityForm = WebUtils.uploadForm2Bean(request, CommodityForm.class);
		//修改商品信息实体
		service.updateCommodity(commodityForm);
		//重定向到展示的列表(先查询所有的商品信息再重定向)
		return "r:/AdminCommodityServlet?method=findAllCommodity";
	}

	/**
	 * 多条件查询商品信息
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String queryCommodity(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获得url
		String url = getUrl(request);
		//获取页面传递过来的当前页码数
		int pageCode = getPageCode(request);
		//给pageSize,每页的记录数赋值
		int pageSize = 10;
		//把提交的表单封装成一个bean对象
		CommodityForm commodityForm = WebUtils.request2Bean(request, CommodityForm.class);
		//得到商品信息实体集合
		PageBean<Commodity> pb = service.queryCommodity(pageCode,pageSize,commodityForm);
		//设置url
		pb.setUrl(url);
		//存入request域中
		request.setAttribute("pb", pb);
		//转发到修改的列表
		return "/adminjsps/admin/commodity/list.jsp";
	}

}


text:
<title>
JsonCpp - JSON data format manipulation library
</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

      JsonCpp project page

      JsonCpp home page

Main Page

Related Pages

Namespaces

Classes

Files

File List

File Members

include

json

Classes |
Namespaces |
Functions

reader.h File Reference

#include "features.h"

#include "value.h"

#include <deque>

#include <iosfwd>

#include <stack>

#include <string>

#include <istream>

Go to the source code of this file.

Classes

class  	Json::Reader

 	Unserialize a JSON document into a Value.  More...

struct  	Json::Reader::StructuredError

 	An error tagged with where in the JSON text it was encountered.  More...

class  	Json::CharReader

 	Interface for reading JSON from a char array.  More...

class  	Json::CharReader::Factory

class  	Json::CharReaderBuilder

 	Build a CharReader implementation.  More...

Namespaces

  	Json

 	JSON (JavaScript Object Notation).

Functions

bool 	Json::parseFromStream (CharReader::Factory const &, std::istream &, Value *root, std::string *errs)

 	Consume entire stream and use its begin/end.  More...

std::istream & 	Json::operator>> (std::istream &, Value &)

 	Read from 'sin' into 'root'.  More...

redpajama_set_name: RedPajamaGithub


text:
var CouchDBAttachmentUploader = function() {}

CouchDBAttachmentUploader.prototype.upload = function(filepath, couchURI, docID, docRevision,  success, failure, options) {

    var request = {};
    var progress = window.plugins.CouchDBAttachmentUploader.dummyProgress;

    // Process options
    for(var key in options) {
		var value = options[key];

		if( key === 'progress' && typeof(value) === 'function' ) {
			// Callback for progress
			progress = value;

		} else if( 'contentType' === key
		  || 'method' === key
		  || 'attachmentName' === key
		   ){
		   // Pass these options to request
		   request[key] = value;
		};
    };

	// Prepare callbacks
    var key = 'f' + this.callbackIdx++;
    window.plugins.CouchDBAttachmentUploader.callbackMap[key] = {
        success: function(result) {
        	if( result.error ) {
        		failure(result.error);
        	} else {
            	success(result);
            };
            delete window.plugins.CouchDBAttachmentUploader.callbackMap[key]
        },
        failure: function(result) {
            failure(result);
            delete window.plugins.CouchDBAttachmentUploader.callbackMap[key]
        }
        ,progress: progress
    }
    var callback = 'window.plugins.CouchDBAttachmentUploader.callbackMap.' + key;
    return cordova.exec('CouchDBAttachmentUploader.upload', filepath, couchURI, docID,
                         docRevision, callback + '.success', callback + '.failure',
                         callback + '.progress', request);
}

CouchDBAttachmentUploader.prototype.callbackMap = {};
CouchDBAttachmentUploader.prototype.callbackIdx = 0;
CouchDBAttachmentUploader.prototype.dummyProgress = function(bytes, total){};

cordova.addConstructor(function()  {
    if(!window.plugins) {
        window.plugins = {};
    }
    window.plugins.CouchDBAttachmentUploader = new CouchDBAttachmentUploader();
});


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.mobilenetwork.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.resourcemanager.mobilenetwork.models.ProvisioningState;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Data network properties. */
@Fluent
public final class DataNetworkPropertiesFormat {
    /*
     * The provisioning state of the data network resource.
     */
    @JsonProperty(value = "provisioningState", access = JsonProperty.Access.WRITE_ONLY)
    private ProvisioningState provisioningState;

    /*
     * An optional description for this data network.
     */
    @JsonProperty(value = "description")
    private String description;

    /**
     * Get the provisioningState property: The provisioning state of the data network resource.
     *
     * @return the provisioningState value.
     */
    public ProvisioningState provisioningState() {
        return this.provisioningState;
    }

    /**
     * Get the description property: An optional description for this data network.
     *
     * @return the description value.
     */
    public String description() {
        return this.description;
    }

    /**
     * Set the description property: An optional description for this data network.
     *
     * @param description the description value to set.
     * @return the DataNetworkPropertiesFormat object itself.
     */
    public DataNetworkPropertiesFormat withDescription(String description) {
        this.description = description;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web.Helpers;
using System.Web.Script.Serialization;

namespace Jasolver
{
    internal class Reader
    {
        internal dynamic ReadFromJson(string rawJson, string groupName)
        {
            var jsonObj = JsonConvert.DeserializeObject<dynamic>(rawJson);

            var data = jsonObj.data;

            if (data != null)
            {
                if (data is JArray)
                {

                    int i = 0;

                    // getting first member only to get the type so collection can be created.
                    var obj = Resolver.GetEnityObject(data[i].type.ToString(),groupName);
                    IList objectCollection =  (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(obj.GetType()));
                    objectCollection.Add(prepareObject(obj, jsonObj.data[i], jsonObj.included));

                    for (i = 1; i < data.Count; i++)
                    {
                        obj = Resolver.GetEnityObject(data[i].type.ToString(), groupName);
                        objectCollection.Add(prepareObject(obj, jsonObj.data[i], jsonObj.included));
                    }

                    return objectCollection;
                }
                else
                {
                    var obj = Resolver.GetEnityObject(data.type.ToString(), groupName);

                    prepareObject(obj, jsonObj.data, jsonObj.included);
                    return obj;
                }
            }

            return null;
        }

        private dynamic prepareObject(dynamic obj, dynamic data, dynamic included) {
            Type targetType = obj.GetType();
            PropertyInfo p = targetType.GetProperty("Id");
            if (p != null)
            {
                var value = ChangeType(data.id, p.PropertyType);
                if(value != null)
                    p.SetValue(obj, value);
            }

            setAttributesToPropertiesOfObject(obj, data.attributes);
            setRelationShipToPropertiesOfObject(obj, data.relationships, included);
            return obj;
        }

        private void setAttributesToPropertiesOfObject(dynamic obj, dynamic attributes)
        {
            if (attributes == null)
                return;

            Type targetType = obj.GetType();

            foreach (var item in attributes)
            {
                PropertyInfo prop = targetType.GetProperty(Resolver.Classify(item.Name, true));
                if (prop != null)
                {
                    var value = ChangeType(item.Value, prop.PropertyType);
                    if(value != null)
                        prop.SetValue(obj, value);
                }
            }
        }

        public static object ChangeType(object value, Type conversion)
        {
            var t = conversion;

            if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                if (JValue.CreateNull().Equals(value))
                {
                    return null;
                }
                t = Nullable.GetUnderlyingType(t);
            }

            return Convert.ChangeType(value, t);
        }

        private dynamic findObjectInIncluded(dynamic included, string id, string type)
        {
            if (included != null && included is JArray)
            {
                for (int i = 0; i < included.Count; i++)
                {
                    if (included[i].id.ToString() == id && included[i].type.ToString() == type)
                    {
                        return included[i];
                    }
                }
            }
            return null;
        }

        private void setRelationShipToPropertiesOfObject(dynamic obj, dynamic relationShips, dynamic included)
        {
            Type targetType = obj.GetType();

            if (relationShips != null)
            {
                foreach (var item in relationShips)
                {
                    PropertyInfo prop = targetType.GetProperty(Resolver.Classify(item.Name, true));
                    if (prop != null)
                    {
                        // if relationships are multiple for e.g. relationships : { id : 1, type: "articles", data:[]}
                        if (item.Value.data is JArray)
                        {

                            IList relationShipObj = (IList)Activator.CreateInstance(prop.PropertyType);

                            // since data is array therefore it is must that relationShipObj is IEnumerable
                            // therefore to create underlying objects we need to findout IEnumerable underlying type
                            // create object from it and set complete object if it exists in include
                            // other wise just set the id and return

                            for (int i = 0; i < item.Value.data.Count; i++)
                            {
                                // creating object of Ienumerable underlying type.
                                var underlyingRelationShipObj = Activator.CreateInstance(prop.PropertyType.GenericTypeArguments[0]);
                                var includeObj = findObjectInIncluded(included, item.Value.data[i].id.ToString(), item.Value.data[i].type.ToString());

                                if (includeObj != null)
                                {
                                    relationShipObj.Add(prepareObject(underlyingRelationShipObj, includeObj, included));
                                }
                                else
                                {
                                    var propertyType = underlyingRelationShipObj.GetType();
                                    var idProperty = propertyType.GetProperty("Id");
                                    if (idProperty == null)
                                    {
                                        idProperty = propertyType.GetProperty(propertyType.Name + "Id");
                                    }
                                    var value = ChangeType(item.Value.data[i].id.ToString(), idProperty.PropertyType);
                                    if (value != null)
                                        idProperty.SetValue(underlyingRelationShipObj, value);
                                    relationShipObj.Add(underlyingRelationShipObj);
                                }

                            }
                            prop.SetValue(obj, relationShipObj);
                        }
                        else
                        {
                            var relationShipObj = Activator.CreateInstance(prop.PropertyType);
                            var includeObj = findObjectInIncluded(included, item.Value.data.id.ToString(), item.Value.data.type.ToString());

                            if (includeObj != null)
                            {
                                prop.SetValue(obj, prepareObject(relationShipObj, includeObj, included));
                            }
                            else
                            {
                                var idProperty = prop.PropertyType.GetProperty("Id");
                                if (idProperty == null)
                                {
                                    idProperty = prop.PropertyType.GetProperty(prop.PropertyType.Name + "Id");
                                }
                                var value = ChangeType(item.Value.data.id.ToString(), idProperty.PropertyType);
                                if (value != null)
                                    idProperty.SetValue(relationShipObj, value);

                                prop.SetValue(obj, relationShipObj);
                            }
                        }
                    }
                }
            }
        }
    }
}


text:
import click
import sys
import ast
import pprint
import jenkins as jenkinsapi
from time import sleep

@click.command()
@click.option('--job',required=True, help='Name of the job to start and monitor.')
@click.option('--wait',required=True, help='Time to wait between each request to check the build\'s status.',type=int)
@click.option('--parameters',required=False, help='Job\s parameters.')
@click.pass_obj
def startAndMonitor(jenkins,job, parameters, wait):
    """Starts and monitors Jenkins job until it is finished."""
    pp = pprint.PrettyPrinter(indent=4)
    server = jenkinsapi.Jenkins(jenkins.url, username=jenkins.username, password=jenkins.password)
    try:
        next_build_number = server.get_job_info(job)['nextBuildNumber']
    except jenkinsapi.NotFoundException:
        print "NotFoundException when looking for job with name '%s'." % job
        exit(1)
    except:
        print "Unexpected error:", sys.exc_info()[0]
        raise
    print "Build #%s of %s started." % (next_build_number,job)
    try:
        server.build_job("JenkinsCLITest-Corentin", ast.literal_eval(parameters), token=None)
    except:
        pp.pprint(sys.exc_info())
        print "Please verify your parameters (especially choice parameters - are the values chosen authorized?"
        exit(2)

    stop = False
    while not stop:
        try:
            build_info = server.get_build_info(job, next_build_number)
        except jenkinsapi.NotFoundException:
            print "NotFoundException when looking for build #%s : build probably still in the queue. Waiting %d sc until next retry." % (next_build_number, wait)
            sleep(wait)
            pass
        except:
            print "Unexpected error:", sys.exc_info()[0]
            raise
        else:
            if build_info['result'] == 'SUCCESS':
                print "Build #%s finished with result : SUCCESS." % next_build_number
                exit(0)
            elif build_info['result'] == 'FAILED':
                print "Build #%s finished with result : FAILED." % next_build_number
                stop = True
                exit(3)
            elif build_info['result'] == None and build_info['building'] == True:
                print "Build #%s is not finished yet. Waiting %d sc until next check." % (next_build_number,wait)
                sleep(wait)
            else:
                print "Unknown build result. Full trace below:"
                pp.pprint(build_info)


text:
package com.podcopic.animationlib.library;

import com.podcopic.animationlib.library.special.in.DropOut;
import com.podcopic.animationlib.library.special.in.Landing;
import com.podcopic.animationlib.library.attention.Bounce;
import com.podcopic.animationlib.library.attention.Flash;
import com.podcopic.animationlib.library.attention.Pulse;
import com.podcopic.animationlib.library.attention.RubberBand;
import com.podcopic.animationlib.library.attention.Shake;
import com.podcopic.animationlib.library.attention.Standup;
import com.podcopic.animationlib.library.attention.Swing;
import com.podcopic.animationlib.library.attention.Tada;
import com.podcopic.animationlib.library.attention.Wave;
import com.podcopic.animationlib.library.attention.Wobble;
import com.podcopic.animationlib.library.attention.ShakeBand;
import com.podcopic.animationlib.library.bouncing_in.BounceIn;
import com.podcopic.animationlib.library.bouncing_in.BounceInDown;
import com.podcopic.animationlib.library.bouncing_in.BounceInLeft;
import com.podcopic.animationlib.library.bouncing_in.BounceInRight;
import com.podcopic.animationlib.library.bouncing_in.BounceInUp;
import com.podcopic.animationlib.library.fading_in.FadingIn;
import com.podcopic.animationlib.library.fading_in.FadingInDown;
import com.podcopic.animationlib.library.fading_in.FadingInLeft;
import com.podcopic.animationlib.library.fading_in.FadingInRight;
import com.podcopic.animationlib.library.fading_in.FadingInUp;
import com.podcopic.animationlib.library.fading_out.FadingOut;
import com.podcopic.animationlib.library.fading_out.FadingOutDown;
import com.podcopic.animationlib.library.fading_out.FadingOutLeft;
import com.podcopic.animationlib.library.fading_out.FadingOutRight;
import com.podcopic.animationlib.library.fading_out.FadingOutUp;
import com.podcopic.animationlib.library.Flips.FlipInXaxis;
import com.podcopic.animationlib.library.Flips.FlipInYaxis;
import com.podcopic.animationlib.library.Flips.FlipOutXaxis;
import com.podcopic.animationlib.library.Flips.FlipOutYaxis;
import com.podcopic.animationlib.library.rotation_in.RotateIn;
import com.podcopic.animationlib.library.rotation_in.RotateInDownLeft;
import com.podcopic.animationlib.library.rotation_in.RotateInDownRight;
import com.podcopic.animationlib.library.rotation_in.RotateInUpLeft;
import com.podcopic.animationlib.library.rotation_in.RotateInUpRight;
import com.podcopic.animationlib.library.rotation_out.RotateOut;
import com.podcopic.animationlib.library.rotation_out.RotateOutDownLeft;
import com.podcopic.animationlib.library.rotation_out.RotateOutDownRight;
import com.podcopic.animationlib.library.rotation_out.RotateOutUpLeft;
import com.podcopic.animationlib.library.rotation_out.RotateOutUpRight;
import com.podcopic.animationlib.library.sliders.SlideInDown;
import com.podcopic.animationlib.library.sliders.SlideInLeft;
import com.podcopic.animationlib.library.sliders.SlideInRight;
import com.podcopic.animationlib.library.sliders.SlideInUp;
import com.podcopic.animationlib.library.sliders.SlideOutDown;
import com.podcopic.animationlib.library.sliders.SlideOutLeft;
import com.podcopic.animationlib.library.sliders.SlideOutRight;
import com.podcopic.animationlib.library.sliders.SlideOutUp;
import com.podcopic.animationlib.library.zoom_in.ZoomIn;
import com.podcopic.animationlib.library.zoom_in.ZoomInRubberBand;
import com.podcopic.animationlib.library.zoom_in.ZoomInDown;
import com.podcopic.animationlib.library.zoom_in.ZoomInLeft;
import com.podcopic.animationlib.library.zoom_in.ZoomInRight;
import com.podcopic.animationlib.library.zoom_in.ZoomInUp;
import com.podcopic.animationlib.library.zoom_out.ZoomOut;
import com.podcopic.animationlib.library.zoom_out.ZoomOutDown;
import com.podcopic.animationlib.library.zoom_out.ZoomOutLeft;
import com.podcopic.animationlib.library.zoom_out.ZoomOutRight;
import com.podcopic.animationlib.library.zoom_out.ZoomOutUp;
import com.podcopic.animationlib.library.special.Hinge;
import com.podcopic.animationlib.library.special.RollIn;
import com.podcopic.animationlib.library.special.RollOut;

public enum AnimationType {

    ShakeBand(ShakeBand.class),
    DropOut(DropOut.class),
    Landing(Landing.class),

    Flash(Flash.class),
    Pulse(Pulse.class),
    RubberBand(RubberBand.class),
    Shake(Shake.class),
    Swing(Swing.class),
    Wobble(Wobble.class),
    Bounce(Bounce.class),
    Tada(Tada.class),
    StandUp(Standup.class),
    Wave(Wave.class),

    Hinge(Hinge.class),
    RollIn(RollIn.class),
    RollOut(RollOut.class),

    BounceIn(BounceIn.class),
    BounceInDown(BounceInDown.class),
    BounceInLeft(BounceInLeft.class),
    BounceInRight(BounceInRight.class),
    BounceInUp(BounceInUp.class),

    FadeIn(FadingIn.class),
    FadeInUp(FadingInUp.class),
    FadeInDown(FadingInDown.class),
    FadeInLeft(FadingInLeft.class),
    FadeInRight(FadingInRight.class),

    FadeOut(FadingOut.class),
    FadeOutDown(FadingOutDown.class),
    FadeOutLeft(FadingOutLeft.class),
    FadeOutRight(FadingOutRight.class),
    FadeOutUp(FadingOutUp.class),

    FlipInX(FlipInXaxis.class),
    FlipOutX(FlipOutXaxis.class),
    FlipInY(FlipInYaxis.class),
    FlipOutY(FlipOutYaxis.class),
    RotateIn(RotateIn.class),
    RotateInDownLeft(RotateInDownLeft.class),
    RotateInDownRight(RotateInDownRight.class),
    RotateInUpLeft(RotateInUpLeft.class),
    RotateInUpRight(RotateInUpRight.class),

    RotateOut(RotateOut.class),
    RotateOutDownLeft(RotateOutDownLeft.class),
    RotateOutDownRight(RotateOutDownRight.class),
    RotateOutUpLeft(RotateOutUpLeft.class),
    RotateOutUpRight(RotateOutUpRight.class),

    SlideInLeft(SlideInLeft.class),
    SlideInRight(SlideInRight.class),
    SlideInUp(SlideInUp.class),
    SlideInDown(SlideInDown.class),

    SlideOutLeft(SlideOutLeft.class),
    SlideOutRight(SlideOutRight.class),
    SlideOutUp(SlideOutUp.class),
    SlideOutDown(SlideOutDown.class),

    ZoomIn(ZoomIn.class),
    ZoomInDown(ZoomInDown.class),
    ZoomInLeft(ZoomInLeft.class),
    ZoomInRight(ZoomInRight.class),
    ZoomInUp(ZoomInUp.class),
    ZoomInRubberBand(ZoomInRubberBand.class),

    ZoomOut(ZoomOut.class),
    ZoomOutDown(ZoomOutDown.class),
    ZoomOutLeft(ZoomOutLeft.class),
    ZoomOutRight(ZoomOutRight.class),
    ZoomOutUp(ZoomOutUp.class);

    private Class CreatingAnimation;

    private AnimationType(Class clazz) {
        CreatingAnimation = clazz;
    }

    public BaseViewAnimator getAnimator() {
        try {
            return (BaseViewAnimator) CreatingAnimation.newInstance();
        } catch (Exception e) {
            throw new Error("Can not init animatorClazz instance");
        }
    }
}


text:
import { allCountries } from 'country-region-data';

angular
  .module('confRegistrationWebApp')
  .filter('eventAddressFormat', () => (city, state, zip, country) => {
    // Existing conferences will have a default country value of an empty string
    // To prevent issues, default their country to 'US' if country is falsey
    const currentCountry = country ? country : 'US';
    const filteredRegions = allCountries
      .find((c) => c[1] === currentCountry)[2]
      .filter((r) => r[1] === state);
    const formattedState =
      state && filteredRegions.length >= 1 ? filteredRegions[0][0] : state;

    const addressLine3 = city
      ? state
        ? zip
          ? `${city}, ${formattedState} ${zip}`
          : `${city}, ${formattedState}`
        : zip
        ? `${city} ${zip}`
        : `${city}`
      : formattedState
      ? zip
        ? `${formattedState} ${zip}`
        : `${formattedState}`
      : zip
      ? `${zip}`
      : '';

    const addressCountry = allCountries.find((c) => c[1] === currentCountry)[0];

    return {
      addressLine3,
      addressCountry,
    };
  });

export const getCurrentRegions = (country) =>
  allCountries.find((c) => c[1] === country)[2];


text: """The Azure Service Bus integration."""


text:
typedef struct Status {
  bool ok;     // Bool indicating success or failure
  int errnum;  // Error number indicating type of failure. Often set to errno.
} Status;

// Create a new Status object with 'ok' and 'errnum' values as specified
Status make_status(bool ok, int errnum);

// Create a new Status object
// - If 'ok' is true, set 'errnum' to 0
// - If 'ok' is false, set 'errnum' to errno
Status get_status(bool ok);

#endif // STATUS_H


text:
//////////////////
// Link Helpers //
//////////////////

/**
 * Return a post's link if it has one, else return its post page URL
 * @param {Object} post
 */
Posts.getLink = function (post, isAbsolute) {
  return !!post.url ? Telescope.utils.getOutgoingUrl(post.url) : this.getPageUrl(post, isAbsolute);
};
Posts.helpers({getLink: function (isAbsolute) {return Posts.getLink(this, isAbsolute);}});

/**
 * Depending on the settings, return either a post's URL link (if it has one) or its page URL.
 * @param {Object} post
 */
Posts.getShareableLink = function (post) {
  return Settings.get("outsideLinksPointTo", "link") === "link" ? Posts.getLink(post) : Posts.getPageUrl(post, true);
};
Posts.helpers({getShareableLink: function () {return Posts.getShareableLink(this);}});

/**
 * Whether a post's link should open in a new tab or not
 * @param {Object} post
 */
Posts.getLinkTarget = function (post) {
  return !!post.url ? "_blank" : "";
};
Posts.helpers({getLinkTarget: function () {return Posts.getLinkTarget(this);}});

/**
 * Get URL of a post page.
 * @param {Object} post
 */
Posts.getPageUrl = function(post, isAbsolute){
  var isAbsolute = typeof isAbsolute === "undefined" ? false : isAbsolute; // default to false
  var prefix = isAbsolute ? Telescope.utils.getSiteUrl().slice(0,-1) : "";
  return prefix + FlowRouter.path("postPage", post);
};
Posts.helpers({getPageUrl: function (isAbsolute) {return Posts.getPageUrl(this, isAbsolute);}});

/**
 * Get post edit page URL.
 * @param {String} id
 */
Posts.getEditUrl = function(post, isAbsolute){
  var isAbsolute = typeof isAbsolute === "undefined" ? false : isAbsolute; // default to false
  var prefix = isAbsolute ? Telescope.utils.getSiteUrl().slice(0,-1) : "";
  return prefix + FlowRouter.path("postEdit", post);
};
Posts.helpers({getEditUrl: function (isAbsolute) {return Posts.getEditUrl(this, isAbsolute);}});

///////////////////
// Other Helpers //
///////////////////

/**
 * Get a post author's name
 * @param {Object} post
 */
Posts.getAuthorName = function (post) {
  var user = Meteor.users.findOne(post.userId);
  if (user) {
    return user.getDisplayName();
  } else {
    return post.author;
  }
};
Posts.helpers({getAuthorName: function () {return Posts.getAuthorName(this);}});

/**
 * Get default status for new posts.
 * @param {Object} user
 */
Posts.getDefaultStatus = function (user) {
  var hasAdminRights = typeof user === 'undefined' ? false : Users.is.admin(user);
  if (hasAdminRights || !Settings.get('requirePostsApproval', false)) {
    // if user is admin, or else post approval is not required
    return Posts.config.STATUS_APPROVED;
  } else {
    return Posts.config.STATUS_PENDING;
  }
};

/**
 * Check if a post is approved
 * @param {Object} post
 */
Posts.isApproved = function (post) {
  return post.status === Posts.config.STATUS_APPROVED;
};
Posts.helpers({isApproved: function () {return Posts.isApproved(this);}});

/**
 * Check to see if post URL is unique.
 * We need the current user so we know who to upvote the existing post as.
 * @param {String} url
 */
Posts.checkForSameUrl = function (url) {

  // check that there are no previous posts with the same link in the past 6 months
  var sixMonthsAgo = moment().subtract(6, 'months').toDate();
  var postWithSameLink = Posts.findOne({url: url, postedAt: {$gte: sixMonthsAgo}});

  if (typeof postWithSameLink !== 'undefined') {
    throw new Meteor.Error('603', i18n.t('this_link_has_already_been_posted'), postWithSameLink._id);
  }
};

/**
 * When on a post page, return the current post
 */
Posts.current = function () {
  return Posts.findOne(FlowRouter.getParam("_id"));
};

/**
 * Check to see if a post is a link to a video
 * @param {Object} post
 */
Posts.isVideo = function (post) {
  return post.media && post.media.type === "video";
};
Posts.helpers({isVideo: function () {return Posts.isVideo(this);}});


text:
package org.ujorm.wicket.component.grid;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.jetbrains.annotations.Nullable;
import org.apache.wicket.Component;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.ujorm.Key;
import org.ujorm.Ujo;
import org.ujorm.core.KeyRing;
import org.ujorm.wicket.component.tools.DateTimes;

/**
 * Key column for a Date data type
 * @author Pavel Ponec
 * @param <U extends Ujo> The Model object type
 */
public class KeyColumnDate<U extends Ujo> extends KeyColumn<U, java.util.Date> {
    private static final long serialVersionUID = 1L;

    /** Default CSS class for  */
    public static String DEFAULT_CSS_CLASS = "date";

    /** Default 'date' format key for localizations */
    private final String localeDateFormatKey;

    /** Constructor with the default value localeDateFormatKey = {@code "locale.date.pattern"}. */
    public KeyColumnDate(KeyRing<U> key, KeyRing<U> keySortable) {
        this(key, keySortable, DateTimes.LOCALE_DATE_FORMAT_KEY);
    }

    public KeyColumnDate(KeyRing<U> key, KeyRing<U> keySortable, String localeDateFormatKey) {
        super(key, keySortable);
        this.localeDateFormatKey = localeDateFormatKey;
        setCssClass(DEFAULT_CSS_CLASS);
    }

    /** Create the Label for a Value component */
    @Override
    @Nullable
    protected Component createValueCoponent(final String componentId, final IModel<?> valueModel, final U ujo) {
        final Label result = new Label(componentId);
        result.setDefaultModel(new Model() {
            @Override public Serializable getObject() {
                final Date modelObject = (Date) valueModel.getObject();
                if (modelObject != null) {
                    final SimpleDateFormat form = new SimpleDateFormat(getDatePattern(result));
                    return form.format(modelObject);
                } else {
                    return null;
                }
            }
        });
        return result;
    }

    /** Returns localizadDate pattern */
    protected String getDatePattern(final Component component) {
        return component.getLocalizer().getString(localeDateFormatKey, component, DateTimes.getDefaultPattern(localeDateFormatKey));
    }

    // =============== STATIC FACTORY METHODS ===============

    /**
     * A factory method
     * @param key Domain Key
     * @param sorted Sorted column
     * @param cssClass Class for a value {@code Boolean.TRUE} where a default value is {@link #DEFAULT_CSS_OK_CLASS}.
     * @return New instance of the KeyColumn class
     */
    public static <U extends Ujo, T> KeyColumn<U,T> of(Key<U,T> key, boolean sorted, String cssClass) {
        return of(key, sorted, cssClass, DateTimes.LOCALE_DATE_FORMAT_KEY);
    }

    /**
     * A factory method
     * @param key Domain Key
     * @param sorted Sorted column
     * @param cssClass Class for a value {@code Boolean.TRUE} where a default value is {@link #DEFAULT_CSS_OK_CLASS}.
     * @return New instance of the KeyColumn class
     */
    public static <U extends Ujo, T> KeyColumn<U,T> of(Key<U,T> key, boolean sorted, String cssClass, String localeDateFormatKey) {
        final KeyRing serializableKey = KeyRing.of(key);
        final KeyColumn<U, T> result = new KeyColumnDate
                ( serializableKey
                , sorted ? serializableKey : null
                , localeDateFormatKey);
        result.setCssClass(cssClass);
        return result;
    }

}


text:
package com.intellij.refactoring;

import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.codeInspection.deadCode.UnusedDeclarationInspection;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actions.EditorActionUtil;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiTypeElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.changeSignature.ChangeSignatureHandler;
import com.intellij.refactoring.changeSignature.inplace.ApplyChangeSignatureAction;
import com.intellij.refactoring.changeSignature.inplace.InplaceChangeSignature;
import com.intellij.testFramework.PlatformTestCase;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;

import java.util.Optional;

/**
 * User: anna
 * Date: Sep 9, 2010
 */
@PlatformTestCase.WrapInCommand
public class ChangeSignatureGestureTest extends LightCodeInsightFixtureTestCase {

  private void doTest(final Runnable run, boolean shouldShow) {
    myFixture.configureByFile("/refactoring/changeSignatureGesture/" + getTestName(false) + ".java");
    myFixture.enableInspections(new UnusedDeclarationInspection());
    final EditorEx editor = (EditorEx)myFixture.getEditor();
    final Document document = editor.getDocument();
    CommandProcessor.getInstance().executeCommand(myFixture.getProject(), () -> new InplaceChangeSignature(myFixture.getProject(), editor, myFixture.getFile().findElementAt(myFixture.getCaretOffset())),
                                                  ChangeSignatureHandler.REFACTORING_NAME, null);
    new WriteCommandAction.Simple(getProject()) {
      @Override
      protected void run() throws Throwable {
        run.run();
      }
    }.execute().throwException();

    myFixture.doHighlighting();
    Optional<IntentionAction> intentionAction =
      myFixture.getAvailableIntentions().stream().filter(action -> action instanceof ApplyChangeSignatureAction).findFirst();
    if (shouldShow) {
      final IntentionAction intention = intentionAction.orElse(null);
      assertNotNull(intention);
      myFixture.launchAction(intention);
      myFixture.checkResultByFile("/refactoring/changeSignatureGesture/" + getTestName(false) + "_after.java");
    }
    else {
      assertFalse(intentionAction.isPresent());
    }
  }

  public void testSimple() {
    doTypingTest(", int param");
  }

  public void testNoUsages() {
    doTypingTest("int param");
  }

  public void testOccurrencesInSameFile() {
    doTypingTest("int param");
  }

  public void testMultiParams() {
    doTypingTest("int x, int y");
  }

  public void testAddParameter2Constructor() {
    doTypingTest("int param");
  }

  public void testAddParamChangeReturnType() {
    doTest(() -> {
      myFixture.type("int param");
      PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
      CaretModel model = myFixture.getEditor().getCaretModel();
      PsiElement element = myFixture.getElementAtCaret();
      PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class, false);
      assertTrue(method != null);
      PsiTypeElement returnTypeElement = method.getReturnTypeElement();
      assertTrue(returnTypeElement != null);
      model.moveToOffset(returnTypeElement.getTextRange().getEndOffset());
      int i = returnTypeElement.getTextLength();
      while (i-- > 0) {
        myFixture.type('\b');
      }
      myFixture.type("boolean");
    }, true);
  }

  public void testNewParam() {
    doTypingTest(", int param");
  }

  public void testNewParamInSuper() {
    doTypingTest(", int param");
  }

  public void testNewParamInSuperUsed() {
    doTypingTest(", int param");
  }

  private void doTypingTest(final String param) {
    doTest(() -> myFixture.type(param), true);
  }

  public void testModifier() {
    doTypingTest("private ");
  }

  public void testAddParameterFinal() {
    doTypingTest("final int param");
  }

  private void doTypingNoBorderTest(final String param) {
    doTest(() -> myFixture.type(param), false);
  }

  public void testDeleteParamInSuperUsed() {
    try {
      BaseRefactoringProcessor.ConflictsInTestsException.setTestIgnore(true);
      doDeleteTest();
    }
    finally {
      BaseRefactoringProcessor.ConflictsInTestsException.setTestIgnore(false);
    }
  }

  private void doDeleteTest() {
    doTest(() -> {
      final Editor editor = myFixture.getEditor();
      final Document document = editor.getDocument();
      final int selectionStart = editor.getSelectionModel().getSelectionStart();
      final int selectionEnd = editor.getSelectionModel().getSelectionEnd();
      CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
      document.deleteString(selectionStart, selectionEnd);
      editor.getCaretModel().moveToOffset(selectionStart);
    }, true);
  }

  @Override
  protected String getBasePath() {
    return JavaTestUtil.getRelativeJavaTestDataPath();
  }
}


text:
Given(/^I am logged in as a user$/) do
  visit "http://localhost:3000/logout"			#First, log out.

  @current_user = User.create!(:email => 'user@fake.com', :name => 'fakeuser', :password => 'password', :password_confirmation => 'password')

  visit "http://localhost:3000" #Home page

  #Fill out login form, then log in
  fill_in("session_email", :with => @current_user.email)
  fill_in("session_password", :with => @current_user.password)
  click_button("submit")

  #Should now be in profile page, logged in
end

When (/^I navigate to Log In page and enter an email and password$/) do
  visit "http://localhost:3000/login"

  #Fill out login form, then log in
  fill_in("session_email", :with => "notregistered@fake.com")
  fill_in("session_password", :with => "somepassword")
  click_button("submit")
end

When (/^I navigate to Log In page and enter my information$/) do
  visit "http://localhost:3000/login"

  #Fill out login form, then log in
  fill_in("session_email", :with => @current_user.email)
  fill_in("session_password", :with => @current_user.password)
  click_button("submit")
end

Given (/^I log out$/) do
  visit "http://localhost:3000/logout"
end

Then(/^the Log In page is loaded$/) do
  page.should have_content("Log In")
end


text:
<?php

namespace openacalendar\staticweb\warnings;

class DataWarningGroupHasNoSlug extends BaseWarning {

}


text:
/*  HOly Walk walk.cpp
 *  Ways to move limbs that make the robot walk
 *  Laurenz & Simon 2015-05-29
 */

#ifndef _WALK_H_
#define _WALK_H_

#include "../poses/poses.h"
#include "fsm_defines.h"

class Core;

class Walk {
public:
    Walk(Core* core);

    void executeStateMachine();

    // FSMs
    typedef enum {iSHIFT_LEFT,iLIFT_RIGHT,iFWD_RIGHT,iDUAL_RIGHT, iSHIFT_FRONT_RIGHT} INIT_FSM;
    typedef enum {lLIFT_LEFT,lFWD_LEFT,lDUAL_LEFT,lSHIFT_FRONT_LEFT,lLIFT_RIGHT,lFWD_RIGHT,lDUAL_RIGHT,lSHIFT_FRONT_RIGHT} LOOP_FSM;
    typedef enum {sLIFT_LEFT,sFWD_LEFT,sLIFT_RIGHT,sFWD_RIGHT,sDEFAULT} STOP_FSM;

    Walk_FSM walk_fsm;
    INIT_FSM init_fsm;
    LOOP_FSM loop_fsm;
    STOP_FSM stop_fsm;

    // State machine
    void StateMachine();

    void init_StateMachine();

private:
    Core* core;
    // poses object
    Poses walk_poses;

};

#endif


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.github.gv2011</groupId>
    <artifactId>util-parent</artifactId>
    <version>0.9</version>
  </parent>

  <artifactId>util-gcol</artifactId>

  <dependencies>

    <dependency>
      <groupId>com.github.gv2011</groupId>
      <artifactId>util-apis</artifactId>
    </dependency>

    <dependency>
      <groupId>jakarta.activation</groupId>
      <artifactId>jakarta.activation-api</artifactId>
    </dependency>

    <dependency>
      <groupId>com.github.gv2011</groupId>
      <artifactId>guava-core</artifactId>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifestEntries>
              <Automatic-Module-Name>com.github.gv2011.util.gcol</Automatic-Module-Name>
            </manifestEntries>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
local nn = require 'nn'
require 'spatial-pooling'
local paths = require 'paths'

local function createModel(opt)

    if opt.backend == 'cudnn' then
        require 'cunn'
        require 'cudnn'
    end

    -- load model
    if opt.netInit == '' then
        local filename = 'data/pretrained_models/resnet-101.t7'
        paths.mkdir('data/pretrained_models')
        if not paths.filep(filename) then
            local url = 'https://d2j0dndfm35trm.cloudfront.net/resnet-101.t7'
            os.execute('wget ' .. url .. ' -O ' .. filename)
        end
        opt.netInit = filename
    end
    print('[model] read model: ' .. opt.netInit)
    local pretrainedModel = torch.load(opt.netInit)
    pretrainedModel = pretrainedModel:float()

    -- create model network and remove the last fully-connected layer
    local model = nn.Sequential()
    for i=1,8 do
        model:add(pretrainedModel:get(i))
    end
    if opt.backend == 'cudnn' then
        cudnn.convert(model, nn)
    end
    model = model:float()
    collectgarbage()
    local numPretrainedParam = model:getParameters():size(1)

    -- add new fully-connected layer for target dataset
    local transfert = nn.SpatialConvolution(2048, opt.nClasses, 1, 1, 1, 1)
    transfert.bias:zero()
    model:add(transfert)
    model = model:float()

    -- find the output size to define the spatial aggregation layer
    local input = torch.rand(1, 3, opt.imageSize, opt.imageSize):float()
    print('[model] input ' .. input:size(1) .. ' x ' .. input:size(2) .. ' x ' .. input:size(3) .. ' x ' .. input:size(4))
    local output = model:forward(input)
    print('[model] output after convolutions: ' .. output:size(1) .. ' x ' .. output:size(2) .. ' x ' .. output:size(3) .. ' x ' .. output:size(4))

    -- add spatial aggregation layer
    model:add(nn.GlobalAveragePooling())
    model:add(nn.Reshape(opt.nClasses))

    model = model:float()
    local output = model:forward(input)
    print('[model] output ' .. output:size(1) .. ' x ' .. output:size(2))
    local numParam = model:getParameters():size(1)

    opt.lastconv = 9

    if opt.LRp ~= 1 and opt.LRp >= 0 then
        print('[model] initialize learningRates', opt.LRp)
        local lrs = torch.Tensor(numParam):zero()
        for i = 1, numParam do
            if i > numPretrainedParam then
                lrs[i] = 1.0
            else
                lrs[i] = opt.LRp
            end
        end
        opt.learningRates = lrs
        if opt.backend == 'cudnn' then
            opt.learningRates = opt.learningRates:cuda()
        end
    end

    return model
end

return createModel


text:
// ======================================================================
/*!
 * \brief Parameter configuration loading
 */
// ======================================================================

#include "ParamConfig.h"

#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <macgyver/StringConversion.h>

#include <fstream>

#include <json/json.h>
#include <json/reader.h>

namespace SmartMet
{
namespace Plugin
{
namespace WCS
{
ParamConfig::ParamConfig(const FilePathType& filePath) : mFilePath(filePath)
{
  if (filePath.empty())
  {
    throw std::runtime_error("Empty ParamConfig file path detected.");
  }
}

ParamConfig::~ParamConfig() {}

void ParamConfig::addParamMetaItem(const ParamMetaItemType& paramItem)
{
  long ident = paramItem.mWantedParam.GetIdent();

  auto it = mParamMetaItemMap.find(ident);
  if (it != mParamMetaItemMap.end())
  {
    std::ostringstream msg;
    msg << "Duplicate parameter item id '" << ident << "' detected";
    throw std::runtime_error(msg.str());
  }
  mParamMetaItemMap.emplace(ident, std::make_shared<ParamMetaItemType>(paramItem));
}

std::shared_ptr<ParamConfig::ParamMetaItemType> ParamConfig::getParamMetaItem(
    const ParamIdType& paramId) const
{
  auto it = mParamMetaItemMap.find(paramId);
  if (it != mParamMetaItemMap.end())
    return it->second;
  else
    return std::shared_ptr<ParamMetaItemType>();
}

NetcdfParamConfig::NetcdfParamConfig(const FilePathType& filePath) : ParamConfig(filePath)
{
  ParamChangeTable paramTable = readParamConfig(filePath, false);
  for (const auto& item : paramTable)
    addParamMetaItem(item);
}

NetcdfParamConfig::~NetcdfParamConfig() {}

// ======================================================================
/*!
 * \brief Parameter configuration item
 */
// ======================================================================

ParamChangeItem::ParamChangeItem()
    : mOriginalParamId(0),
      mWantedParam(
          0, "", kFloatMissing, kFloatMissing, kFloatMissing, kFloatMissing, "%.1f", kLinearly),
      mConversionBase(0),
      mConversionScale(1.0),
      mLevel(NULL),
      mPeriodLengthMinutes(0),
      mTemplateNumber(0)
{
}

ParamChangeItem::~ParamChangeItem()
{
  if (mLevel)
    delete mLevel;
}

ParamChangeItem::ParamChangeItem(const ParamChangeItem& theOther)
    : mOriginalParamId(theOther.mOriginalParamId),
      mWantedParam(theOther.mWantedParam),
      mConversionBase(theOther.mConversionBase),
      mConversionScale(theOther.mConversionScale),
      mLevel(theOther.mLevel ? new NFmiLevel(*theOther.mLevel) : NULL),
      mStepType(theOther.mStepType),
      mPeriodLengthMinutes(theOther.mPeriodLengthMinutes),
      mUnit(theOther.mUnit),
      mStdName(theOther.mStdName),
      mLongName(theOther.mLongName),
      mCentre(theOther.mCentre),
      mTemplateNumber(theOther.mTemplateNumber)
{
}

ParamChangeItem& ParamChangeItem::operator=(const ParamChangeItem& theOther)
{
  if (this != &theOther)
  {
    mOriginalParamId = theOther.mOriginalParamId;
    mWantedParam = theOther.mWantedParam;
    mConversionBase = theOther.mConversionBase;
    mConversionScale = theOther.mConversionScale;
    mLevel = theOther.mLevel ? new NFmiLevel(*theOther.mLevel) : NULL;
    mStepType = theOther.mStepType;
    mPeriodLengthMinutes = theOther.mPeriodLengthMinutes;
    mUnit = theOther.mUnit;
    mStdName = theOther.mStdName;
    mLongName = theOther.mLongName;
    mCentre = theOther.mCentre;
    mTemplateNumber = theOther.mTemplateNumber;
  }

  return *this;
}

// ======================================================================
/*!
 * \brief Functions to convert a json value to a number or a string.
 */
// ======================================================================
unsigned long asUInt64(const std::string& name, const Json::Value& json, uint arrayIndex)
{
  if (json.isUInt64())
    return json.asUInt64();

  throw std::runtime_error("'" + name + "': uint64 value expected at array index " +
                           Fmi::to_string(arrayIndex) + ", got value " + json.asString() +
                           " instead");
}

unsigned int asUInt(const std::string& name, const Json::Value& json, uint arrayIndex)
{
  if (json.isUInt())
    return json.asUInt();

  throw std::runtime_error("'" + name + "': uint value expected at array index " +
                           Fmi::to_string(arrayIndex));
}

float asFloat(const std::string& name, const Json::Value& json, uint arrayIndex)
{
  if (json.isDouble())
    return json.asFloat();

  throw std::runtime_error("'" + name + "': float value expected at array index " +
                           Fmi::to_string(arrayIndex));
}

std::string asString(const std::string& name, const Json::Value& json, uint arrayIndex)
{
  // json.isConvertibleTo(Json::stringValue) for a number returns true but json.asString() fails
  //
  // if (json.isConvertibleTo(Json::stringValue))

  if (json.isString())
    return json.asString();

  throw std::runtime_error("'" + name + "': string value expected at array index " +
                           Fmi::to_string(arrayIndex));
}

// ======================================================================
/*!
 * \brief Load grib format specific configuration fields.
 */
// ======================================================================

bool readGribParamConfigField(const std::string& name,
                              const Json::Value& json,
                              ParamChangeItem& p,
                              unsigned int arrayIndex)
{
  if (name == "gribid")
  {
    p.mOriginalParamId = asUInt64(name, json, arrayIndex);
  }
  else if (name == "leveltype")
  {
    p.mLevelType = asString(name, json, arrayIndex);
  }
  else if (name == "levelvalue")
  {
    p.mLevelValue = asFloat(name, json, arrayIndex);
  }
  else if (name == "center")
  {
    p.mCentre = asString(name, json, arrayIndex);
  }
  else if (name == "templatenumber")
  {
    p.mTemplateNumber = asUInt(name, json, arrayIndex);
  }
  else
  {
    // Unknown setting
    //
    return false;
  }

  return true;
}

// ======================================================================
/*!
 * \brief Load netcdf format specific configuration fields.
 */
// ======================================================================

bool readNetCdfParamConfigField(const std::string& name,
                                const Json::Value& json,
                                ParamChangeItem& p,
                                unsigned int arrayIndex)
{
  if (name == "standardname")
    p.mStdName = asString(name, json, arrayIndex);
  else if (name == "longname")
    p.mLongName = asString(name, json, arrayIndex);
  else if (name == "unit")
    p.mUnit = asString(name, json, arrayIndex);
  else
    // Unknown setting
    //
    return false;

  return true;
}

// ======================================================================
/*!
 * \brief Load parameter configuration.
 */
// ======================================================================

ParamChangeTable readParamConfig(const boost::filesystem::path& configFilePath, bool grib)
{
  // Read and parse the JSON formatted configuration

  Json::Reader reader;
  Json::Value theJson;
  std::vector<ParamChangeItem> paramChangeTable;

  std::ifstream in(configFilePath.c_str());
  if (!in)
    throw std::runtime_error("Failed to open '" + configFilePath.string() + "' for reading");

  std::string content;
  content.assign(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());

  if (!reader.parse(content, theJson))
    throw std::runtime_error("Failed to parse '" + configFilePath.string() +
                             "': " + reader.getFormattedErrorMessages());

  if (!theJson.isArray())
    throw std::runtime_error("Parameter configuration must contain an array of JSON objects");

  // Iterate through all the objects

  auto& fmtConfigFunc(grib ? readGribParamConfigField : readNetCdfParamConfigField);

  for (unsigned int i = 0; i < theJson.size(); i++)
  {
    const Json::Value& paramJson = theJson[i];

    if (!paramJson.isObject())
      throw std::runtime_error("JSON object expected at array index " + Fmi::to_string(i));

    ParamChangeItem p;
    std::string paramName;
    uint paramId = 0;

    const auto members = paramJson.getMemberNames();
    BOOST_FOREACH (const auto& name, members)
    {
      const Json::Value& json = paramJson[name];
      if (json.isArray() || json.isObject())
        throw std::runtime_error(name + ": value is neither a string nor a number at array index " +
                                 Fmi::to_string(i));

      // Ignore null values

      if (json.isNull())
        continue;
      //
      // Handle common settings
      //
      if (name == "newbaseid")
        paramId = asUInt(name, json, i);
      else if (name == "name")
        paramName = asString(name, json, i);
      else if (name == "offset")
        p.mConversionBase = asFloat(name, json, i);
      else if (name == "divisor")
        p.mConversionScale = asFloat(name, json, i);
      else if (name == "aggregatetype")
        p.mStepType = asString(name, json, i);
      else if (name == "aggregatelength")
        p.mPeriodLengthMinutes = asUInt(name, json, i);
      //
      // Handle format specific settings
      //
      else if (!fmtConfigFunc(name, json, p, i))
        throw std::runtime_error(std::string(grib ? "Grib" : "Netcdf") +
                                 " parameter configuration does not have a setting named '" + name +
                                 "'");
    }

    // Set parameter id and name

    p.mWantedParam.SetIdent(paramId);
    p.mWantedParam.SetName(paramName);

    // Create level object if level data was given

    if (p.mLevelValue || (!p.mLevelType.empty()))
      p.mLevel = new NFmiLevel(0, p.mLevelType, p.mLevelValue ? *(p.mLevelValue) : 0);

    paramChangeTable.push_back(p);
  }

  return paramChangeTable;
}
}  // namespace WCS
}  // namespace Plugin
}  // namespace SmartMet


text:
<?php

defined("DB_HOST")
    || define("DB_HOST", 'localhost');

defined("DB_NAME")
    || define("DB_NAME", 'search');

defined("DB_USER")
    || define("DB_USER", '');

defined("DB_PASSWORD")
    || define("DB_PASSWORD", '');


text:
import Ember from 'ember';
import layout from '../templates/components/ui-test-map';
import UIAbstractMap from './ui-abstract-map';

export default UIAbstractMap.extend({
  layout: layout,
  tagName: 'ui-test-map',
  classNames: ['ui-test-map'],

  setup() {
    return new Ember.RSVP.Promise((resolve) => {
      resolve();
    });
  },

  teardown() {
    return new Ember.RSVP.Promise((resolve) => {
      resolve();
    });
  }
});


text:
package net.binarypaper.springbootframework.email;

import java.io.Serializable;
import lombok.Data;

/**
 * An email message to be sent the system
 *
 * @author Willy Gadney
 */
// Lombok annotations
@Data
public class EmailMessage implements Serializable {

    private static final long serialVersionUID = 1L;

    private String userName;

    private String toAddress;

    private String subject;

    private String body;

}


text:
package org.springframework.social.facebook.api;

import java.util.Map;

/**
 * Model class representing a Facebook page.
 * A Facebook page could represent any number of things, including businesses, government agencies, people, organizations, etc.
 * A page may even represent a place that a user may check into using Facebook Places, if the page has location data.
 * The data available for a page will vary depending on the category it belongs to and what data the page administrator has entered.
 * @author Craig Walls
 */
public class Page extends FacebookObject {

	private final String id;

	private final String name;

	private final String category;

	private final String link;

	private String description;

	private String about;

	private Location location;

	private String website;

	private String picture;

	private CoverPhoto cover;

	private String phone;

	private String affiliation;

	private String companyOverview;

	private int likes;

	private int talkingAboutCount;

	private int checkins;

	private boolean canPost;

	private boolean isPublished;

	private boolean isCommunityPage;

	private boolean hasAddedApp;

	private Map<String, String> hours;

	public Page(String id, String name, String link, String category) {
		super();
		this.id = id;
		this.name = name;
		this.link = link;
		this.category = category;
	}

	/**
	 * @return The page's ID.
	 */
	public String getId() {
		return id;
	}

	/**
	 * @return The page's name.
	 */
	public String getName() {
		return name;
	}

	/**
	 * @return Link to the page on Facebook.
	 */
	public String getLink() {
		return link;
	}

	/**
	 * @return The page's category.
	 */
	public String getCategory() {
		return category;
	}

	/**
	 * @return A description of this page.
	 */
	public String getDescription() {
		return description;
	}

	/**
	 * @return Text telling what this page is about.
	 */
	public String getAbout() {
		return about;
	}

	/**
	 * @return The page's street address and longitude/latitude coordinates (if available).
	 */
	public Location getLocation() {
		return location;
	}

	/**
	 * @return Link to the external website for the page.
	 */
	public String getWebsite() {
		return website;
	}

	/**
	 * The page's picture.
	 * @deprecated This method will be replaced in Spring 1.1.0 with a new version that returns an object with more details about the picture.
	 */
	@Deprecated
	public String getPicture() {
		return picture;
	}

	/**
	 * The page's cover photo.
	 */
	public CoverPhoto getCover() {
		return cover;
	}

	/**
	 * @return The phone number for the page.
	 */
	public String getPhone() {
		return phone;
	}

	/**
	 * @return The name of an organization that this page is affiliated with.
	 */
	public String getAffiliation() {
		return affiliation;
	}

	/**
	 * @return Text giving a brief description of the company this page serves.
	 */
	public String getCompanyOverview() {
		return companyOverview;
	}

	/**
	 * @return The number of users who like this page. For Global Brand pages, this count is fall all pages across the brand.
	 */
	public int getLikes() {
		return likes;
	}

	public int getTalkingAboutCount() {
		return talkingAboutCount;
	}

	/**
	 * @return The total number of users that have checked in to the page.
	 */
	public int getCheckins() {
		return checkins;
	}

	/**
	 * Indicates whether or not the authenticated user can post on this page.
	 * @return true if the user can post to the page; false otherwise
	 */
	public boolean canPost() {
		return canPost;
	}

	/**
	 * @return true if the page has been published; false otherwise.
	 */
	public boolean isPublished() {
		return isPublished;
	}

	/**
	 * @return true if the page is a community page; false otherwise.
	 */
	public boolean isCommunityPage() {
		return isCommunityPage;
	}

	/**
	 * @return true if the page has added the app making the query in a Page tab; false otherwise.
	 */
	public boolean hasAddedApp() {
		return hasAddedApp;
	}

	public Map<String, String> getHours() {
		return hours;
	}

}


text:
class Extension;
class GURL;

namespace extension_sidebar_utils {

// Returns id of an extension owning a sidebar identified by |content_id|.
std::string GetExtensionIdByContentId(const std::string& content_id);

// Resolves |relative_path| relative to |extension|'s url.
// In case of any problem, returns an empty invalid GURL and |error| receives
// the corresponding error message.
GURL ResolveRelativePath(const std::string& relative_path,
                         const Extension* extension,
                         std::string* error);

}  // namespace extension_sidebar_utils

#endif  // CHROME_COMMON_EXTENSIONS_EXTENSION_SIDEBAR_UTILS_H_


text:
import React, { Component } from 'react'
import { connect } from 'react-redux'

import StaticPage from '~/components/staticPages/StaticPage'
import RequireNotLoggedIn from '~/components/utils/RequireNotLoggedIn'
import ResendActivationMessageForm from './ResendActivationMessage/ResendActivationMessageForm'
import T from '~/components/utils/T'
import t from '~/utils/i18n/t'

class ResendActivationMessage extends Component {
  constructor() {
    super()
    this.state = {
      msg: null
    }
    this.handleSubmitSuccess = this.handleSubmitSuccess.bind(this)
  }
  handleSubmitSuccess(data) {
    this.setState({
      msg: data.msg
    })
  }
  render() {
    return (

<T t="Resend activation message" />

          {this.state.msg && (

{this.state.msg}

          ) || (
            <ResendActivationMessageForm
              onSubmitSuccess={this.handleSubmitSuccess}
            />
          )}

    )
  }
}

ResendActivationMessage = StaticPage(ResendActivationMessage)

const mapStateToProps = (state) => ({
  meta: {
    title: t(state, 'Resend activation message')
  }
})
ResendActivationMessage = connect(
  mapStateToProps
)(ResendActivationMessage)

ResendActivationMessage = RequireNotLoggedIn(ResendActivationMessage)

export default ResendActivationMessage


text:
from django.contrib.auth.models import User

class MasqueradeMiddleware(object):
    def process_request(self, request):
        """Checks for the presence of "mask_user" in the session. The value
        should be the username of the user to be masqueraded as. Note we
        also set the "is_masked" attribute to true in that case so that when we
        hit the "mask" or "unmask" URLs this user is properly recognized,
        rather than the user they're masquerading as :) """

        request.user.is_masked = False

        if 'mask_user' in request.session:
            try:
                request.user = \
                  User.objects.get(username=request.session['mask_user'])
                request.user.is_masked = True
            except User.DoesNotExist:
                pass


text:
from __future__ import unicode_literals

import datetime
from django.db import migrations, models
from django.utils.timezone import utc

class Migration(migrations.Migration):

    dependencies = [
        ('momentum', '0018_auto_20160615_0711'),
    ]

    operations = [
        migrations.AlterField(
            model_name='goal',
            name='last_completed_date',
            field=models.DateField(blank=True, default=datetime.datetime(2016, 6, 15, 13, 18, 23, 8537, tzinfo=utc), null=True),
        ),
        migrations.AlterField(
            model_name='goal',
            name='last_entry_date',
            field=models.DateField(blank=True, default=datetime.datetime(2016, 6, 15, 13, 18, 23, 8493, tzinfo=utc), null=True),
        ),
    ]


text:
namespace FeatureFlagger
{
    using System.Linq;

    public static class FeatureFlagExtensions
    {
        public static bool IsEnabled(
            this IFeatureFlag featureFlag)
        {
            var behaviours = FeatureFlagger.Behaviours.ToList();
            var feature    = FeatureFlagger.Reader.Read(featureFlag.GetType().Name);

            // TODO: exception handling.
            return !(from flag in feature.Flags
                        let behaviour = behaviours.FirstOrDefault(b => b.GetType().Name.Contains(flag.Name))
                        let func = behaviour.Behaviour()
                        where func(flag.Properties) == false
                        select flag).Any();
        }
    }
}


text:
var modules = angular.module('gransk.modules');

modules.controller('StatisticsCtrl', ['$scope', function($scope) {
  $scope.$parent.mode = 'statistics';
  $scope.$parent.submit_query($scope.$parent.query_string);
}]);

modules.service('stats', function(config, client, aggs) {
  var statistics = {
    aggs: {},
    counts: {}
  };

  return {
    load: function(callback) {
      var _aggs = JSON.parse(JSON.stringify(aggs.get(true)));
      _aggs.entities = {
        cardinality: {
          field: "raw_entity"
        }
      };
      _aggs.documents = {
        cardinality: {
          field: "id"
        }
      };

      _aggs.added_histogram = {
        nested : {
            path : 'meta'
        },
        aggs: {
          by_hour: {
            date_histogram: {
              field: 'meta.added',
              interval: '10s',
              format: 'epoch_second'
            }
          }
        }
      }

      client.search({
        index: 'gransk',
        body: {
          size: 0,
          query: {
            match_all: {}
          },
          aggs: _aggs
        }
      }).then(function(resp) {
        statistics.counts = {
          entities: resp.aggregations.entities.value,
          documents: resp.aggregations.documents.value
        };

        delete resp.aggregations.entities;
        delete resp.aggregations.documents;

        resp.aggregations.raw_entity.buckets.map(function(entity, i) {
          resp.aggregations.raw_entity.buckets[i].key = JSON.parse(resp.aggregations.raw_entity.buckets[i].key);
        });

        statistics.histogram = resp.aggregations.added_histogram;
        delete resp.aggregations.added_histogram;
        statistics.aggs = resp.aggregations;

        callback(statistics);
      });
    }
  };
});

modules.directive('histogram', function() {
  return {
    transclude: true,
    restrict: "E",
    template: '

Added documents

{{histogram}}

',
    scope: {
      histogram: '='
    },
    link: function(scope, element) {
      scope.$watch('histogram', function() {
        if (!scope.histogram) return;
        var margin = {top: 10, right: 30, bottom: 30, left: 50},
		    width = document.getElementById('mainstats').offsetWidth - margin.left - margin.right - 30,
		    height = 200 - margin.top - margin.bottom;

  		var parseDate = d3.time.format("%m/%d/%Y %I:%M:%S %p").parse;
  		var formatDate = d3.time.format("%d/%m %H:%M");
  		var formatCount = d3.format(",.0f");

  		var x = d3.time.scale().range([0, width]);
  		var y = d3.scale.linear().range([height, 0]);

  		var xAxis = d3.svg.axis().scale(x).orient("bottom").ticks(6).tickFormat(formatDate);
  		var yAxis = d3.svg.axis().scale(y).orient("left").ticks(6);

  		// Create the SVG drawing area
      angular.element(element.children()[0]).children()[1].innerHTML = '';
  		var svg = d3.select(angular.element(element.children()[0]).children()[1])
  		  .append("svg")
  		  .attr("width", width + margin.left + margin.right)
  		  .attr("height", height + margin.top + margin.bottom)
        //.attr('fill', '#FEFFFE')
        .attr('fill', '#888')
  		  .append("g")
  		  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  		// Get the data

      var data = [];

      scope.histogram.by_hour.buckets.map(function(bucket) {
        for (var i=0; i<bucket.doc_count; i++) {
          data.push({
            created_date: new Date(bucket.key*1000)
          });
        }
      })

  		  // Determine the first and list dates in the data set
  		  var monthExtent = d3.extent(data, function(d) { return d.created_date; });

  		  // Create one bin per month, use an offset to include the first and last months
  		  var monthBins = d3.time.hours(d3.time.hour.offset(new Date(monthExtent[0].getTime() - 60 * 60 * 12 * 1000),-1),
  		                                 d3.time.hour.offset(new Date(new Date().getTime() + 60 * 60 * 12 * 1000),1));

  		  // Use the histogram layout to create a function that will bin the data
  		  var binByMonth = d3.layout.histogram()
  		    .value(function(d) { return d.created_date; })
  		    .bins(monthBins);

  		  // Bin the data by month
  		  var histData = binByMonth(data);

  		  // Scale the range of the data by setting the domain
  		  x.domain(d3.extent(monthBins));
  		  y.domain([0, d3.max(histData, function(d) { return d.y; })]);

  		  svg.selectAll(".bar")
  		      .data(histData)
  		    .enter().append("rect")
  		      .attr("class", "bar")
  		      .attr("x", function(d) { return x(d.x); })
  		      .attr("width", function(d) { return x(new Date(d.x.getTime() + d.dx))-x(d.x)-1; })
  		      .attr("y", function(d) { return y(d.y); })
  		      .attr("height", function(d) { return height - y(d.y); });

  		  // Add the X Axis
  		  svg.append("g")
  		      .attr("class", "x axis")
  		      .attr("transform", "translate(0," + height + ")")
  		      .call(xAxis);

  		  // Add the Y Axis and label
  		  svg.append("g")
  		     .attr("class", "y axis")
  		     .call(yAxis)
  		    .append("text")
  		      .attr("transform", "rotate(-90)")
  		      .attr("y", 6)
  		      .attr("dy", ".71em")
  		      .style("text-anchor", "end");

  		});
    }
  }
});

modules.directive('pie', function($timeout) {
  var colors = "#369EAD #C24642 #7F6084 #86B402 #A2D1CF #C8B631 #6DBCEB #52514E #4F81BC #A064A1 #F79647".split(' ');
  var width = window.innerWidth;

  return {
    transclude: true,
    restrict: "E",
    template: '

{{pid}}

',
    scope: {
      pid: '=',
      data: '='
    },
    link: function(scope, element) {
      var pie = new d3pie(angular.element(angular.element(element[0]).children()[0]).children()[1], {
        header: {
         title: {text: null}
       },
        size: {
          canvasHeight: 200,
          canvasWidth: 270,
          pieOuterRadius: "88%"
        },
        data: {
          content: []
        },
        labels: {
          outer: {
            pieDistance: 25
          },
          inner: {
            format: "value"
          },
          mainLabel: {
            font: "verdana",
            fontSize: 13
          },
          percentage: {
            color: "#e1e1e1",
            font: "verdana",
            decimalPlaces: 0
          },
          value: {
            color: "#e1e1e1",
            font: "verdana",
            fontSize: 13
          },
          lines: {
            enabled: true,
            color: "#cccccc"
          },
          truncation: {
            enabled: true
          }
        },
        effects: {
          pullOutSegmentOnClick: {
            effect: "linear",
            speed: 100,
            size: 8
          },
          load: {
        		effect: "none"
        	}
        }
      });

      scope.$watch('data', function() {
        scope.content = [];

        scope.data.buckets.map(function(bucket, i) {
          scope.content.push({
            label: bucket.key,
            value: bucket.doc_count,
            color: colors[i % colors.length]
          });
        });

        pie.updateProp("data.content", scope.content);
      });
    }
  };
});


text:
macro(append_c_source_file new_c_file)
    list(APPEND local_c_source_files "${new_c_file}")
endmacro()

macro(append_cpp_source_file new_cpp_file)
    list(APPEND local_cpp_source_files "${new_cpp_file}")
endmacro()

macro(append_asm_source_file new_asm_file)
    list(APPEND local_asm_source_files "${new_asm_file}")
endmacro()

macro(append_imp_c_source_file new_import_c_file)
    list(APPEND local_imp_c_files "${new_import_c_file}")
endmacro()

# files are relative to the src directory

function(set_c_files input_c_source_files)
    set(local_c_source_files "")
    append_c_source_file("kmp_ftn_cdecl.c")
    append_c_source_file("kmp_ftn_extra.c")
    append_c_source_file("kmp_version.c")
    if(${STUBS_LIBRARY})
        append_c_source_file("kmp_stub.c")
    else()
        append_c_source_file("kmp_alloc.c")
        append_c_source_file("kmp_atomic.c")
        append_c_source_file("kmp_csupport.c")
        append_c_source_file("kmp_debug.c")
        append_c_source_file("kmp_debugger.c")
        append_c_source_file("kmp_itt.c")
        append_c_source_file("kmp_environment.c")
        append_c_source_file("kmp_error.c")
        append_c_source_file("kmp_global.c")
        append_c_source_file("kmp_i18n.c")
        append_c_source_file("kmp_io.c")
        append_c_source_file("kmp_runtime.c")
        append_c_source_file("kmp_settings.c")
        append_c_source_file("kmp_str.c")
        append_c_source_file("kmp_tasking.c")
        append_c_source_file("kmp_taskq.c")
        append_c_source_file("kmp_threadprivate.c")
        append_c_source_file("kmp_utility.c")
        if(${LIBOMP_OMPT_SUPPORT})
            append_c_source_file("ompt-general.c")
        endif()
        if(${LIBOMP_USE_ITT_NOTIFY})
            append_c_source_file("thirdparty/ittnotify/ittnotify_static.c")
        endif()
        if(${WINDOWS})
            append_c_source_file("z_Windows_NT_util.c")
            append_c_source_file("z_Windows_NT-586_util.c")
        else()
            append_c_source_file("z_Linux_util.c")
            append_c_source_file("kmp_gsupport.c")
            append_c_source_file("thirdparty/safeclib/ignore_handler_s.c")
            append_c_source_file("thirdparty/safeclib/mem_primitives_lib.c")
            append_c_source_file("thirdparty/safeclib/memcpy_s.c")
            append_c_source_file("thirdparty/safeclib/safe_mem_constraint.c")
            append_c_source_file("thirdparty/safeclib/safe_str_constraint.c")
            append_c_source_file("thirdparty/safeclib/strcpy_s.c")
            append_c_source_file("thirdparty/safeclib/strncpy_s.c")
            append_c_source_file("thirdparty/safeclib/strnlen_s.c")
            append_c_source_file("thirdparty/safeclib/snprintf_support.c")
        endif()
    endif()
    set(${input_c_source_files} "${local_c_source_files}" PARENT_SCOPE)
endfunction()

function(set_cpp_files input_cpp_source_files)
    set(local_cpp_source_files "")
    if(NOT ${STUBS_LIBRARY})
        append_cpp_source_file("kmp_barrier.cpp")
        append_cpp_source_file("kmp_wait_release.cpp")
        append_cpp_source_file("kmp_affinity.cpp")
        append_cpp_source_file("kmp_dispatch.cpp")
        append_cpp_source_file("kmp_lock.cpp")
        append_cpp_source_file("kmp_sched.cpp")
        if(${LIBOMP_OMP_VERSION} GREATER 40 OR ${LIBOMP_OMP_VERSION} EQUAL 40)
            append_cpp_source_file("kmp_taskdeps.cpp")
            append_cpp_source_file("kmp_cancel.cpp")
        endif()
        if(${LIBOMP_STATS})
            append_cpp_source_file("kmp_stats.cpp")
            append_cpp_source_file("kmp_stats_timing.cpp")
        endif()
    endif()

    set(${input_cpp_source_files} "${local_cpp_source_files}" PARENT_SCOPE)
endfunction()

function(set_asm_files input_asm_source_files)
    set(local_asm_source_files "")
    if(NOT ${STUBS_LIBRARY})
        if(${WINDOWS})
            append_asm_source_file("z_Windows_NT-586_asm.asm")
        else()
            append_asm_source_file("z_Linux_asm.s")
        endif()
    endif()
    set(${input_asm_source_files} "${local_asm_source_files}" PARENT_SCOPE)
endfunction()

function(set_imp_c_files input_imp_c_files)
    set(local_imp_c_files "")
    if(${WINDOWS})
        append_imp_c_source_file("kmp_import.c")
    endif()
    set(${input_imp_c_files} "${local_imp_c_files}" PARENT_SCOPE)
endfunction()


text:
@extends('layouts.app')

@section('content')

Edit Patient

      {!! Form::model($patient, ['method' => 'PATCH', 'route'=> ['patients.update', $patient->id]]) !!}

      @include ('patients._form', ['submitBtText' => 'Update'])

      {!! Form::close() !!}

@endsection


text:
var app = {};
app._endpoint_handlers = {}

app.endpoint_handler = function(endpoint, func) {
    app._endpoint_handlers[endpoint] = app._endpoint_handlers[endpoint] || []
    app._endpoint_handlers[endpoint].push(func)
}

//= require pages/media

jQuery(function($) {
    app.endpoint = $('body').data('endpoint');
    var endpoint_handlers = app._endpoint_handlers[app.endpoint] || [];
    $.each(endpoint_handlers, function(i, func) {
        func();
    });
});


text:
require 'time'
require 'skype'

module SkypeChat

  class SkypeApp
    class << self
      def get_recent_chats
        api_res = Skype.search('recentchats')
        chat_ids = api_res.sub(/^CHATS\s+/, '').split(', ')
        chats = chat_ids.map { |id| Chat.new(id) }
        return chats
      end

      def get_chat_topic(chat_id)
        api_res = Skype.get(:chat, chat_id, :topic)
        topic = api_res.split(' ')[3..-1].join(' ')
        return nil if topic.empty?
        return topic
      end

      def get_chat_members(chat_id)
        api_res = Skype.get(:chat, chat_id, :members)
        members = api_res.split(' ')[3..-1]
        return members
      end

      def get_recent_messages(chat_id)
        api_res = Skype.get(:chat, chat_id, :recentchatmessages)
        message_ids =
          api_res.sub(/^CHAT\s.+RECENTCHATMESSAGES\s/, '').split(', ')

        chat = Chat.new(chat_id)
        messages = message_ids.map { |id| Message.new(id, chat) }

        messages.each { |m| self.mark_as_read(m.id) }

        return messages
      end

      def get_message_body(message_id)
        api_res = Skype.get(:message, message_id, :body)
        body = api_res.split(' ', 4).last
        return body
      end

      def get_message_sender(message_id)
        api_res = Skype.get(:message, message_id, :from_dispname)
        sender = api_res.split(' ', 4).last
        return sender
      end

      def get_message_timestamp(message_id)
        api_res = Skype.get(:message, message_id, :timestamp)
        timestamp = api_res.split(' ', 4).last.to_i
        return Time.at(timestamp)
      end

      def send_message(chat_id, text)
        Skype.chatmessage(chat_id, text)
      end

      def mark_as_read(message_id)
        Skype.set(:message, message_id, :seen)
      end
    end
  end

end


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

import com.google.common.hash.Hasher;
import com.google.common.hash.Hashing;
import com.google.gerrit.extensions.restapi.RestResource;
import com.google.gerrit.extensions.restapi.RestResource.HasETag;
import com.google.gerrit.extensions.restapi.RestView;
import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.CurrentUser;
import com.google.gerrit.server.edit.ChangeEdit;
import com.google.gerrit.server.notedb.ChangeNotes;
import com.google.gerrit.server.permissions.PermissionBackend;
import com.google.inject.TypeLiteral;
import java.util.Optional;

public class RevisionResource implements RestResource, HasETag {
  public static final TypeLiteral<RestView<RevisionResource>> REVISION_KIND =
      new TypeLiteral<RestView<RevisionResource>>() {};

  public static RevisionResource createNonCachable(ChangeResource change, PatchSet ps) {
    return new RevisionResource(change, ps, Optional.empty(), false);
  }

  private final ChangeResource change;
  private final PatchSet ps;
  private final Optional<ChangeEdit> edit;
  private final boolean cacheable;

  public RevisionResource(ChangeResource change, PatchSet ps) {
    this(change, ps, Optional.empty());
  }

  public RevisionResource(ChangeResource change, PatchSet ps, Optional<ChangeEdit> edit) {
    this(change, ps, edit, true);
  }

  private RevisionResource(
      ChangeResource change, PatchSet ps, Optional<ChangeEdit> edit, boolean cachable) {
    this.change = change;
    this.ps = ps;
    this.edit = edit;
    this.cacheable = cachable;
  }

  public boolean isCacheable() {
    return cacheable;
  }

  public PermissionBackend.ForChange permissions() {
    return change.permissions();
  }

  public ChangeResource getChangeResource() {
    return change;
  }

  public Change getChange() {
    return getChangeResource().getChange();
  }

  public Project.NameKey getProject() {
    return getChange().getProject();
  }

  public ChangeNotes getNotes() {
    return getChangeResource().getNotes();
  }

  public PatchSet getPatchSet() {
    return ps;
  }

  @Override
  public String getETag() {
    Hasher h = Hashing.murmur3_128().newHasher();
    prepareETag(h, getUser());
    return h.hash().toString();
  }

  public void prepareETag(Hasher h, CurrentUser user) {
    // Conservative estimate: refresh the revision if its parent change has changed, so we don't
    // have to check whether a given modification affected this revision specifically.
    change.prepareETag(h, user);
  }

  public Account.Id getAccountId() {
    return getUser().getAccountId();
  }

  public CurrentUser getUser() {
    return getChangeResource().getUser();
  }

  public Optional<ChangeEdit> getEdit() {
    return edit;
  }

  @Override
  public String toString() {
    String s = ps.getId().toString();
    if (edit.isPresent()) {
      s = "edit:" + s;
    }
    return s;
  }

  public boolean isCurrent() {
    return ps.getId().equals(getChange().currentPatchSetId());
  }
}


text:
using System;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Internal;

namespace MongoDB.Driver.Tests
{
    public static class FailPointName
    {
        // public constants
        public const string MaxTimeAlwaysTimeout = "maxTimeAlwaysTimeOut";
    }

    public class FailPoint : IDisposable
    {
        // private fields
        private readonly MongoDatabase _adminDatabase;
        private readonly string _name;
        private readonly IDisposable _request;
        private readonly MongoServer _server;
        private readonly MongoServerInstance _serverInstance;
        private bool _disposed;
        private bool _wasSet;

        // constructors
        public FailPoint(string name, MongoServer server, MongoServerInstance serverInstance)
        {
            if (name == null) { throw new ArgumentNullException("name"); }
            if (server == null) { throw new ArgumentNullException("server"); }
            if (serverInstance == null) { throw new ArgumentNullException("serverInstance"); }

            if (server.RequestConnection != null)
            {
                throw new InvalidOperationException("FailPoint cannot be used when you are already in a RequestStart.");
            }

            _name = name;
            _server = server;
            _serverInstance = serverInstance;
            _adminDatabase = server.GetDatabase("admin");
            _request = server.RequestStart(_adminDatabase, serverInstance);
        }

        // public methods
        public bool IsSupported()
        {
            return AreFailPointsSupported() && IsThisFailPointSupported();
        }

        public void Dispose()
        {
            if (!_disposed)
            {
                try
                {
                    try
                    {
                        _request.Dispose();
                    }
                    finally
                    {
                        if (_wasSet)
                        {
                            // use a new request to set the mode off because the original connection could be closed if an error occurred
                            using (_server.RequestStart(_adminDatabase, _serverInstance))
                            {
                                SetMode("off");
                            }
                        }
                    }
                }
                finally
                {
                    _disposed = true;
                }
            }
        }

        public void SetAlwaysOn()
        {
            SetMode("alwaysOn");
            _wasSet = true;
        }

        public void SetTimes(int n)
        {
            SetMode(new BsonDocument("times", n));
            _wasSet = true;
        }

        // private methods
        private bool AreFailPointsSupported()
        {
            return _serverInstance.BuildInfo.Version >= new Version(2, 4, 0);
        }

        private bool IsThisFailPointSupported()
        {
            // some failpoints aren't supported everywhere
            switch (_name)
            {
                case FailPointName.MaxTimeAlwaysTimeout:
                    if (_serverInstance.InstanceType == MongoServerInstanceType.ShardRouter)
                    {
                        return false;
                    }
                    break;
            }

            return true;
        }

        private void SetMode(BsonValue mode)
        {
            var command = new CommandDocument
            {
                { "configureFailPoint", _name },
                { "mode", mode }
            };
            _adminDatabase.RunCommand(command);
        }
    }
}


text:
require 'spec_helper'

describe UserQuiz do
end


text:
from ednet.util import Util
from ednet.ad import AD
from ednet.student import Student
from ednet.faculty import Faculty

import os

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def index(): return dict(message="hello from import.py")

def start_create_home_directory():
	# Start the worker process
	cmd = "/usr/bin/nohup /usr/bin/python " + os.path.join(request.folder, 'static/scheduler/start_create_home_directory_scheduler.py') + " > /dev/null 2>&1 &"
	p = subprocess.Popen(cmd, shell=True, close_fds=True)
	ret = ""
	#ret = p.wait()
	#ret = p.communicate()[0]
	#p.wait()
	#time.sleep(2)
	#p.kill()
	#ret = ""
	return ret

def start_process_queue():
	return start_create_home_directory()

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def student_pick_excel():
	f = None
	excel_output = None
	form = SQLFORM(db.student_excel_uploads).process()
	if form.accepted:
		#session.flash = "Processing File."
		f = form.vars.excel_file
		redirect(URL('student_show_excel_contents', vars=dict(excel_file=f)))
	elif form.errors:
		response.flash = "Form Errors"
	else:
		response.flash = "Upload Excel file or choose previous import."
	return dict(form=form, file_name=f, out=excel_output)

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def student_pick_excel_prev_workbooks():
	delete_id = request.vars.delete_id
	if (delete_id != None):
		# Delete id was passed, remove it
		db(db.student_excel_uploads.id==delete_id).delete()
		# This should remove uploaded file too
	rows = db(db.student_excel_uploads).select(orderby=~db.student_excel_uploads.created_on)
	return dict(rows=rows)

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def student_show_excel_contents():
	excel_file = request.vars.excel_file
	return locals()

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def student_show_excel_contents_process():
	# Process the files...
	excel_file = request.vars.excel_file
	f = os.path.join(request.folder,'uploads',excel_file)
	excel_output = Student.ProcessExcelFile(f)
	response.js = "ImportComplete();"
	return excel_output

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def student_show_excel_contents_sheet_dropdown():
	o = [OPTION(cat.sheet_name, _value=cat.sheet_name) for cat in db().select(db.student_import_queue.sheet_name, groupby=db.student_import_queue.sheet_name)]
	s = SELECT(o, _id='pick_sheet', _onchange="SheetChanged();")
	response.js = "SheetChanged();"

	erase_current_password = INPUT(_type='checkbox', _name='erase_current_password', _id='erase_current_password', _value="False", _onclick='if ($("#erase_current_password").val() == "True") { $("#erase_current_password").val("False"); } else { $("#erase_current_password ").val("True"); }')

	erase_current_quota = INPUT(_type='checkbox', _name='erase_current_quota', _id='erase_current_quota', _value="False", _onclick='if ($("#erase_current_quota").val() == "True") { $("#erase_current_quota").val("False"); } else { $("#erase_current_quota").val("True"); }')

	go = INPUT(_type='button', _name='go', _value='Import Sheet', _onclick='StartImport();')
	return dict(dropdown=s, erase_current_password=erase_current_password, erase_current_quota=erase_current_quota, go_button=go)

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def student_show_excel_contents_sheet_grid():
	sheet_name = request.vars.sheet_name
	query = (db.student_import_queue.sheet_name==sheet_name)
	#rows = db(query).select()
	g = SQLFORM.grid(query,editable=False, create=False, deletable=False,csv=False,links=False,links_in_grid=False,details=False,searchable=False,orderby=[~db.student_import_queue.account_enabled,db.student_import_queue.user_id])
	response.js = "ColorDisabledRows();"
	return g

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def student_do_import():
	AD.Close()

	sheet_name = request.vars.sheet_name
	erase_current_password = False
	if (request.vars.erase_current_password == "True"):
		erase_current_password = True
	erase_current_quota = False
	if (request.vars.erase_current_quota == "True"):
		erase_current_quota = True

	# Add student account to student_info table
	count = Student.CreateW2PyAccounts(sheet_name, erase_current_password, erase_current_quota)

	# Setup queue for canvas and for ad imports
	count2 = Student.QueueActiveDirectoryImports(sheet_name)
	count2 = Student.QueueCanvasImports(sheet_name)
	if (count2 > count):
		count = count2

	return dict(sheet_name=sheet_name, count=count)

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def student_do_import_ad():
	session.forget(response) # Don't need the session so don't block on it
	#session._unlock(response)
	# Pop off the list an item and process it
	result = Student.ProcessADStudent()

	# Make it call us again until we are done
	response.js = "ImportAD();"

	# Make sure the scheduler is running
	start_process_queue()
	return result

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def student_do_import_canvas():
	session.forget(response) # Don't need the session so don't block on it
	#session._unlock(response)
	# Pop off the list an item and process it
	result = Student.ProcessCanvasStudent()

	# Make it call us again until we are done
	response.js = "ImportCanvas();"

	# Make sure the scheduler is running
	start_process_queue()
	return result

#######################
# Faculty Functions

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def faculty_pick_excel():
	f = None
	excel_output = None
	form = SQLFORM(db.faculty_excel_uploads).process()
	if form.accepted:
		#session.flash = "Processing File."
		f = form.vars.excel_file
		redirect(URL('faculty_show_excel_contents', vars=dict(excel_file=f)))
	elif form.errors:
		response.flash = "Form Errors"
	else:
		response.flash = "Upload Excel file or choose previous import."
	return dict(form=form, file_name=f, out=excel_output)

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def faculty_pick_excel_prev_workbooks():
	delete_id = request.vars.delete_id
	if (delete_id != None):
		# Delete id was passed, remove it
		db(db.faculty_excel_uploads.id==delete_id).delete()
		# This should remove uploaded file too
	rows = db(db.faculty_excel_uploads).select(orderby=~db.faculty_excel_uploads.created_on)
	return dict(rows=rows)

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def faculty_show_excel_contents():
	excel_file = request.vars.excel_file
	return locals()

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def faculty_show_excel_contents_process():
	# Process the files...
	excel_file = request.vars.excel_file
	f = os.path.join(request.folder,'uploads',excel_file)
	excel_output = Faculty.ProcessExcelFile(f)
	response.js = "ImportComplete();"
	return excel_output

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def faculty_show_excel_contents_sheet_dropdown():
	o = [OPTION(cat.sheet_name, _value=cat.sheet_name) for cat in db().select(db.faculty_import_queue.sheet_name, groupby=db.faculty_import_queue.sheet_name)]
	s = SELECT(o, _id='pick_sheet', _onchange="SheetChanged();")
	response.js = "SheetChanged();"

	erase_current_password = INPUT(_type='checkbox', _name='erase_current_password', _id='erase_current_password', _value="False", _onclick='if ($("#erase_current_password").val() == "True") { $("#erase_current_password").val("False"); } else { $("#erase_current_password ").val("True"); }')

	erase_current_quota = INPUT(_type='checkbox', _name='erase_current_quota', _id='erase_current_quota', _value="False", _onclick='if ($("#erase_current_quota").val() == "True") { $("#erase_current_quota").val("False"); } else { $("#erase_current_quota").val("True"); }')

	go = INPUT(_type='button', _name='go', _value='Import Sheet', _onclick='StartImport();')
	return dict(dropdown=s, erase_current_password=erase_current_password, erase_current_quota=erase_current_quota, go_button=go)

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def faculty_show_excel_contents_sheet_grid():
	sheet_name = request.vars.sheet_name
	query = (db.faculty_import_queue.sheet_name==sheet_name)
	#rows = db(query).select()
	g = SQLFORM.grid(query,editable=False, create=False, deletable=False,csv=False,links=False,links_in_grid=False,details=False,searchable=False,orderby=[~db.faculty_import_queue.account_enabled,db.faculty_import_queue.user_id])
	response.js = "ColorDisabledRows();"
	return g

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def faculty_do_import():
	AD.Close()
	sheet_name = request.vars.sheet_name
	erase_current_password = False
	if (request.vars.erase_current_password == "True"):
		erase_current_password = True
	erase_current_quota = False
	if (request.vars.erase_current_quota == "True"):
		erase_current_quota = True

	# Add faculty account to faculty_info table
	count = Faculty.CreateW2PyAccounts(sheet_name, erase_current_password, erase_current_quota)

	# Setup queue for canvas and for ad imports
	count2 = Faculty.QueueActiveDirectoryImports(sheet_name)
	count2 = Faculty.QueueCanvasImports(sheet_name)
	if (count2 > count):
		count = count2
	return dict(sheet_name=sheet_name, count=count)

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def faculty_do_import_ad():
	#session.forget(response) # Don't need the session so don't block on it
	# Pop off the list an item and process it
	result = Faculty.ProcessADFaculty()

	# Make it call us again until we are done
	response.js = "ImportAD();"

	# Make sure the scheduler is running
	start_process_queue()
	return result

@auth.requires(auth.has_membership('Import') or auth.has_membership('Administrators'))
def faculty_do_import_canvas():
	#session.forget(response) # Don't need the session so don't block on it
	# Pop off the list an item and process it
	result = Faculty.ProcessCanvasFaculty()

	# Make it call us again until we are done
	response.js = "ImportCanvas();"

	# Make sure the scheduler is running
	start_process_queue()
	return result


text:
@(group: Group)
@import helper._
@import models.enums.GroupType

				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

					@if(group.groupType == GroupType.close) {

					Gruppe verlassen
					}
					@if(group.groupType == GroupType.open) {

					Gruppe verlassen
					}
					@if(group.groupType == GroupType.course) {

					Kurs verlassen
					}

				Möchtest Du @truncate(group.title,30) wirklich verlassen?

				Ja
				Nein