text:
from generator.actions import Actions, Variable
from random import choice, randint
from os.path import dirname, abspath, join
import sys
import struct

sys.path.append(join(dirname(dirname(dirname(abspath(__file__)))), "support"))
import support as sp
from common import DEBUG, CONFIG
from election import Election, ElectionManager, Voter, Candidate, Vote

class VotingMachine(Actions):

    ELECTION_NAME           = "Enter election name: "
    ELECTION_CREATED        = "Election Created.\n"
    ELECTION_OPEN           = "Voting Open.\n"
    ELECTION_CLOSED         = "Voting Closed.\n"
    CREATE_E_MGR            = "## Create election manager ##\n"
    CREATE_VOTER            = "## Create voter ##\n"
    CREATE_CANDIDATE        = "## Create candidate ##\n"
    CANDIDATE_ADDED         = "Candidate Added.\n"
    CANDIDATE_INVALID       = "New candidate invalid\n"

    ZERO_CANDIDATES         = "\tThere were zero candidates.\n"
    CANDIDATE_ORDER         = "\t| Rank | Votes | Candidate Name |\n"
    ZERO_VOTERS             = "\tThere were zero voters.\n"
    VOTER_ORDER             = "\t| Voted? | Voter Name |\n"

    VOTING_RESULTS          = "## Voting Results ##\n"
    CANDIDATE_SUMMARY       = "## Candidate Summary ##\n"
    VOTER_TURNOUT           = "## Voter Turnout ##\n"

    SELECT_CANDIDATE        = "Select one candidate from the folloowing:\n"
    EMPTY_CANDIDATES        = "There are no candidates. Go add some.\n"
    FULL_CANDIDATES         = "Not accepting additional candidates.\n"
    INVALID_CANDIDATE       = "Invalid candidate. Try again.\n"

    F_NAME                  = "\tEnter first name: "
    L_NAME                  = "\tEnter last name: "

    ENTER_ID                = "\tEnter your ID number: "
    ENTER_AUTH_KEY          = "\tEnter auth key: "
    NEW_AUTH_KEY            = "\tYour auth key is: "
    NEW_UID                 = "\tYour ID number is: "

    NUM_WINNERS_Q           = "Enter number of election winners desired: "
    MAX_CANDIDATES_Q        = "Enter the max number of candidates allowed: "
    WRITE_IN_OK_Q           = "Can voters write-in new candidates? (Yy/Nn): "

    CHOOSE                  = "Choose an option: "

    MENU_LOGIN              = "14: Login\n"
    MENU_MAIN               = "15: Main Menu\n"
    MENU_CREATE_ELECTION    = "17: Create Election\n"
    MENU_OPEN_VOTING        = "18. Open Voting\n"
    MENU_CLOSE_VOTING       = "20. Close Voting\n"
    MENU_ELECTION_STATUS    = "22. Election Status\n"

    MENU_REGISTER_VOTER     = "38. Register Voter\n"
    MENU_VOTE               = "36. Vote\n"
    MENU_ADD_CANDIDATE      = "54. Add Candidate\n"
    MENU_VOTING_RESULTS     = "56. Voting Results\n"
    MENU_VOTER_TURNOUT      = "72. Voter Turnout\n"
    MENU_CANDIDATE_SUMMARY  = "88. Candidate Summary\n"

    MENU_QUIT               = "95. Quit\n"

    FAIL                    = "Is voting too hard?!\n"

    MENU_ENTRIES            = {
                                0x0E: MENU_LOGIN,
                                0x0F: MENU_MAIN,

                                0x11: MENU_CREATE_ELECTION,
                                0x12: MENU_OPEN_VOTING,
                                0x14: MENU_CLOSE_VOTING,
                                0x16: MENU_ELECTION_STATUS,

                                0x24: MENU_VOTE,
                                0x26: MENU_REGISTER_VOTER,

                                0x36: MENU_ADD_CANDIDATE,

                                0x38: MENU_VOTING_RESULTS,
                                0x48: MENU_VOTER_TURNOUT,
                                0x58: MENU_CANDIDATE_SUMMARY,

                                0x5F: MENU_QUIT,
                            }

    def _receive_by_len(self, a_str, delim='', term=''):
        line = "{0}{1}{2}".format(a_str, delim, term)
        self.read(length=len(line), expect=line)

    def _receive_by_delim(self, delim=''):
        self.read(delim=delim)

    def _send_str(self, cmd):
        self.write(sp.pack_single_string("{0}{1}".format(cmd, CONFIG['DELIM'])))

    def _receive_prompt_send_answer(self, prompt, answer):
        self._receive_by_len(prompt, term=CONFIG['TERM'])
        self._send_str(answer)

    def _send_first_last_name(self, f_name, l_name):
        self._receive_prompt_send_answer(self.F_NAME, f_name)
        self._receive_prompt_send_answer(self.L_NAME, l_name)

    def _is_menu_id_valid_op(self, menu_id):
        creds = False
        op = 0 != (menu_id & self.state['e'].state)

        if 0x0E == menu_id:
            creds = (False == self.state['e'].have_authd_user())
        elif 0x0F == menu_id:
            creds = (True == self.state['e'].have_authd_user())

        elif 0x11 == menu_id:
            creds = (False == self.state['e'].have_authd_user())
        elif 0x12 == menu_id:
            creds = (True == self.state['e'].have_authd_e_mgr())
        elif 0x14 == menu_id:
            creds = (True == self.state['e'].have_authd_e_mgr())
        elif 0x16 == menu_id:
            creds = (True == self.state['e'].have_authd_e_mgr())

        elif 0x24 == menu_id:
            creds = (True == self.state['e'].have_authd_voter())
        elif 0x26 == menu_id:
            creds = (False == self.state['e'].have_authd_user())

        elif 0x36 == menu_id:
            creds = (((True == self.state['e'].have_authd_e_mgr()) or \
                    ((True == self.state['e'].have_authd_user()) and (1 == self.state['e'].write_in_ok))) and \
                    (self.state['e'].get_candidate_count() < self.state['e'].max_candidates))

        elif 0x38 == menu_id:
            creds = (True == self.state['e'].have_authd_user())
        elif 0x48 == menu_id:
            creds = (True == self.state['e'].have_authd_e_mgr())
        elif 0x58 == menu_id:
            creds = (True == self.state['e'].have_authd_e_mgr())
        else:
            creds = False

        return op and creds

    def _receive_fail(self):
        self._receive_by_len(self.FAIL, term=CONFIG['TERM'])

    def _process_menu(self):
        '''
        Receive the relevant lines in the menu.

        # login_menu
        # admin_menu
        # voting_menu
        # results_menu
        # quit entry
        '''
        cmds = self.MENU_ENTRIES.keys()
        cmds.sort()
        menu = ''
        for m_id in cmds:
            if True == self._is_menu_id_valid_op(m_id):
                menu += self.MENU_ENTRIES[m_id] + CONFIG['TERM']

        menu += self.MENU_QUIT + CONFIG['TERM']
        self._receive_by_len(menu)

        self._receive_by_len(self.CHOOSE, term=CONFIG['TERM'])

    def _back_to_main_menu(self):
        '''
        Option to go from sub_menu back to main_menu.
        '''
        self._process_menu()

        cmd = 0x0F
        self._send_str(cmd)

        if True == self._is_menu_id_valid_op(cmd):
            self.state['e'].authd_user = None
            return 0
        else:
            self._receive_fail()
            return -1

    def _create_election(self):
        '''
        Create the election manager profile and setup the election parameters
        '''
        self._process_menu()

        self.state['e'].authd_user = None

        cmd = 0x11
        self._send_str(cmd)

        if True == self._is_menu_id_valid_op(cmd):

            # create election mgr
            self._receive_by_len(self.CREATE_E_MGR, term=CONFIG['TERM'])
            mgr = self.state['e'].make_random_e_mgr()
            self._send_first_last_name(mgr.f_name, mgr.l_name)
            self._receive_by_len(self.NEW_UID)
            self._receive_by_len(mgr.id, delim=CONFIG['DELIM'])
            self._receive_by_len(self.NEW_AUTH_KEY)
            auth_key = Variable('authkey')
            auth_key.set_slice(0)
            self.read(delim=CONFIG['DELIM'], assign=auth_key)
            self.state['e'].set_e_mgr_auth_key(auth_key)

            # send election name
            self._receive_prompt_send_answer(self.ELECTION_NAME, self.state['e'].name)

            # set election conf
            num_winners = randint(1, 4)
            max_candidates = randint(5, 20)
            write_in_ok = choice(['Y', 'N'])
            self._receive_prompt_send_answer(self.NUM_WINNERS_Q, num_winners)
            self._receive_prompt_send_answer(self.MAX_CANDIDATES_Q, max_candidates)
            self._receive_prompt_send_answer(self.WRITE_IN_OK_Q, write_in_ok)

            self.state['e'].num_winners = num_winners
            self.state['e'].max_candidates = max_candidates
            self.state['e'].write_in_ok = 1 if 'Y' == write_in_ok else 0
            self.state['e'].is_configured = True

            # set state to NEW
            self.state['e'].set_state('NEW')

            # recv ELECTION_CREATED
            self._receive_by_len(self.ELECTION_CREATED, term=CONFIG['TERM'])
            return 0
        else:
            self._receive_fail()
            return -1

    def _register_voter(self):
        '''
        Register a new voter
        '''
        self._process_menu()
        cmd = 0x26
        self._send_str(cmd)
        self.state['e'].authd_user = None

        if True == self._is_menu_id_valid_op(cmd):
            self._receive_by_len(self.CREATE_VOTER, term=CONFIG['TERM'])

            voter = self.state['e'].make_random_voter()
            # send voter's first and last name
            self._send_first_last_name(voter.f_name, voter.l_name)

            # receive "NEW_UID" msg and voter's ID
            self._receive_by_len(self.NEW_UID)
            self._receive_by_len(voter.id, delim=CONFIG['DELIM'])

            self.state['e'].add_voter(voter)
            return 0
        else:
            self._receive_fail()
            return -1

    def _login(self, who="VOTER"):
        '''
        Login either a voter or the election manager, or cause login error
        '''
        self._process_menu()
        cmd = 0x0E
        self._send_str(cmd)

        if True == self._is_menu_id_valid_op(cmd):
            self.state['e'].authd_user = None
            user = None
            if who is "ERROR":
                user = self.state['e'].make_random_voter(is_valid=False)
            elif who is "E_MGR":
                user = self.state['e'].e_mgr
            elif who is "VOTER":
                user = self.state['e'].get_random_voter()
                if user is None:
                    who = "ERROR"
                    user = self.state['e'].make_random_voter(is_valid=False)

            # send creds
            self._receive_prompt_send_answer(self.ENTER_ID, user.id)
            self._receive_prompt_send_answer(self.L_NAME, user.l_name)

            if who is "E_MGR":
                self._receive_by_len(self.ENTER_AUTH_KEY, term=CONFIG['TERM'])
                self.write(user.auth_key) # auth_key is a Variable()

            if who is "ERROR":
                self._receive_fail()
                return -1
            else:
                self.state['e'].authd_user = user

            return 0
        else:
            self._receive_fail()
            return -1

    def _open_voting(self):
        '''
        Set voting to OPEN state
        '''
        self._process_menu()
        cmd = 0x12
        self._send_str(cmd)

        if True == self._is_menu_id_valid_op(cmd):
            self.state['e'].set_state('OPEN')
            self._receive_by_len(self.ELECTION_OPEN, term=CONFIG['TERM'])

            self.state['e'].authd_user = None
            return 0
        else:
            self._receive_fail()
            return -1

    def _close_voting(self):
        '''
        Set voting to CLOSED state
        '''
        self._process_menu()
        cmd = 0x14
        self._send_str(cmd)

        if True == self._is_menu_id_valid_op(cmd):
            self.state['e'].set_state('CLOSED')
            self._receive_by_len(self.ELECTION_CLOSED, term=CONFIG['TERM'])

            self.state['e'].authd_user = None
            return 0
        else:
            self._receive_fail()
            return -1

    def _election_status(self):
        '''
        Get the status of the election.
        '''
        self._process_menu()
        cmd = 0x16
        self._send_str(cmd)

        fmt = "\tNumber of voters: {0}\n\tNumber of votes: {1}\n\tNumber of candidates: {2}\n"

        if True == self._is_menu_id_valid_op(cmd):
            msg = fmt.format(self.state['e'].get_voter_count(),
                                self.state['e'].get_vote_count(),
                                self.state['e'].get_candidate_count())
            self._receive_by_len(msg)

            self.state['e'].authd_user = None
            return 0
        else:
            self._receive_fail()
            return -1

    def _add_candidate(self):
        '''
        Add a new candidate for the election.
        '''
        self._process_menu()
        cmd = 0x36
        self._send_str(cmd)

        if True == self._is_menu_id_valid_op(cmd):

            if self.state['e'].get_candidate_count() >= self.state['e'].max_candidates:
                self._receive_by_len(self.FULL_CANDIDATES, term=CONFIG['TERM'])
            else:
                self._receive_by_len(self.CREATE_CANDIDATE, term=CONFIG['TERM'])

                candidate = None
                c_invalid = False
                # occassionally, submit candidate with same name
                if self.chance(0.01) and 0 is not self.state['e'].get_candidate_count():
                    candidate = self.state['e'].get_random_candidate()
                    c_invalid = True
                else:
                    candidate = self.state['e'].make_random_candidate()
                # send first and last name
                self._send_first_last_name(candidate.f_name, candidate.l_name)

                if c_invalid is True:
                    self._receive_by_len(self.CANDIDATE_INVALID, term=CONFIG['TERM'])
                else:
                    self._receive_by_len(self.CANDIDATE_ADDED, term=CONFIG['TERM'])
                    self.state['e'].add_candidate(candidate)

            self.state['e'].authd_user = None
            return 0
        else:
            self._receive_fail()
            return -1

    def _vote(self):
        '''
        Place a vote.
        '''
        self._process_menu()
        cmd = 0x24
        self._send_str(cmd)

        if True == self._is_menu_id_valid_op(cmd):

            # check to see if there are any candidates to vote for
            if 0 == self.state['e'].get_candidate_count():
                self._receive_by_len(self.EMPTY_CANDIDATES, term=CONFIG['TERM'])
            else:
                # read candidate list
                self._receive_by_len(self.SELECT_CANDIDATE, term=CONFIG['TERM'])
                fmt = "\t{0}: {1} {2}\n"
                for c in self.state['e'].candidates:
                    line = fmt.format(c.id, c.f_name, c.l_name)
                    self._receive_by_len(line)

                self._receive_by_len(self.CHOOSE, term=CONFIG['TERM'])

                # make selection
                c = self.state['e'].get_random_candidate()
                self._send_str(c.id)

                # receive voting receipt
                p1 = "Confirmation #"
                p2 = " Vote recorded for candidate: {0} {1}.\n"

                self._receive_by_len(p1)

                vote_id = Variable('voteid{0}'.format(self.state['e'].authd_user.id))
                vote_id.set_slice(0)
                self.read(delim='.', assign=vote_id)

                self._receive_by_len(p2.format(c.f_name, c.l_name))

                # record vote
                v = Vote(vote_id, self.state['e'].authd_user, c)
                self.state['e'].add_vote(v)

            self.state['e'].authd_user = None
            return 0
        else:
            self._receive_fail()
            return -1

    def _voting_results(self):
        '''
        Get the voting results
        '''
        self._process_menu()
        cmd = 0x38
        self._send_str(cmd)

        if True == self._is_menu_id_valid_op(cmd):
            self._receive_by_len(self.VOTING_RESULTS, term=CONFIG['TERM'])

            # check to see if there were any candidates voted for
            if 0 == self.state['e'].get_candidate_count():
                self._receive_by_len(self.ZERO_CANDIDATES, term=CONFIG['TERM'])
            else:
                # calculate voting results
                v_res = self.state['e'].get_voting_results()

                # read candidate list
                self._receive_by_len(self.CANDIDATE_ORDER, term=CONFIG['TERM'])
                fmt = "\t{0}.\t{1}\t"
                winners = 0
                for (count, c) in v_res:
                    if winners >= self.state['e'].num_winners:
                        break
                    winners += 1
                    line = fmt.format(winners, count)
                    self._receive_by_len(line)
                    # use a wild card recv for the name portion because python and C code
                    # have different results from a sort with multiple equal sort-keys.
                    self._receive_by_delim(delim='\n')

            self.state['e'].authd_user = None
            return 0
        else:
            self._receive_fail()
            return -1

    def _voter_turnout(self):
        '''
        Get the voter turnout results
        '''
        self._process_menu()
        cmd = 0x48
        self._send_str(cmd)
        fmt = "\tNumber of voters: {0}\n\tNumber of votes: {1}\n";

        if True == self._is_menu_id_valid_op(cmd):
            self._receive_by_len(self.VOTER_TURNOUT, term=CONFIG['TERM'])

            if 0 is self.state['e'].get_voter_count():
                self._receive_by_len(self.ZERO_VOTERS, term=CONFIG['TERM'])
            else:
                # get counts
                line = fmt.format(self.state['e'].get_voter_count(), self.state['e'].get_vote_count())
                self._receive_by_len(line)

                # get all voters
                self._receive_by_len(self.VOTER_ORDER, term=CONFIG['TERM'])
                for i in range(self.state['e'].get_voter_count()):
                    # use a wild card recv for the names portion because python and C code
                    # have different ordering when reading all values from a hash table.
                    self._receive_by_delim(delim='\n')

            self.state['e'].authd_user = None
            return 0
        else:
            self._receive_fail()
            return -1

    def _candidate_summary(self):
        '''
        Get the candidate summary
        '''
        self._process_menu()
        cmd = 0x58
        self._send_str(cmd)
        fmt = "\tNumber of candidates: {0}\n";

        if True == self._is_menu_id_valid_op(cmd):
            self._receive_by_len(self.CANDIDATE_SUMMARY, term=CONFIG['TERM'])

            if 0 is self.state['e'].get_voter_count():
                self._receive_by_len(self.ZERO_CANDIDATES, term=CONFIG['TERM'])
            else:
                # get counts
                line = fmt.format(self.state['e'].get_candidate_count())
                self._receive_by_len(line)

                # read candidate list
                v_res = self.state['e'].get_voting_results()
                self._receive_by_len(self.CANDIDATE_ORDER, term=CONFIG['TERM'])
                fmt = "\t{0}.\t{1}\t"
                winners = 0
                for (count, c) in v_res:
                    winners += 1
                    line = fmt.format(winners, count)
                    self._receive_by_len(line)
                    # use a wild card recv for the name portion because python and C code
                    # have different results from a sort with multiple equal sort-keys.
                    self._receive_by_delim(delim='\n')

            self.state['e'].authd_user = None
            return 0
        else:
            self._receive_fail()
            return -1

    def _quit(self):
        '''
        Quit cleanly
        '''
        self._process_menu()
        cmd = 0x5F
        self._send_str(cmd)
        return -1

    def start(self):
        #self.delay(100)
        self.state['e'] = Election()

    def init_state(self):
        '''
        Process the Election in the INIT state
        '''
        if self.chance(0.8):
            return self._create_election()
        else:
            return self._quit()

    def new_state(self):
        '''
        Process the Election in the NEW state
        '''
        # create some voters
        for i in range(randint(5,15)):
            if 0 != self._register_voter():
                return -1

        # add a candidate
        if self.chance(0.5):
            # e_mgr do it
            if 0 != self._login("E_MGR") or 0 != self._add_candidate():
                return -1
        else:
            # voter do it
            if 0 != self._login("VOTER") or 0 != self._add_candidate():
                return -1
        # check election status
        if self.chance(0.1):
            if 0 != self._login("E_MGR") or 0 != self._election_status():
                return -1
        # open voting
        if 0 != self._login("E_MGR") or 0 != self._open_voting():
            return -1

        # rarely use go back to main menu command
        if self.chance(0.01):
            # e_mgr do it
            if 0 != self._login("E_MGR") or 0 != self._back_to_main_menu():
                return -1
        elif self.chance(0.01):
            # voter do it
            if 0 != self._login("VOTER") or 0 != self._back_to_main_menu():
                return -1

        # rarely use quit command
        if self.chance(0.01):
            # e_mgr do it
            if 0 != self._login("E_MGR") or 0 != self._quit():
                return -1
        elif self.chance(0.01):
            # voter do it
            if 0 != self._login("VOTER") or 0 != self._quit():
                return -1
        elif self.chance(0.01):
            # main menu do it
            return self._quit()

        # rarely do bogus login
        if self.chance(0.01):
            if 0 != self._login("ERROR"):
                return -1

        return 0

    def open_state(self):
        '''
        Process the Election in the OPEN state
        '''
        # create some voters
        for i in range(randint(5,15)):
            if 0 != self._register_voter():
                return -1

        for c in range(1, self.state['e'].max_candidates):
            # add a candidate
            if self.chance(0.5):
                # e_mgr do it
                if 0 != self._login("E_MGR") or 0 != self._add_candidate():
                    return -1
            else:
                # voter do it
                if 0 != self._login("VOTER") or 0 != self._add_candidate():
                    return -1

        # do some voting
        for v in range(5, self.state['e'].get_voter_count()):
            if 0 != self._login("VOTER") or 0 != self._vote():
                return -1

        # check election status
        if self.chance(0.1):
            if 0 != self._login("E_MGR") or 0 != self._election_status():
                return -1

        # close voting
        if 0 != self._login("E_MGR") or 0 != self._close_voting():
            return -1

        # use go back to main menu option
        if self.chance(0.01):
            # e_mgr do it
            if 0 != self._login("E_MGR") or 0 != self._back_to_main_menu():
                return -1
        elif self.chance(0.01):
            # voter do it
            if 0 != self._login("VOTER") or 0 != self._back_to_main_menu():
                return -1

        # rarely use quit command
        if self.chance(0.01):
            # e_mgr do it
            if 0 != self._login("E_MGR") or 0 != self._quit():
                return -1
        elif self.chance(0.01):
            # voter do it
            if 0 != self._login("VOTER") or 0 != self._quit():
                return -1
        elif self.chance(0.01):
            # main menu do it
            return self._quit()

        # rarely do bogus login
        if self.chance(0.01):
            if 0 != self._login("ERROR"):
                return -1

        return 0

    def closed_state(self):
        '''
        Process the Election in the CLOSED state
        '''
        # check voting results
        if self.chance(0.5):
            if 0 != self._login("E_MGR") or 0 != self._voting_results():
                return -1
        else:
            if 0 != self._login("VOTER") or 0 != self._voting_results():
                return -1

        # check voter turnout
        if 0 != self._login("E_MGR") or 0 != self._voter_turnout():
            return -1

        # check candidate summary
        if 0 != self._login("E_MGR") or 0 != self._candidate_summary():
            return -1

        # use go back to main menu option
        if self.chance(0.01):
            # e_mgr do it
            if 0 != self._login("E_MGR") or 0 != self._back_to_main_menu():
                return -1
        elif self.chance(0.01):
            # voter do it
            if 0 != self._login("VOTER") or 0 != self._back_to_main_menu():
                return -1

        # rarely use quit command
        if self.chance(0.01):
            # e_mgr do it
            if 0 != self._login("E_MGR") or 0 != self._quit():
                return -1
        elif self.chance(0.01):
            # voter do it
            if 0 != self._login("VOTER") or 0 != self._quit():
                return -1
        elif self.chance(0.01):
            # main menu do it
            return self._quit()

        # rarely do bogus login
        if self.chance(0.01):
            if 0 != self._login("ERROR"):
                return -1

        return 0


text:
//Distant Terrain Mod for Daggerfall-Unity
//http://www.reddit.com/r/dftfu
//http://www.dfworkshop.net/
//Author: Michael Rauter (a.k.a. Nystul)
//License: MIT License (http://www.opensource.org/licenses/mit-license.php)

using UnityEngine;
using System.Collections;
using DaggerfallWorkshop.Game;
using DaggerfallWorkshop.Game.UserInterface;
using DaggerfallWorkshop.Game.Utility.ModSupport;   //required for modding features
using DaggerfallWorkshop.Game.Utility.ModSupport.ModSettings; //required for mod settings

using DistantTerrain;

namespace DistantTerrain
{
    public class _startupMod : MonoBehaviour
    {
        public static Mod mod;
        private static GameObject gameobjectDistantTerrain = null;
        private static DistantTerrain componentDistantTerrain = null;

        // Settings
        private static bool enableTerrainTransition = true;
        private static bool enableFadeIntoSkybox = true;
        private static bool enableSeaReflections = true;
        private static bool enableImprovedTerrain = true;
        private static bool indicateLocations = true;

        private static Shader shaderDistantTerrainTilemap = null;
        private static Shader shaderBillboardBatchFaded = null;
        private static Shader shaderTransitionRingTilemap = null;
        private static Shader shaderTransitionRingTilemapTextureArray = null;

        [Invoke(StateManager.StateTypes.Start, 0)]
        public static void InitStart(InitParams initParams)
        {
            mod = initParams.Mod;

            gameobjectDistantTerrain = new GameObject("DistantTerrain");
            componentDistantTerrain = gameobjectDistantTerrain.AddComponent<DistantTerrain>();

            ModSettings settings = mod.GetSettings();

            shaderDistantTerrainTilemap = mod.GetAsset<Shader>("Shaders/DistantTerrainTilemap.shader");
            shaderBillboardBatchFaded = mod.GetAsset<Shader>("Shaders/DaggerfallBillboardBatchFaded.shader");
            shaderTransitionRingTilemap = mod.GetAsset<Shader>("Shaders/TransitionRingTilemap.shader");
            shaderTransitionRingTilemapTextureArray = mod.GetAsset<Shader>("Shaders/TransitionRingTilemapTextureArray.shader");

            enableTerrainTransition = settings.GetValue<bool>("GeneralSettings", "TerrainTransition");
            enableFadeIntoSkybox = settings.GetValue<bool>("GeneralSettings", "FadeIntoSkybox");
            enableSeaReflections = settings.GetValue<bool>("GeneralSettings", "SeaReflections");
            enableImprovedTerrain = settings.GetValue<bool>("ImprovedTerrainSettings", "EnableImprovedTerrain");
            indicateLocations = settings.GetValue<bool>("ImprovedTerrainSettings", "IndicateLocations");

            componentDistantTerrain.EnableTerrainTransition = enableTerrainTransition;
            componentDistantTerrain.EnableFadeIntoSkybox = enableFadeIntoSkybox;
            componentDistantTerrain.EnableSeaReflections = enableSeaReflections;
            componentDistantTerrain.EnableImprovedTerrain = enableImprovedTerrain;
            componentDistantTerrain.IndicateLocations = indicateLocations;
            componentDistantTerrain.ShaderDistantTerrainTilemap = shaderDistantTerrainTilemap;
            componentDistantTerrain.ShaderBillboardBatchFaded = shaderBillboardBatchFaded;
            componentDistantTerrain.ShaderTransitionRingTilemap = shaderTransitionRingTilemap;
            componentDistantTerrain.ShaderTransitionRingTilemapTextureArray = shaderTransitionRingTilemapTextureArray;
        }

        void Awake()
        {
            mod.IsReady = true;
        }

        //[Invoke(StateManager.StateTypes.Start)]
        //public static void InitStart(InitParams initParams)
        //{
        //    // check if debug gameobject is present, if so do not initalize mod
        //    if (GameObject.Find("debug_DistantTerrain"))
        //        return;

        //    // Get this mod
        //    mod = initParams.Mod;

        //    // Load settings.
        //    ModSettings settings = mod.GetSettings();

        //    // settings
        //    enableTerrainTransition = settings.GetValue<bool>("GeneralSettings", "TerrainTransition");
        //    enableFadeIntoSkybox = settings.GetValue<bool>("GeneralSettings", "FadeIntoSkybox");
        //    enableSeaReflections = settings.GetValue<bool>("GeneralSettings", "SeaReflections");
        //    enableImprovedTerrain = settings.GetValue<bool>("ImprovedTerrainSettings", "EnableImprovedTerrain");
        //    indicateLocations = settings.GetValue<bool>("ImprovedTerrainSettings", "IndicateLocations");

        //    shaderDistantTerrainTilemap = mod.GetAsset<Shader>("Shaders/DistantTerrainTilemap.shader");
        //    shaderBillboardBatchFaded = mod.GetAsset<Shader>("Shaders/DaggerfallBillboardBatchFaded.shader");
        //    shaderTransitionRingTilemap = mod.GetAsset<Shader>("Shaders/TransitionRingTilemap.shader");
        //    shaderTransitionRingTilemapTextureArray = mod.GetAsset<Shader>("Shaders/TransitionRingTilemapTextureArray.shader");

        //    initMod();

        //    //after finishing, set the mod's IsReady flag to true.
        //    ModManager.Instance.GetMod(initParams.ModTitle).IsReady = true;
        //}

        ///*
        //*   used for debugging
        //*   howto debug:
        //*       -) add a dummy GameObject to DaggerfallUnityGame scene
        //*       -) attach this script (_startupMod) as component
        //*       -) deactivate mod in mod list (since dummy gameobject will start up mod)
        //*       -) attach debugger and set breakpoint to one of the mod's cs files and debug
        //*/
        //void Awake()
        //{
        //    shaderDistantTerrainTilemap = Shader.Find("Daggerfall/DistantTerrain/DistantTerrainTilemap");
        //    shaderBillboardBatchFaded = Shader.Find("Daggerfall/DistantTerrain/BillboardBatchFaded");
        //    shaderTransitionRingTilemap = Shader.Find("Daggerfall/DistantTerrain/TransitionRingTilemap");
        //    shaderTransitionRingTilemapTextureArray = Shader.Find("Daggerfall/DistantTerrain/TransitionRingTilemapTextureArray");

        //    initMod();
        //}

        //public static void initMod()
        //{
        //    gameobjectDistantTerrain = new GameObject("DistantTerrain");
        //    componentDistantTerrain = gameobjectDistantTerrain.AddComponent<DistantTerrain>();
        //    componentDistantTerrain.EnableTerrainTransition = enableTerrainTransition;
        //    componentDistantTerrain.EnableFadeIntoSkybox = enableFadeIntoSkybox;
        //    componentDistantTerrain.EnableSeaReflections = enableSeaReflections;
        //    componentDistantTerrain.EnableImprovedTerrain = enableImprovedTerrain;
        //    componentDistantTerrain.IndicateLocations = indicateLocations;
        //    componentDistantTerrain.ShaderDistantTerrainTilemap = shaderDistantTerrainTilemap;
        //    componentDistantTerrain.ShaderBillboardBatchFaded = shaderBillboardBatchFaded;
        //    componentDistantTerrain.ShaderTransitionRingTilemap = shaderTransitionRingTilemap;
        //    componentDistantTerrain.ShaderTransitionRingTilemapTextureArray = shaderTransitionRingTilemapTextureArray;
        //}
    }
}

redpajama_set_name: RedPajamaGithub


text:
module CacheBar
  describe "register_api_to_cache" do
    it 'should raise ArgumentError if host is blank' do
      expect{ CacheBar.register_api_to_cache('', {key_name: 'api', expire_in: 1})}.to raise_error(ArgumentError)
    end

    it 'should raise ArgumentError if no :key_name' do
      expect{ CacheBar.register_api_to_cache('api.org', {expire_in: 1})}.to raise_error(ArgumentError)
    end

    it 'should raise ArgumentError if no :expire_in ' do
      expect{ CacheBar.register_api_to_cache('api.org', {key_name: 'api'})}.to raise_error(ArgumentError)
    end

    it 'should add host to apis if valid' do
      expect(CacheBar.register_api_to_cache('api.org', {key_name: 'api', expire_in: 1})).to eq({key_name: 'api', expire_in: 1})
      expect(HTTParty::HTTPCache.apis).to include('api.org')
    end
  end

  describe ClassMethods do
    describe 'caches_api_responses' do
      pending "I haven't had time to look into what it does"
    end
  end

  describe 'using HTTParty with CacheBar' do
    describe 'and gets a good response' do
      before do
        mock_data_store
        setup_cachebar
        turn_on_caching
        VCR.insert_cassette('good_response')
      end

      after do
        VCR.eject_cassette
      end
      it 'calls data_store#store_response with response hash and expiration' do
        #TODO: I'd like to verify those return values, but how?
        expect_any_instance_of(HTTParty::Request).to receive(:cacheable?).and_call_original
        expect_any_instance_of(HTTParty::Request).to receive(:response_exists?).and_call_original
        expect_any_instance_of(HTTParty::Request).to receive(:graceable?).and_call_original

        expect_any_instance_of(HTTParty::Request).to receive(:store_in_cache).with(hash_including(:code, :body)).and_call_original
        expect_any_instance_of(MockDataStore).to receive(:store_response).with(hash_including(:code, :body), 5)
        TwitterAPI.user_timeline('viget')
      end

      it 'calls data_store#store_backup with response hash' do
        #TODO: I'd like to verify those return values, but how?
        expect_any_instance_of(HTTParty::Request).to receive(:cacheable?).and_call_original
        expect_any_instance_of(HTTParty::Request).to receive(:response_exists?).and_call_original
        expect_any_instance_of(HTTParty::Request).to receive(:graceable?).and_call_original

        expect_any_instance_of(HTTParty::Request).to receive(:store_in_backup).with(hash_including(:code, :body)).and_call_original
        expect_any_instance_of(MockDataStore).to receive(:store_backup)
        TwitterAPI.user_timeline('viget')
      end

      it 'returns a HTTParty::Response' do
        #TODO: I'd like to verify those return values, but how?
        expect_any_instance_of(HTTParty::Request).to receive(:cacheable?).and_call_original
        expect_any_instance_of(HTTParty::Request).to receive(:response_exists?).and_call_original
        expect_any_instance_of(HTTParty::Request).to receive(:graceable?).and_call_original
        expect(TwitterAPI.user_timeline('viget').class).to eq(HTTParty::Response)
      end
    end
    describe 'and response exists' do
      before do
        mock_data_store
        setup_cachebar
        turn_on_caching
        VCR.insert_cassette('good_response')
      end

      after do
        VCR.eject_cassette
      end

      it 'returns a HTTParty::Response' do
        expect_any_instance_of(HTTParty::Request).to receive(:cacheable?).and_call_original
        expect_any_instance_of(HTTParty::Request).to receive(:response_exists?).and_return(true)
        expect_any_instance_of(HTTParty::Request).to receive(:get_response).and_return({code: 200, body:{status:"OK"}.to_json})
        expect_any_instance_of(HTTParty::Request).to receive(:response_from).and_call_original
        response = TwitterAPI.user_timeline('viget')
        expect(response.class).to eq(HTTParty::Response)
      end
    end

    describe 'and response timeouts' do
      it 'retrives from backup if it exists' do
        mock_data_store
        setup_cachebar
        turn_on_caching

        expect_any_instance_of(HTTParty::Request).to receive(:cacheable?).and_call_original
        expect_any_instance_of(HTTParty::Request).to receive(:response_exists?).and_call_original
        expect_any_instance_of(HTTParty::Request).to receive(:backup_exists?).and_return(true)
        expect_any_instance_of(HTTParty::Request).to receive(:get_backup).and_return({code: 200, body:{status:"OK"}.to_json})
        expect_any_instance_of(HTTParty::Request).to receive(:response_from).and_call_original

        expect_any_instance_of(HTTParty::Request).to receive(:timeout).and_raise(Timeout::Error)
        response = TwitterAPI.user_timeline('viget')
        expect(response.class).to eq(HTTParty::Response)
        expect(response.parsed_response["status"]).to eq("OK")
      end

      it 'stores backup in cache if it exists' do
        mock_data_store
        setup_cachebar
        turn_on_caching

        expect_any_instance_of(HTTParty::Request).to receive(:cacheable?).and_call_original
        expect_any_instance_of(HTTParty::Request).to receive(:response_exists?).and_call_original
        expect_any_instance_of(HTTParty::Request).to receive(:backup_exists?).and_return(true)
        expect_any_instance_of(HTTParty::Request).to receive(:get_backup).and_return({code: 200, body:{status:"OK"}.to_json})
        expect_any_instance_of(HTTParty::Request).to receive(:store_in_cache).with({code: 200, body:{status:"OK"}.to_json}, 300).and_call_original
        expect_any_instance_of(MockDataStore).to receive(:store_response).with(hash_including(:code, :body), 300)

        expect_any_instance_of(HTTParty::Request).to receive(:timeout).and_raise(Timeout::Error)
        TwitterAPI.user_timeline('viget')
      end
    end
  end
end


text:
class ResponseNotAuthenticException(Exception):
    def __init__(self):
        return super(ResponseNotAuthenticException, self).__init__('AuthenticationResponseNotValid')


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\SdRunlog */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'r_type')->textInput() ?>

    <?= $form->field($model, 'r_content')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'r_logtime')->textInput() ?>

    <?= $form->field($model, 'r_operator')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'r_operateitem')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'r_status')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
#include "msg.hpp"
#include "zmq.h"

#include <string.h>
#include <stdlib.h>
#include <new>

#include "stdint.hpp"
#include "likely.hpp"
#include "err.hpp"

//  Check whether the sizes of public representation of the message (zmq_msg_t)
//  and private representation of the message (zmq::msg_t) match.
typedef char zmq_msg_size_check
    [2 * ((sizeof (zmq::msg_t) == sizeof (zmq_msg_t)) != 0) - 1];

bool zmq::msg_t::check ()
{
     return u.base.type >= type_min && u.base.type <= type_max;
}

int zmq::msg_t::init ()
{
    u.vsm.type = type_vsm;
    u.vsm.flags = 0;
    u.vsm.size = 0;
    return 0;
}

int zmq::msg_t::init_size (size_t size_)
{
    if (size_ <= max_vsm_size) {
        u.vsm.type = type_vsm;
        u.vsm.flags = 0;
        u.vsm.size = (unsigned char) size_;
    }
    else {
        u.lmsg.type = type_lmsg;
        u.lmsg.flags = 0;
        u.lmsg.content =
            (content_t*) malloc (sizeof (content_t) + size_);
        if (unlikely (!u.lmsg.content)) {
            errno = ENOMEM;
            return -1;
        }

        u.lmsg.content->data = u.lmsg.content + 1;
        u.lmsg.content->size = size_;
        u.lmsg.content->ffn = NULL;
        u.lmsg.content->hint = NULL;
        new (&u.lmsg.content->refcnt) zmq::atomic_counter_t ();
    }
    return 0;
}

int zmq::msg_t::init_data (void *data_, size_t size_, msg_free_fn *ffn_,
    void *hint_)
{
    //  If data is NULL and size is not 0, a segfault
    //  would occur once the data is accessed
    assert (data_ != NULL || size_ == 0);

    //  Initialize constant message if there's no need to deallocate
    if(ffn_ == NULL) {
        u.cmsg.type = type_cmsg;
        u.cmsg.flags = 0;
        u.cmsg.data = data_;
        u.cmsg.size = size_;
    }
    else {
        u.lmsg.type = type_lmsg;
        u.lmsg.flags = 0;
        u.lmsg.content = (content_t*) malloc (sizeof (content_t));
        if (!u.lmsg.content) {
            errno = ENOMEM;
            return -1;
        }

        u.lmsg.content->data = data_;
        u.lmsg.content->size = size_;
        u.lmsg.content->ffn = ffn_;
        u.lmsg.content->hint = hint_;
        new (&u.lmsg.content->refcnt) zmq::atomic_counter_t ();
    }
    return 0;

}

int zmq::msg_t::init_delimiter ()
{
    u.delimiter.type = type_delimiter;
    u.delimiter.flags = 0;
    return 0;
}

int zmq::msg_t::close ()
{
    //  Check the validity of the message.
    if (unlikely (!check ())) {
        errno = EFAULT;
        return -1;
    }

    if (u.base.type == type_lmsg) {

        //  If the content is not shared, or if it is shared and the reference
        //  count has dropped to zero, deallocate it.
        if (!(u.lmsg.flags & msg_t::shared) ||
              !u.lmsg.content->refcnt.sub (1)) {

            //  We used "placement new" operator to initialize the reference
            //  counter so we call the destructor explicitly now.
            u.lmsg.content->refcnt.~atomic_counter_t ();

            if (u.lmsg.content->ffn)
                u.lmsg.content->ffn (u.lmsg.content->data,
                    u.lmsg.content->hint);
            free (u.lmsg.content);
        }
    }

    //  Make the message invalid.
    u.base.type = 0;

    return 0;

}

int zmq::msg_t::move (msg_t &src_)
{
    //  Check the validity of the source.
    if (unlikely (!src_.check ())) {
        errno = EFAULT;
        return -1;
    }

    int rc = close ();
    if (unlikely (rc < 0))
        return rc;

    *this = src_;

    rc = src_.init ();
    if (unlikely (rc < 0))
        return rc;

    return 0;
}

int zmq::msg_t::copy (msg_t &src_)
{
    //  Check the validity of the source.
    if (unlikely (!src_.check ())) {
        errno = EFAULT;
        return -1;
    }

    int rc = close ();
    if (unlikely (rc < 0))
        return rc;

    if (src_.u.base.type == type_lmsg) {

        //  One reference is added to shared messages. Non-shared messages
        //  are turned into shared messages and reference count is set to 2.
        if (src_.u.lmsg.flags & msg_t::shared)
            src_.u.lmsg.content->refcnt.add (1);
        else {
            src_.u.lmsg.flags |= msg_t::shared;
            src_.u.lmsg.content->refcnt.set (2);
        }
    }

    *this = src_;

    return 0;

}

void *zmq::msg_t::data ()
{
    //  Check the validity of the message.
    zmq_assert (check ());

    switch (u.base.type) {
    case type_vsm:
        return u.vsm.data;
    case type_lmsg:
        return u.lmsg.content->data;
    case type_cmsg:
        return u.cmsg.data;
    default:
        zmq_assert (false);
        return NULL;
    }
}

size_t zmq::msg_t::size ()
{
    //  Check the validity of the message.
    zmq_assert (check ());

    switch (u.base.type) {
    case type_vsm:
        return u.vsm.size;
    case type_lmsg:
        return u.lmsg.content->size;
    case type_cmsg:
        return u.cmsg.size;
    default:
        zmq_assert (false);
        return 0;
    }
}

unsigned char zmq::msg_t::flags ()
{
    return u.base.flags;
}

void zmq::msg_t::set_flags (unsigned char flags_)
{
    u.base.flags |= flags_;
}

void zmq::msg_t::reset_flags (unsigned char flags_)
{
    u.base.flags &= ~flags_;
}

bool zmq::msg_t::is_identity () const
{
    return (u.base.flags & identity) == identity;
}

bool zmq::msg_t::is_delimiter ()
{
    return u.base.type == type_delimiter;
}

bool zmq::msg_t::is_vsm ()
{
    return u.base.type == type_vsm;
}

bool zmq::msg_t::is_cmsg ()
{
    return u.base.type == type_cmsg;
}

void zmq::msg_t::add_refs (int refs_)
{
    zmq_assert (refs_ >= 0);

    //  No copies required.
    if (!refs_)
        return;

    //  VSMs, CMSGS and delimiters can be copied straight away. The only
    //  message type that needs special care are long messages.
    if (u.base.type == type_lmsg) {
        if (u.lmsg.flags & msg_t::shared)
            u.lmsg.content->refcnt.add (refs_);
        else {
            u.lmsg.content->refcnt.set (refs_ + 1);
            u.lmsg.flags |= msg_t::shared;
        }
    }
}

bool zmq::msg_t::rm_refs (int refs_)
{
    zmq_assert (refs_ >= 0);

    //  No copies required.
    if (!refs_)
        return true;

    //  If there's only one reference close the message.
    if (u.base.type != type_lmsg || !(u.lmsg.flags & msg_t::shared)) {
        close ();
        return false;
    }

    //  The only message type that needs special care are long messages.
    if (!u.lmsg.content->refcnt.sub (refs_)) {
        //  We used "placement new" operator to initialize the reference
        //  counter so we call the destructor explicitly now.
        u.lmsg.content->refcnt.~atomic_counter_t ();

        if (u.lmsg.content->ffn)
            u.lmsg.content->ffn (u.lmsg.content->data, u.lmsg.content->hint);
        free (u.lmsg.content);

        return false;
    }

    return true;
}


text:
package com.agileapes.powerpack.reflection.tools.impl;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * This filter will only include any method that matches the descriptions expected of a 'setter' method
 *
 * @author Mohammad Milad Naseri (m.m.naseri@gmail.com)
 * @since 1.0 (2012/11/14, 23:47)
 * @see ReadAccessMethodFilter
 */
public class WriteAccessMethodFilter extends PatternMethodFilter {

    public WriteAccessMethodFilter() {
        super("set[A-Z].*");
    }

    @Override
    public boolean accept(Method method) {
        return super.accept(method) && Modifier.isPublic(method.getModifiers()) && !Modifier.isAbstract(method.getModifiers())
                && method.getParameterTypes().length == 1 && method.getReturnType().equals(Void.TYPE);
    }

}


text:
$(function () {

    module("bootstrap-alerts")

      test("should be defined on jquery object", function () {
        ok($(document.body).alert, 'alert method is defined')
      })

      test("should return element", function () {
        ok($(document.body).alert()[0] == document.body, 'document.body returned')
      })

      test("should fade element out on clicking .close", function () {
        var alertHTML = '
'
          + '×'
          + '
Holy guacamole! Best check yo self, you're not looking too good.
'
          + '
'
          , alert = $(alertHTML).alert()

        alert.find('.close').click()

        ok(!alert.hasClass('in'), 'remove .in class on .close click')
      })

      test("should remove element when clicking .close", function () {
        $.support.transition = false

        var alertHTML = '
'
          + '×'
          + '
Holy guacamole! Best check yo self, you're not looking too good.
'
          + '
'
          , alert = $(alertHTML).appendTo('#qunit-runoff').alert()

        ok($('#qunit-runoff').find('.alert-message').length, 'element added to dom')

        alert.find('.close').click()

        ok(!$('#qunit-runoff').find('.alert-message').length, 'element removed from dom')
      })

})


text:
<!DOCTYPE html>

		<title>three.js webgl - loader - ttf</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

			three.js - TTFLoader using opentype by gero3

type to enter new text, drag to spin the text

change color,
			change bevel


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta name="robots" content="noindex">

	<title>Reset password</title>
	<meta name = "viewport" content = "width = 630">

	<link rel="stylesheet" href="../assets/stylesheets/reset.css" type="text/css" media="all" charset="utf-8">
	<link rel="stylesheet" href="../assets/stylesheets/login.css" type="text/css" media="all" charset="utf-8">

	<link rel="shortcut icon" href="../assets/images/admin/admin_favicon.ico" type="image/ico">

	<form>

Introduzca el email y le enviaremos un correo

<input class="text" placeholder="email" type="email" />

		<input type="submit" value="Enviar" />
	</form>


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

<title>bbdd Class Hierarchy</title>
<meta name="date" content="2016-11-16">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package bbdd

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

bbdd.HibernateUtil

bbdd.MainDBManager (implements bbdd.InterfazBD)

bbdd.HibernateManager

bbdd.MySqlManager

bbdd.ManagerBd (implements bbdd.InterfazBD)

Interface Hierarchy

bbdd.InterfazBD

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package org.apache.jmeter.protocol.http.util;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.jmeter.util.SlowSocket;

/**
 * Commons HttpClient protocol factory to generate "slow" sockets for emulating dial-up modems
 */

public class SlowHttpClientSocketFactory implements ProtocolSocketFactory {

    private final int CPS; // Characters per second to emulate

    /**
     *
     * @param cps - characters per second
     */
    public SlowHttpClientSocketFactory(final int cps) {
        super();
        CPS = cps;
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress clientHost,
            int clientPort) throws IOException, UnknownHostException {
        return new SlowSocket(CPS,host,port,clientHost,clientPort);
    }

    @Override
    public Socket createSocket(String host, int port) throws IOException,
            UnknownHostException {
        return new SlowSocket(CPS,host,port);
    }

    @Override
    public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
            HttpConnectionParams params)
    throws IOException, UnknownHostException, ConnectTimeoutException {
        int timeout = params.getConnectionTimeout();
        if (timeout == 0) {
            return new SlowSocket(CPS,host,port,localAddress,localPort);
        } else {
            return new SlowSocket(CPS,host,port,localAddress,localPort, timeout);
        }
    }
}


text:
package hash

import (
	"crypto/sha256"
	"encoding/hex"
)

func Raw(data []byte) [32]byte {
	return sha256.Sum256(data)
}

func String(data []byte) string {
	hv := Raw(data)
	return hex.EncodeToString(hv[:])
}


text:
using Erpk.Models.Common;
using Erpk.Models.Exchange;

namespace Erpk.Models.Donations
{
    public interface IDonateTask
    {
        int RecipientCitizenId { get; }
    }

    public interface IDonateItemsTask : IDonateTask
    {
        Industry Industry { get; }
        int Quality { get; }
        int Amount { get; }
    }

    public interface IDonateMoneyTask : IDonateTask
    {
        Currency Currency { get; }
        float Amount { get; }
    }

    public abstract class DonateTask : IDonateTask
    {
        public int RecipientCitizenId { get; set; }
    }

    public class DonateItemsTask : DonateTask, IDonateItemsTask
    {
        public Industry Industry { get; set; }
        public int Quality { get; set; }
        public int Amount { get; set; }
    }

    public class DonateMoneyTask : DonateTask, IDonateMoneyTask
    {
        public Currency Currency { get; set; }
        public float Amount { get; set; }
    }
}


text:
<?php

namespace Catalog\VideoGalleryBundle\Controller\Video_category;

use Admingenerated\CatalogVideoGalleryBundle\BaseVideo_categoryController\ListController as BaseListController;

/**
 * ListController
 */
class ListController extends BaseListController
{
    protected function processQuery($query)
    {
        $projectId = $this->get('session')->get('project_id');
        $project = $this->getDoctrine()->getRepository('CatalogProjectBundle:Project')->find($projectId);
        $query->andWhere('q.project =:project')
                ->setParameter('project', $project);

        return $query;
    }
}


text:
<?php

namespace Integrated\Bundle\ContentBundle\Document\Content\Embedded\Storage;

use Doctrine\Common\Collections\ArrayCollection;
use Integrated\Common\Content\Document\Storage\Embedded\MetadataInterface;

/**
 * @author Johnny Borg <johnny@e-active.nl>
 */
class Metadata implements MetadataInterface
{
    /**
     * @var string
     */
    protected $extension;

    /**
     * @var string
     */
    protected $mimeType;

    /**
     * @var string
     */
    protected $credits;

    /**
     * @var string
     */
    protected $description;

    /**
     * @var array
     */
    protected $headers = [];

    /**
     * @var array
     */
    protected $metadata = [];

    /**
     * {@inheritdoc}
     */
    public function __construct($extension, $mimeType, ArrayCollection $headers, ArrayCollection $metadata)
    {
        $this->extension = $extension;
        $this->mimeType = $mimeType;
        $this->headers = $headers->toArray();
        $this->metadata = $metadata->toArray();
    }

    /**
     * {@inheritdoc}
     */
    public function storageData()
    {
        return new ArrayCollection(
            array_merge_recursive(
                $this->metadata,
                [
                    'headers' => array_replace($this->headers, ['Content-Type' => $this->mimeType]),
                ],
                ['credits' => $this->getCredits()],
                ['description' => $this->getDescription()]
            )
        );
    }

    /**
     * {@inheritdoc}
     */
    public function getExtension()
    {
        return $this->extension;
    }

    /**
     * {@inheritdoc}
     */
    public function getMimeType()
    {
        return $this->mimeType;
    }

    /**
     * @return ?string
     */
    public function getCredits(): ?string
    {
        return $this->credits;
    }

    /**
     * @param ?string $credits
     */
    public function setCredits(?string $credits): void
    {
        $this->credits = $credits;
    }

    /**
     * @return ?string
     */
    public function getDescription(): ?string
    {
        return $this->description;
    }

    /**
     * @param ?string $description
     */
    public function setDescription(?string $description): void
    {
        $this->description = $description;
    }

    /**
     * {@inheritdoc}
     */
    public function getHeaders()
    {
        return new ArrayCollection($this->headers);
    }

    /**
     * {@inheritdoc}
     */
    public function getMetadata()
    {
        return new ArrayCollection($this->metadata);
    }
}


text:
import sys
from typing import TYPE_CHECKING

if sys.version_info < (3, 7) or TYPE_CHECKING:
    from ._button import Button
    from ._font import Font
    from ._pad import Pad
else:
    from _plotly_utils.importers import relative_import

    __all__, __getattr__, __dir__ = relative_import(
        __name__, [], ["._button.Button", "._font.Font", "._pad.Pad"]
    )


text:
rm -rf cmake-build-*

mkdir -p cmake-build-release
pushd cmake-build-release
cmake -DCMAKE_BUILD_TYPE=Release ..
popd

mkdir -p cmake-build-release-symbol
pushd cmake-build-release-symbol
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo ..
popd

mkdir -p cmake-build-debug
pushd cmake-build-debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
popd


text:
function getGlobal () {
  return window || global
}

let GLOBAL = getGlobal()

GLOBAL.__apiCount__ = 0
GLOBAL.__apiCounter = {
  add () {
    GLOBAL.__apiCount__++
  },
  remove () {
    GLOBAL.__apiCount__--
  },
  get: function () {
    return GLOBAL.__apiCount__
  }
}

// function getMessage (xhr) {
//   let message = ''
//   try {
//     let response = JSON.parse(xhr.responseText)
//     message = response.message || response.msg
//   } catch (e) {
//     message = xhr.responseText
//   }
//   if (xhr.status === 0 && xhr.statusText === 'timeout') message = '请求超时'
//   if (xhr.status === 200 && !message) message = xhr.statusText
//   return message
// }
// function handleError (errTextMap = {}, xhr, toast) {
//   let message = getMessage(xhr)
//   if (message) console.warn('Ajax: ' + message)
//   if (xhr.status !== 200 && toast) toast({message: errTextMap[xhr.status] || message || '请求失败', duration: 3500})
// }
// function handleSuccess (xhr, toast) {
//   let message = getMessage(xhr)
//   if (xhr.status === 200) {
//     if (toast) toast({ message: '请求成功' })
//   } else {
//     if (toast) {
//       toast({
//         message: '请求异常',
//         iconClass: 'ion-android-cancel'
//       })
//     }
//     if (message) console.warn('Ajax: ' + message)
//   }
// }

if (!GLOBAL.__apiConfig__) GLOBAL.__apiConfig__ = {}
if (!GLOBAL.__apiRoot__) GLOBAL.__apiRoot__ = null

function getUrl (modelName, modelConfig = {}, registerConfig = {}, config = {}) {
  let windowApiConfig = GLOBAL.__apiConfig__[modelName]
  if (!windowApiConfig) windowApiConfig = {}
  let url = windowApiConfig.url ||
    config.url ||
    modelConfig.url ||
    registerConfig.url || ''
  let apiRoot = GLOBAL.__apiRoot__ ||
    config.__apiRoot ||
    modelConfig.__apiRoot ||
    registerConfig.__apiRoot || ''
  let ignoreGlobalApiRoot = windowApiConfig.ignoreGlobalApiRoot ||
    config.__ignoreGlobalApiRoot ||
    modelConfig.__ignoreGlobalApiRoot ||
    registerConfig.__ignoreGlobalApiRoot
  return ignoreGlobalApiRoot ? url : (apiRoot + url)
}

let apiRegister = function (modelsArray = [], registerConfig = {}, jquery) {
  let $ = jquery
  // merge all models
  let models = {}
  modelsArray.forEach((m, i) => {
    for (let key in m) {
      let model = m[key]
        // test if there are api useing same name
      // if (key in models) throw new Error(`model: api should not have same name "${key}".`)
      if (key in models) console.warn(`ajaxManager: api in models should not have same name "${key}".`)
      models[key] = model
    }
    if (!models.__default) models.__default = {}
  })
  // globle config
  // $.ajaxSetup(Object.assign({}, models.__default || {}, {
  //   // reset data and event
  //   data: null,
  //   beforeSend: null,
  //   success: null,
  //   error: null,
  //   complete: null
  // }))
  let globalEvents = { // events set in __default and register should be add in this array
    beforeSend: [],
    success: [],
    error: [],
    complete: []
  }
  function fireGlobalEvents (funcArray, argsArray) {
    for (let i = 0; i < funcArray.length; i++) {
      if (typeof funcArray[i] === 'function') funcArray[i](...argsArray)
    }
  }
  function fireLocalEvent (localEvent, argsArray) {
    if (typeof localEvent === 'function') localEvent(...argsArray)
  }
  let startAndStopEvents = {
    ajaxStart: [],
    ajaxStop: []
  }
  function fireStartAndStopEvents (eventType, argsArray) {
    for (let i = 0; i < startAndStopEvents[eventType].length; i++) {
      if (typeof startAndStopEvents[eventType][i] === 'function') startAndStopEvents[eventType][i](...argsArray)
    }
  }
  let apis = {}
  for (let key in models) {
    if (!/^__/g.test(key)) {
      apis[key] = function (config = {}, triggerAjaxStartAndStopEvent = true, triggerGlobalEvents = true) {
        // merge event
        Object.keys(globalEvents).map(eventName => {
          if (registerConfig[eventName]) globalEvents[eventName].push(registerConfig[eventName])
          if (models.__default[eventName]) globalEvents[eventName].push(models.__default[eventName])
        })
        Object.keys(startAndStopEvents).map(eventName => {
          if (registerConfig[eventName]) startAndStopEvents[eventName].push(registerConfig[eventName])
          if (models.__default[eventName]) startAndStopEvents[eventName].push(models.__default[eventName])
        })

        let localEvents = {
          beforeSend: null,
          success: null,
          error: null,
          complete: null
        }
        Object.keys(localEvents).map(eventName => {
          localEvents[eventName] = config[eventName] || models[key][eventName]
        })
        // merge data
        let allData = Object.assign(
          {},
          registerConfig.data || {},
          models.__default.data || {},
          models[key].data || {},
          config.data || {})
        // merge config
        let allConfig = Object.assign(
          {},
          models.__default || {},
          registerConfig || {},
          models[key] || {},
          config,
          {
            url: getUrl(key, models[key], registerConfig, config),
            data: allData,
            beforeSend (xhr) {
              if (triggerAjaxStartAndStopEvent) {
                GLOBAL.__apiCounter.add()
                fireStartAndStopEvents('ajaxStart', [xhr])
              }
              if (triggerGlobalEvents) fireGlobalEvents(globalEvents.beforeSend, [xhr])
              fireLocalEvent(localEvents.beforeSend, [xhr])
            },
            success (data, statusText, xhr) {
              if (triggerGlobalEvents) fireGlobalEvents(globalEvents.success, [data, statusText, xhr])
              fireLocalEvent(localEvents.success, [data, statusText, xhr])
            },
            error (xhr, statusText, error) {
              if (triggerGlobalEvents) fireGlobalEvents(globalEvents.error, [xhr, statusText, error])
              fireLocalEvent(localEvents.error, [xhr, statusText, error])
            },
            complete (xhr, statusText) {
              if (triggerAjaxStartAndStopEvent) {
                GLOBAL.__apiCounter.remove()
                fireStartAndStopEvents('ajaxStop', [xhr, statusText])
              }
              if (triggerGlobalEvents) fireGlobalEvents(globalEvents.complete, [xhr, statusText])
              fireLocalEvent(localEvents.complete, [xhr, statusText])
            }
          }
        )
        // if got window api config then use it
        if (GLOBAL.__apiConfig__ && GLOBAL.__apiConfig__[key] && GLOBAL.__apiConfig__[key].type) {
          allConfig = Object.assign({}, allConfig, GLOBAL.__apiConfig__[key])
        }
        // format data when post application json
        if (
          allConfig.method &&
          allConfig.method.toLowerCase().trim() === 'post' &&
          allConfig.contentType &&
          allConfig.contentType.toLowerCase().trim() === 'application/json') {
            allConfig.data = JSON.stringify(allData)
        }
        return $.ajax(allConfig)
      }
    }
  }
  return apis
}

export default apiRegister


text:
namespace Serenity.Data
{
    /// <summary>
    /// Sets modify permission for the row.
    /// Modify permission is used for Insert/Update/Delete if they are
    /// not explicitly specified.
    /// </summary>
    /// <seealso cref="PermissionAttributeBase" />
    public class ModifyPermissionAttribute : PermissionAttributeBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ModifyPermissionAttribute"/> class.
        /// </summary>
        /// <param name="permission">The permission.</param>
        public ModifyPermissionAttribute(object permission)
            : base(permission)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ModifyPermissionAttribute"/> class.
        /// A colon is inserted between module and permission to generate permission key.
        /// </summary>
        /// <param name="module">The module.</param>
        /// <param name="permission">The permission.</param>
        public ModifyPermissionAttribute(object module, object permission)
            : base(module, permission)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ModifyPermissionAttribute"/> class.
        /// A colon is inserted between module, submodule and permission to generate permission key.
        /// </summary>
        /// <param name="module">The module.</param>
        /// <param name="submodule">The submodule.</param>
        /// <param name="permission">The permission.</param>
        public ModifyPermissionAttribute(object module, object submodule, object permission)
            : base(module, submodule, permission)
        {
        }
    }
}


text:
<?php

namespace Phlexible\Bundle\UserBundle;

use Phlexible\Bundle\MessageBundle\Entity\Message;

/**
 * Users message.
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
class UsersMessage extends Message
{
    /**
     * {@inheritdoc}
     */
    public static function getDefaultChannel()
    {
        return 'users';
    }

    /**
     * {@inheritdoc}
     */
    public static function getDefaultRole()
    {
        return 'ROLE_USERS';
    }
}


text:
import decode from 'jwt-decode';
import _ from 'lodash';

export function getTokenExpirationDate(token) {
  const decoded = decode(token)
  if(!decoded.exp) {
    return null
  }

  const date = new Date(0) // The 0 here is the key, which sets the date to the epoch
  date.setUTCSeconds(decoded.exp);
  return date;
}

export function isTokenExpired(token) {
    if (_.isNil(token)) {
        return true;
    }
  const date = getTokenExpirationDate(token);
  const offsetSeconds = 0
  if (date === null) {
    return false;
  }
  return !(date.valueOf() > (new Date().valueOf() + (offsetSeconds * 1000)));
}


text:
from MidiOutStream import MidiOutStream
from MidiOutFile import MidiOutFile
from MidiInStream import MidiInStream
from MidiInFile import MidiInFile
from MidiToText import MidiToText


text:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

source "${DIR}/load-env.sh"

"$DIR/docker-compose.sh" Environment/Build/docker-compose.yml run npm $@


text:
<resources>

    <string name="title">"Open Location Codes DEBUG"</string>

</resources>


text:
namespace blink {

class WebMessagePortChannel;
class WebString;
class WebURL;

typedef WebCallbacks<void, void> WebNavigatorConnectCallbacks;

class WebNavigatorConnectProvider {
public:
    virtual ~WebNavigatorConnectProvider() { }

    // Initiates a connection from the given origin to the given URL. When
    // successful the service can communicate with the client over the given
    // channel. The origin isn't passed as WebSecurityOrigin because that would
    // be a layering violation (platform/ code shouldn't depend on web/ code).
    // Ownership of the WebMessagePortChannel and WebNavigatorConnectCallbacks
    // objects are both transferred to the provider.
    virtual void connect(const WebURL&, const WebString& origin, WebMessagePortChannel*, WebNavigatorConnectCallbacks*) { }
};

} // namespace blink

#endif // WebNavigatorConnectProvider_h


text:
@import Foundation;
#import "CoreDataManager.h"

@interface CoreDataManager (extensions)
- (BOOL)resetDatastore;
@end


text:
<?php

declare(strict_types=1);

namespace Tests\CarbonImmutable;

use Carbon\CarbonImmutable as Carbon;
use DateTime;
use Tests\AbstractTestCase;

class LastErrorTest extends AbstractTestCase
{
    /**
     * @var array
     */
    protected $lastErrors;

    /**
     * @var array
     */
    protected $noErrors;

    protected function setUp(): void
    {
        parent::setUp();

        $this->noErrors = [
            'warning_count' => 0,
            'warnings' => [],
            'error_count' => 0,
            'errors' => [],
        ];

        $this->lastErrors = [
            'warning_count' => 1,
            'warnings' => ['11' => 'The parsed date was invalid'],
            'error_count' => 0,
            'errors' => [],
        ];
    }

    public function testCreateHandlesLastErrors()
    {
        $carbon = new Carbon('2017-02-30');
        $datetime = new DateTime('2017-02-30');

        $this->assertSame($this->lastErrors, $carbon->getLastErrors());
        $this->assertSame($carbon->getLastErrors(), $datetime->getLastErrors());

        $carbon = new Carbon('2017-02-15');

        $this->assertSame($this->noErrors, $carbon->getLastErrors());
    }
}


text:
using System;

public static partial class Extensions
{
    /// <summary>
    ///     Converts a time to the time in a particular time zone.
    /// </summary>
    /// <param name="dateTime">The date and time to convert.</param>
    /// <param name="destinationTimeZone">The time zone to convert  to.</param>
    /// <returns>The date and time in the destination time zone.</returns>
    public static DateTime ConvertTime(this DateTime dateTime, TimeZoneInfo destinationTimeZone)
    {
        return TimeZoneInfo.ConvertTime(dateTime, destinationTimeZone);
    }

    /// <summary>
    ///     Converts a time from one time zone to another.
    /// </summary>
    /// <param name="dateTime">The date and time to convert.</param>
    /// <param name="sourceTimeZone">The time zone of .</param>
    /// <param name="destinationTimeZone">The time zone to convert  to.</param>
    /// <returns>
    ///     The date and time in the destination time zone that corresponds to the  parameter in the source time zone.
    /// </returns>
    public static DateTime ConvertTime(this DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
    {
        return TimeZoneInfo.ConvertTime(dateTime, sourceTimeZone, destinationTimeZone);
    }
}


text:
package com.novbank.ndp.kernel.util.function;

import com.novbank.ndp.kernel.util.Wrapper;

/**
 * Created by hp on 2015/5/15.
 */
public class JavaToGuavaPredicateWrapper<T> implements com.google.common.base.Predicate<T>,Wrapper<java.util.function.Predicate<T>> {
    private java.util.function.Predicate<T> predicate;

    public JavaToGuavaPredicateWrapper(java.util.function.Predicate<T> predicate) {
        this.predicate = predicate;
    }

    @Override
    public boolean apply(T input) {
        return predicate.test(input);
    }

    @Override
    public java.util.function.Predicate<T> unwrap() {
        return predicate;
    }
}