text:
import React, {Component, PropTypes} from 'react';

export default class NavigationLink extends Component {

  render() {
    var {classname, text, url} = this.props;

    var style = {
      display: "inline"
    };

    var a_style = {
      color: "black",
      display: "inline-block",
      padding: "30px",
      textDecoration: "none"
    }
    //should change later

    return (

        {text}

    )
  }

}

NavigationLink.propTypes = {
    url: PropTypes.string,
    text: PropTypes.string
 }


text:
#pragma once
#include <aws/opensearch/OpenSearchService_EXPORTS.h>
#include <aws/core/client/GenericClientConfiguration.h>
#include <aws/core/endpoint/DefaultEndpointProvider.h>
#include <aws/core/endpoint/EndpointParameter.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>

#include <aws/opensearch/OpenSearchServiceEndpointRules.h>

namespace Aws
{
namespace OpenSearchService
{
namespace Endpoint
{
using EndpointParameters = Aws::Endpoint::EndpointParameters;
using Aws::Endpoint::EndpointProviderBase;
using Aws::Endpoint::DefaultEndpointProvider;

using OpenSearchServiceClientContextParameters = Aws::Endpoint::ClientContextParameters;

using OpenSearchServiceClientConfiguration = Aws::Client::GenericClientConfiguration<false>;
using OpenSearchServiceBuiltInParameters = Aws::Endpoint::BuiltInParameters;

/**
 * The type for the OpenSearchService Client Endpoint Provider.
 * Inherit from this Base class / "Interface" should you want to provide a custom endpoint provider.
 * The SDK must use service-specific type for each service per specification.
 */
using OpenSearchServiceEndpointProviderBase =
    EndpointProviderBase<OpenSearchServiceClientConfiguration, OpenSearchServiceBuiltInParameters, OpenSearchServiceClientContextParameters>;

using OpenSearchServiceDefaultEpProviderBase =
    DefaultEndpointProvider<OpenSearchServiceClientConfiguration, OpenSearchServiceBuiltInParameters, OpenSearchServiceClientContextParameters>;

/**
 * Default endpoint provider used for this service
 */
class AWS_OPENSEARCHSERVICE_API OpenSearchServiceEndpointProvider : public OpenSearchServiceDefaultEpProviderBase
{
public:
    using OpenSearchServiceResolveEndpointOutcome = Aws::Endpoint::ResolveEndpointOutcome;

    OpenSearchServiceEndpointProvider()
      : OpenSearchServiceDefaultEpProviderBase(Aws::OpenSearchService::OpenSearchServiceEndpointRules::Rules)
    {}

    ~OpenSearchServiceEndpointProvider()
    {
    }
};
} // namespace Endpoint
} // namespace OpenSearchService
} // namespace Aws

redpajama_set_name: RedPajamaGithub


text:
import {Component} from '@angular/core';

@Component({
  selector: 'ngbd-tooltip-target',
  templateUrl: './tooltip-target.html'
})
export class NgbdTooltipTarget {
}


text:
angular.module('cloudmedic.login.resetPassword', ['ui.router', 'cloudmedic.resources', 'ui.bootstrap'])
.config(['$stateProvider', function config($stateProvider) {
    $stateProvider
    .state("login.resetPassword", {
        url: "/resetPassword?userId&token",
        onEnter: ['$modal', function ($modal) {
            $modal.open({
                templateUrl: "login/login.resetPassword.tpl.html",
                controller: 'ResetPasswordCtrl'
            });
        }]
    });
}])
.controller('ResetPasswordCtrl', ['$scope', 'notifications', '$state', '$stateParams', '$modalInstance', '$http', 'APP_CONFIG',
    function ($scope, notifications, $state, $stateParams, $modalInstance, $http, APP_CONFIG) {
        $scope.data = {
            isSubmitting: false,
            newPassword: '',
            confirmPassword: ''
        };

        $scope.resetPassword = function () {
            notifications.removeForCurrent();
            $scope.data.isSubmitting = true;
            var resetPasswordUrl = APP_CONFIG.api_url + 'account/resetPassword';

            $http.post(resetPasswordUrl, {
                UserId: $stateParams.userId,
                Token: $stateParams.token,
                NewPassword: $scope.data.newPassword,
                ConfirmPassword: $scope.data.confirmPassword
            }).success(function (data, status, headers, config) {
                notifications.addForNext({
                    type: 'success',
                    message: data
                });
                $modalInstance.close();
            })
            .error(function (data, status, headers, config) {
                $scope.data.isSubmitting = false;
                notifications.addForCurrent({
                    type: 'danger',
                    message: data
                });
            });
        };

        $modalInstance.result.then(function () {
            $state.go("login", $stateParams);
        }, function () {
            return $state.go("login", $stateParams);
        });
    }
]);


text:
@interface CANetworkEndpoints : NSObject

extern NSString * const CASessionEndpoint;
extern NSString * const CAEventEndpoint;
extern NSString * const CAPurchaseEndpoint;
extern NSString * const CAViewEndpoint;
extern NSString * const CAGlanceEndpoint;

@end


text:
package mdb.com.view.moviesgrid;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import android.support.design.widget.Snackbar;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import mdb.com.R;
import mdb.com.di.component.MoviesGridComponent;
import mdb.com.repository.MoviesRepository;
import mdb.com.util.Sort;

import javax.inject.Inject;

import mdb.com.util.Utils;
import mdb.com.view.moviesgrid.util.AbstractMoviesGridFragment;
import mdb.com.view.moviesgrid.util.EndlessRecyclerViewOnScrollListener;

/**
 * @author james on 8/31/17.
 */

public class FragmentMoviesList extends AbstractMoviesGridFragment {

    public static final String SORT = "SORT";

    @Inject
    MoviesRepository moviesRepository;
    private String sort;

    private EndlessRecyclerViewOnScrollListener endlessRecyclerViewOnScrollListener;

    public static FragmentMoviesList newInstance(String state) {
        FragmentMoviesList fragmentMoviesList = new FragmentMoviesList();
        Bundle bundle = new Bundle();
        bundle.putString(SORT, state);
        fragmentMoviesList.setArguments(bundle);
        return fragmentMoviesList;
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(MoviesRepository.BROADCAST_UPDATE_FINISHED)) {
                if (!intent.getBooleanExtra(MoviesRepository.EXTRA_IS_SUCCESSFUL_UPDATED, true)) {
                    Snackbar.make(swipeRefreshLayout, R.string.error_failed_to_update_movies,
                            Snackbar.LENGTH_LONG)
                            .show();
                }
                swipeRefreshLayout.setRefreshing(false);
                endlessRecyclerViewOnScrollListener.setLoading(false);
                updateGridLayout();
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getComponent(MoviesGridComponent.class).inject(this);
        sort = getArguments().getString(SORT, String.valueOf(Sort.MOST_POPULAR));
    }

    @Override
    public void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(MoviesRepository.BROADCAST_UPDATE_FINISHED);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcastReceiver, intentFilter);
        if (endlessRecyclerViewOnScrollListener != null) {
            Log.d(SORT, moviesRepository.toString());
            Log.d(SORT, sort);
            endlessRecyclerViewOnScrollListener.setLoading(moviesRepository.isLoading());
        }
        swipeRefreshLayout.setRefreshing(moviesRepository.isLoading());
    }

    @Override
    public void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(broadcastReceiver);
    }

    @NonNull
    @Override
    protected Uri getContentUri() {
        return Utils.getSortedMoviesUri(sort);
    }

    @Override
    protected void onCursorLoaded(Cursor data) {
        // the first time the favorites cursor data is empty
        if (sort.equals(Sort.FAVORITES)) {
            getAdapter().changeCursor(data);
        } else {
            getAdapter().changeCursor(data);
            if (data == null || data.getCount() == 0) {
                refreshMovies();
            }
        }
    }

    private void refreshMovies() {
        swipeRefreshLayout.setRefreshing(true);
        moviesRepository.refreshMovies(sort);
    }

    @Override
    protected void onRefreshAction() {
        refreshMovies();
    }

    @Override
    protected void onMoviesGridInitialisationFinished() {
        endlessRecyclerViewOnScrollListener = new EndlessRecyclerViewOnScrollListener(getGridLayoutManager()) {
            @Override
            public void onLoadMore() {
                swipeRefreshLayout.setRefreshing(true);
                moviesRepository.loadMoreMovies(sort);
            }
        };
        recyclerView.addOnScrollListener(endlessRecyclerViewOnScrollListener);
    }

}


text:
package jmini3d.gwt.input;

import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Touch;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.EventListener;

import java.util.HashMap;

import jmini3d.input.KeyListener;
import jmini3d.input.TouchListener;
import jmini3d.input.TouchPointer;

public class InputController implements EventListener {

	static final Integer MOUSE_POINTER_ID = 666;

	TouchListener touchListener;
	KeyListener keyListener;

	TouchPointer mousePointer;

	HashMap<Integer, TouchPointer> pointers = new HashMap<Integer, TouchPointer>();
	HashMap<Integer, TouchPointer> pointersAux = new HashMap<Integer, TouchPointer>();

	Element element;
	int eventBits;

	public float scale = 1;

	public InputController(final Element element) {
		this.element = element;
		Event.setEventListener(element, this);

		mousePointer = new TouchPointer();
		eventBits = 0;
	}

	public void setScale(float scale) {
		this.scale = scale;
	}

	public void setTouchListener(TouchListener touchListener) {
		int mask = Event.ONMOUSEDOWN | Event.ONMOUSEUP | Event.ONMOUSEMOVE | Event.ONMOUSEOUT | //
				Event.ONTOUCHSTART | Event.ONTOUCHMOVE | Event.ONTOUCHEND | Event.ONTOUCHCANCEL;

		if (touchListener != null) {
			eventBits |= mask;
		} else {
			eventBits &= ~mask;
		}
		Event.sinkEvents(element, eventBits);

		this.touchListener = touchListener;
	}

	public void setKeyListener(KeyListener keyListener) {
		int mask = Event.ONKEYDOWN | Event.ONKEYUP | Event.ONMOUSEWHEEL;

		if (keyListener != null) {
			eventBits |= mask;
		} else {
			eventBits &= ~mask;
		}
		Event.sinkEvents(element, eventBits);

		this.keyListener = keyListener;
	}

	@Override
	public void onBrowserEvent(Event event) {
		if ((event.getTypeInt() & Event.ONMOUSEDOWN) != 0) {
			mousePointer.x = (int) (scale * (event.getClientX() - element.getAbsoluteLeft()));
			mousePointer.y = (int) (scale * (event.getClientY() - element.getAbsoluteTop()));
			mousePointer.status = TouchPointer.TOUCH_DOWN;
			pointers.put(MOUSE_POINTER_ID, mousePointer);
			touchListener.onTouch(pointers);
			event.preventDefault();
		}
		if ((event.getTypeInt() & Event.ONMOUSEDOWN) != 0) {
			mousePointer.x = (int) (scale * (event.getClientX() - element.getAbsoluteLeft()));
			mousePointer.y = (int) (scale * (event.getClientY() - element.getAbsoluteTop()));
			mousePointer.status = TouchPointer.TOUCH_MOVE;

			if (pointers.containsKey(MOUSE_POINTER_ID)) {
				touchListener.onTouch(pointers);
			}
			event.preventDefault();
		}
		if ((event.getTypeInt() & Event.ONMOUSEMOVE) != 0) {
			mousePointer.x = (int) (scale * (event.getClientX() - element.getAbsoluteLeft()));
			mousePointer.y = (int) (scale * (event.getClientY() - element.getAbsoluteTop()));
			mousePointer.status = TouchPointer.TOUCH_MOVE;

			if (pointers.containsKey(MOUSE_POINTER_ID)) {
				touchListener.onTouch(pointers);
			}
			event.preventDefault();
		}
		if ((event.getTypeInt() & Event.ONMOUSEUP) != 0) {
			mousePointer.x = (int) (scale * (event.getClientX() - element.getAbsoluteLeft()));
			mousePointer.y = (int) (scale * (event.getClientY() - element.getAbsoluteTop()));
			mousePointer.status = TouchPointer.TOUCH_UP;

			if (pointers.containsKey(MOUSE_POINTER_ID)) {
				touchListener.onTouch(pointers);
				pointers.remove(MOUSE_POINTER_ID);
			}
			event.preventDefault();
		}
		if ((event.getTypeInt() & Event.ONMOUSEOUT) != 0) {
			mousePointer.x = (int) (scale * (event.getClientX() - element.getAbsoluteLeft()));
			mousePointer.y = (int) (scale * (event.getClientY() - element.getAbsoluteTop()));
			mousePointer.status = TouchPointer.TOUCH_UP;

			if (pointers.containsKey(MOUSE_POINTER_ID)) {
				touchListener.onTouch(pointers);
				pointers.remove(MOUSE_POINTER_ID);
			}
			event.preventDefault();
		}
		if ((event.getTypeInt() & Event.ONTOUCHSTART) != 0) {
			for (int i = 0; i < event.getChangedTouches().length(); i++) {
				Touch touch = event.getChangedTouches().get(i);
				TouchPointer pointer = pointersAux.get(touch.getIdentifier());
				if (pointer == null) {
					pointer = new TouchPointer();
				}
				pointer.x = (int) (scale * (touch.getClientX() - element.getAbsoluteLeft()));
				pointer.y = (int) (scale * (touch.getClientY() - element.getAbsoluteTop()));
				pointer.status = TouchPointer.TOUCH_DOWN;
				pointers.put(touch.getIdentifier(), pointer);
			}
			touchListener.onTouch(pointers);

			for (TouchPointer pointer : pointers.values()) {
				pointer.status = TouchPointer.TOUCH_MOVE;
			}
			event.preventDefault();
		}
		if ((event.getTypeInt() & Event.ONTOUCHMOVE) != 0) {
			for (int i = 0; i < event.getChangedTouches().length(); i++) {
				Touch touch = event.getChangedTouches().get(i);
				TouchPointer pointer = pointers.get(touch.getIdentifier());
				pointer.x = (int) (scale * (touch.getClientX() - element.getAbsoluteLeft()));
				pointer.y = (int) (scale * (touch.getClientY() - element.getAbsoluteTop()));
				pointer.status = TouchPointer.TOUCH_MOVE;
			}
			touchListener.onTouch(pointers);
			event.preventDefault();
		}
		if ((event.getTypeInt() & Event.ONTOUCHEND) != 0) {
			for (Integer key : pointers.keySet()) {
				if (!MOUSE_POINTER_ID.equals(key)) {
					TouchPointer pointer = pointers.get(key);
					pointer.status = TouchPointer.TOUCH_UP;
				}
			}

			for (int i = 0; i < event.getTouches().length(); i++) {
				Touch touch = event.getTouches().get(i);
				TouchPointer pointer = pointers.get(touch.getIdentifier());
				pointer.status = TouchPointer.TOUCH_MOVE;
			}
			touchListener.onTouch(pointers);

			for (Integer key : pointers.keySet()) {
				if (!MOUSE_POINTER_ID.equals(key)) {
					TouchPointer pointer = pointers.get(key);
					if (pointer.status == TouchPointer.TOUCH_UP) {
						pointers.remove(key);
					}
				}
			}
			event.preventDefault();
		}
		if ((event.getTypeInt() & Event.ONTOUCHCANCEL) != 0) {
			mousePointer.status = TouchPointer.TOUCH_UP;
			touchListener.onTouch(pointers);
			event.preventDefault();
		}
		if ((event.getTypeInt() & Event.ONKEYDOWN) != 0 || (event.getTypeInt() & Event.ONKEYUP) != 0) {
			int key = 0;
			switch (event.getKeyCode()) {
				case KeyCodes.KEY_UP:
					key = KeyListener.KEY_UP;
					break;
				case KeyCodes.KEY_DOWN:
					key = KeyListener.KEY_DOWN;
					break;
				case KeyCodes.KEY_LEFT:
					key = KeyListener.KEY_LEFT;
					break;
				case KeyCodes.KEY_RIGHT:
					key = KeyListener.KEY_RIGHT;
					break;
				case KeyCodes.KEY_ENTER:
					key = KeyListener.KEY_ENTER;
					break;
				case KeyCodes.KEY_ESCAPE:
					key = KeyListener.KEY_BACK;
					break;
				case KeyCodes.KEY_BACKSPACE:
					key = KeyListener.KEY_BACKSPACE;
					break;
			}
			if (key != 0) {
				boolean managed = false;
				if ((event.getTypeInt() & Event.ONKEYDOWN) != 0) {
					managed = keyListener.onKeyDown(key);
				}
				if ((event.getTypeInt() & Event.ONKEYUP) != 0) {
					managed = keyListener.onKeyUp(key);
				}
				if (managed) {
					event.preventDefault();
				}
			}
		}
		if ((event.getTypeInt() & Event.ONMOUSEWHEEL) != 0) {
			boolean managed = false;
			if (event.getMouseWheelVelocityY() > 0) {
				managed |= keyListener.onKeyDown(KeyListener.KEY_ZOOM_OUT);
				managed |= keyListener.onKeyUp(KeyListener.KEY_ZOOM_OUT);
			} else {
				managed |= keyListener.onKeyDown(KeyListener.KEY_ZOOM_IN);
				managed |= keyListener.onKeyUp(KeyListener.KEY_ZOOM_IN);
			}
			if (managed) {
				event.preventDefault();
			}
		}
	}

}


text:
#ifndef __STDBOOL_H
#define __STDBOOL_H

/* Don't define bool, true, and false in C++ */
#ifndef __cplusplus
#define bool _Bool
#define true 1
#define false 0
#endif

#define __bool_true_false_are_defined 1

#endif /* __STDBOOL_H */


text:
package in.ac.iitb.cfilt.cpost.stemmer;

import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.Vector;

public class StemmedToken implements Serializable {

	private static final long serialVersionUID = 8424882257677766336L;

	private String token;
	private Vector<StemmerRuleResult> stemmedOutputs;

	public StemmedToken(String token){
		this.token = token;
		stemmedOutputs = new Vector<StemmerRuleResult>();
	}

	public void setToken(String token){
		this.token = token;
	}

	public void sortResults(){
		Collections.sort(stemmedOutputs);
	}

	public String getToken(){
		return token;
	}

	public boolean addStemmerOutput(StemmerRuleResult srresult){
		return stemmedOutputs.add(srresult);
	}

	public boolean addAllStemmerOutputs(Vector<StemmerRuleResult> srresult){
		return stemmedOutputs.addAll(srresult);
	}

	public Vector<StemmerRuleResult> getStemmedOutputs(){
		return stemmedOutputs;
	}

	public void clearOutputs() {
		stemmedOutputs.clear();
	}

	public String getAmbiguityScheme(){
		String retVal = "";

		HashSet<String> categorySet = new HashSet<String>();
		for(StemmerRuleResult stemmedOutput : stemmedOutputs){
			String cat = stemmedOutput.getCategory().trim();
			if(!cat.equals("unknown")){
				categorySet.add(cat);
			}
		}
		Vector<String> categoryList = new Vector<String>(categorySet);
		Collections.sort(categoryList);
		for(int i = 0; i < categoryList.size(); i++){
			retVal += categoryList.get(i) + "*";
		}
		if(!retVal.equals(""))
			retVal = retVal.substring(0, retVal.length() - 1);
		return retVal;
	}
}


text:
from parameterized import parameterized
from combinatrix.testintegration import load_parameter_sets

from doajtest.fixtures import ArticleFixtureFactory, JournalFixtureFactory, AccountFixtureFactory
from doajtest.helpers import DoajTestCase
from portality.bll import DOAJ
from portality.bll import exceptions
from portality.models import Article, Journal, Account
from portality.lib.paths import rel2abs
from doajtest.mocks.bll_article import BLLArticleMockFactory
from datetime import datetime

def load_cases():
    return load_parameter_sets(rel2abs(__file__, "..", "matrices", "article_get_duplicates"), "get_duplicates", "test_id",
                               {"test_id" : []})

EXCEPTIONS = {
    "ArgumentException" : exceptions.ArgumentException
}

class TestBLLArticleGetDuplicates(DoajTestCase):

    def setUp(self):
        super(TestBLLArticleGetDuplicates, self).setUp()
        self.svc = DOAJ.articleService()
        self._old_discover_duplicates = self.svc.discover_duplicates

    def tearDown(self):
        self.svc.discover_duplicates = self._old_discover_duplicates
        super(TestBLLArticleGetDuplicates, self).tearDown()

    @parameterized.expand(load_cases)
    def test_01_get_duplicates(self, name, kwargs):

        article_arg = kwargs.get("article")
        owner_arg = kwargs.get("owner")
        doi_duplicates_arg = kwargs.get("doi_duplicates")
        fulltext_duplicates_arg = kwargs.get("fulltext_duplicates")
        overlap_arg = kwargs.get("overlap")
        raises_arg = kwargs.get("raises")

        raises = EXCEPTIONS.get(raises_arg)

        doi_duplicates = -1
        if doi_duplicates_arg not in ["-"]:
            doi_duplicates = int(doi_duplicates_arg)

        fulltext_duplicates = -1
        if fulltext_duplicates_arg not in ["-"]:
            fulltext_duplicates = int(fulltext_duplicates_arg)

        overlap = -1
        if overlap_arg not in ["-"]:
            overlap = int(overlap_arg)

        expected_count = doi_duplicates + fulltext_duplicates - overlap

        ###############################################
        ## set up

        owner = None
        if owner_arg != "no":
            owner = Account(**AccountFixtureFactory.make_publisher_source())

        owner_id = None
        if owner is not None:
            owner_id = owner.id

        # generate our incoming article
        article = None
        if article_arg == "yes":
            source = ArticleFixtureFactory.make_article_source()
            article = Article(**source)
            article.set_id()

        mock = BLLArticleMockFactory.discover_duplicates(doi_duplicates, fulltext_duplicates, overlap)
        self.svc.discover_duplicates = mock

        # determine if we expect a merge conflict
        dds = 0 if doi_duplicates < 0 else doi_duplicates
        fds = 0 if fulltext_duplicates < 0 else fulltext_duplicates
        ol = 0 if overlap < 0 else overlap
        expect_merge_conflict = dds + fds - ol > 1

        ###########################################################
        # Execution

        first_article = None

        # first do get_duplicates
        if raises is not None:
            with self.assertRaises(raises):
                self.svc.get_duplicates(article)
        else:
            duplicates = self.svc.get_duplicates(article)

            if len(duplicates) > 0:
                first_article = duplicates[0]

            # check that we have the number of results we expected
            assert len(duplicates) == expected_count

            # check that the articles are unique in the list
            article_ids = [a.id for a in duplicates]
            article_ids.sort()
            deduped = list(set(article_ids))
            deduped.sort()  # so it's comparable to the article_ids list, as the set() call destroys ordering
            assert article_ids == deduped   # i.e. that there were no duplicates

            # check that the articles are ordered by last_updated
            last_updateds = [datetime.strptime(a.last_updated, "%Y-%m-%dT%H:%M:%SZ") for a in duplicates]
            sorted_lu = sorted(last_updateds, reverse=True)
            assert sorted_lu == last_updateds   # i.e. they were already sorted

        # then the same again on the singular get_duplicate
        if raises is not None:
            with self.assertRaises(raises):
                self.svc.get_duplicate(article)
        elif expect_merge_conflict:
            with self.assertRaises(exceptions.ArticleMergeConflict):
                self.svc.get_duplicate(article)
        else:
            duplicate = self.svc.get_duplicate(article)

            if expected_count > 0:
                assert isinstance(duplicate, Article)
                assert duplicate.id == first_article.id
            else:
                assert duplicate is None


text:
var env = require('./settings');//importing settings file, environment variables
/**************thingSpeak client**************/
var ThingSpeakClient = require('thingspeakclient');
var client = new ThingSpeakClient({
  server:'http://10.129.139.139:3000',
  updateTimeout:20000
});

/***************Adding websocket feature*******/
//var uuid = require('node-uuid');
//var WebSocketServer = require('ws').Server,
//    wss = new WebSocketServer({port: 8181});
var WebSocket = require('ws');
var ws=null;
wsConnect();
//var wscon=null;
//var clients=[];
  ///////////////////////
////initiating the bunyan log
var Logger = require('bunyan');
var log = new Logger({name:'Serial-Sensor',
         streams: [
    {
      level: 'info',
      stream: process.stdout            // log INFO and above to stdout
    },
    {
      level: 'error',
      stream: process.stdout            // log ERROR and above to stdout
    },
    {
      level: 'warn',
      stream: process.stdout            // log warning and above to stdout
    },
    {
      level: 'error',
      path: './log/iot.log'  // log ERROR and above to a file
    },
    {
      level: 'warn',
      path: './log/iot.log'  // log WARNING and above to a file
    },
    {
      level: 'info',
      path: './log/iot.log'  // log INFO and above to a file
    }
  ]

});
/////////
///mysql
var mysql      = require('mysql');
///mysql
var localdb_config={
  host     : env.localhost,
  user     : env.user,
  password : env.password1,
  database : env.database
}
var remote_config={ //for remote
  host     : env.mhost2,
  user     : env.user,
  password : env.password2,
  database : env.database//remote
}
var thingspeak_config={ //for thingspeak
  host     : env.mhost2,
  user     : env.user,
  password : env.password2,
  database : env.database2//thingspeak
}
var connectionlocal = mysql.createConnection(localdb_config);
var connectionRemote = mysql.createConnection(remote_config);
var connectionThingspeak = mysql.createConnection(thingspeak_config);
connectionlocal.connect();//general
connectionRemote.connect();//remote
connectionThingspeak.connect();//thingspeak
//configuration ended
/////serial config
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort(env.portNo, {
  baudrate: 9600,
  stopBits: 1,//new editions
  dataBits: 6,
  parity: 'odd'
})
/////////////////
//serial listen
serialPort.on("open", function () {
  log.info(env.portNo+' port opened');
  serialPort.flush();//flushing previous data
  attachChannels(); //attaching the api-keys
  //console.log('open');
  var count=0
  var res, dataout;
  serialPort.on('error', function(err) {
    log.error("Some error in reading the data "+err);
    var jsonS={
         "action":'Serial Error',
         "data"  :"Some error in reading the data "+err
    };
    sendAll(jsonS);//sending button status to all device
  });
  serialPort.on('disconnect', function(disc) {
    log.error("Port closed: "+disc);
    var jsonS={
         "action":'Serial Error',
         "data"  :"Port closed: "+disc
    };
    sendAll(jsonS);//sending button status to all device
  });
  serialPort.on('data', function(data) {
    log.info('data received: '+data);
    var jsonS={
         "action":'Serial data',
         "data"  :"data received: "+data
    };
    sendAll(jsonS);//sending button status to all device

    //console.log("Time: "+date);

    dataout=String(data);
    res = dataout.split(",");//getting strings
   // console.log(res[0]);//stores device id
    //console.log(res[1]);//stored packet number or id
   // console.log(res[2]);//gets device type

    //find if the device is new
    var post  = {macid: res[0]};
    //if(res[2].substring()){ //check if the data is corrupt or not by checking the third parameter, string

      connectionRemote.query('SELECT EXISTS(SELECT * FROM devices WHERE deviceId=\''+post.macid+'\') as find', function(err, rows, fields) {
      //console.log('Inside client connected '+val);

        if (err)
          log.error(err);
        else{
            var find=rows[0]['find'];
           // console.log('Inside client connected '+find);
           if(find==0 && res[0]>9){ //check device is the new one, find=0 means new device found, no previous entry in the table
               //var devdis='INSERT INTO devices VALUES (DEFAULT,NULL,\''+post.macid+'\',NULL,2,1, DEFAULT,NULL,\''+res[2]+'\')';
               var thingspeak=null;
               if(res[2]==='bthm'){//for bthm
                  var devdis='INSERT INTO devices(deviceId, description, type, switches, field1, field2, field3, field4, field5, field6) VALUES (\''+post.macid+'\', \'It records battery, temperature, humidity and moisture value\', 2,0, \'bthm\', \'packetId\', \'battery\', \'temperature\', \'humidity\', \'moisture\')';//table restructured
                  thingspeakchannelrow={
                      'api_key' : env.apiKey,
                      'name'    : res[0],
                      'description' : 'It records battery, temperature, humidity and moisture value',
                      'field1'  :'batValue',
                      'field2'  :'tempValue',
                      'field3'  :'humidValue',
                      'field4'  :'moistValue',
                      'field5'  :'packetId'
                  }
               }
               else if(res[2]==='b'){//for hub
                  var devdis='INSERT INTO devices(deviceId, description, type, switches, field1, field2, field3) VALUES (\''+post.macid+'\', \'It is a Hub conneccting various sensor nodes\', 2,0, \'b\', \'packetId\', \'battery\')';//for the normal Hub connection
                  thingspeakchannelrow={
                      'api_key' : env.apiKey,
                      'name'    : res[0],
                      'description' : 'It is a Hub conneccting various sensor nodes',
                      'field1'  :'batValue',
                      'field2'  :'packetId'
                  }
               }
               else if(res[2]==='bm'){//for moisture only sensor
                  var devdis='INSERT INTO devices(deviceId, description, type, switches, field1, field2, field3, field4) VALUES (\''+post.macid+'\', \'It records battery and moisture value\', 2,0, \'bm\', \'packetId\', \'battery\', \'moisture\')';//for the moisture sensor only
                  thingspeakchannelrow={
                      'api_key' : env.apiKey,
                      'name'    : res[0],
                      'description' : 'It records battery and moisture value',
                      'field1'  :'batValue',
                      'field2'  :'moistValue',
                      'field3'  :'packetId'
                  }
               }
                connectionlocal.query(devdis, function(err, rows, fields) { //insert into the table
                  if (err)
                  log.error(err);
                  else{
                    log.info('New Sensor Device found, adding '+post.macid+' into device table');
                    var jsonS={
                         "action":'Device',
                         "data"  :"New Sensor Device found, adding "+post.macid+" into device table"
                    };
                    sendAll(jsonS);//sending button status to all device
                    client.createChannel(1, thingspeakchannelrow, function(err) {
                      if (!err) {//channel creation done
                          log.info('New channel created for sensor: '+res[0]+' type '+res[2]);
                          var jsonS={
                               "action":'thingspeak',
                               "data"  :"New channel created for sensor: "+res[0]+" type "+res[2]
                          };
                          sendAll(jsonS);//sending button status to all device
                          attachChannel(res[0]);//attaching the channel;
                      }
                      else
                      {
                        console.log(err)
                      }
                     });
                    connectionRemote.query(devdis, function(err, rows, fields) { //insert into the remote table
                      if (err)
                      log.error(err);
                      else{
                        log.info('New Sensor Device found, adding '+post.macid+' into Remote device table');
                      }
                    });
                  }
                });

           }//end of find if condition

           else{
             log.info('Device '+post.macid+' sent new data');
            //var devdis='UPDATE devices SET status=1, seen= now() where status in (0,2) and macid=\''+post.macid+'\'';
             deviceStatus(post.macid, function(status,row){
                if(status==0){//insert only if the last row for that device was vice versa
                  var devdis='INSERT INTO deviceStatus VALUES (DEFAULT,\''+row+'\',1, DEFAULT)';
                  connectionlocal.query(devdis, function(err, rows, fields) { //update the table //query3
                    if (err)
                      log.error("MYSQL ERROR "+err);
                    else{
                      //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                      log.info('Device '+row+' went online');
                          connectionRemote.query(devdis, function(err, rows, fields) { //update the remote table //query3
                        if (err)
                          log.error("MYSQL ERROR "+err);
                        else{
                          //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                          log.info('Updated remote table for the online status');
                        }
                      });
                    }
                  });
                }
                else if (status==2){//if no last row exists
                  var devdis='INSERT INTO deviceStatus VALUES (DEFAULT,\''+row+'\',1, DEFAULT)';
                  connectionlocal.query(devdis, function(err, rows, fields) { //update the table //query3
                    if (err)
                      log.error("MYSQL ERROR "+err);
                    else{
                      //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                      log.info('Device '+row+' went online');
                      connectionRemote.query(devdis, function(err, rows, fields) { //update the remote table //query3
                        if (err)
                          log.error("MYSQL ERROR "+err);
                        else{
                          //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                          log.info('Updated remote table for the online status');
                        }
                      });
                    }
                  });
                }
             });
             var jsonS={
                     "deviceId":post.macid,
                     "status":1
               };
               sendAll(jsonS);//sending  online status to website
            }

         }
       });
    ///
    if(res[2]==='bthm')
    {
      //console.log(res[3]);//gets battery
      //console.log(res[4]);//gets temp
      //console.log(res[5]);//gets humidity
     // console.log(res[6]);//gets moisture
      if(!isNaN(res[3])&&!isNaN(res[4])&&!isNaN(res[5])&&!isNaN(res[6]))
      {
        var sensorVal='INSERT INTO feeds(device_Id, field1, field2, field3, field4, field5, field6) VALUES (\''+res[0]+'\',\''+res[2]+'\',\''+res[1]+'\',\''+res[3]+'\',\''+res[4]+'\',\''+res[5]+'\',\''+res[6]+'\')';
        connectionlocal.query(sensorVal, function(err, rows, fields) { //insert into the feed table
          if (err)
            log.error('Error in inserting serial data, error: '+err);
          else{
            // log.info('Feed added for '+res[0]+' on '+date);
            connectionRemote.query(sensorVal, function(err, rows, fields) { //insert into the remote feed table
              if (err){
                log.error('Error in inserting serial data, error: '+err);
                var jsonS={
                     "action":'Error',
                     "data"  :"Error in inserting serial data, error: "+err
                };
                sendAll(jsonS);//sending button status to all device
              }
              else
                 log.info('Remote feed updated with new data');
            });
          }
          });
          var jsonS={
            "deviceId":res[0],
            "action": 'data',
             "packetNo":res[1],
             "deviceType":res[2],
             "batValue":res[3],
             "tempValue":res[4],
             "humidityValue":res[5],
             "moistValue":res[6]
          };
          sendAll(jsonS);//to websocket client
          findChannel(res[0], function(channel_Id){//updating the thingspeak feed
                client.updateChannel(channel_Id, { "field1":res[3],"field2":res[4],"field3":res[5],"field4":res[6],"field5":res[1]}, function(err, resp) {
                if (!err && resp > 0) {
                    log.info('Thingspeak feed update successfully for channel id '+channel_Id);
                    var jsonS={
                         "action":'thingspeak',
                         "data"  :"Thingspeak feed update successfully for channel id "+channel_Id
                    };
                    sendAll(jsonS);//sending button status to all device
                }
                });

          });

      }
      else
         log.warn('Packet is corrupted, client id: '+res[0]);
    }
    else if(res[2]==='bm')
    {
      var sensorVal='INSERT INTO feeds(device_Id, field1, field2, field3, field4) VALUES (\''+res[0]+'\',\''+res[2]+'\',\''+res[1]+'\',\''+res[3]+'\',\''+res[4]+'\')';//only battery and moisture
      connectionlocal.query(sensorVal, function(err, rows, fields) { //insert into the feed table
        if (err){
         log.error('Error in inserting serial data, error: '+err);
         var jsonS={
               "action":'Error',
               "data"  :"Error in inserting serial data, error: "+err
          };
          sendAll(jsonS);//sending button status to all device
        }
        else{
           //log.info('Feed added for '+res[0]+' on '+date);
           connectionRemote.query(sensorVal, function(err, rows, fields) { //insert into the feed table
              if (err){
                 log.error('Error in inserting serial data, error: '+err);
                 var jsonS={
                       "action":'Error',
                       "data"  :"Error in inserting serial data, error: "+err
                  };
                  sendAll(jsonS);//sending button status to all device
               }
              else
                 log.info('Remote feed updated with new data');
            });
         }
      });
      var jsonS={
        "deviceId":res[0],
        "action": 'data',
         "packetNo":res[1],
         "deviceType":res[2],
         "batValue":res[3],
         "moistValue":res[4]
      };
      sendAll(jsonS);//to websocket client
      findChannel(res[0], function(channel_Id){//updating the thingspeak feed
            client.updateChannel(channel_Id, { "field1":res[3],"field2":res[4],"field3":res[1]}, function(err, resp) {
            if (!err && resp > 0) {
                log.info('Thingspeak feed update successfully for channel id '+channel_Id);
                var jsonS={
                     "action":'thingspeak',
                     "data"  :"Thingspeak feed update successfully for channel id "+channel_Id
                };
                sendAll(jsonS);//sending button status to all device
            }
            });

      });

    }
    else if(res[2]==='b')
    {
      var sensorVal='INSERT INTO feeds(device_Id, field1, field2, field3) VALUES (\''+res[0]+'\',\''+res[2]+'\',\''+res[1]+'\',\''+res[3]+'\')';//only battery
      connectionlocal.query(sensorVal, function(err, rows, fields) { //insert into the feed table
        if (err)
         log.error('Error in inserting serial data, error: '+err);
        else{
           //log.info('Feed added for '+res[0]+' on '+date);
           connectionRemote.query(sensorVal, function(err, rows, fields) { //insert into the feed table
              if (err){
               log.error('Error in inserting serial data, error: '+err);
               var jsonS={
                     "action":'Error',
                     "data"  :"Error in inserting serial data, error: "+err
                };
                sendAll(jsonS);//sending button status to all device
              }
              else
                 log.info('Remote feed updated with new data');
            });
         }
      });
      var jsonS={
        "deviceId":res[0],
        "action": 'data',
         "packetNo":res[1],
         "deviceType":res[2],
         "batValue":res[3]
      };
      sendAll(jsonS);//to websocket client
      findChannel(res[0], function(channel_Id){//updating the thingspeak feed
            client.updateChannel(channel_Id, { "field1":res[3],"field2":res[1]}, function(err, resp) {
            if (!err && resp > 0) {
                log.info('Thingspeak feed update successfully for channel id '+channel_Id);
                var jsonS={
                     "action":'thingspeak',
                     "data"  :"Thingspeak feed update successfully for channel id "+channel_Id
                };
                sendAll(jsonS);//sending button status to all device
            }
            });

      });
    }
    //count++;
    //console.log('data count : ' + count);
  //}
  //else
       //  log.warn('Packet is corrupted, client id: '+res[0]+' '+date);
  });
  serialPort.on('error', function(errors) {
     log.error('error in reading: ' + errors);
  });

});
/****************implementing websocket***********/
/*wss.on('connection', function(ws) {
  wscon=ws;
  var client_uuid=uuid.v4();
  clients.push({"id": client_uuid, "ws": wscon});//adds client detail
  log.info('client [%s] connected',client_uuid);

  ws.on('message', function(message) {
    var stock_request = JSON.parse(message);
  });

  ws.on('close', function() {
      console.log("connection closed");
      wscon=null;
  });
});*/
/**************************************Websocket con*********************************/
function wsConnect() {//creating a websocket connection to the mosca-mysql-server.js for transfering the sensor value to the latter script
    ws = new WebSocket("ws://10.129.139.139:8180");
    ws.onopen = function() {
      log.info('connected to websocket server');
    };
   /* ws.onmessage = function(msg) {
      console.log(msg);
    };
*/
    ws.onclose = function(evt) {
      if (evt.code == 3110) {
        log.error('ws closed');
        ws = null;
      }
      else {
        ws = null;
        console.log('ws connection error');
        var jsonS={
             "action":'Error',
             "data"  :"unable to send the sensor data, reconnecting to mosca-mysql-server"
        };
        sendAll(jsonS);//sending button status to all device
      }
    };

    ws.onerror = function(evt) {
      //if (ws.readyState == 1) {
       console.log('ws normal error: ' + evt.type);
      //}
    };
}
/******************broadcast*****************/
function sendAll(jsonS){  //
  if(ws!=null){//sending data via websocket
    try{
      ws.send(JSON.stringify(jsonS));
    }
    catch(e){
      //wsConnect();
      log.error('error in sending the websocket data');
      wsConnect();
    }
  }
  else
    wsConnect();
}
//////////////////////////////////

setInterval(function() {
  //checking for sensor device is offline or not, also for checking if the weboscket connection is alive or not
  //var query='Select feeds.device_id from  (Select device_id, MAX(id) as cid  from feeds where device_type!=1 group by device_id) as temp left join feeds on temp.cid= feeds.id where now()-feeds.created_at>275';
  var query="Select *, TIMEDIFF(now(),feeds.created_at) from (Select device_id, MAX(id) as cid from feeds where field1!=1 group by device_id) as temp left join feeds on temp.cid= feeds.id where TIMEDIFF(now(),feeds.created_at)>STR_TO_DATE('00:04:35','%H:%i:%s')";
  //var checkstatus='Update devices SET status=0, seen=now() where macid in (select feeds.device_id from  (Select device_id, MAX(id) as cid  from feeds where device_type!=1 group by device_id) as temp left join feeds on temp.cid= feeds.id where now()-feeds.created_at>275) and status not in (0,2)';
  connectionRemote.query(query,function(err,rows,fields){//query 1
    try{
      if(rows.length>0){
            if(err)
            log.error('Error in getting devid of the sensor, '+err);
            else{
              for (var j=0;j<rows.length;j++)//going through all the macid
              {
                  deviceStatus(rows[j].device_id, function(status,row){
                      if(status==1){//insert only if the last row for that device was vice versa
                        var devdis='INSERT INTO deviceStatus VALUES (DEFAULT,\''+row+'\',0, DEFAULT)';
                        connectionlocal.query(devdis, function(err, rows, fields) { //update the table //query3
                          if (err)
                            log.error("MYSQL ERROR "+err);
                          else{
                            //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                            log.info('Device '+row+' went offline');
                            connectionRemote.query(devdis, function(err, rows, fields) { //update the remote table //query3
                              if (err)
                                log.error("MYSQL ERROR "+err);
                              else{
                                //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                                log.info('Remote entry for device offline');
                                var jsonS={
                                       "deviceId":row,
                                       "status":1
                                 };
                                 sendAll(jsonS);//sending  online status to website
                              }
                            });
                          }
                        });
                      }
                      else if (status==2){//if no last row exists
                        var devdis='INSERT INTO deviceStatus VALUES (DEFAULT,\''+row+'\',0, DEFAULT)';
                        connectionlocal.query(devdis, function(err, rows, fields) { //update the table //query3
                          if (err)
                            log.error("MYSQL ERROR "+err);
                          else{
                            //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                            log.info('Device '+row+' went offline');
                            connectionRemote.query(devdis, function(err, rows, fields) { //update the remote table //query3
                              if (err)
                                log.error("MYSQL ERROR "+err);
                              else{
                                //log.info('Devices Entry for '+rows[0].device_id+'Updated, Set to 0/offline');
                                log.info('Remote entry for device offline');
                                var jsonS={
                                         "deviceId":row,
                                         "status":1
                                   };
                                   sendAll(jsonS);//sending  online status to website
                                }
                            });
                          }
                        });
                      }
                   });
              }//end of for loop

            }
      }
    }
    catch(e){
      log.error('Error struck '+e);
    }
  });
 }, 10000);

/******************************
*function: attachChannels()
*
*logic: it attaches the apikeys to their channel ids
*so that their feeds can be updated on the fly
*
*/
function attachChannels(){
      var query='Select api_key, channel_id from api_keys where write_flag=1';
      connectionThingspeak.query(query,function(err,rows,fields){
      if(err)
        log.error('Error in checking apikeys, thingspeak, '+err);
      else{
        for (var j=0;j<rows.length;j++)//going through all the macid
        {
            log.info("attaching apikey for channel id "+rows[j].channel_id)
            client.attachChannel(rows[j].channel_id, { writeKey:rows[j].api_key});
            var jsonS={
                 "action":'thingspeak',
                 "data"  :"attaching apikey for channel id "+rows[j].channel_id
            };
            sendAll(jsonS);//sending button status to all device
        }

      }
  });
}

/******************************
*function: attachChannel(name)
*input: takes channel name
*logic: attaches apikey to the newly added channel id
*
*/
function attachChannel(name){
      var query='Select channel_id from channels where name='+name;
      findChannel(name, function(channel_Id){//updating the thingspeak feed

            var query='Select api_key from api_keys where write_flag=1 and channel_id='+channel_Id;  //findapikey
            connectionThingspeak.query(query,function(err,rows,fields){
      				if(rows.length>0){
      		          if(err)
      		          log.error('Error in checking apikey, thingspeak, '+err);
      		          else{
      		              client.attachChannel(channel_Id, { writeKey:rows[0].api_key});
      		              log.info("Apikey "+rows[0].api_key+" attached to channel id "+channel_Id);
                        var jsonS={
                             "action":'thingspeak',
                             "data"  :"Apikey "+rows[0].api_key+" attached to channel id "+channel_Id
                        };
                        sendAll(jsonS);//sending button status to all device
      		          }
      				}
            });

      });
}

/******************************
*function: findChannel(name, callback)
*input: takes channel name
*output; callback, returns the concerend channel id
*logic: finds channel id by the channel name, it will be used for
*updating the concerend channel id feed
*
*/
function findChannel(name, callback){
    var query='Select id from channels where name='+name;
    connectionThingspeak.query(query,function(err,rows,fields){
      if(err)
        log.error('Error in finding channel id, thingspeak, '+err);
      else{
        //log.info('Channel id  ',rows[0].id," for sensor ",name);
        if(rows.length>0)
          callback(rows[0].id);
        else
          callback(0);//no id found
      }
  });
}

/******************************
*function: deviceStatus(name, callback)
*input: takes device_id from feeds
*output; callback, returns the concerned status of the device in the deviceStatus
*logic: check if theire is any previous entry of the deivce in deviceStatus table
*also if the previous entry for the status was1
*
*/
function deviceStatus(row, callback){
    var devid='Select status from deviceStatus where deviceId=\''+row+'\' order by id desc limit 1';
    connectionRemote.query(devid, function(err, drows, fields) { //update the table //query2
      if (err)
        log.error("MYSQL ERROR "+err);
      else{
        if(drows.length>0){
          callback(drows[0].status,row);
        }
        else{//if no last row exists
          callback(2,row);//2 is arbitrary, but should not be 0
        }
      }
    });
}

/******************************
*function: remoteDisconnect()
*input: none
*output; return new connection to mysql db
*logic: check if connection is lost, then tries to connect again, for handling thingspeak connection
*
*********************************/
function remoteDisconnect() {
  connectionRemote = mysql.createConnection(remote_config); // Recreate the connection, since
                                                  // the old one cannot be reused.

  connectionRemote.connect(function(err) {              // The server is either down
    if(err) {                                     // or restarting (takes a while sometimes).
     //log.error('error when connecting to db:', err);
      setTimeout(remoteDisconnect, 2000); //introduce a delay before attempting to reconnect,
    }                                     // to avoid a hot loop, and to allow our node script to
  });                                     // process asynchronous requests in the meantime.
                                          // If you're also serving http, display a 503 error.
  connectionRemote.on('error', function(err) {
    //log.error('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      remoteDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });
}

//check if connection has fallen then to this, error caching
connectionRemote.on('error', function(err) {
    log.error('thingspeak db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      remoteDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
}
});

/******************************
*function: thingspeakDisconnect()
*input: none
*output; return new connection to mysql db
*logic: check if connection is lost, then tries to connect again, for handling thingspeak connection
*
*********************************/
function thingspeakDisconnect() {
  connectionThingspeak = mysql.createConnection(remote_config); // Recreate the connection, since
                                                  // the old one cannot be reused.

  connectionThingspeak.connect(function(err) {              // The server is either down
    if(err) {                                     // or restarting (takes a while sometimes).
     //log.error('error when connecting to db:', err);
      setTimeout(thingspeakDisconnect, 2000); //introduce a delay before attempting to reconnect,
    }                                     // to avoid a hot loop, and to allow our node script to
  });                                     // process asynchronous requests in the meantime.
                                          // If you're also serving http, display a 503 error.
  connectionThingspeak.on('error', function(err) {
    //log.error('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      thingspeakDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });
}

//check if connection has fallen then to this, error caching
connectionThingspeak.on('error', function(err) {
    log.error('thingspeak db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      thingspeakDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
}
});

/******************************
*function: localdbDisconnect()
*input: none
*output; return new connection to mysql db
*logic: check if connection is lost, then tries to connect again, for handling localdb connection
*
*********************************/
function localdbDisconnect() {
  connectionlocal = mysql.createConnection(localdb_config); // Recreate the connection, since
                                                  // the old one cannot be reused.

  connectionlocal.connect(function(err) {              // The server is either down
    if(err) {                                     // or restarting (takes a while sometimes).
     //log.error('error when connecting to db:', err);
      setTimeout(localdbDisconnect, 2000); //introduce a delay before attempting to reconnect,
    }                                     // to avoid a hot loop, and to allow our node script to
  });                                     // process asynchronous requests in the meantime.
                                          // If you're also serving http, display a 503 error.
  connectionlocal.on('error', function(err) {
    //log.error('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      localdbDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });
}

connectionlocal.on('error', function(err) {
    log.error('db error', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
      localdbDisconnect();                         // lost due to either server restart, or a
    } else {                                      // connnection idle timeout (the wait_timeout
      throw err;                                  // server variable configures this)
    }
  });


text:
package backup

// Copyright (c) Microsoft and contributors.  All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"context"
	"github.com/Azure/go-autorest/autorest"
	"github.com/Azure/go-autorest/autorest/azure"
	"net/http"
)

// FeatureSupportClient is the open API 2.0 Specs for Azure RecoveryServices Backup service
type FeatureSupportClient struct {
	BaseClient
}

// NewFeatureSupportClient creates an instance of the FeatureSupportClient client.
func NewFeatureSupportClient(subscriptionID string) FeatureSupportClient {
	return NewFeatureSupportClientWithBaseURI(DefaultBaseURI, subscriptionID)
}

// NewFeatureSupportClientWithBaseURI creates an instance of the FeatureSupportClient client.
func NewFeatureSupportClientWithBaseURI(baseURI string, subscriptionID string) FeatureSupportClient {
	return FeatureSupportClient{NewWithBaseURI(baseURI, subscriptionID)}
}

// Validate sends the validate request.
//
// azureRegion is azure region to hit Api parameters is feature support request object
func (client FeatureSupportClient) Validate(ctx context.Context, azureRegion string, parameters BasicFeatureSupportRequest) (result AzureVMResourceFeatureSupportResponse, err error) {
	req, err := client.ValidatePreparer(ctx, azureRegion, parameters)
	if err != nil {
		err = autorest.NewErrorWithError(err, "backup.FeatureSupportClient", "Validate", nil, "Failure preparing request")
		return
	}

	resp, err := client.ValidateSender(req)
	if err != nil {
		result.Response = autorest.Response{Response: resp}
		err = autorest.NewErrorWithError(err, "backup.FeatureSupportClient", "Validate", resp, "Failure sending request")
		return
	}

	result, err = client.ValidateResponder(resp)
	if err != nil {
		err = autorest.NewErrorWithError(err, "backup.FeatureSupportClient", "Validate", resp, "Failure responding to request")
	}

	return
}

// ValidatePreparer prepares the Validate request.
func (client FeatureSupportClient) ValidatePreparer(ctx context.Context, azureRegion string, parameters BasicFeatureSupportRequest) (*http.Request, error) {
	pathParameters := map[string]interface{}{
		"azureRegion":    autorest.Encode("path", azureRegion),
		"subscriptionId": autorest.Encode("path", client.SubscriptionID),
	}

	const APIVersion = "2017-07-01"
	queryParameters := map[string]interface{}{
		"api-version": APIVersion,
	}

	preparer := autorest.CreatePreparer(
		autorest.AsJSON(),
		autorest.AsPost(),
		autorest.WithBaseURL(client.BaseURI),
		autorest.WithPathParameters("/Subscriptions/{subscriptionId}/providers/Microsoft.RecoveryServices/locations/{azureRegion}/backupValidateFeatures", pathParameters),
		autorest.WithJSON(parameters),
		autorest.WithQueryParameters(queryParameters))
	return preparer.Prepare((&http.Request{}).WithContext(ctx))
}

// ValidateSender sends the Validate request. The method will close the
// http.Response Body if it receives an error.
func (client FeatureSupportClient) ValidateSender(req *http.Request) (*http.Response, error) {
	return autorest.SendWithSender(client, req,
		azure.DoRetryWithRegistration(client.Client))
}

// ValidateResponder handles the response to the Validate request. The method always
// closes the http.Response Body.
func (client FeatureSupportClient) ValidateResponder(resp *http.Response) (result AzureVMResourceFeatureSupportResponse, err error) {
	err = autorest.Respond(
		resp,
		client.ByInspecting(),
		azure.WithErrorUnlessStatusCode(http.StatusOK),
		autorest.ByUnmarshallingJSON(&result),
		autorest.ByClosing())
	result.Response = autorest.Response{Response: resp}
	return
}


text:
package com.shaubert.ui.adapters;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class RecyclerCheckableAdapter extends RecyclerAdapterWrapper {

    private CheckableAdapterState state;

    /**
     * Constructor wrapping a supplied ListAdapter
     *
     * @param wrapped - wrapped adapter
     */
    public RecyclerCheckableAdapter(RecyclerView.Adapter<RecyclerView.ViewHolder> wrapped) {
        this(wrapped, 0);
    }

    public RecyclerCheckableAdapter(RecyclerView.Adapter<RecyclerView.ViewHolder> wrapped, int checkableViewId) {
        super(wrapped);
        state = new CheckableAdapterState(checkableViewId) {
            @Override
            protected void adapterNotifyDataSetChanged() {
                notifyDataSetChanged();
            }
        };
    }

    public void setCheckableViewId(int checkableViewId) {
        state.setCheckableViewId(checkableViewId);
    }

    public int getCheckableViewId() {
        return state.getCheckableViewId();
    }

    public void clearCheckedState() {
        state.clearCheckedState();
    }

    public boolean hasCheckedItems() {
        return state.hasCheckedItems();
    }

    public long[] getCheckedItemIds() {
        return state.getCheckedItemIds();
    }

    public void setCheckedItems(long[] itemIds) {
        state.setCheckedItems(itemIds);
    }

    public int getCheckedItemsCount() {
        return state.getCheckedItemsCount();
    }

    public boolean isItemChecked(long itemId) {
        return state.isItemChecked(itemId);
    }

    public void setItemChecked(long itemId, boolean checked) {
        state.setItemChecked(itemId, checked);
    }

    public void toggle(long itemId) {
        state.toggle(itemId);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        super.onBindViewHolder(holder, position);
        state.refreshViewCheckedState(holder.itemView, getItemId(position));
    }

}


text:
<?php
/*
 * This file is part of the Gisoft package.
 *
 * (c) Damian Ostraszewski
 *
 */
namespace Web\PagesBundle\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use App\PagesBundle\Form\Type\Page as PageType;
use App\PagesBundle\Twig\UrlExtension as uri;
use App\CoreBundle\Controller\BaseController;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Web\PagesBundle\Form\NewsletterType;

/**
* Frontend Newsletter controller.
*
 * @author Damian Ostraszewski <info@gisoft.pl>
*/
class NewsletterController extends BaseController
{
    protected $namespace = 'WebPagesBundle';
    protected $module = 'Newsletter';
    protected $fieldName = "Strony";
    protected $redirectShow = "_pages_show";

   /**
    * show action
    *
    * @param Request $request
    * @return \Symfony\Component\HttpFoundation\RedirectResponse
    */
   public function showAction(Request $request) {

        $template = "show";
        $form = $this->createForm(NewsletterType::class);
        if ('POST' == $request->getMethod()) {
            $form->handleReque($request);
            if ($form->isValid()) {
                $formData = $form->getData();

            }
        }

        $data = array(
            'form' => $form->createView(),
         );

       return $this->render('WebPagesBundle:'.$this->module.':'.$template.'.html.twig',$data);
    }
}


text:
using Ds3.Calls;
using Ds3.Models;
using System;
using System.Collections.Generic;
using System.IO;

namespace Ds3.Helpers.Transferrers
{
    internal class WriteTransferrer : ITransferrer
    {
        public void Transfer(
            IDs3Client client,
            string bucketName,
            string objectName,
            long blobOffset,
            Guid jobId,
            IEnumerable<Range> ranges,
            Stream stream)
        {
            client.PutObject(new PutObjectRequest(
                bucketName,
                objectName,
                jobId,
                blobOffset,
                stream
            ));
        }
    }
}


text:
package org.apache.polygene.test.indexing.layered;

public interface TestCase
{
    void given()
        throws Exception;

    void when()
        throws Exception;

    void expect()
        throws Exception;
}


text:
namespace Collision
{
	extern bool AABB(Vector2<int> point, WRect rect);
	extern bool AABB(Vector2<float> point, WRect rect);
}


text:
package org.springframework.security.core.context;

import org.junit.Test;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests {@link SecurityContextImpl}.
 *
 * @author Ben Alex
 */
public class SecurityContextImplTests {

	@Test
	public void testEmptyObjectsAreEquals() {
		SecurityContextImpl obj1 = new SecurityContextImpl();
		SecurityContextImpl obj2 = new SecurityContextImpl();
		assertThat(obj1.equals(obj2)).isTrue();
	}

	@Test
	public void testSecurityContextCorrectOperation() {
		SecurityContext context = new SecurityContextImpl();
		Authentication auth = new UsernamePasswordAuthenticationToken("rod", "koala");
		context.setAuthentication(auth);
		assertThat(context.getAuthentication()).isEqualTo(auth);
		assertThat(context.toString().lastIndexOf("rod") != -1).isTrue();
	}

}


text:
class Gws::Job::Log
  include SS::Model::JobLog
  # include Gws::Reference::Site
  include Gws::SitePermission

  belongs_to :group, class_name: "Gws::Group"
  validates :group_id, presence: true
  scope :site, ->(site) { where( group_id: site.id ) }

  alias site group
  alias site_id group_id

  class << self
    def create_from_active_job!(job)
      self.create!(
        group_id: job.try(:site_id),
        user_id: job.try(:user_id),
        job_id: job.job_id,
        state: 'stop',
        pool: job.queue_name,
        class_name: job.class.name,
        args: job.arguments
      )
    end
  end
end


text:
namespace three {
namespace geometry {

class CircleParams
{
protected:
  float _radius = 50;
  unsigned _segments = 8;
  float _thetaStart = 0;
  float _thetaLength = (float)M_PI * 2;

  CircleParams(float radius, unsigned segments, float thetaStart, float thetaLength)
  : _radius(radius), _segments(segments), _thetaStart(thetaStart), _thetaLength(thetaLength) {}
};

class DLX Circle : public LinearGeometry, private CircleParams
{
  Circle(const Circle &circle) : LinearGeometry(circle), CircleParams(circle) {}

protected:
  Circle(float radius, unsigned segments, float thetaStart, float thetaLength);

public:
  using Ptr = std::shared_ptr<Circle>;
  static Ptr make(float radius, unsigned segments, float thetaStart, float thetaLength) {
    return Ptr(new Circle(radius, segments, thetaStart, thetaLength));
  }

  Circle *cloned() const override {
    return new Circle(*this);
  }
};

namespace buffer {

class DLX Circle : public BufferGeometry, private CircleParams
{
  friend class three::geometry::Circle;

  Circle(const Circle &circle);

protected:
  Circle(float radius, unsigned segments, float thetaStart, float thetaLength);

public:
  using Ptr = std::shared_ptr<Circle>;
  static Ptr make(float radius, unsigned segments, float thetaStart=0, float thetaLength=2.0f*(float)M_PI) {
    return Ptr(new Circle(radius, segments, thetaStart, thetaLength));
  }

  Circle *cloned() const override {
    return new Circle(*this);
  }
};

}

}
}

#endif //THREEPP_CIRCLE_H


text:
<!doctype html>

		<title>Zabuun - Learn Egyptian Arabic for English speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

Essays > Try to Sleep

						Expand All | Collapse All

Try to Sleep

  Norma went to bed. It was eleven o'clock. She turned out the light. She lay in bed. It was dark. It was quiet. She couldn't sleep. She closed her eyes. She tried to sleep, but she couldn't. She turned the light back on. She opened her book. She started to read her book. It was a good book. She read one page. Then she read another page. After a while, she felt sleepy. She closed the book. She turned out the light. She closed her eyes. She went straight to sleep.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
define(['exports'], function (exports) { 'use strict';

	const valueOnLib = 42;

	exports.valueOnLib = valueOnLib;

	Object.defineProperty(exports, '__esModule', { value: true });

});


text:
OroChartBundle
====================

Chart bundle provide functionality for display different types of chart.
It is solution that allows user to view data in useful chart format.
Bundle support such chart types as:
    - line chart
    - pie chart
    - flow chart

Please see [documentation](./Resources/doc/index.md) for more details.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Hedwigia 52: 83 (1912)

#### Original name
Verrucaria subdiscrepans Nyl.

### Remarks
null


text:
class RenameConfigurationsToGraderConfigurations < ActiveRecord::Migration
  def change
    rename_table 'configurations', 'grader_configurations'
  end
end


text:
/* jshint sub: true */
/* global define */

define(["Modernizr"], function (M) {

	var tests = {
		"standalone": {
			"ambientlight": M.ambientlight,
			"applicationcache": M.applicationcache,
			"audio": M.audio,
			"battery": M.batteryapi,
			"blob": M.blobconstructor,
			"canvas": M.canvas,
			"canvastext": M.canvastext,
			"contenteditable": M.contenteditable,
			"contextmenu": M.contextmenu,
			"cookies": M.cookies,
			"cors": M.cors,
			"custom-protocol-handler": M.customprotocolhandler,
			"customevent": M.customevent,
			"dart": M.dart,
			"dataview-api": M.dataview,
			"draganddrop": M.draganddrop,
			"emoji": M.emoji,
			"eventlistener": M.eventlistener,
			"exif-orientation": M.exiforientation,
			"flash": M.flash,
			"fullscreen-api": M.fullscreen,
			"gamepad": M.gamepads,
			"geolocation": M.geolocation,
			"hashchange": M.hashchange,
			"hiddenscroll": M.hiddenscroll,
			"history": M.history,
			"htmlimports": M.htmlimports,
			"ie8compat": M.ie8compat,
			"indexeddb": M.indexeddb,
			"indexeddbblob": M.indexeddbblob,
			"input": M.input,
			"inputsearchevent": M.search,
			"inputtypes": M.inputtypes,
			"intl": M.intl,
			"json": M.json,
			"lists-reversed": M.olreversed,
			"mathml": M.mathml,
			"notification": M.notification,
			"pagevisibility-api": M.pagevisibility,
			"performance": M.performance,
			"pointerevents": M.pointerevents,
			"pointerlock-api": M.pointerlock,
			"postmessage": M.postmessage,
			"proximity": M.proximity,
			"queryselector": M.queryselector,
			"quota-management-api": M.quotamanagement,
			"requestanimationframe": M.requestanimationframe,
			"serviceworker": M.serviceworker,
			"svg": M.svg,
			"templatestrings": M.templatestrings,
			"touchevents": M.touchevents,
			"typed-arrays": M.typedarrays,
			"unicode-range": M.unicoderange,
			"unicode": M.unicode,
			"userdata": M.userdata,
			"vibration": M.vibrate,
			"video": M.video,
			"vml": M.vml,
			"web-intents": M.webintents,
			"webanimations": M.animation,
			"webgl": M.webgl,
			"websockets": M.websockets
		},
		"a": {
			"download": M.adownload
		},
		"audio": {
			"loop": M.audioloop,
			"preload": M.audiopreload,
			"webaudio": M.webaudio
		},
		"battery": {
			"lowbattery": M.lowbattery
		},
		"canvas": {
			"blending": M.canvasblending,
			"todataurl": [
				M["todataurljpeg"],
				M["todataurlpng"],
				M["todataurlwebp"]
			],
			"winding": [
				M["canvaswinding"]
			]
		},
		"crypto": {
			"getrandomvalues": M.getrandomvalues
		},
		"css": {
			"all": M.cssall,
			"animations": M.cssanimations,
			"appearance": M.appearance,
			"backgroundblendmode": M.backgroundblendmode,
			"backgroundcliptext": M.backgroundcliptext,
			"backgroundposition-shorthand": M.bgpositionshorthand,
			"backgroundposition-xy": M.bgpositionxy,
			"backgroundrepeat": [
				M["bgrepeatspace"],
				M["bgrepeatround"]
			],
			"backgroundsize": M.backgroundsize,
			"backgroundsizecover": M.bgsizecover,
			"borderimage": M.borderimage,
			"borderradius": M.borderradius,
			"boxshadow": M.boxshadow,
			"boxsizing": M.boxsizing,
			"calc": M.csscalc,
			"checked": M.checked,
			"chunit": M.csschunit,
			"columns": M.csscolumns,
			"cubicbezierrange": M.cubicbezierrange,
			"displayrunin": M["display-runin"],
			"displaytable": M.displaytable,
			"ellipsis": M.ellipsis,
			"escape": M.cssescape,
			"exunit": M.cssexunit,
			"filters": M.cssfilters,
			"flexbox": M.flexbox,
			"flexboxlegacy": M.flexboxlegacy,
			"flexboxtweener": M.flexboxtweener,
			"flexwrap": M.flexwrap,
			"fontface": M.fontface,
			"generatedcontent": M.generatedcontent,
			"gradients": M.cssgradients,
			"hsla": M.hsla,
			"hyphens": [
				M["csshyphens"],
				M["softhyphens"],
				M["softhyphensfind"]
			],
			"invalid": M.cssinvalid,
			"lastchild": M.lastchild,
			"mask": M.cssmask,
			"mediaqueries": M.mediaqueries,
			"multiplebgs": M.multiplebgs,
			"nthchild": M.nthchild,
			"objectfit": M.objectfit,
			"opacity": M.opacity,
			"overflow-scrolling": M.overflowscrolling,
			"pointerevents": M.csspointerevents,
			"positionsticky": M.csspositionsticky,
			"pseudoanimations": M.csspseudoanimations,
			"pseudotransitions": M.csspseudotransitions,
			"reflections": M.cssreflections,
			"regions": M.regions,
			"remunit": M.cssremunit,
			"resize": M.cssresize,
			"rgba": M.rgba,
			"scrollbars": M.cssscrollbar,
			"shapes": M.shapes,
			"siblinggeneral": M.siblinggeneral,
			"subpixelfont": M.subpixelfont,
			"supports": M.supports,
			"target": M.target,
			"textalignlast": M.textalignlast,
			"textshadow": M.textshadow,
			"transforms": M.csstransforms,
			"transforms3d": M.csstransforms3d,
			"transformstylepreserve3d": M.preserve3d,
			"transitions": M.csstransitions,
			"userselect": M.userselect,
			"valid": M.cssvalid,
			"vhunit": M.cssvhunit,
			"vmaxunit": M.cssvmaxunit,
			"vminunit": M.cssvminunit,
			"vwunit": M.cssvwunit,
			"will-change": M.willchange,
			"wrapflow": M.wrapflow
		},
		"dom": {
			"classlist": M.classlist,
			"createElement-attrs": [
				M["createelementattrs"],
				M["createelement-attrs"]
			],
			"dataset": M.dataset,
			"documentfragment": M.documentfragment,
			"hidden": M.hidden,
			"microdata": M.microdata,
			"mutationObserver": M.mutationobserver
		},
		"elem": {
			"datalist": M.datalistelem,
			"details": M.details,
			"output": M.outputelem,
			"picture": M.picture,
			"progress-meter": [
				M["progressbar"],
				M["meter"]
			],
			"ruby": M.ruby,
			"template": M.template,
			"time": M.time,
			"track": [
				M["texttrackapi"],
				M["track"]
			],
			"unknown": M.unknownelements
		},
		"es5": {
			"array": M.es5array,
			"date": M.es5date,
			"function": M.es5function,
			"object": M.es5object,
			"specification": M.es5,
			"strictmode": M.strictmode,
			"string": M.es5string,
			"syntax": M.es5syntax,
			"undefined": M.es5undefined
		},
		"es6": {
			"array": M.es6array,
			"contains": M.contains,
			"generators": M.generators,
			"math": M.es6math,
			"number": M.es6number,
			"object": M.es6object,
			"promises": M.promises,
			"string": M.es6string
		},
		"event": {
			"deviceorientation-motion": [
				M["devicemotion"],
				M["deviceorientation"]
			],
			"oninput": M.oninput
		},
		"file": {
			"api": M.filereader,
			"filesystem": M.filesystem
		},
		"forms": {
			"capture": M.capture,
			"fileinput": M.fileinput,
			"fileinputdirectory": M.directory,
			"formattribute": M.formattribute,
			"inputnumber-l10n": M.localizednumber,
			"placeholder": M.placeholder,
			"requestautocomplete": M.requestautocomplete,
			"validation": M.formvalidation
		},
		"iframe": {
			"sandbox": M.sandbox,
			"seamless": M.seamless,
			"srcdoc": M.srcdoc
		},
		"img": {
			"apng": M.apng,
			"jpegxr": M.jpegxr,
			"sizes": M.sizes,
			"srcset": M.srcset,
			"webp-alpha": M.webpalpha,
			"webp-animation": M.webpanimation,
			"webp-lossless": [
				M["webplossless"],
				M["webp-lossless"]
			],
			"webp": M.webp
		},
		"input": {
			"formaction": M.inputformaction,
			"formenctype": M.inputformenctype,
			"formmethod": M.inputformmethod,
			"formtarget": M.inputformtarget
		},
		"network": {
			"beacon": M.beacon,
			"connection": M.lowbandwidth,
			"eventsource": M.eventsource,
			"xhr-responsetype-arraybuffer": M.xhrresponsetypearraybuffer,
			"xhr-responsetype-blob": M.xhrresponsetypeblob,
			"xhr-responsetype-document": M.xhrresponsetypedocument,
			"xhr-responsetype-json": M.xhrresponsetypejson,
			"xhr-responsetype-text": M.xhrresponsetypetext,
			"xhr-responsetype": M.xhrresponsetype,
			"xhr2": M.xhr2
		},
		"script": {
			"async": M.scriptasync,
			"defer": M.scriptdefer
		},
		"speech": {
			"speech-recognition": M.speechrecognition,
			"speech-synthesis": M.speechsynthesis
		},
		"storage": {
			"localstorage": M.localstorage,
			"sessionstorage": M.sessionstorage,
			"websqldatabase": M.websqldatabase
		},
		"style": {
			"scoped": M.stylescoped
		},
		"svg": {
			"asimg": M.svgasimg,
			"clippaths": M.svgclippaths,
			"filters": M.svgfilters,
			"foreignobject": M.svgforeignobject,
			"inline": M.inlinesvg,
			"smil": M.smil
		},
		"textarea": {
			"maxlength": M.textareamaxlength
		},
		"url": {
			"bloburls": M.bloburls,
			"data-uri": M.datauri,
			"parser": M.urlparser
		},
		"video": {
			"autoplay": M.videoautoplay,
			"loop": M.videoloop,
			"preload": M.videopreload
		},
		"webgl": {
			"extensions": M.webglextensions
		},
		"webrtc": {
			"datachannel": M.datachannel,
			"getusermedia": M.getusermedia,
			"peerconnection": M.peerconnection
		},
		"websockets": {
			"binary": M.websocketsbinary
		},
		"window": {
			"framed": M.framed,
			"matchmedia": M.matchmedia
		},
		"workers": {
			"blobworkers": M.blobworkers,
			"dataworkers": M.dataworkers,
			"sharedworkers": M.sharedworkers,
			"transferables": M.transferables,
			"webworkers": M.webworkers
		}
	};

	return M;

});


text:
class vector3_t
{
public:
  double coord[3];

  // constructors
  vector3_t():coord{0.0,0.0,0.0} {}
  vector3_t(double x, double y, double z) : coord{x,y,z} {}

  // getters
  double inline x() const {return coord[0];}
  double inline y() const {return coord[1];}
  double inline z() const {return coord[2];}

  // Vector operator functions (return new vector)
  double    dot(const vector3_t& v) const;
  vector3_t cross(const vector3_t& v) const;
  vector3_t project(vector3_t v) const;

  // Vector metric functions
  double distance(const vector3_t&  v) const;
  double length() const;

  // Transformation functions
  void scale(double s);
  void normalize();

  // Vector arithmatic functions
  friend vector3_t& operator+= (vector3_t& v1, const vector3_t& v2);
  friend vector3_t& operator-= (vector3_t& v1, const vector3_t& v2);

  friend vector3_t operator+ (const vector3_t& v1, const vector3_t& v2);
  friend vector3_t operator- (const vector3_t& v1, const vector3_t& v2);

  // Vector comparison functions
  // TODO remove these because we shouldn't do double comparisons like this
  //friend bool operator== (const vector3_t& v1, const vector3_t& v2);
  //friend bool operator!= (const vector3_t& v1, const vector3_t& v2);

  // cout operator overload
  friend std::ostream& operator<<(std::ostream& os, const vector3_t& v);
};

class ray3_t
{
public:
  vector3_t components[2];

  // getters (used in constructor, so defined first)
  auto inline point() const {return components[0];}
  auto inline dir()   const {return components[1];}

  // constructors
  ray3_t(const vector3_t& point_, const vector3_t& dir_);

  // cout operator overload
  friend std::ostream& operator<<(std::ostream& os, const ray3_t& r);
};

class poly3_t
{
public:
  vector3_t points[4];

  // constructors
  poly3_t(vector3_t p1, vector3_t p2, vector3_t p3)
  {
    // copy in points (do not pass in by reference)
    points[0] = p1;
    points[1] = p2;
    points[3] = p3;
    set_normal();
  }

  // getters
  auto inline p1() const {return points[0];}
  auto inline p2() const {return points[1];}
  auto inline p3() const {return points[2];}
  auto inline n()  const {return points[3];}

  // cout operator overload
  friend std::ostream& operator<<(std::ostream& os, const poly3_t& t);

private:
  // helper functions
  void set_normal();
};

#endif //OCTREE_TYPES_3D_H


text:
package org.apache.samoa.evaluation;

public interface ClassificationPerformanceEvaluator extends PerformanceEvaluator {
}


text:
if $(grc &>/dev/null)
then
  GRC=`which grc`
  if [ "$TERM" != dumb ] && [ -n GRC ]
  then
    alias colourify="$GRC -es --colour=auto"
    alias configure='colourify ./configure'
    alias diff='colourify diff'
    alias make='colourify make'
    alias gcc='colourify gcc'
    alias g++='colourify g++'
    alias as='colourify as'
    alias gas='colourify gas'
    alias ld='colourify ld'
    alias netstat='colourify netstat'
    alias ping='colourify ping'
    alias traceroute='colourify /usr/sbin/traceroute'
  fi
fi


text:
class DashboardController < ApplicationController

  before_action :authenticate_member!

  def index
    #render(:controller => 'post', :action => 'views/posts/index')
  end

end


text:
using System.Linq;

namespace Localization.Core
{
	public static class StringExtensions
	{
		private static readonly string[] _platformSuffix = {Constants.WINDOWS_PHONE_SUFFIX, Constants.ANDROID_SUFFIX, Constants.IOS_SUFFIX};

		public static string ProcessKey(this string source)
		{
			return source?.Replace(".", "__");
		}

		public static string UnprocessKey(this string source)
		{
			return source?.Replace("__", ".");
		}

		public static string SimplifyKey(this string source)
		{
			if (source == null)
			{
				return null;
			}

			foreach (string suffix in _platformSuffix)
			{
				if (source.EndsWith(suffix))
				{
					return source.Substring(0, source.Length - suffix.Length);
				}
			}

			return source;
		}

		public static bool IsPlatformSpecificString(this string source)
		{
			if (source == null)
			{
				return false;
			}
			return _platformSuffix.Any(source.EndsWith);
		}

		public static bool IsAndroidString(this string source)
		{
			if (source == null)
			{
				return false;
			}
			return source.EndsWith(Constants.ANDROID_SUFFIX);
		}

		public static bool IsIosString(this string source)
		{
			if (source == null)
			{
				return false;
			}
			return source.EndsWith(Constants.IOS_SUFFIX);
		}

		public static bool IsWindowsPhoneString(this string source)
		{
			if (source == null)
			{
				return false;
			}
			return source.EndsWith(Constants.WINDOWS_PHONE_SUFFIX);
		}
	}
}


text:
package com.moldedbits.argus;

/**
 * Overall state of the system.
 */

public enum ArgusState {
    SIGNED_OUT,
    SIGNED_IN
}


text:
import {
  PROJECT_ADMIN_ROLE,
  PROJECT_MANAGER_ROLE,
} from '@waldur/core/constants';
import { RootState } from '@waldur/store/reducers';

import { isOwnerOrStaff, isManager, isAdmin } from './selectors';

describe('isOwnerOrStaff selector', () => {
  const staff = {
    is_staff: true,
    is_support: false,
    url: 'staff_url',
    uuid: 'staff_uuid',
  };

  const owner = {
    is_staff: false,
    is_support: false,
    url: 'owner_url',
    uuid: 'owner_uuid',
  };

  it('returns true if user is staff', () => {
    const workspace = { user: staff };
    const actual = isOwnerOrStaff({ workspace } as RootState);
    expect(actual).toBe(true);
  });

  it('returns true if user is organization owner', () => {
    const workspace = {
      user: owner,
      customer: {
        name: 'Alice',
        url: 'url',
        uuid: 'uuid',
        owners: [owner],
      },
    };
    const actual = isOwnerOrStaff({ workspace } as RootState);
    expect(actual).toBe(true);
  });

  it('returns false if user is not staff and is not organization owner', () => {
    const workspace = {
      user: owner,
      customer: {
        name: 'Alice',
        url: 'url',
        uuid: 'uuid',
        owners: [staff],
      },
    };
    const actual = isOwnerOrStaff({ workspace } as RootState);
    expect(actual).toBe(false);
  });
});

describe('isManager selector', () => {
  it('should return true if project has a manager who is a current user', () => {
    const user = {
      is_staff: false,
      is_support: false,
      url: 'manager_url',
      uuid: 'manager_uuid',
    };
    const manager = {
      user_uuid: 'manager_uuid',
      role: PROJECT_MANAGER_ROLE,
    };
    const workspace = {
      user,
      project: {
        name: 'Project 1',
        url: 'url',
        uuid: 'uuid',
        permissions: [manager],
        quotas: [],
      },
    };
    const actual = isManager({ workspace } as RootState);
    expect(actual).toBe(true);
  });
});

describe('isAdmin selector', () => {
  it('should return true if project has an admin who is a current user', () => {
    const user = {
      is_staff: false,
      is_support: false,
      url: 'admin_url',
      uuid: 'admin_uuid',
    };
    const admin = {
      user_uuid: 'admin_uuid',
      role: PROJECT_ADMIN_ROLE,
    };
    const workspace = {
      user,
      project: {
        name: 'Project 1',
        url: 'url',
        uuid: 'uuid',
        permissions: [admin],
        quotas: [],
      },
    };
    const actual = isAdmin({ workspace } as RootState);
    expect(actual).toBe(true);
  });
});


text:
<!--
Include Base: /Users/jtsm/Chukong-Inc/pr/en/src/kochava/v3-cpp
-->

#Kochava

##Integration
Open a terminal and use the following command to install the SDKBOX Kochava plugin. Make sure you setup SDKBOX installer correctly.
```bash
$ sdkbox import kochava
```

<<[../../shared/notice.md]

## Configuration
SDKBOX Installer will automatically inject a sample configuration to your `sdkbox_config.json`, that you have to modify it before you can use it for your own app

Here is an example of the Kochava configuration, you need to replace
`<KOCHAVA_APP_ID>` with your specific [Kochava](https://kochava.com/) account information.
Here is an example adding `Kochava`:
```json
"kochava" :
{
    "kochavaAppId" : "<KOCHAVA_APP_ID>",
    "enableLogging" : 1,
    "retrieveAttribution" : 1
}
```

<<[sdkbox-config-encrypt.md]

##Usage
<<[usage.md]

<<[api-reference.md]

<<[manual_integration.md]

<<[manual_ios.md]

##Manual Integration For Android and Android Studio
Both __Android__ development using a command-line and using __Android Studio__ are supported. `proj.android` will be used as our `<project_root>` for __command-line__ development, while `proj.android-studio` will be used as our `<project_root>` for __Android Studio__.
<<[manual_android.md]

<<[extra-step.md]


text:
<!DOCTYPE html>

  <title>HeaderConstants.java</title>
  <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
  <link rel='stylesheet' type='text/css' href='../../../../../coverage.css'/>
  <link rel='shortcut icon' type='image/png' href='../../../../../logo.png'/>

httpclient-cache/src/main/java/org/apache/http/client/cache/HeaderConstants.java

/*...*/

      27

package org.apache.http.client.cache;

import org.apache.http.annotation.Immutable;

import ...

/**
 * Records static constants for various HTTP header names.
 * @since 4.1
 */
/*...*/

      35

@Immutable

      36

public class HeaderConstants {

      38

    public static final String GET_METHOD = "GET";

      39

    public static final String HEAD_METHOD = "HEAD";

      40

    public static final String OPTIONS_METHOD = "OPTIONS";

      41

    public static final String PUT_METHOD = "PUT";

      42

    public static final String DELETE_METHOD = "DELETE";

      43

    public static final String TRACE_METHOD = "TRACE";

      45

    public static final String LAST_MODIFIED = "Last-Modified";

      46

    public static final String IF_MATCH = "If-Match";

      47

    public static final String IF_RANGE = "If-Range";

      48

    public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since";

      49

    public static final String IF_MODIFIED_SINCE = "If-Modified-Since";

      50

    public static final String IF_NONE_MATCH = "If-None-Match";

      52

    public static final String PRAGMA = "Pragma";

      53

    public static final String MAX_FORWARDS = "Max-Forwards";

      54

    public static final String ETAG = "ETag";

      55

    public static final String EXPIRES = "Expires";

      56

    public static final String AGE = "Age";

      57

    public static final String VARY = "Vary";

      58

    public static final String ALLOW = "Allow";

      59

    public static final String VIA = "Via";

      60

    public static final String PUBLIC = "public";

      61

    public static final String PRIVATE = "private";

      63

    public static final String CACHE_CONTROL = "Cache-Control";

      64

    public static final String CACHE_CONTROL_NO_STORE = "no-store";

      65

    public static final String CACHE_CONTROL_NO_CACHE = "no-cache";

      66

    public static final String CACHE_CONTROL_MAX_AGE = "max-age";

      67

    public static final String CACHE_CONTROL_MAX_STALE = "max-stale";

      68

    public static final String CACHE_CONTROL_MIN_FRESH = "min-fresh";

      69

    public static final String CACHE_CONTROL_MUST_REVALIDATE = "must-revalidate";

      70

    public static final String CACHE_CONTROL_PROXY_REVALIDATE = "proxy-revalidate";

      71

    public static final String STALE_IF_ERROR = "stale-if-error";

      72

    public static final String STALE_WHILE_REVALIDATE = "stale-while-revalidate";

      74

    public static final String WARNING = "Warning";

      75

    public static final String RANGE = "Range";

      76

    public static final String CONTENT_RANGE = "Content-Range";

      77

    public static final String WWW_AUTHENTICATE = "WWW-Authenticate";

      78

    public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate";

      79

    public static final String AUTHORIZATION = "Authorization";

      81

}


text:
"""
Tests for :mod:`~exa.isotopes`
#############################################
Note that elements and isotope singletons are created on module import.
"""
from unittest import TestCase
from exa.util import isotopes

class TestIsotopes(TestCase):
    """Tests for isotope and element generation."""
    def test_created(self):
        """Check that elements and isotope objects were created."""
        iso = isotopes.as_df()
        for sym in iso['symbol'].unique():
            self.assertTrue(hasattr(isotopes, sym))

    def test_element(self):
        """Test element attributes."""
        self.assertEqual(isotopes.H.Z, 1)
        self.assertGreater(isotopes.H.mass, 1.007)
        self.assertGreater(isotopes.H.radius, 0.6)

    def test_isotope(self):
        """Test isotope attributes."""
        self.assertEqual(isotopes.H['1'].Z, 1)
        self.assertEqual(isotopes.H['1'].A, 1)
        self.assertGreater(isotopes.H['1'].mass, 1.007)
        self.assertGreater(isotopes.H['1'].radius, 0.6)