text:
package in.bigo.saytrees.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONException;
import org.json.JSONObject;

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

import in.bigo.saytrees.R;
import in.bigo.saytrees.activity.LauncherActivity;
import in.bigo.saytrees.adapter.FeedListAdapter;
import in.bigo.saytrees.controller.SharedPreferencesController;
import in.bigo.saytrees.customview.EndlessListView;
import in.bigo.saytrees.model.CompletedEvent;
import in.bigo.saytrees.utils.AppConstants;
import in.bigo.saytrees.utils.AppController;
import in.bigo.saytrees.utils.GPSTracker;

public class VolunteeringFragment extends Fragment implements View.OnClickListener, EndlessListView.EndLessListener {

    LauncherActivity activityVolunteeringFragment;
    private ImageView swachhButton;
    private View rootView;
    private int API_OFFSET = 1;
    private int API_LIMIT = 100;
    private ProgressBar progressBar;
    private EndlessListView listView;
    private FeedListAdapter listAdapter;
    private List<CompletedEvent> feedItems;
    private List<CompletedEvent> returnedfeedItems;
    private String URL_FEED = AppConstants.SERVER_HOST_ADDRESS + AppConstants.FETCH_ALL_ASSIGNED;
    private String URL_SUFFIX1 = "&size=";
    private String URL_SUFFIX2 = "&start=";
    private double latitude, longitude;
    SharedPreferencesController sharedPreferencesController;

    private String TAG = VolunteeringFragment.class.toString();

    public VolunteeringFragment() {
    }

    /**
     * Returns a new instance of this fragment
     */
    public static VolunteeringFragment newInstance() {
        VolunteeringFragment fragment = new VolunteeringFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.fragment_volunteerting, container, false);
        initUI();
        GPSTracker gps = new GPSTracker(this.getActivity());

        // check if GPS enabled
        if (gps.canGetLocation()) {
            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
        } else {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gps.showSettingsAlert();
        }

        URL_FEED += latitude + "," + longitude;

        String latLongValue = latitude + "," + longitude;

        sharedPreferencesController = SharedPreferencesController.getSharedPreferencesController(this.getActivity());
        sharedPreferencesController.getSharedPreferencesEditor();
        sharedPreferencesController.putString("latLong", latLongValue);

        //Log.d("api key", sharedPreferencesController.getString("APIKey"));

        // Dirt Feed code start

        listView = (EndlessListView) rootView.findViewById(R.id.endlesslist);

        feedItems = new ArrayList<CompletedEvent>();
        returnedfeedItems = new ArrayList<CompletedEvent>();

        listAdapter = new FeedListAdapter(this.getActivity(), feedItems);

        listView.setLoadingView(R.layout.loading_layout);
        listView.setListener(new EndlessListView.EndLessListener() {
            @Override
            public void loadData() {
               // Log.d("listview", " inside listener count " + URL_FEED + URL_SUFFIX1 + API_LIMIT + URL_SUFFIX2 + API_OFFSET);

//
//
//                // making fresh volley request and getting json
//                JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL_FEED + URL_SUFFIX1 + API_LIMIT + URL_SUFFIX2 + API_OFFSET, null, new Response.Listener<JSONObject>() {
//
//                    @Override
//                    public void onResponse(JSONObject response) {
//                        VolleyLog.d(TAG, "Response feed: " + response.toString());
//                        if (response != null) {
//
//                            API_OFFSET += API_LIMIT;
//                            returnedfeedItems = new ArrayList<CompletedEvent>();
//                            returnedfeedItems = parseJsonFeed(response);
//                            if (returnedfeedItems != null) {
//                                //  for (int i = 0; i < returnedfeedItems.size(); i++)
//                                //    feedItems.add(returnedfeedItems.get(i));
//
//                                listView.addNewData(returnedfeedItems);
//
//                            }
//                            //progressBar.setVisibility(View.GONE);
//                            //listView.setVisibility(View.VISIBLE);
//                        }
//                    }
//                }, new Response.ErrorListener() {
//
//                    @Override
//                    public void onErrorResponse(VolleyError error) {
//                        VolleyLog.d(TAG, "Error: " + error.getMessage());
//                    }
//                });
//
//                // Adding request to volley request queue
//                AppController.getInstance(getActivity().getApplicationContext()).addToRequestQueue(request);
            }
        });

        listView.setAdapter(listAdapter);

        //Log.d("url work", URL_FEED + URL_SUFFIX1 + API_LIMIT + URL_SUFFIX2 + API_OFFSET);

        // making fresh volley request and getting json
        JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, URL_FEED + URL_SUFFIX1 + API_LIMIT + URL_SUFFIX2 + API_OFFSET, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                VolleyLog.d(TAG, "Response feed: " + response.toString());
                if (response != null) {

                    returnedfeedItems = parseJsonFeed(response);

                    if (returnedfeedItems != null) {
                        for (int i = 0; i < returnedfeedItems.size(); i++)
                            feedItems.add(returnedfeedItems.get(i));

                        // notify data changes to list adapater
                        listAdapter.notifyDataSetChanged();

                        progressBar.setVisibility(View.GONE);
                        listView.setVisibility(View.VISIBLE);

                        API_OFFSET += API_LIMIT;
                    }

                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        }){
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> actualHeader = new HashMap<String, String>();
                String apiKey = sharedPreferencesController.getString("APIKey");
                actualHeader.put("APIKey", apiKey);
                return actualHeader;
            }
        };
        // Adding request to volley request queue
        AppController.getInstance(this.getActivity().getApplicationContext()).addToRequestQueue(req);
        // }

        // Dirt Feed close

        return rootView;
    }

    @Override
    public void loadData() {
        //Log.d("listview", " reached end " + URL_FEED + URL_SUFFIX1 + API_LIMIT + URL_SUFFIX2 + API_OFFSET);

        // making fresh volley request and getting json
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, URL_FEED + URL_SUFFIX1 + API_LIMIT + URL_SUFFIX2 + API_OFFSET, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                VolleyLog.d(TAG, "Response feed: " + response.toString());
                if (response != null) {

                    API_OFFSET += API_LIMIT;
                    returnedfeedItems = new ArrayList<CompletedEvent>();
                    returnedfeedItems = parseJsonFeed(response);
                    if (returnedfeedItems != null) {
                        for (int i = 0; i < returnedfeedItems.size(); i++)
                            feedItems.add(returnedfeedItems.get(i));

                        listView.addNewData(feedItems);

                    }
                    //progressBar.setVisibility(View.GONE);
                    //listView.setVisibility(View.VISIBLE);
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
            }
        });

        // Adding request to volley request queue
        AppController.getInstance(this.getActivity().getApplicationContext()).addToRequestQueue(request);

    }

    /**
     * Parsing json reponse and passing the data to feed view list adapter
     */
    private List<CompletedEvent> parseJsonFeed(JSONObject feedArray) {
        List<CompletedEvent> parsedItems = new ArrayList<CompletedEvent>();
        /*try {

            int length = feedArray.length();
            if (length == 0) {
                CompletedEvent item = new CompletedEvent();
                item.setEventName("No Content available");
                return null;
            }

            Iterator iterator = feedArray.keys();
            while (iterator.hasNext()) {
                String id = iterator.next().toString();
                JSONObject feedObj = (JSONObject) feedArray.get(id);

                CompletedEvent item = new CompletedEvent();
                item.setId(id);
                item.setName(feedObj.getString("userId"));

                // Image might be null sometimes
                String image = feedObj.isNull("imageUrl") ? null : feedObj
                        .getString("imageUrl");
                item.setImage(image);
                item.setStatus(feedObj.getString("status"));
                item.setProfilePic(AppConstants.GRAPH_API_URL + feedObj.getString("userId") + AppConstants.GRAPH_API_IMAGE_SUFFIX);
                item.setTimeStamp(feedObj.getString("timestamp"));
                item.setSeverity(feedObj.getString("severity"));
                item.setDescription(feedObj.getString("description"));
                item.setLatitude((Double) feedObj.getJSONArray("location").get(0));
                item.setLongitude((Double) feedObj.getJSONArray("location").get(1));
                //item.setCommentsCount(feedObj.getInt("commentsCount"));
                //item.setLikesCount(feedObj.getInt("likesCount"));
                //item.setLiked(feedObj.getBoolean("isLiked"));
                item.setUserHandle(feedObj.getString("userhandle"));
                //item.setEmail(feedObj.getString("email"));
                item.setFbUserId(feedObj.getString("userId"));
                item.setLocationAddress(feedObj.getString("locationAddress"));
              //  JSONArray jsonArray = new JSONArray();

//                ArrayList<CommentItem> commentItemArrayList = new ArrayList<CommentItem>();
//
//                jsonArray = feedObj.getJSONArray("comments");
//
//
//                if (jsonArray.length() > 0) {
//                    for (int i = 0; i < jsonArray.length(); i++) {
//                        JSONObject jObj = new JSONObject();
//                        CommentItem commentItem = new CommentItem();
//                        jObj = jsonArray.getJSONObject(i);
//                        commentItem.setComment(jObj.getString("comment"));
//                        commentItem.setDirtId(jObj.getString("dirtId"));
//                        commentItem.setTimestamp(jObj.getString("timestamp"));
//                        commentItem.setUserId(jObj.getString("userId"));
//                        //commentItem.setUserHandle(jObj.getString("userHandle"));
//                        commentItemArrayList.add(commentItem);
//                    }
//                    item.setCommentItems(commentItemArrayList);
//                }

                // url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj
                        .getString("url");
                item.setUrl(feedUrl);

                parsedItems.add(item);
            }
*/
            return parsedItems;

        /*} catch (JSONException e) {
            e.printStackTrace();
            return null;
        }*/
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        this.getActivity().getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void initUI() {

        progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);

    }

    @Override
    public void onResume() {
        super.onResume();
        /**Dynamically*/
      //  Rect bounds = progressBar.getIndeterminateDrawable().getBounds();
      //  progressBar.setIndeterminateDrawable(getProgressDrawable());
      //  progressBar.getIndeterminateDrawable().setBounds(bounds);
    }

//    private Drawable getProgressDrawable() {
//        Drawable progressDrawable = new FoldingCirclesDrawable.Builder(getActivity())
//                .colors(getProgressDrawableColors())
//                .build();
//
//        return progressDrawable;
//    }

    private int[] getProgressDrawableColors() {
        int[] colors = new int[10];
        colors[0] = getResources().getColor(R.color.color_2);
        colors[1] = getResources().getColor(R.color.color_5);
        colors[2] = getResources().getColor(R.color.color_8);
        colors[3] = getResources().getColor(R.color.color_7);
        return colors;
    }

    @Override
    public void onClick(View v) {
        //do what you want to do when button is clicked
        switch (v.getId()) {
            case R.id.swachh:
                //launchSwachhPostActivity();
                break;
        }
    }

//    private void launchSwachhPostActivity() {
//        //Call main activ ity
//        Intent i = new Intent(getActivity(), SwachhPostActivity.class);
//        startActivity(i);
//        getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
//    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        try {
            activityVolunteeringFragment = ((LauncherActivity) activity);
            activityVolunteeringFragment.onSectionAttached(
                    2);
        } catch (Exception e) {
            e.printStackTrace();
            getActivity().finish();
            Intent newIntent = new Intent(getActivity(), LauncherActivity.class);
            startActivity(newIntent);

        }
    }

}


text:
var express = require("express");
var app = express();
var path = require("path");

app.use(express.static('development'));

app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/development/index.html'));
});

app.listen(3000);

redpajama_set_name: RedPajamaGithub


text:
import distutils
from distutils.core import setup, Extension
from distutils.command.build_ext import build_ext
from distutils.cmd import Command
import platform
import os
import re

CURR_DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))

# when compiling for Windows Python 2.7, force distutils to use Visual Studio
# 2010 instead of 2008, as the latter doesn't support c++0x
if platform.system() == 'Windows':
    try:
        import distutils.msvc9compiler
    except distutils.errors.DistutilsPlatformError:
        pass  # importing msvc9compiler raises when running under MinGW
    else:
        orig_find_vcvarsall = distutils.msvc9compiler.find_vcvarsall
        def patched_find_vcvarsall(version):
            return orig_find_vcvarsall(version if version != 9.0 else 10.0)
        distutils.msvc9compiler.find_vcvarsall = patched_find_vcvarsall

def get_version():
    """ Return BROTLI_VERSION string as defined in 'brotlimodule.cc' file. """
    brotlimodule = os.path.join(CURR_DIR, 'python', 'brotlimodule.cc')
    with open(brotlimodule, 'r') as f:
        for line in f:
            m = re.match(r'#define\sBROTLI_VERSION\s"(.*)"', line)
            if m:
                return m.group(1)
    return ""

class TestCommand(Command):
    """ Run all *_test.py scripts in 'tests' folder with the same Python
    interpreter used to run setup.py.
    """

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        import sys, subprocess, glob

        test_dir = os.path.join(CURR_DIR, 'python', 'tests')
        os.chdir(test_dir)

        for test in glob.glob("*_test.py"):
            try:
                subprocess.check_call([sys.executable, test])
            except subprocess.CalledProcessError:
                raise SystemExit(1)

class BuildExt(build_ext):
    def get_source_files(self):
        filenames = build_ext.get_source_files(self)
        for ext in self.extensions:
            filenames.extend(ext.depends)
        return filenames

    def build_extension(self, ext):
        c_sources = []
        cxx_sources = []
        for source in ext.sources:
            if source.endswith(".c"):
                c_sources.append(source)
            else:
                cxx_sources.append(source)
        extra_args = ext.extra_compile_args or []

        objects = []
        for lang, sources in (("c", c_sources), ("c++", cxx_sources)):
            if lang == "c++":
                if platform.system() == "Darwin":
                    extra_args.extend(["-stdlib=libc++", "-mmacosx-version-min=10.7"])
                if self.compiler.compiler_type in ["unix", "cygwin", "mingw32"]:
                    extra_args.append("-std=c++0x")
                elif self.compiler.compiler_type == "msvc":
                    extra_args.append("/EHsc")

            macros = ext.define_macros[:]
            if platform.system() == "Darwin":
                macros.append(("OS_MACOSX", "1"))
            elif self.compiler.compiler_type == "mingw32":
                # On Windows Python 2.7, pyconfig.h defines "hypot" as "_hypot",
                # This clashes with GCC's cmath, and causes compilation errors when
                # building under MinGW: http://bugs.python.org/issue11566
                macros.append(("_hypot", "hypot"))
            for undef in ext.undef_macros:
                macros.append((undef,))

            objs = self.compiler.compile(sources,
                                         output_dir=self.build_temp,
                                         macros=macros,
                                         include_dirs=ext.include_dirs,
                                         debug=self.debug,
                                         extra_postargs=extra_args,
                                         depends=ext.depends)
            objects.extend(objs)

        self._built_objects = objects[:]
        if ext.extra_objects:
            objects.extend(ext.extra_objects)
        extra_args = ext.extra_link_args or []
        # when using GCC on Windows, we statically link libgcc and libstdc++,
        # so that we don't need to package extra DLLs
        if self.compiler.compiler_type == "mingw32":
            extra_args.extend(['-static-libgcc', '-static-libstdc++'])

        ext_path = self.get_ext_fullpath(ext.name)
        # Detect target language, if not provided
        language = ext.language or self.compiler.detect_language(sources)

        self.compiler.link_shared_object(
            objects, ext_path,
            libraries=self.get_libraries(ext),
            library_dirs=ext.library_dirs,
            runtime_library_dirs=ext.runtime_library_dirs,
            extra_postargs=extra_args,
            export_symbols=self.get_export_symbols(ext),
            debug=self.debug,
            build_temp=self.build_temp,
            target_lang=language)

brotli = Extension("brotli",
                    sources=[
                        "python/brotlimodule.cc",
                        "enc/backward_references.cc",
                        "enc/block_splitter.cc",
                        "enc/brotli_bit_stream.cc",
                        "enc/encode.cc",
                        "enc/entropy_encode.cc",
                        "enc/histogram.cc",
                        "enc/literal_cost.cc",
                        "enc/metablock.cc",
                        "enc/static_dict.cc",
                        "enc/streams.cc",
                        "dec/bit_reader.c",
                        "dec/decode.c",
                        "dec/huffman.c",
                        "dec/streams.c",
                        "dec/state.c",
                    ],
                    depends=[
                        "enc/backward_references.h",
                        "enc/bit_cost.h",
                        "enc/block_splitter.h",
                        "enc/brotli_bit_stream.h",
                        "enc/cluster.h",
                        "enc/command.h",
                        "enc/context.h",
                        "enc/dictionary.h",
                        "enc/dictionary_hash.h",
                        "enc/encode.h",
                        "enc/entropy_encode.h",
                        "enc/fast_log.h",
                        "enc/find_match_length.h",
                        "enc/hash.h",
                        "enc/histogram.h",
                        "enc/literal_cost.h",
                        "enc/metablock.h",
                        "enc/port.h",
                        "enc/prefix.h",
                        "enc/ringbuffer.h",
                        "enc/static_dict.h",
                        "enc/static_dict_lut.h",
                        "enc/streams.h",
                        "enc/transform.h",
                        "enc/write_bits.h",
                        "dec/bit_reader.h",
                        "dec/context.h",
                        "dec/decode.h",
                        "dec/dictionary.h",
                        "dec/huffman.h",
                        "dec/prefix.h",
                        "dec/port.h",
                        "dec/streams.h",
                        "dec/transform.h",
                        "dec/types.h",
                        "dec/state.h",
                    ],
                    language="c++",
                    )

setup(
    name="Brotli",
    version=get_version(),
    url="https://github.com/google/brotli",
    description="Python binding of the Brotli compression library",
    author="Khaled Hosny",
    author_email="khaledhosny@eglug.org",
    license="Apache 2.0",
    ext_modules=[brotli],
    cmdclass={
        'build_ext': BuildExt,
        'test': TestCommand
        },
)


text:
// Production specific configuration
// =================================
/* eslint key-spacing: 0*/
module.exports = {
  // Server IP
  ip:       process.env.OPENSHIFT_NODEJS_IP ||
            process.env.IP ||
            undefined,

  // Server port
  port:     process.env.OPENSHIFT_NODEJS_PORT ||
            process.env.PORT ||
            8080,

  // MongoDB connection options
  mongo: {
    uri:    process.env.MONGOLAB_URI ||
            process.env.MONGOHQ_URL ||
            process.env.OPENSHIFT_MONGODB_DB_URL + process.env.OPENSHIFT_APP_NAME ||
            'mongodb://localhost/michalBlog'
  },

  corsOptions: {
    origin: function(origin, callback){
      const whitelist = ['http://localhost:9000'];

      var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
      callback(null, originIsWhitelisted);
    }
  }
};


text:
package com.yahoo.athenz.instance.provider;

import org.testng.annotations.Test;

import java.util.HashMap;

import static org.testng.Assert.*;

public class InstanceConfirmationTest {

    @SuppressWarnings("unlikely-arg-type")
    @Test
    public void testInstanceConfirmationEquals() {
        InstanceConfirmation confirm = new InstanceConfirmation();
        assertEquals(confirm, confirm);
        //noinspection ConstantConditions,ObjectEqualsNull,SimplifiedTestNGAssertion
        assertFalse(confirm.equals(null));
        assertNotEquals("invalid-class", confirm);

        InstanceConfirmation confirm2 = new InstanceConfirmation();
        assertEquals(confirm, confirm2);

        confirm.setAttestationData("data");
        assertNotEquals(confirm, confirm2);
        confirm2.setAttestationData("data-fail");
        assertNotEquals(confirm, confirm2);
        confirm2.setAttestationData("data");
        assertEquals(confirm, confirm2);

        confirm.setDomain("domain");
        assertNotEquals(confirm, confirm2);
        confirm2.setDomain("domain-fail");
        assertNotEquals(confirm, confirm2);
        confirm2.setDomain("domain");
        assertEquals(confirm, confirm2);

        confirm.setService("service");
        assertNotEquals(confirm, confirm2);
        confirm2.setService("service-fail");
        assertNotEquals(confirm, confirm2);
        confirm2.setService("service");
        assertEquals(confirm, confirm2);

        confirm.setProvider("provider");
        assertNotEquals(confirm, confirm2);
        confirm2.setProvider("provider-fail");
        assertNotEquals(confirm, confirm2);
        confirm2.setProvider("provider");
        assertEquals(confirm, confirm2);

        HashMap<String, String> attributes = new HashMap<>();
        confirm.setAttributes(attributes);
        assertNotEquals(confirm, confirm2);
        HashMap<String, String> attributes2 = new HashMap<>();
        attributes2.put("key", "value");
        confirm2.setAttributes(attributes2);
        assertNotEquals(confirm, confirm2);
        attributes.put("key", "value");
        assertEquals(confirm, confirm2);
    }
}


text:
import { AppState } from './app-state'

export const INITIAL_STATE: AppState = {
  todos: [],
  filter: 'ALL'
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WhatForensics
{
    public partial class SearchSettingsView : Form
    {
        public SearchSettingsView()
        {
            InitializeComponent();
        }

        public string connectionString = "";

        private void btnSearch_Click(object sender, EventArgs e)
        {
            performSearch();
        }

        private void performSearch()
        {
            MessageView messageView = new MessageView();
            messageView.Text = "Search results for " + txtSearchQuery.Text;

            messageView.IsGroupMessage = false;
            messageView.InitializeMessages(0, connectionString, txtSearchQuery.Text);
            messageView.Show();

            this.Close();

        }

        private void txtSearchQuery_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                e.Handled = true;
                performSearch();
            }

        }
    }
}


text:
cask 'ilok-license-manager' do
  version :latest
  sha256 :no_check

  url 'https://installers.ilok.com/iloklicensemanager/LicenseSupportInstallerMac.zip'
  name 'iLok License Manager'
  homepage 'https://ilok.com/#!license-manager'

  pkg 'License Support.pkg'

  uninstall pkgutil:   [
                         'com.paceap.pkg.eden.iLokLicenseManager',
                         'com.paceap.pkg.eden.licensed',
                         'com.paceap.pkg.eden.activationexperience',
                       ],
            launchctl: 'com.paceap.eden.licensed'
end


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

<title>B-Index</title>
<meta name="date" content="2015-09-30">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

B C E G H I L M N O P S T U V W

B

BasicFileHttpHandler - Class in com.jessieamorris.httpserver.handlers

A simple implementation of a file serving HTTP handler.

BasicFileHttpHandler() - Constructor for class com.jessieamorris.httpserver.handlers.BasicFileHttpHandler

BasicFileHttpHandlerTest - Class in com.jessieamorris.httpserver.tests

Created by jessie.

BasicFileHttpHandlerTest() - Constructor for class com.jessieamorris.httpserver.tests.BasicFileHttpHandlerTest

B C E G H I L M N O P S T U V W

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
hyperstream.itertools2 package
==============================

Submodules
----------

hyperstream.itertools2.itertools2 module
----------------------------------------

.. automodule:: hyperstream.itertools2.itertools2
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: hyperstream.itertools2
    :members:
    :undoc-members:
    :show-inheritance:


text:
package hello

import (
	"fmt"

	"github.com/FogCreek/victor"
	"github.com/groob/radigast/plugins"
)

// Configuration struct
// toml will unmarshal any options provided under [hello] in
// radigast.toml
type Hello struct {
	// AnOption      string
	// AnotherOption string
}

// Register implements plugins.Registrator
func (h Hello) Register() []victor.HandlerDocPair {
	var handlers []victor.HandlerDocPair
	handlers = append(handlers,
		&victor.HandlerDoc{
			CmdHandler:     h.helloFunc,
			CmdName:        "hello",
			CmdDescription: "reply back with the user name",
			CmdUsage:       []string{"NAME"},
		},
		&victor.HandlerDoc{
			CmdHandler:     h.byeFunc,
			CmdName:        "bye",
			CmdDescription: "Tell someone GoodBye",
			CmdUsage:       []string{"NAME"},
		},
	)
	return handlers
}

// Bot Handler
// write your plugin logic here.
func (h Hello) helloFunc(s victor.State) {
	msg := fmt.Sprintf("Hello %s!", s.Message().User().Name())
	s.Chat().Send(s.Message().Channel().ID(), msg)
}

// another handler for the hello plugin
func (h Hello) byeFunc(s victor.State) {
	msg := fmt.Sprintf("Bye %s!", s.Message().User().Name())
	s.Reply(msg)
}

func init() {
	// register the plugin
	plugins.Add("hello", func() plugins.Registrator {
		return &Hello{}
	})
}


text:
Glaze TODO
=====

## Multiple elements for multiple array items
```php
	glazyMultipleElements('p', array(
		'Paragraph 1',
		'Paragraph 2',
		'Paragraph 3'
	));

	glazyPrepareMultipleElements('p', $descriptionLines);
```

## Register your own escaping functions
```php
	define('EXAMPLE_SPECIAL_URL_FINDER', 'EXAMPLE_SPECIAL_URL_FINDER');

	function exampleSpecialURLFinder($content) {
		$content = ...

		return $content;
	}

	glazyRegisterContentTransformer(EXAMPLE_SPECIAL_URL_FINDER, 'exampleSpecialURLFinder');
	glazyContent('Make this a <a> link: http://www.burntcaramel.com/');

	define('GARNISH_ORDINAL_GLAZE_TYPE', 'GARNISH_ORDINAL_GLAZE_TYPE');

	glazyRegisterContentType(GARNISH_ORDINAL_GLAZE_TYPE, 'garnishNumberWithOrdinals');
	glazyContent(22, GARNISH_ORDINAL_GLAZE_TYPE); // 22nd
```

## Preparing and changing elements
```php
	define('EXAMPLE_INFO_TYPE', 'EXAMPLE_INFO_TYPE');

	function exampleInfoTypeTransformer($info) {
		$preparedContent = ...

		return $preparedContent;
	}

	glazyRegisterInfoType(EXAMPLE_INFO_TYPE, 'exampleInfoTypeTransformer');

	$preparedInfo = glazyPrepareInfo('uniqueType', array(
		'associativeArray' => 1,
		'ofAnything' => 5.0,
		'youNeed' => true
	));

	glazyServe($preparedInfo);
```

## Doesn't support siblings text with elements

Displaying inside `glazyBegin()` with echoed text then an element such as a `<span>` then more text will group the text together at the end. A way around this is to echo all output as unique identifiers, such as `{glazy_RANDOM_element34_begin}`, `{glazy_RANDOM_element34_finish}` and find and replace after all tags and attributes.

## Serve to arbitrary strings
http://evertpot.com/222/


text:
;
var assign = require('tslib').__assign

module.exports = function (config) {
  'use strict'
  require('./karma.conf.js')(config) // setup test config
  require('../support/karma-coverage.conf.js')(config) // add coverage
  config.set({ // overwrites arrays
    coverageReporter: assign({}, config.coverageReporter, {
      dir: '../reports/coverage/worker'
    })
  })
}


text:
"""
This is a convenience module that imports a set of platform-dependent
defaults.
"""

from misc.utils import ensurepath
ensurepath(["/sbin", "/bin", "/usr/sbin", "/usr/bin"])
del ensurepath

from session import Session

import os

if os.uname()[0] == "Linux":
    from netns import nodes
    try:
        from xen import xen
    except ImportError:
        #print "Xen support disabled."
        pass
elif os.uname()[0] == "FreeBSD":
    from bsd import nodes
from phys import pnodes
del os


text:
package edu.villanova.ece.inv.manager;

import android.os.Handler;
import android.os.Looper;
import android.util.Base64;
import android.util.Log;

import com.breadtech.util.HttpTask;
import com.breadtech.util.HttpTask.HttpResponder;
import com.google.gson.Gson;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import javax.net.ssl.HttpsURLConnection;

import edu.villanova.ece.inv.model.Asset;
import edu.villanova.ece.inv.model.Inventory;
import edu.villanova.ece.inv.model.Item;
import edu.villanova.ece.inv.model.Label;
import edu.villanova.ece.inv.model.Location;
import edu.villanova.ece.inv.model.Token;
import edu.villanova.ece.inv.model.User;

/**
 * Created by bk on 7/27/15.
 */
public class ApiManager {

    // constants
    private static final String API_URL = "https://ceer-008-t430-2.villanova.edu/api/v1/";
    // private static final String API_URL = "http://153.104.46.199:5000/api/v1/";
    private static final String USER_URL = API_URL + "user";
    private static final String SELF_URL = USER_URL + "/me";
    private static final String ITEM_URL = API_URL + "item";
    private static final String CATEGORY_URL = ITEM_URL + "/category";
    private static final String MANUFACTURER_URL = ITEM_URL + "/manufacturer";
    private static final String LOCATION_URL = API_URL + "location";
    private static final String BUILDING_URL = LOCATION_URL + "/building";
    private static final String ASSET_URL = API_URL + "asset";
    private static final String INV_URL = API_URL + "inv";
    private static final String TAG = "ApiManager";

    // api convenience methods
    private static String user_url( String id ) { return USER_URL+'/'+id; }
    private static String item_url( int id ) { return ITEM_URL+'/'+id; }
    private static String location_url( int id ) { return LOCATION_URL+'/'+id; }
    private static String asset_url( String id ) { return ASSET_URL+'/'+id; }
    private static String inv_url( int id ) { return INV_URL+'/'+id; }

    // convenience method to return the right url for the given class
    public static String mkurl( Class type ) {
        return mkurl(type, 0);
    }

    public static String mkurl( Class type, int id ) {
        String url = API_URL;
        if      (type == User.class)      url = id>0 ? user_url("")     : USER_URL;
        else if (type == Item.class)      url = id>0 ? item_url(id)     : ITEM_URL;
        else if (type == Location.class)  url = id>0 ? location_url(id) : LOCATION_URL;
        else if (type == Asset.class)     url = id>0 ? asset_url("")    : ASSET_URL;
        else if (type == Inventory.class) url = id>0 ? inv_url(id)      : INV_URL;
        else if (type == Label.ItemCategory.class) url = CATEGORY_URL;
        else if (type == Label.ItemManufacturer.class) url = MANUFACTURER_URL;
        else if (type == Label.LocationBuilding.class) url = BUILDING_URL;
        return url;
    }
    public static String mkurl( Class type, String id ) {
        String url = API_URL;
        if      (type == User.class)      url = id.equals("") ? USER_URL : user_url(id);
        else if (type == Asset.class)     url = id.equals("") ? ASSET_URL : asset_url(id);
        return url;
    }

    // convenience method to construct an api request
    private static HttpURLConnection makeUrlConnection( String url_s, String uname, String passwd ) {
        HttpURLConnection conn = null;
        try {
            URL url = new URL(url_s);
            conn = (HttpURLConnection) url.openConnection();
            if (conn.getClass() == HttpsURLConnection.class) {
                HttpsURLConnection sconn = (HttpsURLConnection)conn;
            }
            String authInfo = new String(Base64.encode((uname + ':' + passwd).getBytes(), Base64.NO_WRAP));
            String basicAuth = "Basic "+authInfo;
            conn.setRequestProperty("Authorization", basicAuth);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    private static HttpURLConnection makeUrlConnection( String url_s, String token ) {
        return makeUrlConnection(url_s, token, "");
    }

    // convenience method to convert object to json

    public static String obj2urlencode( Object obj ) {
        String y = "";
        String json_str = new Gson().toJson(obj);
        try {
            JSONObject jsonobj = new JSONObject(json_str);
            Iterator<String> it = jsonobj.keys();
            do {
                String key = it.next();
                y += key+'='+jsonobj.getString(key);
                if (it.hasNext()) y += '&';
            } while(it.hasNext());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return y;
    }

    // handling token based authentication
    public static void getToken( String uname, String passwd, int expire, final TokenDelegate delegate) {
        // construct the http connection
        String query = "expire="+expire;
        HttpURLConnection conn = makeUrlConnection(API_URL, uname, passwd);
        HttpResponder responder = new HttpResponder() {
            @Override
            public void success() {
                // convert the json to token
                Token t = new Gson().fromJson(body, Token.class);
                // tell the delegate that we got the token
                delegate.gotToken(t.getToken());
            }

            @Override
            public void failure()
            {
                delegate.getTokenFailed(code,body);
            }
        };

        // execute the http connection
        new HttpTask(conn,responder,query).execute((Void) null);
    }

    public static void getToken( String token, int expire, final TokenDelegate delegate) {
        getToken(token, "", expire, delegate);
    }

    // user information
    public static void getUser( String token, final GetMethodDelegate delegate ) {
        // construct the http connection
        HttpURLConnection conn = makeUrlConnection(SELF_URL, token);
        HttpResponder responder = new HttpResponder() {
            @Override
            public void success() {
                final User user = new Gson().fromJson(body, User.class);
                // alert the delegate that login is successful
                delegate.gotEntity(user);
            }

            @Override
            public void failure() {
                delegate.getEntityFailed(code,body);
            }
        };
        // execute the http connection
        new HttpTask(conn,responder).execute((Void) null);
    }

    // generic method to make api requests
    public static void getEntity( final Class type, int id, String token, final GetMethodDelegate delegate ) {
        // determine the correct url to use
        String url = mkurl(type, id);
        HttpURLConnection conn = makeUrlConnection( url, token );

        // construct the http connection
        HttpResponder responder = new HttpResponder() {
            @Override
            public void success() {
                Object obj = new Gson().fromJson(body, type);
                // alert the delegate that login is successful
                delegate.gotEntity(obj);
            }

            @Override
            public void failure() {
                delegate.getEntityFailed(code,body);
            }
        };

        // execute the http connection
        new HttpTask(conn,responder).execute((Void) null);
    }

    public static void getEntityAll( final Class type, String token, final GetAllMethodDelegate delegate ) {
        // determine the correct url to use
        String url = mkurl(type);
        HttpURLConnection conn = makeUrlConnection( url, token );

        // construct the http connection
        HttpResponder responder = new HttpResponder() {
            @Override
            public void success() {
                ArrayList list = new ArrayList();
                try {
                    // convert the body into the json array
                    JSONArray array = new JSONArray(body);
                    int n = array.length();
                    if (n==0) {
                        delegate.gotEntityAll(type,new ArrayList());
                        return;
                    }
                    // break down the json array and convert to a list of java objects
                    for (int i = 0; i < n; i++) {
                        JSONObject obj = array.getJSONObject(i);
                        list.add( new Gson().fromJson(obj.toString(),type));
                    }
                    // alert the delegate that the entities have been fetched
                    delegate.gotEntityAll(type,list);
                }
                catch (Exception e) {
                    e.printStackTrace();
                    delegate.getEntityFailed(code,"Bad JSON");
                }
            }

            @Override
            public void failure() {
                delegate.getEntityFailed(code,body);
            }
        };

        // execute the http connection
        new HttpTask(conn,responder).execute((Void) null);
    }

    // generic method to make api requests (for items, locations, and invs)
    public static void setEntity( final Class type, int id, Object obj, String token, final SetMethodDelegate delegate ) {
        // determine the correct url to use
        String url = mkurl(type, id);
        HttpURLConnection conn = makeUrlConnection( url, token );
        try {
            // customize the url for doing an update
            conn.setRequestMethod("PUT");
        }
        catch (ProtocolException e) {
            e.printStackTrace();

        }

        // construct the http connection
        HttpResponder responder = new HttpResponder() {
            @Override
            public void success() {
                Object obj = new Gson().fromJson(body, type);
                // alert the delegate that login is successful
                delegate.setEntitySuccess(obj);
            }

            @Override
            public void failure() {
                delegate.setEntityFailure(code,body);
            }
        };

        String query = obj2urlencode(obj);
        // execute the http connection
        new HttpTask(conn,responder,query).execute((Void) null);
    }

    // generic method to make api requests (for users and assets)
    public static void setEntity( final Class type, String id, Object obj, String token, final SetMethodDelegate delegate ) {
        // determine the correct url to use
        String url = mkurl(type, id);
        HttpURLConnection conn = makeUrlConnection( url, token );
        try {
            // customize the url for doing an update
            conn.setRequestMethod("PUT");
        }
        catch (ProtocolException e) {
            e.printStackTrace();

        }

        // construct the http connection
        HttpResponder responder = new HttpResponder() {
            @Override
            public void success() {
                Object obj = new Gson().fromJson(body, type);
                // alert the delegate that login is successful
                delegate.setEntitySuccess(obj);
            }

            @Override
            public void failure() {
                delegate.setEntityFailure(code,body);
            }
        };

        String query = obj2urlencode(obj);
        // execute the http connection
        new HttpTask(conn,responder,query).execute((Void) null);
    }

    // generic method to make api requests
    public static void addEntity( final Class type, Object obj, String token, final AddMethodDelegate delegate ) {

        // determine the correct url to use
        String url = mkurl(type);
        HttpURLConnection conn = makeUrlConnection( url, token );

        Log.d( "APIManager", conn.toString() + "\t" + obj.toString() );
        // construct the http connection
        HttpResponder responder = new HttpResponder() {
            @Override
            public void success() {
                Object obj = new Gson().fromJson(body, type);
                // alert the delegate that login is successful
                delegate.addEntitySuccess(obj);
            }

            @Override
            public void failure() {
                delegate.addEntityFailure(code, body);
            }
        };

        String query = obj2urlencode(obj);
        // execute the http connection
        new HttpTask(conn,responder,query).execute((Void) null);
    }

    // generic method to make api requests
    public static void deleteEntity( final Class type, int id, String token, final RemoveMethodDelegate delegate ) {
        // determine the correct url to use
        String url = mkurl(type, id);
        HttpURLConnection conn = makeUrlConnection( url, token );
        try {
            // customize the url for doing an update
            conn.setRequestMethod("DELETE");
        }
        catch (ProtocolException e) {
            e.printStackTrace();
        }

        // construct the http connection
        HttpResponder responder = new HttpResponder() {
            @Override
            public void success() {
                // alert the delegate that login is successful
                delegate.removeEntitySuccess(body);
            }

            @Override
            public void failure() {
                delegate.removeEntityFailure(code,body);
            }
        };

        // execute the http connection
        new HttpTask(conn,responder).execute((Void) null);
    }

    // generic method to make api requests
    public static void deleteEntity( final Class type, String id, String token, final RemoveMethodDelegate delegate ) {
        // determine the correct url to use
        String url = mkurl(type, id);
        HttpURLConnection conn = makeUrlConnection( url, token );
        try {
            // customize the url for doing an update
            conn.setRequestMethod("DELETE");
        }
        catch (ProtocolException e) {
            e.printStackTrace();
        }

        // construct the http connection
        HttpResponder responder = new HttpResponder() {
            @Override
            public void success() {
                // alert the delegate that login is successful
                delegate.removeEntitySuccess(body);
            }

            @Override
            public void failure() {
                delegate.removeEntityFailure(code,body);
            }
        };

        // execute the http connection
        new HttpTask(conn,responder).execute((Void) null);
    }

    // inner class definition of delegate response to method calls
    public interface TokenDelegate {
        public void gotToken(String t);
        public void getTokenFailed(int code, String reason);
    }

    public interface GetMethodDelegate {
        public void gotEntity(Object obj);
        public void getEntityFailed(int code, String info);
    }

    public interface GetAllMethodDelegate {
        public void gotEntityAll(Class type, ArrayList obj);
        public void getEntityFailed(int code, String info);
    }
    public interface SetMethodDelegate {
        public void setEntitySuccess(Object item);

        public void setEntityFailure(int code, String reason);
    }
    public interface AddMethodDelegate {
        public void addEntitySuccess(Object item);

        public void addEntityFailure(int code, String reason);
    }
    public interface RemoveMethodDelegate {
        public void removeEntitySuccess(String msg);
        public void removeEntityFailure(int code, String reason);
    }
}


text:
var mongodb = require('mongodb');
var fs = require('fs');
var breezeMongo = require('breeze-mongodb');

//var MongoQuery = breezeMongo.MongoQuery;
//var MongoSaveHandler = breezeMongo.MongoSaveHandler;

var host = 'localhost';
var port = 27017;
var dbName = 'NorthwindIB';
var dbServer = new mongodb.Server(host, port, { auto_reconnect: true});
var db = new mongodb.Db(dbName, dbServer, { strict:true, w: 1});
db.open(function () {

});

exports.getMetadata = function(req, res, next) {
    var filename = "metadata.json";
    if (!fs.existsSync(filename)) {
        next(new Error("Unable to locate file: " + filename));
    }
    var metadata = fs.readFileSync(filename, 'utf8');
    res.sendfile(filename);
}

exports.get = function (req, res, next) {

    var slug = req.params.slug;
    if (namedQuery[slug]) {
        namedQuery[slug](req, res, next);
    } else {
        var query = new breezeMongo.MongoQuery(req.query);
        query.execute(db, slug, processResults(res, next));
    }
};

exports.getProducts = function(req, res, next) {
    var query = new breezeMongo.MongoQuery(req.query);
    // add your own filters here
    query.execute(db, "Products", processResults(res, next));
}

exports.saveChanges = function(req, res, next) {
    var saveHandler = new breezeMongo.MongoSaveHandler(db, req.body, processResults(res, next));
    saveHandler.beforeSaveEntity = beforeSaveEntity;
    saveHandler.beforeSaveEntities = beforeSaveEntities;
    saveHandler.save();
};

function beforeSaveEntity(entity) {
    if ( entity.entityAspect.entityTypeName.indexOf("Region") >= 0 && entity.entityAspect.entityState == "Added") {
        if (entity.RegionDescription.toLowerCase().indexOf("error") === 0) return false;
    }
    return true;
}

function beforeSaveEntities(callback) {
    var tag = this.saveOptions.tag;
    if (tag === "increaseProductPrice") {
        this.registerEntityType("Product", "Products", "Identity");
    }
    var categories = this.saveMap["Category"] || [];
    categories.forEach(function(cat) {
       // NOT YET IMPLEMENTED

    });
    callback();
}

// C# version
//protected override Dictionary<Type, List<EntityInfo>> BeforeSaveEntities(Dictionary<Type, List<EntityInfo>> saveMap) {
//    if ((string)SaveOptions.Tag == "increaseProductPrice") {
//        Dictionary<Type, List<EntityInfo>> saveMapAdditions = new Dictionary<Type, List<EntityInfo>>();
//        foreach (var type in saveMap.Keys) {
//            if (type == typeof(Category)) {
//                foreach (var entityInfo in saveMap[type]) {
//                    if (entityInfo.EntityState == EntityState.Modified) {
//                        Category category = (entityInfo.Entity as Category);
//                        var products = this.Context.Products.Where(p => p.CategoryID == category.CategoryID);
//                        foreach (var product in products) {
//                            if (!saveMapAdditions.ContainsKey(typeof(Product)))
//                                saveMapAdditions[typeof(Product)] = new List<EntityInfo>();
//
//                            var ei = this.CreateEntityInfo(product, EntityState.Modified);
//                            ei.ForceUpdate = true;
//                            var incr = (Convert.ToInt64(product.UnitPrice) % 2) == 0 ? 1 : -1;
//                            product.UnitPrice += incr;
//                            saveMapAdditions[typeof(Product)].Add(ei);
//                        }
//                    }
//                }
//            }
//        }
//        foreach (var type in saveMapAdditions.Keys) {
//            if (!saveMap.ContainsKey(type)) {
//                saveMap[type] = new List<EntityInfo>();
//            }
//            foreach (var enInfo in saveMapAdditions[type]) {
//                saveMap[type].Add(enInfo);
//            }
//        }
//        return saveMap;
//    }
//
//    return base.BeforeSaveEntities(saveMap);

exports.saveWithFreight = function(req, res, next) {
    var saveHandler = new breezeMongo.MongoSaveHandler(db, req.body, processResults(res, next));
    saveHandler.beforeSaveEntity = checkFreightOnOrder;
    saveHandler.save(db, req.body, processResults(res,next));
}

exports.saveWithFreight2 = function(req, res, next) {
    var saveHandler = new breezeMongo.MongoSaveHandler(db, req.body, processResults(res, next));
    saveHandler.beforeSaveEntities = checkFreightOnOrders;
    saveHandler.save(db, req.body, processResults(res,next));
}

exports.saveWithExit = function(req, res, next) {
    res.setHeader("Content-Type:", "application/json");
    results = {
        insertedKeys: [],
        deletedKeys: [],
        updatedKeys: [],
        keyMappings: [],
        entitiesCreatedOnServer: []
    }
    res.send(results);
}

function checkFreightOnOrder(order) {
    if (this.saveOptions.tag === "freight update") {
        order.Freight = order.Freight + 1;
    } else if (this.saveOptions.tag === "freight update-ov") {
        order.Freight = order.Freight + 1;
        order.entityAspect.originalValuesMap["Freight"] = null;
    } else if (this.saveOptions.tag === "freight update-force") {
        order.Freight = order.Freight + 1;
        order.entityAspect.forceUpdate = true;
    }
    return true;
}

function checkFreightOnOrders(callback) {
    var orderTypeName = this.qualifyTypeName("Order");
    var orders = this.saveMap[orderTypeName] || [];
    var fn = checkFreightOnOrder.bind(this);
    orders.forEach(function(order) {
        fn(order);
    });
    callback();
}

exports.saveWithComment = function(req, res, next) {
    var saveHandler = new breezeMongo.MongoSaveHandler(db, req.body, processResults(res, next));
    var dataProperties = [ {
        name: "_id",
        dataType: "MongoObjectId"
    }];

    saveHandler.registerEntityType("Comment", "Comments", "Identity", dataProperties);
    saveHandler.beforeSaveEntities = function(callback) {
        var tag = this.saveOptions.tag;
        var entity = {
            Comment1: (tag == null) ? "Generic comment" : tag,
            CreatedOn: new Date(),
            SeqNum: 1
        };
        this.addToSaveMap(entity, "Comment");
        callback();
    }
    saveHandler.save(db, req.body, processResults(res,next));

}

var namedQuery = {};

namedQuery.EmployeesMultipleParams = function(req, res, next) {
    var query = new breezeMongo.MongoQuery(req.query);
    var empId = req.query.employeeId;
    var city = req.query.city;
    query.filter = { "$or": [{ "_id": empId }, { "city": city }] };
    query.execute(db, "Employees", processResults(res, next));
};

namedQuery.CompanyNames = function(req, res, next) {
    executeQuery(db, "Customers", { select: { "CompanyName": 1, "_id": 0 }}, processResults(res, next));
};

namedQuery.CompanyNamesAndIds = function(req, res, next) {
    var query = new breezeMongo.MongoQuery(req.query);
    query.select = { "CompanyName": 1, "_id": 1 };
    query.execute(db, "Customers", processResults(res, next));
};

namedQuery.CustomersStartingWithA = function(req, res, next) {
    var query = new breezeMongo.MongoQuery(req.query);
    query.filter["CompanyName"] = new RegExp("^A",'i' ) ;
    query.execute(db, "Customers", processResults(res, next));
};

namedQuery.CustomersStartingWith = function(req, res, next) {
    // start with client query and add an additional filter.
    var query = new breezeMongo.MongoQuery(req.query);
    var companyName = req.query.companyName;
    if (companyName === undefined) {
       next(new Error("Unable to find 'companyName' parameter"));
       return;
    }
    query.filter["CompanyName"] =  new RegExp("^"+companyName,'i' );
    query.execute(db, "Customers", processResults(res, next));
};

namedQuery.CustomerWithScalarResult = function(req, res, next) {
    var query = new breezeMongo.MongoQuery(req.query);
    query.options.limit = 1;
    query.resultEntityType = "Customer";
    query.execute(db, "Customers", processResults(res, next));
};

namedQuery.CustomersWithHttpError = function(req, res, next) {
    var err = { statusCode: 404, message: "Unable to do something"  };
    next(err);
};

namedQuery.EmployeesFilteredByCountryAndBirthdate= function(req, res, next) {
    var query = new breezeMongo.MongoQuery(req.query);
    var birthDate = new Date(Date.parse(req.query.birthDate));
    var country = req.query.country;
    query.filter["BirthDate"] = { "$gte": birthDate };
    query.filter["Country"] = country ;
    query.execute(db, "Employees", processResults(res, next));
};

// not yet implemented
//public Object CustomerCountsByCountry() {
//    return ContextProvider.Context.Customers.GroupBy(c => c.Country).Select(g => new { g.Key, Count = g.Count() });

// need expand support for these.
//public IQueryable<Object> CustomersWithBigOrders() {
//    var stuff = ContextProvider.Context.Customers.Select(c => new { Customer = c, BigOrders = c.Orders.Where(o => o.Freight > 100) });

//public IQueryable<Object> CompanyInfoAndOrders() {
//    var stuff = ContextProvider.Context.Customers.Select(c => new { c.CompanyName, c.CustomerID, c.Orders });

//public Object CustomersAndProducts() {
//    var stuff = new { Customers = ContextProvider.Context.Customers.ToList(), Products = ContextProvider.Context.Products.ToList() };

//public IQueryable<Customer> CustomersAndOrders() {
//    var custs = ContextProvider.Context.Customers.Include("Orders");

//public IQueryable<Order> OrdersAndCustomers() {
//    var orders = ContextProvider.Context.Orders.Include("Customer");

// if you don't want to use a Mongo query
function executeQuery(db, collectionName, query, fn) {
    var that = this;
    db.collection(collectionName, {strict: true} , function (err, collection) {
        if (err) {
            err = { statusCode: 404, message: "Unable to locate: " + collectionName, error: err };
            fn(err, null);
            return;
        }

        // Mongo doesn't handle limit = 0 as a real limit.
        if (query.options && query.options.limit && query.options.limit === 0) {
            fn(err, []);
            return;
        }

        var src = collection.find(query.filter || {}, query.select || {}, query.options || {});
        src.toArray(function (err, results) {
            results == results || [];
            if (query.resultEntityType) {
                results.forEach(function(r) { r.$type = query.resultEntityType} )
            }
            fn(err, results || []);
        });

    });

};

function processResults(res, next) {

    return function(err, results) {
        if (err) {
            next(err);
        } else {
            res.setHeader("Content-Type:", "application/json");
            res.send(results);
        }
    }
}


text:
{% if page.url == "/" %}

  <link rel="stylesheet" href="{{ "/css/galeries.css" | prepend: site.baseurl }}">

{% endif %}

{% if page.kenburns-images %}

{% elsif page.header-img %}

{% else %}

{% endif %}
    {% if page.kenburns-images %}

    {% else %}

    {% endif %}

{{ page.title }}

	    {% if page.subtitle %}

{{ page.subtitle }}

	    {% endif %}

	{% if page.kenburns-images %}
	<canvas id="kenburns"></canvas>
	{% for image in page.kenburns-images %}

	{% endfor %}
	{% endif %}

{% if page.url == "/" %}

{% endif %}


text:
/// <reference path="./Log.ts" />
/// <reference path="./Chat.ts" />

module chat {
    export class ChatBoard {
        private board_: HTMLElement;
        private sender_: HTMLElement;
        private group_: number;
        private user_: number;
        private chat_: Chat;

        constructor(board: HTMLElement, sender: HTMLElement, group: number, user: number) {
            this.board_ = board;
            this.sender_ = sender;
            this.group_ = group;
            this.user_ = user;
            this.chat_ = new Chat(group, user);

            this.postReadLog();
            this.sender_.onsubmit = () => {
                var value: string = this.sender_['chat-text'].value || '';
                this.sender_['chat-text'].value = '';
                if (value.length > 0) {
                    this.chat_.sendMessage(value, (chat) => { });
                }
            };
       }

        postReadLog(): void {
            var manager = player.UserManager.instance();
            this.chat_.postReadLog((chat) => {
                    var html: string = '';
                    chat.getLogs().forEach((v) => {
                        html += '
' + manager.find(v.user).name + ' : ' + v.text + '
'
                        });
                    this.board_.innerHTML = html;

                    // タイマーで定期的に取得
                    var timer = util.Timer.createTimer('chat', this.postReadLog, this);
                    timer.setInterval(util.TimeUnit.fromMillis(500));
                    timer.start();
                },
                (chat) => {
                    // タイマーで定期的に取得
                    var timer = util.Timer.createTimer('chat', this.postReadLog, this);
                    timer.setInterval(util.TimeUnit.fromMillis(500));
                    timer.start();
                });
        }
    }
}


text:
module Rack
  class Runtime
    require_relative "runtime/version"

    attr_reader :startstamp
    private :startstamp

    attr_reader :endstamp
    private :endstamp

    attr_reader :label
    private :label

    def initialize(stack, label = "Runtime")
      @stack = stack
      @label = label
    end

    def call(previous_state)
      @state = previous_state
      @startstamp = Time.now

      @status, @headers, @body = stack.call(state)

      @endstamp = Time.now

      unless headers.has_key?(label)
        headers[label] = runtime
      end

      [status, headers, body]
    end

    private def runtime
      (endstamp - startstamp).to_s
    end

    private def stack
      @stack
    end

    private def state
      @state
    end

    private def headers
      @headers
    end

    private def status
      @status
    end

    private def body
      @body
    end
  end
end


text:
package cz.metacentrum.perun.core.impl.modules.attributes;

import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.Resource;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.impl.PerunSessionImpl;
import cz.metacentrum.perun.core.implApi.modules.attributes.ResourceAttributesModuleAbstract;
import cz.metacentrum.perun.core.implApi.modules.attributes.ResourceAttributesModuleImplApi;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Attribute module for apacheAuthzFile attribute. Module checks that
 * attribute is not empty and it also contains unix-like file path.
 *
 * @author Vladimir Mecko vladimir.mecko@gmail.com
 */
public class urn_perun_resource_attribute_def_def_apacheAuthzFile extends ResourceAttributesModuleAbstract implements ResourceAttributesModuleImplApi {

	private static final Pattern pattern = Pattern.compile("^(/[-_a-zA-Z0-9.?*+$%]+)+$");

	@Override
	public void checkAttributeSyntax(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws WrongAttributeValueException {
		if (attribute.getValue() == null) return;

		//checks for valid unix file path in attribute based on pattern
		Matcher match = pattern.matcher(attribute.valueAsString());

		if(!match.matches()) {
			throw new WrongAttributeValueException(attribute, resource, null, "Wrong file path format in attribute (should be like '/dir1/dir2').");
		}
	}

	@Override
	public void checkAttributeSemantics(PerunSessionImpl perunSession, Resource resource, Attribute attribute) throws WrongReferenceAttributeValueException {
		if (attribute.getValue() == null)
			throw new WrongReferenceAttributeValueException(attribute, null, resource, null, "Attribute value can not be null.");
	}

	@Override
	public AttributeDefinition getAttributeDefinition() {
		AttributeDefinition attr = new AttributeDefinition();
		attr.setNamespace(AttributesManager.NS_RESOURCE_ATTR_DEF);
		attr.setFriendlyName("apacheAuthzFile");
		attr.setDisplayName("Apache authz file");
		attr.setType(String.class.getName());
		attr.setDescription("File containing authz entries for Apache.");
		return attr;
	}
}


text:
package com.showka.web.u00;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Menu.
 *
 * @author Administrator
 *
 */
@Controller
public class U00G001Controller {

	// public method called by request
	@RequestMapping(value = "/u00g001", method = RequestMethod.GET)
	public String index(Map<String, Object> model, HttpSession session) {
		return "u00/u00g001";
	}

}


text:
package greycat.internal.task;

import greycat.Node;
import greycat.Action;
import greycat.Constants;
import greycat.Type;
import greycat.base.BaseNode;
import greycat.TaskContext;
import greycat.TaskResult;
import greycat.struct.Buffer;

class ActionSetAttribute implements Action {

    private final String _name;
    private final String _value;
    private final int _propertyType;
    private final boolean _force;

    ActionSetAttribute(final String name, final String propertyType, final String value, final boolean force) {
        this._name = name;
        this._value = value;
        this._propertyType = Type.typeFromName(propertyType);
        this._force = force;
    }

    @Override
    public void eval(final TaskContext ctx) {
        final TaskResult previousResult = ctx.result();
        final String flatRelationName = ctx.template(_name);
        if (previousResult != null) {
            Object toSet;
            String valueAfterTemplate = ctx.template(this._value);
            switch (_propertyType) {
                case Type.BOOL:
                    toSet = parseBoolean(valueAfterTemplate);
                    break;
                case Type.INT:
                    toSet = TaskHelper.parseInt(valueAfterTemplate);
                    break;
                case Type.DOUBLE:
                    toSet = Double.parseDouble(valueAfterTemplate);
                    break;
                case Type.LONG:
                    toSet = Long.parseLong(valueAfterTemplate);
                    break;
                case Type.DOUBLE_ARRAY:
                case Type.LONG_ARRAY:
                case Type.INT_ARRAY: {
                    try {
                        toSet = loadArray(valueAfterTemplate, _propertyType);
                    } catch (NumberFormatException e) {
                        toSet = null;
                        ctx.endTask(null, new Exception("Error while parsing array from string:\"" + valueAfterTemplate + "\"\n" + e.toString()));
                    }
                }
                break;
                default:
                    toSet = valueAfterTemplate;
            }
            for (int i = 0; i < previousResult.size(); i++) {
                Object loopObj = previousResult.get(i);
                if (loopObj instanceof BaseNode) {
                    Node loopNode = (Node) loopObj;

                    if (_force) {
                        loopNode.forceSet(flatRelationName, _propertyType, toSet);
                    } else {
                        loopNode.set(flatRelationName, _propertyType, toSet);
                    }
                }
            }
        }
        ctx.continueTask();
    }

    private Object loadArray(String valueAfterTemplate, int type) throws NumberFormatException {
        String arrayInString = valueAfterTemplate;
        if (arrayInString.charAt(0) == '[') {
            arrayInString = arrayInString.substring(1);
        }
        if (arrayInString.charAt(arrayInString.length() - 1) == ']') {
            arrayInString = arrayInString.substring(0, arrayInString.length() - 1);
        }
        String[] valuesToParse = arrayInString.split(",");

        switch (type) {
            case Type.DOUBLE_ARRAY: {
                double[] finalValues = new double[valuesToParse.length];
                for (int i = 0; i < valuesToParse.length; i++) {
                    finalValues[i] = Double.parseDouble(valuesToParse[i]);
                }
                return finalValues;
            }
            case Type.LONG_ARRAY: {
                long[] finalValues = new long[valuesToParse.length];
                for (int i = 0; i < valuesToParse.length; i++) {
                    finalValues[i] = Long.parseLong(valuesToParse[i]);
                }
                return finalValues;
            }
            case Type.INT_ARRAY: {
                int[] finalValues = new int[valuesToParse.length];
                for (int i = 0; i < valuesToParse.length; i++) {
                    finalValues[i] = Integer.parseInt(valuesToParse[i]);
                }
                return finalValues;
            }
        }
        return null;

    }

    private boolean parseBoolean(String booleanValue) {
        final String lower = booleanValue.toLowerCase();
        return (lower.equals("true") || lower.equals("1"));
    }

    @Override
    public void serialize(final Buffer builder) {
        if (_force) {
            builder.writeString(CoreActionNames.FORCE_ATTRIBUTE);
        } else {
            builder.writeString(CoreActionNames.SET_ATTRIBUTE);
        }
        builder.writeChar(Constants.TASK_PARAM_OPEN);
        TaskHelper.serializeString(_name, builder, true);
        builder.writeChar(Constants.TASK_PARAM_SEP);
        TaskHelper.serializeType(_propertyType, builder);
        builder.writeChar(Constants.TASK_PARAM_SEP);
        TaskHelper.serializeString(_value, builder, true);
        builder.writeChar(Constants.TASK_PARAM_CLOSE);
    }

    @Override
    public final String name() {
        return (_force?CoreActionNames.FORCE_ATTRIBUTE:CoreActionNames.SET_ATTRIBUTE);
    }

}


text:
#include "catch.hpp"
#include "TestUtil.hpp"
#include "../FenParser.hpp"
#include "../MoveGen.hpp"

TEST_CASE("[pawn_movegen] white pawns", "[pawn_movegen]") {
    Board* board = new Board();
    MoveGen* moveGen = new MoveGen();
    FenParser* fenParser = new FenParser();
    MOVE moves[MAX_GENERATED_MOVES];

    fenParser->setFen(board, "4r2k/3P4/p1p5/PpP2ppp/4p1P1/2p5/P1P1P3/4K3 w - b6 0 1");
    moveGen->generateMoves(board, moves);
    Util::removeMovesFrom(moves, "e1"); // Remove King moves

    // Forward moves
    CHECK(Util::isMoveFound(moves, Util::newMove("a2a3")));
    CHECK(Util::isMoveFound(moves, Util::newMove("a2a4")));
    CHECK(Util::isMoveFound(moves, Util::newMove("e2e3")));

    // capture moves
    CHECK(Util::isMoveFound(moves, Util::newMove("g4f5")));
    CHECK(Util::isMoveFound(moves, Util::newMove("g4h5")));

    //promotion moves
    CHECK(Util::isMoveFound(moves, Util::newMove("d7d8", Piece::PieceEnum::Rook)));
    CHECK(Util::isMoveFound(moves, Util::newMove("d7d8", Piece::PieceEnum::Knight)));
    CHECK(Util::isMoveFound(moves, Util::newMove("d7d8", Piece::PieceEnum::Bishop)));
    CHECK(Util::isMoveFound(moves, Util::newMove("d7d8", Piece::PieceEnum::Queen)));

    // promotion moves with capture
    CHECK(Util::isMoveFound(moves, Util::newMove("d7e8", Piece::PieceEnum::Rook)));
    CHECK(Util::isMoveFound(moves, Util::newMove("d7e8", Piece::PieceEnum::Knight)));
    CHECK(Util::isMoveFound(moves, Util::newMove("d7e8", Piece::PieceEnum::Bishop)));
    CHECK(Util::isMoveFound(moves, Util::newMove("d7e8", Piece::PieceEnum::Queen)));

    // En Passant captures
    CHECK(Util::isMoveFound(moves, Util::newMove("a5b6")));
    CHECK(Util::isMoveFound(moves, Util::newMove("c5b6")));

    // Total moves count
    CHECK(Util::countMoves(moves) == 15);

    delete(fenParser);
    delete(moveGen);
    delete(board);
}

//

TEST_CASE("[pawn_movegen] black pawns", "[pawn_movegen]") {
    Board* board = new Board();
    MoveGen* moveGen = new MoveGen();
    FenParser* fenParser = new FenParser();
    MOVE moves[MAX_GENERATED_MOVES];

    fenParser->setFen(board, "4k3/p1p1p3/2P5/4P1p1/pPp2PPP/P1P5/3p4/K3R3 b - b3 0 1");
    moveGen->generateMoves(board, moves);
    Util::removeMovesFrom(moves, "e8"); // Remove King moves

    // Forward moves
    CHECK(Util::isMoveFound(moves, Util::newMove("a7a6")));
    CHECK(Util::isMoveFound(moves, Util::newMove("a7a5")));
    CHECK(Util::isMoveFound(moves, Util::newMove("e7e6")));

    // capture moves
    CHECK(Util::isMoveFound(moves, Util::newMove("g5f4")));
    CHECK(Util::isMoveFound(moves, Util::newMove("g5h4")));

    //promotion moves
    CHECK(Util::isMoveFound(moves, Util::newMove("d2d1", Piece::PieceEnum::Rook)));
    CHECK(Util::isMoveFound(moves, Util::newMove("d2d1", Piece::PieceEnum::Knight)));
    CHECK(Util::isMoveFound(moves, Util::newMove("d2d1", Piece::PieceEnum::Bishop)));
    CHECK(Util::isMoveFound(moves, Util::newMove("d2d1", Piece::PieceEnum::Queen)));

    // promotion moves with capture
    CHECK(Util::isMoveFound(moves, Util::newMove("d2e1", Piece::PieceEnum::Rook)));
    CHECK(Util::isMoveFound(moves, Util::newMove("d2e1", Piece::PieceEnum::Knight)));
    CHECK(Util::isMoveFound(moves, Util::newMove("d2e1", Piece::PieceEnum::Bishop)));
    CHECK(Util::isMoveFound(moves, Util::newMove("d2e1", Piece::PieceEnum::Queen)));

    // En Passant captures
    CHECK(Util::isMoveFound(moves, Util::newMove("a4b3")));
    CHECK(Util::isMoveFound(moves, Util::newMove("c4b3")));

    CHECK(Util::countMoves(moves) == 15);

    delete(fenParser);
    delete(moveGen);
    delete(board);
}


text:
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.

using System.Collections.Generic;

namespace IdentityServer4.Validation
{
    /// <summary>
    /// Validation result for end session callback requests.
    /// </summary>
    /// <seealso cref="IdentityServer4.Validation.ValidationResult" />
    public class EndSessionCallbackValidationResult : ValidationResult
    {
        public IEnumerable<string> ClientLogoutUrls { get; internal set; }

        // var logoutId = context.Request.Query[_options.UserInteractionOptions.LogoutIdParameter].FirstOrDefault();
        public string LogoutId { get; internal set; }

        public string SessionId { get; set; }
    }
}


text:
AMSlideMenu
===========

Version 1.0.0

Initial release of AMSlideMenu


text:
package com.freshplanet.ane.crashlytics.functions;

import android.app.Activity;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;

import com.adobe.fre.FREContext;
import com.adobe.fre.FREObject;

public class GetApiKeyFunction extends BaseFunction
{
	public FREObject call(FREContext context, FREObject[] args)
	{
		super.call(context, args);

		try
		{
			Activity activity = context.getActivity();
			ApplicationInfo ai = activity.getPackageManager().getApplicationInfo(activity.getPackageName(), PackageManager.GET_META_DATA);
		    String apiKey = ai.metaData.getString("com.crashlytics.ApiKey");
			return FREObject.newObject(apiKey);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
}