text:
import copy
import datetime
import logging
import math
import os
import random
import shutil
import sys
import time
# PyQt5
import PyQt5
# library for fits file handling
import pyfits

class ModelWorker:
    logger = logging.getLogger(__name__)

    def __init__(self, app):
        # make main sources available
        self.app = app
        self.results = []
        self.modelRun = False

    @staticmethod
    def timeStamp():
        return time.strftime("%H:%M:%S", time.localtime())

    def clearAlignmentModel(self):
        self.app.modeling.modelAnalyseData = []
        self.app.mountCommandQueue.put('ClearAlign')
        time.sleep(4)

    def setupRunningParameters(self):
        settlingTime = int(float(self.app.ui.settlingTime.value()))
        directory = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime())
        return settlingTime, directory

    def runBaseModel(self):
        if self.app.ui.checkClearModelFirst.isChecked():
            self.app.modelLogQueue.put('Clearing alignment modeling - taking 4 seconds.\n')
            self.clearAlignmentModel()
            self.app.modelLogQueue.put('Model cleared!\n')
        settlingTime, directory = self.setupRunningParameters()
        if len(self.app.modeling.modelPoints.BasePoints) > 0:
            simulation = self.app.ui.checkSimulation.isChecked()
            keepImages = self.app.ui.checkKeepImages.isChecked()
            self.app.modeling.modelData = self.runModel('Base', self.app.modeling.modelPoints.BasePoints, directory, settlingTime, simulation, keepImages)
            self.app.modeling.modelData = self.app.mount.retrofitMountData(self.app.modeling.modelData)
            name = directory + '_base.dat'
            if len(self.app.modeling.modelData) > 0:
                self.app.ui.le_analyseFileName.setText(name)
                self.app.modeling.analyse.saveData(self.app.modeling.modelData, name)
                self.app.mount.saveBaseModel()
        else:
            self.logger.warning('There are no Basepoints for modeling')

    def runRefinementModel(self):
        num = self.app.mount.numberModelStars()
        suc, mes, sizeX, sizeY, canSubframe, gainValue = self.app.modeling.imagingHandler.getCameraProps()
        if sizeX == 800 and sizeY == 600 and suc:
            simulation = True
            self.app.modeling.modelData = []
        else:
            simulation = False
        if num > 2 or simulation:
            settlingTime, directory = self.setupRunningParameters()
            if len(self.app.modeling.modelPoints.RefinementPoints) > 0:
                if self.app.ui.checkKeepRefinement.isChecked():
                    self.app.mount.loadRefinementModel()
                else:
                    self.app.mount.loadBaseModel()
                simulation = self.app.ui.checkSimulation.isChecked()
                keepImages = self.app.ui.checkKeepImages.isChecked()
                refinePoints = self.runModel('Refinement', self.app.modeling.modelPoints.RefinementPoints, directory, settlingTime, simulation, keepImages)
                for i in range(0, len(refinePoints)):
                    refinePoints[i]['Index'] += len(self.app.modeling.modelData)
                self.app.modeling.modelData = self.app.modeling.modelData + refinePoints
                self.app.modeling.modelData = self.app.mount.retrofitMountData(self.app.modeling.modelData)
                name = directory + '_refinement.dat'
                if len(self.app.modeling.modelData) > 0:
                    self.app.ui.le_analyseFileName.setText(name)
                    self.app.modeling.analyse.saveData(self.app.modeling.modelData, name)
                    self.app.mount.saveRefinementModel()
            else:
                self.logger.warning('There are no Refinement Points to modeling')
        else:
            self.app.modelLogQueue.put('Refine stopped, no BASE model available !\n')
            self.app.messageQueue.put('Refine stopped, no BASE model available !\n')

    def runCheckModel(self):
        settlingTime, directory = self.setupRunningParameters()
        points = self.app.modeling.modelPoints.BasePoints + self.app.modeling.modelPoints.RefinementPoints
        if len(points) > 0:
            simulation = self.app.ui.checkSimulation.isChecked()
            keepImages = self.app.ui.checkKeepImages.isChecked()
            self.app.modeling.modelAnalyseData = self.runModel('Check', points, directory, settlingTime, simulation, keepImages)
            name = directory + '_check.dat'
            if len(self.app.modeling.modelAnalyseData) > 0:
                self.app.ui.le_analyseFileName.setText(name)
                self.app.modeling.analyse.saveData(self.app.modeling.modelAnalyseData, name)
        else:
            self.logger.warning('There are no Refinement or Base Points to modeling')

    def runAllModel(self):
        self.runBaseModel()
        self.runRefinementModel()

    def runTimeChangeModel(self):
        settlingTime, directory = self.setupRunningParameters()
        points = []
        for i in range(0, int(float(self.app.ui.numberRunsTimeChange.value()))):
            points.append((int(self.app.ui.azimuthTimeChange.value()), int(self.app.ui.altitudeTimeChange.value()),
                           PyQt5.QtWidgets.QGraphicsTextItem(''), True))
        simulation = self.app.ui.checkSimulation.isChecked()
        keepImages = self.app.ui.checkKeepImages.isChecked()
        self.app.modeling.modelAnalyseData = self.runModel('TimeChange', points, directory, settlingTime, simulation, keepImages)
        name = directory + '_timechange.dat'
        if len(self.app.modeling.modelAnalyseData) > 0:
            self.app.ui.le_analyseFileName.setText(name)
            self.app.modeling.analyse.saveData(self.app.modeling.modelAnalyseData, name)

    def runHystereseModel(self):
        waitingTime, directory = self.setupRunningParameters()
        alt1 = int(float(self.app.ui.altitudeHysterese1.value()))
        alt2 = int(float(self.app.ui.altitudeHysterese2.value()))
        az1 = int(float(self.app.ui.azimuthHysterese1.value()))
        az2 = int(float(self.app.ui.azimuthHysterese2.value()))
        numberRunsHysterese = int(float(self.app.ui.numberRunsHysterese.value()))
        points = []
        for i in range(0, numberRunsHysterese):
            points.append((az1, alt1, PyQt5.QtWidgets.QGraphicsTextItem(''), True))
            points.append((az2, alt2, PyQt5.QtWidgets.QGraphicsTextItem(''), False))
        simulation = self.app.ui.checkSimulation.isChecked()
        keepImages = self.app.ui.checkKeepImages.isChecked()
        self.app.modeling.modelAnalyseData = self.runModel('Hysterese', points, directory, waitingTime, simulation, keepImages)
        name = directory + '_hysterese.dat'
        self.app.ui.le_analyseFileName.setText(name)
        if len(self.app.modeling.modelAnalyseData) > 0:
            self.app.ui.le_analyseFileName.setText(name)
            self.app.modeling.analyse.saveData(self.app.modeling.modelAnalyseData, name)

    def runBatchModel(self):
        nameDataFile = self.app.ui.le_analyseFileName.text()
        self.logger.info('modeling from {0}'.format(nameDataFile))
        data = self.app.modeling.analyse.loadData(nameDataFile)
        if not('RaJNow' in data and 'DecJNow' in data):
            self.logger.warning('RaJNow or DecJNow not in data file')
            self.app.modelLogQueue.put('{0} - mount coordinates missing\n'.format(self.timeStamp()))
            return
        if not('RaJNowSolved' in data and 'DecJNowSolved' in data):
            self.logger.warning('RaJNowSolved or DecJNowSolved not in data file')
            self.app.modelLogQueue.put('{0} - solved data missing\n'.format(self.timeStamp()))
            return
        if not('Pierside' in data and 'LocalSiderealTime' in data):
            self.logger.warning('Pierside and LocalSiderealTime not in data file')
            self.app.modelLogQueue.put('{0} - Time and Pierside missing\n'.format(self.timeStamp()))
            return
        self.app.mount.saveBackupModel()
        self.app.modelLogQueue.put('{0} - Start Batch modeling. Saving Actual modeling to BATCH\n'.format(self.timeStamp()))
        self.app.mount.mountHandler.sendCommand('newalig')
        self.app.modelLogQueue.put('{0} - \tOpening Calculation\n'.format(self.timeStamp()))
        for i in range(0, len(data['Index'])):
            command = 'newalpt{0},{1},{2},{3},{4},{5}'.format(self.app.modeling.transform.decimalToDegree(data['RaJNow'][i], False, True),
                                                              self.app.modeling.transform.decimalToDegree(data['DecJNow'][i], True, False),
                                                              data['Pierside'][i],
                                                              self.app.modeling.transform.decimalToDegree(data['RaJNowSolved'][i], False, True),
                                                              self.app.modeling.transform.decimalToDegree(data['DecJNowSolved'][i], True, False),
                                                              self.app.modeling.transform.decimalToDegree(data['LocalSiderealTimeFloat'][i], False, True))
            reply = self.app.mount.mountHandler.sendCommand(command)
            if reply == 'E':
                self.logger.warning('point {0} could not be added'.format(reply))
                self.app.modelLogQueue.put('{0} - \tPoint could not be added\n'.format(self.timeStamp()))
            else:
                self.app.modelLogQueue.put('{0} - \tAdded point {1} @ Az:{2}, Alt:{3} \n'
                                           .format(self.timeStamp(), reply, int(data['Azimuth'][i]), int(data['Altitude'][i])))
        reply = self.app.mount.mountHandler.sendCommand('endalig')
        if reply == 'V':
            self.app.modelLogQueue.put('{0} - Model successful finished! \n'.format(self.timeStamp()))
            self.logger.info('Model successful finished!')
        else:
            self.app.modelLogQueue.put('{0} - Model could not be calculated with current data! \n'.format(self.timeStamp()))
            self.logger.warning('Model could not be calculated with current data!')

    def slewMountDome(self, az, alt):
        self.app.mountCommandQueue.put('Sz{0:03d}*{1:02d}'.format(int(az), int((az - int(az)) * 60 + 0.5)))
        self.app.mountCommandQueue.put('Sa+{0:02d}*{1:02d}'.format(int(alt), int((alt - int(alt)) * 60 + 0.5)))
        self.app.mountCommandQueue.put('MS')
        self.logger.info('Connected:{0}'.format(self.app.dome.connected))
        break_counter = 0
        while not self.app.mount.data['Slewing']:
            time.sleep(0.1)
            break_counter += 1
            if break_counter == 30:
                break
        if self.app.dome.connected == 1:
            if az >= 360:
                az = 359.9
            elif az < 0.0:
                az = 0.0
            try:
                self.app.dome.ascom.SlewToAzimuth(float(az))
            except Exception as e:
                self.logger.error('value: {0}, error: {1}'.format(az, e))
            self.logger.info('Azimuth:{0}'.format(az))
            while not self.app.mount.data['Slewing']:
                if self.app.modeling.cancel:
                    self.logger.info('Modeling cancelled after mount slewing')
                    break
                time.sleep(0.1)
            while self.app.mount.data['Slewing'] or self.app.dome.slewing:
                if self.app.modeling.cancel:
                    self.logger.info('Modeling cancelled after dome slewing')
                    break
                time.sleep(0.1)
        else:
            while self.app.mount.data['Slewing']:
                if self.app.modeling.cancel:
                    self.logger.info('Modeling cancelled after mount slewing')
                    break
                time.sleep(0.1)

    def prepareImaging(self, modelData, directory):
        # do all the calculations once
        suc, mes, sizeX, sizeY, canSubframe, gainValue = self.app.modeling.imagingHandler.getCameraProps()
        if suc:
            self.logger.info('camera props: {0}, {1}, {2}'.format(sizeX, sizeY, canSubframe))
        else:
            self.logger.warning('SgGetCameraProps with error: {0}'.format(mes))
            return {}
        if canSubframe and self.app.ui.checkDoSubframe.isChecked():
            scaleSubframe = self.app.ui.scaleSubframe.value() / 100
            modelData['SizeX'] = int(sizeX * scaleSubframe)
            modelData['SizeY'] = int(sizeY * scaleSubframe)
            modelData['OffX'] = int((sizeX - modelData['SizeX']) / 2)
            modelData['OffY'] = int((sizeY - modelData['SizeY']) / 2)
            modelData['CanSubframe'] = True
        else:
            modelData['SizeX'] = 0
            modelData['SizeY'] = 0
            modelData['OffX'] = 0
            modelData['OffY'] = 0
            modelData['CanSubframe'] = False
            self.logger.warning('Camera does not support subframe.')
        modelData['GainValue'] = gainValue
        modelData['BaseDirImages'] = self.app.modeling.IMAGEDIR + '/' + directory
        if self.app.ui.checkFastDownload.isChecked():
            modelData['Speed'] = 'HiSpeed'
        else:
            modelData['Speed'] = 'Normal'
        modelData['Binning'] = int(float(self.app.ui.cameraBin.value()))
        modelData['Exposure'] = int(float(self.app.ui.cameraExposure.value()))
        modelData['Iso'] = int(float(self.app.ui.isoSetting.value()))
        modelData['Blind'] = self.app.ui.checkUseBlindSolve.isChecked()
        modelData['ScaleHint'] = float(self.app.ui.pixelSize.value()) * modelData['Binning'] * 206.6 / float(self.app.ui.focalLength.value())
        if 'Binning' in modelData:
            modelData['SizeX'] = int(modelData['SizeX'] / modelData['Binning'])
            modelData['SizeY'] = int(modelData['SizeY'] / modelData['Binning'])
        return modelData

    def capturingImage(self, modelData, simulation):
        if self.app.modeling.cancel:
            self.logger.info('Modeling cancelled after capturing image')
            return False, 'Cancel modeling pressed', modelData
        LocalSiderealTimeFitsHeader = modelData['LocalSiderealTime'][0:10]
        RaJ2000FitsHeader = self.app.modeling.transform.decimalToDegree(modelData['RaJ2000'], False, False, ' ')
        DecJ2000FitsHeader = self.app.modeling.transform.decimalToDegree(modelData['DecJ2000'], True, False, ' ')
        RaJNowFitsHeader = self.app.modeling.transform.decimalToDegree(modelData['RaJNow'], False, True, ' ')
        DecJNowFitsHeader = self.app.modeling.transform.decimalToDegree(modelData['DecJNow'], True, True, ' ')
        if modelData['Pierside'] == '1':
            pierside_fits_header = 'E'
        else:
            pierside_fits_header = 'W'
        self.logger.info('modelData: {0}'.format(modelData))
        suc, mes, modelData = self.app.modeling.imagingHandler.getImage(modelData)
        if suc:
            if simulation:
                if getattr(sys, 'frozen', False):
                    # we are running in a bundle
                    bundle_dir = sys._MEIPASS
                else:
                    # we are running in a normal Python environment
                    bundle_dir = os.path.dirname(sys.modules['__main__'].__file__)
                shutil.copyfile(bundle_dir + self.app.modeling.REF_PICTURE, modelData['ImagePath'])
            else:
                self.logger.info('suc: {0}, modelData{1}'.format(suc, modelData))
                fitsFileHandle = pyfits.open(modelData['ImagePath'], mode='update')
                fitsHeader = fitsFileHandle[0].header
                if 'FOCALLEN' in fitsHeader and 'XPIXSZ' in fitsHeader:
                    modelData['ScaleHint'] = float(fitsHeader['XPIXSZ']) * 206.6 / float(fitsHeader['FOCALLEN'])
                fitsHeader['DATE-OBS'] = datetime.datetime.now().isoformat()
                fitsHeader['OBJCTRA'] = RaJ2000FitsHeader
                fitsHeader['OBJCTDEC'] = DecJ2000FitsHeader
                fitsHeader['CDELT1'] = str(modelData['ScaleHint'])
                fitsHeader['CDELT2'] = str(modelData['ScaleHint'])
                fitsHeader['PIXSCALE'] = str(modelData['ScaleHint'])
                fitsHeader['SCALE'] = str(modelData['ScaleHint'])
                fitsHeader['MW_MRA'] = RaJNowFitsHeader
                fitsHeader['MW_MDEC'] = DecJNowFitsHeader
                fitsHeader['MW_ST'] = LocalSiderealTimeFitsHeader
                fitsHeader['MW_MSIDE'] = pierside_fits_header
                fitsHeader['MW_EXP'] = modelData['Exposure']
                fitsHeader['MW_AZ'] = modelData['Azimuth']
                fitsHeader['MW_ALT'] = modelData['Altitude']
                self.logger.info('DATE-OBS:{0}, OBJCTRA:{1} OBJTDEC:{2} CDELT1:{3} MW_MRA:{4} '
                                 'MW_MDEC:{5} MW_ST:{6} MW_PIER:{7} MW_EXP:{8} MW_AZ:{9} MW_ALT:{10}'
                                 .format(fitsHeader['DATE-OBS'], fitsHeader['OBJCTRA'], fitsHeader['OBJCTDEC'],
                                         fitsHeader['CDELT1'], fitsHeader['MW_MRA'], fitsHeader['MW_MDEC'],
                                         fitsHeader['MW_ST'], fitsHeader['MW_MSIDE'], fitsHeader['MW_EXP'],
                                         fitsHeader['MW_AZ'], fitsHeader['MW_ALT']))
                fitsFileHandle.flush()
                fitsFileHandle.close()
            self.app.imageQueue.put(modelData['ImagePath'])
            return True, 'OK', modelData
        else:
            return False, mes, modelData

    def addSolveRandomValues(self, modelData):
        modelData['RaJ2000Solved'] = modelData['RaJ2000'] + (2 * random.random() - 1) / 3600
        modelData['DecJ2000Solved'] = modelData['DecJ2000'] + (2 * random.random() - 1) / 360
        modelData['Scale'] = 1.3
        modelData['Angle'] = 90
        modelData['TimeTS'] = 2.5
        ra, dec = self.app.modeling.transform.transformERFA(modelData['RaJ2000Solved'], modelData['DecJ2000Solved'], 3)
        modelData['RaJNowSolved'] = ra
        modelData['DecJNowSolved'] = dec
        modelData['RaError'] = (modelData['RaJ2000Solved'] - modelData['RaJ2000']) * 3600
        modelData['DecError'] = (modelData['DecJ2000Solved'] - modelData['DecJ2000']) * 3600
        modelData['ModelError'] = math.sqrt(modelData['RaError'] * modelData['RaError'] + modelData['DecError'] * modelData['DecError'])
        return modelData

    def solveImage(self, modelData, simulation):
        modelData['UseFitsHeaders'] = True
        suc, mes, modelData = self.app.modeling.imagingHandler.solveImage(modelData)
        self.logger.info('suc:{0} mes:{1}'.format(suc, mes))
        if suc:
            ra_sol_Jnow, dec_sol_Jnow = self.app.modeling.transform.transformERFA(modelData['RaJ2000Solved'], modelData['DecJ2000Solved'], 3)
            modelData['RaJNowSolved'] = ra_sol_Jnow
            modelData['DecJNowSolved'] = dec_sol_Jnow
            modelData['RaError'] = (modelData['RaJ2000Solved'] - modelData['RaJ2000']) * 3600
            modelData['DecError'] = (modelData['DecJ2000Solved'] - modelData['DecJ2000']) * 3600
            modelData['ModelError'] = math.sqrt(modelData['RaError'] * modelData['RaError'] + modelData['DecError'] * modelData['DecError'])
            fitsFileHandle = pyfits.open(modelData['ImagePath'], mode='update')
            fitsHeader = fitsFileHandle[0].header
            fitsHeader['MW_PRA'] = modelData['RaJNowSolved']
            fitsHeader['MW_PDEC'] = modelData['DecJNowSolved']
            fitsHeader['MW_SRA'] = modelData['RaJ2000Solved']
            fitsHeader['MW_SDEC'] = modelData['DecJ2000Solved']
            fitsHeader['MW_PSCAL'] = modelData['Scale']
            fitsHeader['MW_PANGL'] = modelData['Angle']
            fitsHeader['MW_PTS'] = modelData['TimeTS']
            self.logger.info('MW_PRA:{0} MW_PDEC:{1} MW_PSCAL:{2} MW_PANGL:{3} MW_PTS:{4}'.
                             format(fitsHeader['MW_PRA'], fitsHeader['MW_PDEC'], fitsHeader['MW_PSCAL'],
                                    fitsHeader['MW_PANGL'], fitsHeader['MW_PTS']))
            fitsFileHandle.flush()
            fitsFileHandle.close()
            if simulation:
                modelData = self.addSolveRandomValues(modelData)
            return True, mes, modelData
        else:
            return False, mes, modelData

    def addRefinementStar(self, ra, dec):
        self.logger.info('ra:{0} dec:{1}'.format(ra, dec))
        self.app.mount.mountHandler.sendCommand('Sr{0}'.format(ra))
        self.app.mount.mountHandler.sendCommand('Sd{0}'.format(dec))
        starNumber = self.app.mount.numberModelStars()
        reply = self.app.mount.mountHandler.sendCommand('CMS')
        starAdded = self.app.mount.numberModelStars() - starNumber
        if reply == 'E':
            # 'E' says star could not be added
            if starAdded == 1:
                self.logger.error('star added, but return value was E')
                return True
            else:
                self.logger.error('error adding star')
                return False
        else:
            self.logger.info('refinement star added')
            return True

    def syncMountModel(self, ra, dec):
        self.logger.info('ra:{0} dec:{1}'.format(ra, dec))
        self.app.mount.mountHandler.sendCommand('Sr{0}'.format(ra))
        self.app.mount.mountHandler.sendCommand('Sd{0}'.format(dec))
        self.app.mount.mountHandler.sendCommand('CMCFG0')
        # send sync command
        reply = self.app.mount.mountHandler.sendCommand('CM')
        if reply[:5] == 'Coord':
            self.logger.info('mount modeling synced')
            return True
        else:
            self.logger.warning('error in sync mount modeling')
            return False

    def plateSolveSync(self, simulation=False):
        self.app.modelLogQueue.put('delete')
        self.app.modelLogQueue.put('{0} - Start Sync Mount Model\n'.format(self.timeStamp()))
        modelData = {}
        modelData = self.prepareImaging(modelData, '')
        modelData['base_dir_images'] = self.app.modeling.IMAGEDIR + '/platesolvesync'
        self.logger.info('modelData: {0}'.format(modelData))
        self.app.mountCommandQueue.put('PO')
        self.app.mountCommandQueue.put('AP')
        if not os.path.isdir(modelData['BaseDirImages']):
            os.makedirs(modelData['BaseDirImages'])
        modelData['File'] = 'platesolvesync.fit'
        modelData['LocalSiderealTime'] = self.app.mount.data['LocalSiderealTime'][0:9]
        modelData['LocalSiderealTimeFloat'] = self.app.modeling.transform.degStringToDecimal(modelData['LocalSiderealTime'])
        modelData['RaJ2000'] = self.app.mount.data['RaJ2000']
        modelData['DecJ2000'] = self.app.mount.data['DecJ2000']
        modelData['RaJNow'] = self.app.mount.data['RaJNow']
        modelData['DecJNow'] = self.app.mount.data['DecJNow']
        modelData['Pierside'] = self.app.mount.data['Pierside']
        modelData['RefractionTemperature'] = self.app.mount.data['RefractionTemperature']
        modelData['RefractionPressure'] = self.app.mount.data['RefractionPressure']
        modelData['Azimuth'] = 0
        modelData['Altitude'] = 0
        self.app.modelLogQueue.put('{0} -\t Capturing image\n'.format(self.timeStamp()))
        suc, mes, imagepath = self.capturingImage(modelData, simulation)
        self.logger.info('suc:{0} mes:{1}'.format(suc, mes))
        if suc:
            self.app.modelLogQueue.put('{0} -\t Solving Image\n'.format(self.timeStamp()))
            suc, mes, modelData = self.solveImage(modelData, simulation)
            self.app.modelLogQueue.put('{0} -\t Image path: {1}\n'.format(self.timeStamp(), modelData['ImagePath']))
            if suc:
                suc = self.syncMountModel(modelData['RaJNowSolved'], modelData['DecJNowSolved'])
                if suc:
                    self.app.modelLogQueue.put('{0} -\t Mount Model Synced\n'.format(self.timeStamp()))
                else:
                    self.app.modelLogQueue.put(
                        '{0} -\t Mount Model could not be synced - please check!\n'.format(self.timeStamp()))
            else:
                self.app.modelLogQueue.put('{0} -\t Solving error: {1}\n'.format(self.timeStamp(), mes))
        if not self.app.ui.checkKeepImages.isChecked():
            shutil.rmtree(modelData['BaseDirImages'], ignore_errors=True)
        self.app.modelLogQueue.put('{0} - Sync Mount Model finished !\n'.format(self.timeStamp()))

    # noinspection PyUnresolvedReferences
    def runModel(self, modeltype, runPoints, directory, settlingTime, simulation=False, keepImages=False):
        # start clearing the data
        modelData = {}
        results = []
        # preparing the gui outputs
        self.app.modelLogQueue.put('status-- of --')
        self.app.modelLogQueue.put('percent0')
        self.app.modelLogQueue.put('timeleft--:--')
        self.app.modelLogQueue.put('delete')
        self.app.modelLogQueue.put('#BW{0} - Start {1} Model\n'.format(self.timeStamp(), modeltype))
        modelData = self.prepareImaging(modelData, directory)
        if not os.path.isdir(modelData['BaseDirImages']):
            os.makedirs(modelData['BaseDirImages'])
        self.logger.info('modelData: {0}'.format(modelData))
        self.app.mountCommandQueue.put('PO')
        self.app.mountCommandQueue.put('AP')
        # counter and timer for performance estimation
        numCheckPoints = 0
        timeStart = time.time()
        # here starts the real model running cycle
        for i, (p_az, p_alt, p_item, p_solve) in enumerate(runPoints):
            self.app.modeling.modelRun = True
            modelData['Azimuth'] = p_az
            modelData['Altitude'] = p_alt
            if p_item.isVisible():
                # todo: put the code to multi thread modeling
                if self.app.modeling.cancel:
                    self.app.modeling.cancel = False
                    self.app.modelLogQueue.put('#BW{0} -\t {1} Model canceled !\n'.format(self.timeStamp(), modeltype))
                    # tracking should be on after canceling the modeling
                    self.app.mountCommandQueue.put('AP')
                    # clearing the gui
                    self.app.modelLogQueue.put('status-- of --')
                    self.app.modelLogQueue.put('percent0')
                    self.app.modelLogQueue.put('timeleft--:--')
                    self.logger.info('Modeling cancelled in main loop')
                    # finally stopping modeling run
                    break
                self.app.modelLogQueue.put('#BG{0} - Slewing to point {1:2d}  @ Az: {2:3.0f}\xb0 Alt: {3:2.0f}\xb0\n'.format(self.timeStamp(), i+1, p_az, p_alt))
                self.logger.info('point {0:2d}  Az: {1:3.0f} Alt: {2:2.0f}'.format(i+1, p_az, p_alt))
                if modeltype in ['TimeChange']:
                    # in time change there is only slew for the first time, than only track during imaging
                    if i == 0:
                        self.slewMountDome(p_az, p_alt)
                        self.app.mountCommandQueue.put('RT9')
                else:
                    self.slewMountDome(p_az, p_alt)
                self.app.modelLogQueue.put('{0} -\t Wait mount settling / delay time:  {1:02d} sec'.format(self.timeStamp(), settlingTime))
                timeCounter = settlingTime
                while timeCounter > 0:
                    time.sleep(1)
                    timeCounter -= 1
                    self.app.modelLogQueue.put('backspace')
                    self.app.modelLogQueue.put('{0:02d} sec'.format(timeCounter))
                self.app.modelLogQueue.put('\n')
            if p_item.isVisible() and p_solve:
                modelData['File'] = self.app.modeling.CAPTUREFILE + '{0:03d}'.format(i) + '.fit'
                modelData['LocalSiderealTime'] = self.app.mount.data['LocalSiderealTime']
                modelData['LocalSiderealTimeFloat'] = self.app.modeling.transform.degStringToDecimal(self.app.mount.data['LocalSiderealTime'][0:9])
                modelData['RaJ2000'] = self.app.mount.data['RaJ2000']
                modelData['DecJ2000'] = self.app.mount.data['DecJ2000']
                modelData['RaJNow'] = self.app.mount.data['RaJNow']
                modelData['DecJNow'] = self.app.mount.data['DecJNow']
                modelData['Pierside'] = self.app.mount.data['Pierside']
                modelData['Index'] = i
                modelData['RefractionTemperature'] = self.app.mount.data['RefractionTemperature']
                modelData['RefractionPressure'] = self.app.mount.data['RefractionPressure']
                if modeltype in ['TimeChange']:
                    self.app.mountCommandQueue.put('AP')
                self.app.modelLogQueue.put('{0} -\t Capturing image for modeling point {1:2d}\n'.format(self.timeStamp(), i + 1))
                suc, mes, imagepath = self.capturingImage(modelData, simulation)
                if modeltype in ['TimeChange']:
                    self.app.mountCommandQueue.put('RT9')
                self.logger.info('suc:{0} mes:{1}'.format(suc, mes))
                if suc:
                    self.app.modelLogQueue.put('{0} -\t Solving Image\n'.format(self.timeStamp()))
                    suc, mes, modelData = self.solveImage(modelData, simulation)
                    self.app.modelLogQueue.put('{0} -\t Image path: {1}\n'.format(self.timeStamp(), modelData['ImagePath']))
                    if suc:
                        if modeltype in ['Base', 'Refinement', 'All']:
                            suc = self.addRefinementStar(modelData['RaJNowSolved'], modelData['DecJNowSolved'])
                            if suc:
                                self.app.modelLogQueue.put('{0} -\t Point added\n'.format(self.timeStamp()))
                                numCheckPoints += 1
                                results.append(copy.copy(modelData))
                                p_item.setVisible(False)
                            else:
                                self.app.modelLogQueue.put('{0} -\t Point could not be added - please check!\n'.format(self.timeStamp()))
                                self.logger.info('raE:{0} decE:{1} star could not be added'.format(modelData['RaError'], modelData['DecError']))
                        self.app.modelLogQueue.put('{0} -\t RA_diff:  {1:2.1f}    DEC_diff: {2:2.1f}\n'.format(self.timeStamp(), modelData['RaError'], modelData['DecError']))
                        self.logger.info('modelData: {0}'.format(modelData))
                    else:
                        self.app.modelLogQueue.put('{0} -\t Solving error: {1}\n'.format(self.timeStamp(), mes))
                self.app.modelLogQueue.put('status{0} of {1}'.format(i+1, len(runPoints)))
                modelBuildDone = (i + 1) / len(runPoints)
                self.app.modelLogQueue.put('percent{0}'.format(modelBuildDone))
                actualTime = time.time() - timeStart
                timeCalculated = actualTime / (i + 1) * (len(runPoints) - i - 1)
                mm = int(timeCalculated / 60)
                ss = int(timeCalculated - 60 * mm)
                self.app.modelLogQueue.put('timeleft{0:02d}:{1:02d}'.format(mm, ss))
        if not keepImages:
            shutil.rmtree(modelData['BaseDirImages'], ignore_errors=True)
        self.app.modelLogQueue.put('#BW{0} - {1} Model run finished. Number of modeled points: {2:3d}\n\n'.format(self.timeStamp(), modeltype, numCheckPoints))
        self.app.modeling.modelRun = False
        return results


text:
require 'faraday'
require 'faraday_middleware'
require 'aweplug/cache'
require 'logger'
require 'json'
require 'uri'

# WARNING: monkey patching faraday
# TODO: See if we can get the new refinements to work
module Faraday
  module Utils
    def build_nested_query(value, prefix = nil)
      case value
      when Array
        value.map { |v| build_nested_query(v, "#{prefix}") }.join("&")
      when Hash
        value.map { |k, v|
          build_nested_query(v, prefix ? "#{prefix}%5B#{escape(k)}%5D" : escape(k))
        }.join("&")
      when NilClass
        prefix
      else
        raise ArgumentError, "value must be a Hash" if prefix.nil?
        "#{prefix}=#{escape(value)}"
      end
    end
  end
end

module Aweplug
  module Helpers
    # Public: A helper class for using Searchisko.
    class Searchisko

      def self.default site, cache_ttl
        cache = Aweplug::Cache.default site, cache_ttl

        Aweplug::Helpers::Searchisko.new({:base_url => site.dcp_base_url,
                                          :authenticate => true,
                                          :searchisko_username => ENV['dcp_user'],
                                          :searchisko_password => ENV['dcp_password'],
                                          :cache => cache,
                                          :logger => site.log_faraday,
                                          :searchisko_warnings => site.searchisko_warnings})
      end

      # Public: Initialization of the object, keeps a Faraday connection cached.
      #
      # opts - symbol keyed hash. Current keys used:
      #        :base_url - base url for the searchisko instance
      #        :authenticate - boolean flag for authentication
      #        :searchisko_username - Username to use for auth
      #        :searchisko_password - Password to use for auth
      #        :logger - Boolean to log responses or an instance of Logger to use
      #        :raise_error - Boolean flag if 404 and 500 should raise exceptions
      #        :adapter - faraday adapter to use, defaults to :net_http
      #        :cache - Instance of a cache to use, required.
      #
      # Returns a new instance of Searchisko.
      def initialize opts={}
        unless [:searchisko_username, :searchisko_password].all? {|required| opts.key? required}
          raise 'Missing searchisko credentials'
        end
        @faraday = Faraday.new(:url => opts[:base_url]) do |builder|
          builder.request :basic_auth, opts[:searchisko_username], opts[:searchisko_password]
          if (opts[:logger])
            if (opts[:logger].is_a?(::Logger))
              builder.response :logger, @logger = opts[:logger]
            else
              builder.response :logger, @logger = ::Logger.new('_tmp/faraday.log', 'daily')
            end
          end
          builder.request :url_encoded
          builder.request :retry
          builder.response :raise_error if opts[:raise_error]
          builder.use FaradayMiddleware::Caching, opts[:cache], {}
          builder.use FaradayMiddleware::FollowRedirects
          #builder.response :json, :content_type => /\bjson$/
          builder.adapter opts[:adapter] || :net_http
        end
        @cache = opts[:cache]
        @searchisko_warnings = opts[:searchisko_warnings] if opts.has_key? :searchisko_warnings
      end

      # Public: Performs a GET normalization against the Searchisko API
      #
      # normalization - The id of the normalization to use
      # id - The id to normalize
      def normalize normalization, id
        key = "normalization-#{normalization}-#{id}"
        json = @cache.read(key)
        if json.nil?
          response = get "/normalization/#{normalization}/#{id}"
          if response.success?
            json = JSON.load(response.body)
            @cache.write(key, json)
          end
        end
        yield json
      end

      # Public: Performs a GET search against the Searchisko instance using
      # provided parameters.
      #
      # params - Hash of parameters to use as query string. See
      #          http://docs.jbossorg.apiary.io/#searchapi for more information
      #          about parameters and how they affect the search.
      #
      # Example
      #
      #   searchisko.search {:query => 'Search query'}
      #   # => {...}
      #
      # Returns the String result of the search.
      def search params = {}
        get '/search', params
      end

      # Public: Makes an HTTP GET to host/v1/rest/#{path} and returns the
      # result from the Faraday request.
      #
      # path   - String containing the rest of the path.
      # params - Hash containing query string parameters.
      #
      # Example
      #
      #   searchisko.get 'feed', {:query => 'Search Query'}
      #   # => Faraday Response Object
      #
      # Returns the Faraday Response for the request.
      def get path, params = {}
        response = @faraday.get URI.escape("/v1/rest/" + path), params
        unless response.success?
          $LOG.warn "Error making searchisko request to #{path}. Status: #{response.status}. Params: #{params}" if $LOG.warn?
        end
        response
      end

      # Public: Posts content to Searchisko.
      #
      # content_type - String of the Searchisko sys_content_type for the content
      #                being posted.
      # content_id   - String of the Searchisko sys_content_id for the content.
      # params       - Hash containing the content to push.
      #
      # Examples
      #
      #   searchisko.push_content 'jbossdeveloper_bom', id, content_hash
      #   # => Faraday Response
      #
      # Returns a Faraday Response from the POST.
      def push_content content_type, content_id, params = {}
        post "/content/#{content_type}/#{content_id}", params
      end

      # Public: Posts bulk content to Searchisko. See
      # http://docs.jbossorg.apiary.io/#post-%2Fv2%2Frest%2Fcontent%2F%7Bsys_content_type%7D
      # for more information.
      #
      # content_type - String of the Searchisko sys_content_type for the content
      #                being posted.
      # params       - Hash containing the content to push. Ids of each value
      #                must be the key in the hash.
      #
      # Examples
      #
      #   searchisko.push_bulk_content 'jbossdeveloper_bom', content_hash
      #   # => Faraday Response
      #
      # Returns a Faraday Response from the POST.
      def push_bulk_content content_type, content = {}
        post "/content/#{content_type}", content
      end

      # Public: Perform an HTTP POST to Searchisko.
      #
      # path   - String containing the rest of the path.
      # params - Hash containing the POST body.
      #
      # Examples
      #
      #   searchisko.post "rating/#{searchisko_document_id}", {rating: 3}
      #   # => Faraday Response
      def post path, params = {}
        resp = @faraday.post do |req|
          req.url "/v1/rest/" + path
          req.headers['Content-Type'] = 'application/json'
          unless params.is_a? String
            req.body = params.to_json
          else
            req.body = params
          end
          if @logger
            @logger.debug "request body: #{req.body}"
          end
        end
        if resp.success?
          body = JSON.parse(resp.body)
          if !@logger.nil? && body.has_key?("warnings")
            @logger.debug "response body: #{resp.body}"
            if !@searchisko_warnings.nil?
              File.open(@searchisko_warnings, File::RDWR|File::CREAT, 0644) do |file|
                file.flock(File::LOCK_EX)
                if file.size > 0
                  content = JSON.load(file)
                else
                  content = []
                end
                content << {:path => path, :body => body, :headers => resp.headers, :status => resp.status}
                file.rewind
                file.write(content.to_json)
              end
            elsif $LOG.warn
              $LOG.warn "Searchisko content POST to '#{path}' succeeded with warnings: #{body["warnings"]}"
            end
          end
        elsif @logger
          @logger.debug "response body: #{resp.body}"
          if $LOG.error
            $LOG.error "Error making searchisko request to '#{path}'. Status: #{resp.status}.
Params: #{params}. Response body: #{resp.body}"
          end
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package com.royalstone.vss.report.cm;

import java.sql.Connection;
import java.util.Map;

import com.royalstone.security.Token;
import com.royalstone.util.InvalidDataException;
import com.royalstone.util.aw.CMQueryService;
import com.royalstone.util.daemon.Filter;
import com.royalstone.util.daemon.ValueAdapter;
import com.royalstone.util.daemon.Values;

public class OrderList extends CMQueryService {

	public OrderList(Connection conn, Token token) {
		super(conn, token);
	}

	public Filter cookFilter(Map map) throws InvalidDataException {
		Filter filter = new Filter();
		String[] ss = null;

		ss = (String[]) map.get("venderid");
		if (ss != null && ss.length > 0) {
			filter.add(" a.venderid IN (" + new Values(ss).toString4String() + ") ");
		}

		ss = (String[]) map.get("goodsid");
		if (ss != null && ss.length > 0) {
			filter.add(" b.goodsid IN (" + new Values(ss).toString4String() + ") ");
		}

		ss = (String[]) map.get("shopid");
		if (ss != null && ss.length > 0) {
			filter.add(" a.shopid IN (" + new Values(ss).toString4String() + ") ");
		}

		ss = (String[]) map.get("checkdate_min");
		if (ss != null && ss.length > 0) {
			filter.add(" a.checkdate >= " + ValueAdapter.std2mdy(ss[0]));
		}

		ss = (String[]) map.get("checkdate_max");
		if (ss != null && ss.length > 0) {
			filter.add(" a.checkdate <= " + ValueAdapter.std2mdy(ss[0]));
		}

		return filter;
	}
}


text:
package bbolt

import (
	"reflect"
	"unsafe"
)

func unsafeAdd(base unsafe.Pointer, offset uintptr) unsafe.Pointer {
	return unsafe.Pointer(uintptr(base) + offset)
}

func unsafeIndex(base unsafe.Pointer, offset uintptr, elemsz uintptr, n int) unsafe.Pointer {
	return unsafe.Pointer(uintptr(base) + offset + uintptr(n)*elemsz)
}

func unsafeByteSlice(base unsafe.Pointer, offset uintptr, i, j int) []byte {
	// See: https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
	//
	// This memory is not allocated from C, but it is unmanaged by Go's
	// garbage collector and should behave similarly, and the compiler
	// should produce similar code.  Note that this conversion allows a
	// subslice to begin after the base address, with an optional offset,
	// while the URL above does not cover this case and only slices from
	// index 0.  However, the wiki never says that the address must be to
	// the beginning of a C allocation (or even that malloc was used at
	// all), so this is believed to be correct.
	return (*[maxAllocSize]byte)(unsafeAdd(base, offset))[i:j:j]
}

// unsafeSlice modifies the data, len, and cap of a slice variable pointed to by
// the slice parameter.  This helper should be used over other direct
// manipulation of reflect.SliceHeader to prevent misuse, namely, converting
// from reflect.SliceHeader to a Go slice type.
func unsafeSlice(slice, data unsafe.Pointer, len int) {
	s := (*reflect.SliceHeader)(slice)
	s.Data = uintptr(data)
	s.Cap = len
	s.Len = len
}


text:
namespace blink {

// Type of <script>'s scheduling.
//
// This is determined by Steps 31-32 of
// https://html.spec.whatwg.org/C/#prepare-the-script-element.
//
// The enum values are used in histograms and thus do not change existing
// enum values when modifying.
enum class ScriptSchedulingType {
  // Because the scheduling type is determined slightly after PendingScript
  // creation, it is set to kNotSet before ScriptLoader::TakePendingScript()
  // is called. kNotSet should not be observed.
  kNotSet,

  // Deferred scripts controlled by HTMLParserScriptRunner.
  //
  // Spec: Step 31.4.
  //
  // Examples:
  // - <script defer> (parser inserted)
  // - <script type="module"> (parser inserted)
  kDefer,

  // Parser-blocking external scripts controlled by XML/HTMLParserScriptRunner.
  //
  // Spec: Step 31.5.
  //
  // Examples:
  // - <script> (parser inserted)
  kParserBlocking,

  // Parser-blocking inline scripts controlled by XML/HTMLParserScriptRunner.
  //
  // Spec: Step 32.2.
  kParserBlockingInline,

  // In-order scripts controlled by ScriptRunner.
  //
  // Spec: Step 31.3.
  //
  // Examples (either classic or module):
  // - Dynamically inserted <script>s with s.async = false
  kInOrder,

  // Async scripts controlled by ScriptRunner.
  //
  // Spec: Step 31.2.
  //
  // Examples (either classic or module):
  // - <script async> and <script async defer> (parser inserted)
  // - Dynamically inserted <script>s
  // - Dynamically inserted <script>s with s.async = true
  kAsync,

  // Inline <script> executed immediately within prepare-the-script-element.
  // Spec: Step 32.3.
  kImmediate,

  // Force deferred scripts controlled by HTMLParserScriptRunner.
  // These are otherwise parser-blocking scripts that are being forced to
  // execute after parsing completes (due to ForceDeferScriptIntervention).
  //
  // Spec: not yet spec'ed. https://crbug.com/976061
  kForceDefer,

  // Force in-order scripts controlled by ScriptRunner.
  //
  // Spec: not yet spec'ed. https://crbug.com/1344772
  kForceInOrder,

  kMaxValue = kForceInOrder,
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_SCRIPT_SCRIPT_SCHEDULING_TYPE_H_


text:
require('ts-node/register');

exports.config = {
  allScriptsTimeout: 11000,
  specs:['features/**/*.feature'],
  // multiCapabilities: [
  //   { 'browserName': 'chrome'},
  //   { 'browserName': 'firefox'}
  // ],
  capabilities: {
    'browserName': 'chrome',
    'chromeOptions': {
      'args': ['show-fps-counter=true']
    }
  },
  plugins: [{
    package: 'protractor-notify-plugin'
  }],
  baseUrl: 'http://localhost:4200/',
  directConnect: true,
  framework: 'custom',
  frameworkPath: require.resolve('protractor-cucumber-framework'),
  cucumberOpts: {
    compiler: "ts:ts-node/register",
    format: "pretty",
    require:[
      'features/step_definitions/**/*.steps.ts'
    ]
  },
  useAllAngular2AppRoots: true,
  onPrepare: function() {
    const globals = require('protractor');
    const browser = globals.browser;
    browser.ignoreSynchronization = true;
  }
};


text:
Zar http = require('http');
var url = require('url');
var port = Number(process.argv[2]);

http.createServer(function(req,res) {
    var parsedUrl = url.parse(req.url, true);
    var pathName = parsedUrl.pathname;
    var isoDate = parsedUrl.query.iso;
    var date = new Date(isoDate);

    if (pathName === '/api/parsetime') {
        var time = {
            "hour": date.getHours(),
            "minute": date.getMinutes(),
            "second": date.getSeconds()
        };
    } else if (pathName === '/api/unixtime') {
        var time = {
            "unixtime" : date.getTime()
        };
    } else {
        res.writeHead(404);
        res.end();
    }

    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify(time));

}).listen(port);


text:
package gov.nij.er.test;

import gov.nij.er.*;
import junit.framework.*;

import org.junit.*;
import org.junit.Test;

public class AlgorithmScoreTest extends TestCase
{

    private static final String JARO_DISTANCE_IMPL = "com.wcohen.ss.Jaro";
    private static final String JARO_WINKLER_DISTANCE_IMPL = "com.wcohen.ss.JaroWinkler";
    private static final String LEVENSTEIN_DISTANCE_IMPL = "uk.ac.shef.wit.simmetrics.similaritymetrics.Levenshtein";
    private static final String SOUNDEX_DISTANCE_IMPL = "uk.ac.shef.wit.simmetrics.similaritymetrics.Soundex";

    private StringDistanceScoreMatcher jaroStringDistanceScoreMatcher;
    private StringDistanceScoreMatcher jaroWinklerStringDistanceScoreMatcher;
    private StringDistanceScoreMatcher levensteinStringDistanceScoreMatcher;
    private StringDistanceScoreMatcher soundexStringDistanceScoreMatcher;

    @Before
    public void setUp() throws Exception
    {
        jaroStringDistanceScoreMatcher = new StringDistanceScoreMatcher(JARO_DISTANCE_IMPL);
        jaroStringDistanceScoreMatcher.init();
        jaroWinklerStringDistanceScoreMatcher = new StringDistanceScoreMatcher(JARO_WINKLER_DISTANCE_IMPL);
        jaroWinklerStringDistanceScoreMatcher.init();
        levensteinStringDistanceScoreMatcher = new StringDistanceScoreMatcher(LEVENSTEIN_DISTANCE_IMPL);
        levensteinStringDistanceScoreMatcher.init();
        soundexStringDistanceScoreMatcher = new StringDistanceScoreMatcher(SOUNDEX_DISTANCE_IMPL);
        soundexStringDistanceScoreMatcher.init();
    }

    @Test
    public void testJaro()
    {
        double score = jaroStringDistanceScoreMatcher.score("Jones", "Johnson");
        assertEquals(0.7904761904761904761904761904754, score, 0.000000000000001); // means they are within 0.000000000000001 of each other, but not necessarily equal
    }

    @Test
    public void testJaro3() {
		double score;
		score = jaroStringDistanceScoreMatcher.score("ABCVWXYZ", "CABVWXYZ");
        assertEquals(0.95833333333333333333333333333238, score, 0.000000000000001);
	}

    @Test
    public void testJaro2() {
		double score;
		score = jaroStringDistanceScoreMatcher.score("Martha", "Marhta");
        assertEquals(0.944444444444444, score, 0.000000000000001);
	}

    @Test
    public void testJaro4()
    {
        double score = jaroWinklerStringDistanceScoreMatcher.score("Jones", "Jones");
        assertEquals(1.0, score, 0.000000000000001);
    }

    @Test
    public void testJaro5()
    {
        double score = jaroWinklerStringDistanceScoreMatcher.score("Clinton", "Bush");
        assertEquals(0.0, score, 0.000000000000001);
    }

    @Test
    public void testJaroWinkler()
    {
        double score = jaroWinklerStringDistanceScoreMatcher.score("Jones", "Johnson");
        assertEquals(0.83238095238095238095238095238, score, 0.000000000000001);
    }

    @Test
    public void testJaroWinkler4()
    {
        double score = jaroWinklerStringDistanceScoreMatcher.score("Jones", "Jones");
        assertEquals(1.0, score, 0.000000000000001);
    }

    @Test
    public void testJaroWinkler5()
    {
        double score = jaroWinklerStringDistanceScoreMatcher.score("Clinton", "Bush");
        assertEquals(0.0, score, 0.000000000000001);
    }

    @Test
    public void testJaroWinkler3() {
		double score;
		score = jaroWinklerStringDistanceScoreMatcher.score("ABCVWXYZ", "CABVWXYZ");
        assertEquals(0.95833333333333333333333333333238, score, 0.000000000000001);
	}

    @Test
    public void testJaroWinkler2() {
		double score;
		score = jaroWinklerStringDistanceScoreMatcher.score("Martha", "Marhta");
        assertEquals(0.9611111111111111, score, 0.000000000000001);
	}

    @Test
    public void testLevenstein()
    {
        double score = levensteinStringDistanceScoreMatcher.score("kitten", "sitting");
        // the implementation of Levenstein in simmetrics scales the true Levenstein distance to a range of 0..1 by dividing
        // by the length of the larger string
        // in this test case, the true distance is 3, the length of the larger string (sitting) is 7, and then the reciprocal
        // percentage is taken
        assertEquals(1.0 - (3.0/7.0), score, 0.0000001);
    }

    @Test
    public void testLevenstein3() {
    	double score = levensteinStringDistanceScoreMatcher.score("Saturday", "Sunday");
        assertEquals(1.0 - (3.0/8.0), score, 0.0000001);
	}

    @Test
    public void testLevenstein2() {
    	double score = levensteinStringDistanceScoreMatcher.score("Saturday", "Saturday");
        assertEquals(1.0, score);
	}

    @Test
    public void testLevenstein4() {
    	double score = levensteinStringDistanceScoreMatcher.score("Clinton", "Bush");
        assertEquals(0.0, score);
	}

}


text:
package com.albedinsky.android.dialog;

import android.test.AndroidTestCase;

import com.albedinsky.android.dialog.TimePickerDialog;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

/**
 * @author Martin Albedinsky
 */
public class TimeParserTest extends AndroidTestCase {

    @SuppressWarnings("unused")
    private static final String TAG = "TimeParserTest";

    static final long ONE_SECOND = 1000;
    static final long ONE_MINUTE = ONE_SECOND * 60;
    static final long ONE_HOUR = ONE_MINUTE * 60;

    private TimePickerDialog.TimeParser mTimeParser;
    private Calendar mCalendar;

    /**
     * Called to set up necessary data before each test.
     */
    @Override
    protected void setUp() throws Exception {
        super.setUp();
        this.mTimeParser = new TimePickerDialog.TimeParser();
        this.mCalendar = Calendar.getInstance(Locale.getDefault());
    }

    /**
     * Test methods --------------------------------------------------------------------------------
     */

    public void testSimpleDateFormat() throws Exception {
        final SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a", Locale.getDefault());
        mCalendar.setTimeInMillis(timeFormat.parse("10:18 PM").getTime());

        assertEquals(10, mCalendar.get(Calendar.HOUR));
        assertEquals(18, mCalendar.get(Calendar.MINUTE));
        assertEquals(Calendar.PM, mCalendar.get(Calendar.AM_PM));
    }

    public void testParseTimeCurrent() {
        testParseTimeString("current");
    }

    public void testParseTimeCurrentPlusMinute() {
        final int offsetBy = 54;
        offsetCalendarBy(0, offsetBy);
        testParseTimeString("current+(00:" + Integer.toString(offsetBy) + ")");
    }

    public void testParseTimeCurrentPlusHour() {
        final int offsetBy = 14;
        offsetCalendarBy(offsetBy, 0);
        testParseTimeString("current+(" + Integer.toString(offsetBy) + ":00)");
    }

    public void testParseTimeCurrentMinusMinute() {
        final int offsetBy = 32;
        offsetCalendarBy(0, -offsetBy);
        testParseTimeString("current-(00:" + Integer.toString(offsetBy) + ")");
    }

    public void testParseTimeCurrentMinusHour() {
        final int offsetBy = 6;
        offsetCalendarBy(-offsetBy, 0);
        testParseTimeString("current-(" + Integer.toString(offsetBy) + ":00)");
    }

    private void offsetCalendarBy(int hours, int minutes) {
        mCalendar.set(Calendar.HOUR_OF_DAY, mCalendar.get(Calendar.HOUR_OF_DAY) + hours);
        mCalendar.set(Calendar.MINUTE, mCalendar.get(Calendar.MINUTE) + minutes);
    }

    private void testParseTimeString(String timeString) {
        assertTimesEquals(mCalendar.getTimeInMillis(), mTimeParser.parse(timeString));
    }

    private void assertTimesEquals(long expected, Long actual) {
        assertNotNull(actual);
        assertTimeFieldsEquals(Calendar.HOUR, expected, actual);
        assertTimeFieldsEquals(Calendar.MINUTE, expected, actual);
        assertTimeFieldsEquals(Calendar.AM_PM, expected, actual);
    }

    private void assertTimeFieldsEquals(int field, long expectedTime, long actualTime) {
        mCalendar.setTimeInMillis(expectedTime);
        final int expectedValue = mCalendar.get(field);

        mCalendar.setTimeInMillis(actualTime);
        final int actualValue = mCalendar.get(field);

        assertEquals(expectedValue, actualValue);
    }
}


text:
package com.github.lunatrius.core.util.vector;

public class Vector2i {
    public int x;
    public int y;

    public Vector2i() {
        this(0, 0);
    }

    public Vector2i(final Vector2i vec) {
        this(vec.x, vec.y);
    }

    public Vector2i(final int num) {
        this(num, num);
    }

    public Vector2i(final int x, final int y) {
        this.x = x;
        this.y = y;
    }

    public final int getX() {
        return this.x;
    }

    public final int getY() {
        return this.y;
    }

    public final void setX(final int x) {
        this.x = x;
    }

    public final void setY(final int y) {
        this.y = y;
    }

    public Vector2i set(final Vector2i vec) {
        return set(vec.x, vec.y);
    }

    public Vector2i set(final int x, final int y) {
        this.x = x;
        this.y = y;
        return this;
    }

    public final double length() {
        return Math.sqrt(lengthSquared());
    }

    public int lengthSquared() {
        return this.x * this.x + this.y * this.y;
    }

    public final double lengthTo(final Vector2i vec) {
        return Math.sqrt(lengthSquaredTo(vec));
    }

    public int lengthSquaredTo(final Vector2i vec) {
        return pow2(this.x - vec.x) + pow2(this.y - vec.y);
    }

    protected final int pow2(final int num) {
        return num * num;
    }

    public final Vector2i normalize() {
        final double len = length();
        if (len != 0.0) {
            return scale(1.0 / len);
        }

        return this;
    }

    public Vector2i negate() {
        this.x = -this.x;
        this.y = -this.y;
        return this;
    }

    public double dot(final Vector2i vec) {
        return this.x * vec.x + this.y * vec.y;
    }

    public Vector2i scale(final double scale) {
        this.x *= scale;
        this.y *= scale;
        return this;
    }

    public Vector2i add(final Vector2i vec) {
        this.x += vec.x;
        this.y += vec.y;
        return this;
    }

    public Vector2i add(final int x, final int y) {
        this.x += x;
        this.y += y;
        return this;
    }

    public Vector2i sub(final Vector2i vec) {
        this.x -= vec.x;
        this.y -= vec.y;
        return this;
    }

    public Vector2i sub(final int x, final int y) {
        this.x -= x;
        this.y -= y;
        return this;
    }

    public Vector2f toVector2f() {
        return new Vector2f(this.x, this.y);
    }

    public Vector2f toVector2f(final Vector2f vec) {
        return vec.set(this.x, this.y);
    }

    public Vector2d toVector2d() {
        return new Vector2d(this.x, this.y);
    }

    public Vector2d toVector2d(final Vector2d vec) {
        return vec.set(this.x, this.y);
    }

    @Override
    public Vector2i clone() {
        return new Vector2i(this);
    }

    @Override
    public boolean equals(final Object obj) {
        return obj instanceof Vector2i && equals((Vector2i) obj);
    }

    public boolean equals(final Vector2i vec) {
        return this.x == vec.x && this.y == vec.y;
    }

    @Override
    public String toString() {
        return String.format("[%s, %s]", this.x, this.y);
    }
}


text:
package com.bennavetta.vetinari.template;

import java.nio.file.Path;

/**
 * Indicates that a template could not be found.
 */
public class MissingTemplateException extends RuntimeException
{
	private static final long serialVersionUID = -1656618673424828278L;

	/**
	 * Creates a new exception indicating that a template could not be found.
	 * @param templateDir the directory containing template files
	 * @param templatePath the name of the missing template
	 */
	public MissingTemplateException(Path templateDir, String templatePath)
	{
		super("Template " + templatePath + " not found in " + templateDir);
	}
}


text:
layout: page
title: Owens Family Reunion
date: 2016-05-24
author: Virginia Holden
tags: weekly links, java
status: published
summary: Mauris sit amet ex suscipit.
banner: images/banner/office-01.jpg
booking:
  startDate: 07/20/2018
  endDate: 07/22/2018
  ctyhocn: OKCYKHX
  groupCode: OFR
published: true
---
Pellentesque a sagittis dolor. Ut sit amet libero sem. Integer ullamcorper ultricies ipsum eget ullamcorper. In ultricies convallis est, quis facilisis nunc congue quis. Integer tempor mi in convallis pellentesque. Aliquam at rhoncus massa, volutpat malesuada lacus. Curabitur id semper leo, eget vestibulum ante. Vestibulum vulputate in diam non pretium. Proin aliquam, magna vel volutpat rhoncus, elit urna lobortis dui, sit amet tincidunt odio nunc at urna. Sed tempus mattis nulla quis ultrices. Aliquam erat volutpat. Vivamus tempus neque eget ipsum aliquam rhoncus. Donec sed porta neque. Sed tristique non diam quis tincidunt.

1 Sed eu massa et nulla malesuada congue non vitae augue
1 Ut euismod elit vitae sollicitudin egestas.

Nunc suscipit ullamcorper turpis at ultrices. Nam felis erat, euismod non mattis vel, gravida quis tellus. Donec a odio augue. Suspendisse ut accumsan dolor, sed luctus est. Quisque fermentum sem et augue sollicitudin, a convallis nisi ultricies. Proin eros purus, ullamcorper non dictum vitae, facilisis scelerisque nisl. Donec sed enim semper, dictum lectus at, semper ex. Cras scelerisque, eros ac ornare feugiat, lorem nisi malesuada risus, nec bibendum dolor neque id orci. Curabitur in arcu vitae tellus semper iaculis in vel tortor. Proin felis purus, pretium at dapibus id, interdum id velit. Integer sit amet congue enim. Praesent gravida iaculis turpis. Integer vestibulum eu nunc in porttitor. Phasellus eget vestibulum nisl.


text:
layout: postag
title: 'DET'
shortdef: 'determiner'
---

Demonstrative `DET`s may be inflected in Hungarian (as a from of grammatical agreement with the noun it precedes):

azokat a könyveket

this-PL-ACC the book-PL-ACC

``those books''

These determiners bear the nominal inflectional features (Number, Case, Number[psor], Person[psor], Number[psed]).
<!-- Interlanguage links updated Po lis 14 15:34:31 CET 2022 -->


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

  var baseConfig = {
    highlight: true,
    hint: false,
    minLength: 1
  };

  // We will prefetch list of techs and locations beforehand
  var getBloodhound = function(url) {
    return new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      limit: 20,
      prefetch: {
        url: url,
        filter: function(list) {
          return $.map(list, function(item) { return { name: item }; });
        }
      }
    });
  }

  var techs = getBloodhound('/techs');
  var locations = getBloodhound('/locations');

  techs.initialize();
  locations.initialize();

  $('input.location').typeahead(baseConfig, {
    name: 'locations',
    displayKey: 'name',
    source: locations.ttAdapter()
  });

  $('input.tech').typeahead(baseConfig, {
    name: 'techs',
    displayKey: 'name',
    source: techs.ttAdapter()
  });

});


text:
package com.acmeair.entities;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class CustomerSession implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@Column(columnDefinition="VARCHAR")
	private String id;
	private String customerid;
	private Date lastAccessedTime;
	private Date timeoutTime;

	public CustomerSession() {
	}

	public CustomerSession(String id, String customerid, Date lastAccessedTime,	Date timeoutTime) {
		this.id= id;
		this.customerid = customerid;
		this.lastAccessedTime = lastAccessedTime;
		this.timeoutTime = timeoutTime;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getCustomerid() {
		return customerid;
	}

	public void setCustomerid(String customerid) {
		this.customerid = customerid;
	}

	public Date getLastAccessedTime() {
		return lastAccessedTime;
	}

	public void setLastAccessedTime(Date lastAccessedTime) {
		this.lastAccessedTime = lastAccessedTime;
	}

	public Date getTimeoutTime() {
		return timeoutTime;
	}

	public void setTimeoutTime(Date timeoutTime) {
		this.timeoutTime = timeoutTime;
	}

	@Override
	public String toString() {
		return "CustomerSession [id=" + id + ", customerid=" + customerid
				+ ", lastAccessedTime=" + lastAccessedTime + ", timeoutTime="
				+ timeoutTime + "]";
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		CustomerSession other = (CustomerSession) obj;
		if (customerid == null) {
			if (other.customerid != null)
				return false;
		} else if (!customerid.equals(other.customerid))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (lastAccessedTime == null) {
			if (other.lastAccessedTime != null)
				return false;
		} else if (!lastAccessedTime.equals(other.lastAccessedTime))
			return false;
		if (timeoutTime == null) {
			if (other.timeoutTime != null)
				return false;
		} else if (!timeoutTime.equals(other.timeoutTime))
			return false;
		return true;
	}

}


text:
from __future__ import print_function, division

from sympy import pi, I
from sympy.core.basic import C
from sympy.core.singleton import S
from sympy.core import Dummy, sympify
from sympy.core.function import Function, ArgumentIndexError
from sympy.functions import assoc_legendre
from sympy.functions.elementary.trigonometric import sin, cos
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.miscellaneous import sqrt

_x = Dummy("x")

class Ynm(Function):
    r"""
    Spherical harmonics defined as

    .. math::
        Y_n^m(\theta, \varphi) := \sqrt{\frac{(2n+1)(n-m)!}{4\pi(n+m)!}}
                                  \exp(i m \varphi)
                                  \mathrm{P}_n^m\left(\cos(\theta)\right)

    Ynm() gives the spherical harmonic function of order `n` and `m`
    in `\theta` and `\varphi`, `Y_n^m(\theta, \varphi)`. The four
    parameters are as follows: `n \geq 0` an integer and `m` an integer
    such that `-n \leq m \leq n` holds. The two angles are real-valued
    with `\theta \in [0, \pi]` and `\varphi \in [0, 2\pi]`.

    Examples
    ========

    >>> from sympy import Ynm, Symbol
    >>> from sympy.abc import n,m
    >>> theta = Symbol("theta")
    >>> phi = Symbol("phi")

    >>> Ynm(n, m, theta, phi)
    Ynm(n, m, theta, phi)

    Several symmetries are known, for the order

    >>> from sympy import Ynm, Symbol
    >>> from sympy.abc import n,m
    >>> theta = Symbol("theta")
    >>> phi = Symbol("phi")

    >>> Ynm(n, -m, theta, phi)
    (-1)**m*exp(-2*I*m*phi)*Ynm(n, m, theta, phi)

    as well as for the angles

    >>> from sympy import Ynm, Symbol, simplify
    >>> from sympy.abc import n,m
    >>> theta = Symbol("theta")
    >>> phi = Symbol("phi")

    >>> Ynm(n, m, -theta, phi)
    Ynm(n, m, theta, phi)

    >>> Ynm(n, m, theta, -phi)
    exp(-2*I*m*phi)*Ynm(n, m, theta, phi)

    For specific integers n and m we can evalute the harmonics
    to more useful expressions

    >>> simplify(Ynm(0, 0, theta, phi).expand(func=True))
    1/(2*sqrt(pi))

    >>> simplify(Ynm(1, -1, theta, phi).expand(func=True))
    sqrt(6)*exp(-I*phi)*sin(theta)/(4*sqrt(pi))

    >>> simplify(Ynm(1, 0, theta, phi).expand(func=True))
    sqrt(3)*cos(theta)/(2*sqrt(pi))

    >>> simplify(Ynm(1, 1, theta, phi).expand(func=True))
    -sqrt(6)*exp(I*phi)*sin(theta)/(4*sqrt(pi))

    >>> simplify(Ynm(2, -2, theta, phi).expand(func=True))
    sqrt(30)*exp(-2*I*phi)*sin(theta)**2/(8*sqrt(pi))

    >>> simplify(Ynm(2, -1, theta, phi).expand(func=True))
    sqrt(30)*exp(-I*phi)*sin(2*theta)/(8*sqrt(pi))

    >>> simplify(Ynm(2, 0, theta, phi).expand(func=True))
    sqrt(5)*(3*cos(theta)**2 - 1)/(4*sqrt(pi))

    >>> simplify(Ynm(2, 1, theta, phi).expand(func=True))
    -sqrt(30)*exp(I*phi)*sin(2*theta)/(8*sqrt(pi))

    >>> simplify(Ynm(2, 2, theta, phi).expand(func=True))
    sqrt(30)*exp(2*I*phi)*sin(theta)**2/(8*sqrt(pi))

    We can differentiate the functions with respect
    to both angles

    >>> from sympy import Ynm, Symbol, diff
    >>> from sympy.abc import n,m
    >>> theta = Symbol("theta")
    >>> phi = Symbol("phi")

    >>> diff(Ynm(n, m, theta, phi), theta)
    m*cot(theta)*Ynm(n, m, theta, phi) + sqrt((-m + n)*(m + n + 1))*exp(-I*phi)*Ynm(n, m + 1, theta, phi)

    >>> diff(Ynm(n, m, theta, phi), phi)
    I*m*Ynm(n, m, theta, phi)

    Further we can compute the complex conjugation

    >>> from sympy import Ynm, Symbol, conjugate
    >>> from sympy.abc import n,m
    >>> theta = Symbol("theta")
    >>> phi = Symbol("phi")

    >>> conjugate(Ynm(n, m, theta, phi))
    (-1)**(2*m)*exp(-2*I*m*phi)*Ynm(n, m, theta, phi)

    To get back the well known expressions in spherical
    coordinates we use full expansion

    >>> from sympy import Ynm, Symbol, expand_func
    >>> from sympy.abc import n,m
    >>> theta = Symbol("theta")
    >>> phi = Symbol("phi")

    >>> expand_func(Ynm(n, m, theta, phi))
    sqrt((2*n + 1)*factorial(-m + n)/factorial(m + n))*exp(I*m*phi)*assoc_legendre(n, m, cos(theta))/(2*sqrt(pi))

    See Also
    ========

    Ynm_c, Znm

    References
    ==========

    .. [1] http://en.wikipedia.org/wiki/Spherical_harmonics
    .. [2] http://mathworld.wolfram.com/SphericalHarmonic.html
    .. [3] http://functions.wolfram.com/Polynomials/SphericalHarmonicY/
    .. [4] http://dlmf.nist.gov/14.30
    """

    @classmethod
    def eval(cls, n, m, theta, phi):
        n, m, theta, phi = [sympify(x) for x in (n, m, theta, phi)]

        # Handle negative index m and arguments theta, phi
        if m.could_extract_minus_sign():
            m = -m
            return S.NegativeOne**m * C.exp(-2*I*m*phi) * Ynm(n, m, theta, phi)
        if theta.could_extract_minus_sign():
            theta = -theta
            return Ynm(n, m, theta, phi)
        if phi.could_extract_minus_sign():
            phi = -phi
            return C.exp(-2*I*m*phi) * Ynm(n, m, theta, phi)

        # TODO Add more simplififcation here

    def _eval_expand_func(self, **hints):
        n, m, theta, phi = self.args
        rv = (sqrt((2*n + 1)/(4*pi) * C.factorial(n - m)/C.factorial(n + m)) *
                C.exp(I*m*phi) * assoc_legendre(n, m, C.cos(theta)))
        # We can do this because of the range of theta
        return rv.subs(sqrt(-cos(theta)**2 + 1), sin(theta))

    def fdiff(self, argindex=4):
        if argindex == 1:
            # Diff wrt n
            raise ArgumentIndexError(self, argindex)
        elif argindex == 2:
            # Diff wrt m
            raise ArgumentIndexError(self, argindex)
        elif argindex == 3:
            # Diff wrt theta
            n, m, theta, phi = self.args
            return (m * C.cot(theta) * Ynm(n, m, theta, phi) +
                    sqrt((n - m)*(n + m + 1)) * C.exp(-I*phi) * Ynm(n, m + 1, theta, phi))
        elif argindex == 4:
            # Diff wrt phi
            n, m, theta, phi = self.args
            return I * m * Ynm(n, m, theta, phi)
        else:
            raise ArgumentIndexError(self, argindex)

    def _eval_rewrite_as_polynomial(self, n, m, theta, phi):
        # TODO: Make sure n \in N
        # TODO: Assert |m| <= n ortherwise we should return 0
        return self.expand(func=True)

    def _eval_rewrite_as_sin(self, n, m, theta, phi):
        return self.rewrite(cos)

    def _eval_rewrite_as_cos(self, n, m, theta, phi):
        # This method can be expensive due to extensive use of simplification!
        from sympy.simplify import simplify, trigsimp
        # TODO: Make sure n \in N
        # TODO: Assert |m| <= n ortherwise we should return 0
        term = simplify(self.expand(func=True))
        # We can do this because of the range of theta
        term = term.xreplace({Abs(sin(theta)):sin(theta)})
        return simplify(trigsimp(term))

    def _eval_conjugate(self):
        # TODO: Make sure theta \in R and phi \in R
        n, m, theta, phi = self.args
        return S.NegativeOne**m * self.func(n, -m, theta, phi)

    def as_real_imag(self, deep=True, **hints):
        # TODO: Handle deep and hints
        n, m, theta, phi = self.args
        re = (sqrt((2*n + 1)/(4*pi) * C.factorial(n - m)/C.factorial(n + m)) *
              C.cos(m*phi) * assoc_legendre(n, m, C.cos(theta)))
        im = (sqrt((2*n + 1)/(4*pi) * C.factorial(n - m)/C.factorial(n + m)) *
              C.sin(m*phi) * assoc_legendre(n, m, C.cos(theta)))
        return (re, im)

    def _eval_evalf(self, prec):
        # Note: works without this function by just calling
        #       mpmath for Legendre polynomials. But using
        #       the dedicated function directly is cleaner.
        from mpmath import mp, workprec
        from sympy import Expr
        n = self.args[0]._to_mpmath(prec)
        m = self.args[1]._to_mpmath(prec)
        theta = self.args[2]._to_mpmath(prec)
        phi = self.args[3]._to_mpmath(prec)
        with workprec(prec):
            res = mp.spherharm(n, m, theta, phi)
        return Expr._from_mpmath(res, prec)

def Ynm_c(n, m, theta, phi):
    r"""Conjugate spherical harmonics defined as

    .. math::
        \overline{Y_n^m(\theta, \varphi)} := (-1)^m Y_n^{-m}(\theta, \varphi)

    See Also
    ========

    Ynm, Znm

    References
    ==========

    .. [1] http://en.wikipedia.org/wiki/Spherical_harmonics
    .. [2] http://mathworld.wolfram.com/SphericalHarmonic.html
    .. [3] http://functions.wolfram.com/Polynomials/SphericalHarmonicY/
    """
    from sympy import conjugate
    return conjugate(Ynm(n, m, theta, phi))

class Znm(Function):
    r"""
    Real spherical harmonics defined as

    .. math::

        Z_n^m(\theta, \varphi) :=
        \begin{cases}
          \frac{Y_n^m(\theta, \varphi) + \overline{Y_n^m(\theta, \varphi)}}{\sqrt{2}} &\quad m > 0 \\
          Y_n^m(\theta, \varphi) &\quad m = 0 \\
          \frac{Y_n^m(\theta, \varphi) - \overline{Y_n^m(\theta, \varphi)}}{i \sqrt{2}} &\quad m < 0 \\
        \end{cases}

    which gives in simplified form

    .. math::

        Z_n^m(\theta, \varphi) =
        \begin{cases}
          \frac{Y_n^m(\theta, \varphi) + (-1)^m Y_n^{-m}(\theta, \varphi)}{\sqrt{2}} &\quad m > 0 \\
          Y_n^m(\theta, \varphi) &\quad m = 0 \\
          \frac{Y_n^m(\theta, \varphi) - (-1)^m Y_n^{-m}(\theta, \varphi)}{i \sqrt{2}} &\quad m < 0 \\
        \end{cases}

    See Also
    ========

    Ynm, Ynm_c

    References
    ==========

    .. [1] http://en.wikipedia.org/wiki/Spherical_harmonics
    .. [2] http://mathworld.wolfram.com/SphericalHarmonic.html
    .. [3] http://functions.wolfram.com/Polynomials/SphericalHarmonicY/
    """

    @classmethod
    def eval(cls, n, m, theta, phi):
        n, m, th, ph = [sympify(x) for x in (n, m, theta, phi)]

        if m.is_positive:
            zz = (Ynm(n, m, th, ph) + Ynm_c(n, m, th, ph)) / sqrt(2)
            return zz
        elif m.is_zero:
            return Ynm(n, m, th, ph)
        elif m.is_negative:
            zz = (Ynm(n, m, th, ph) - Ynm_c(n, m, th, ph)) / (sqrt(2)*I)
            return zz


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

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

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;

/** SetVariable activity properties. */
@Fluent
public final class SetVariableActivityTypeProperties {
    /*
     * Name of the variable whose value needs to be set.
     */
    @JsonProperty(value = "variableName")
    private String variableName;

    /*
     * Value to be set. Could be a static value or Expression
     */
    @JsonProperty(value = "value")
    private Object value;

    /** Creates an instance of SetVariableActivityTypeProperties class. */
    public SetVariableActivityTypeProperties() {
    }

    /**
     * Get the variableName property: Name of the variable whose value needs to be set.
     *
     * @return the variableName value.
     */
    public String variableName() {
        return this.variableName;
    }

    /**
     * Set the variableName property: Name of the variable whose value needs to be set.
     *
     * @param variableName the variableName value to set.
     * @return the SetVariableActivityTypeProperties object itself.
     */
    public SetVariableActivityTypeProperties withVariableName(String variableName) {
        this.variableName = variableName;
        return this;
    }

    /**
     * Get the value property: Value to be set. Could be a static value or Expression.
     *
     * @return the value value.
     */
    public Object value() {
        return this.value;
    }

    /**
     * Set the value property: Value to be set. Could be a static value or Expression.
     *
     * @param value the value value to set.
     * @return the SetVariableActivityTypeProperties object itself.
     */
    public SetVariableActivityTypeProperties withValue(Object value) {
        this.value = value;
        return this;
    }

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


text:
#pragma once
#include <moonstone/chain/evaluator.hpp>

namespace moonstone { namespace chain {

   class worker_create_evaluator : public evaluator<worker_create_evaluator>
   {
      public:
         typedef worker_create_operation operation_type;

         void_result do_evaluate( const operation_type& o );
         object_id_type do_apply( const operation_type& o );
   };

} } // moonstone::chain


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

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.core.CoreContainer (Solr 5.5.0 API)</title>
<meta name="date" content="2016-02-16">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.solr.core.CoreContainer

Packages that use CoreContainer

Package
Description

org.apache.solr.client.solrj.embedded

SolrJ client implementations for embedded solr access.

org.apache.solr.cloud

Classes for dealing with ZooKeeper when operating in SolrCloud mode.

org.apache.solr.cloud.rule

Classes for managing Replica placement strategy when operating in SolrCloud mode.

org.apache.solr.core

Core classes implementin Solr internals and the management of SolrCores

org.apache.solr.handler.admin

SolrRequestHandler implementations for powering he Solr Admin UI

org.apache.solr.logging

APIs related to capturing log event info in the LoggingHandler

org.apache.solr.search.join

Classes related to joins.

org.apache.solr.security

Commonly used classes for Solr security framework.

org.apache.solr.servlet

Servlet related classes for powering the Solr HTTP API

org.apache.solr.update

APIs and classes for managing index updates

org.apache.solr.util

Common utility classes used throughout Solr

Uses of CoreContainer in org.apache.solr.client.solrj.embedded

Fields in org.apache.solr.client.solrj.embedded declared as CoreContainer

Modifier and Type
Field and Description

protected CoreContainer
EmbeddedSolrServer.coreContainer

Methods in org.apache.solr.client.solrj.embedded that return CoreContainer

Modifier and Type
Method and Description

CoreContainer
JettySolrRunner.getCoreContainer()

CoreContainer
EmbeddedSolrServer.getCoreContainer()

Getter method for the CoreContainer

Constructors in org.apache.solr.client.solrj.embedded with parameters of type CoreContainer

Constructor and Description

EmbeddedSolrServer(CoreContainer coreContainer,
                  String coreName)

Create an EmbeddedSolrServer wrapping a CoreContainer.

Uses of CoreContainer in org.apache.solr.cloud

Fields in org.apache.solr.cloud declared as CoreContainer

Modifier and Type
Field and Description

protected CoreContainer
LeaderInitiatedRecoveryThread.coreContainer

Methods in org.apache.solr.cloud with parameters of type CoreContainer

Modifier and Type
Method and Description

static void
ZkController.bootstrapConf(SolrZkClient zkClient,
             CoreContainer cc,
             String solrHome)

If in SolrCloud mode, upload config sets for each SolrCore in solr.xml.

static void
CloudUtil.checkSharedFSFailoverReplaced(CoreContainer cc,
                             CoreDescriptor desc)

See if coreNodeName has been taken over by another baseUrl and unload core
 + throw exception if it has been.

boolean
ZkController.ensureReplicaInLeaderInitiatedRecovery(CoreContainer container,
                                      String collection,
                                      String shardId,
                                      ZkCoreNodeProps replicaCoreProps,
                                      CoreDescriptor leaderCd,
                                      boolean forcePublishState)

When a leader receives a communication error when trying to send a request to a replica,
 it calls this method to ensure the replica enters recovery when connectivity is restored.

static List<org.apache.solr.cloud.Assign.ReplicaCount>
Assign.getNodesForNewReplicas(ClusterState clusterState,
                      String collectionName,
                      String shard,
                      int numberOfNodes,
                      String createNodeSetStr,
                      CoreContainer cc)

Constructors in org.apache.solr.cloud with parameters of type CoreContainer

Constructor and Description

LeaderInitiatedRecoveryThread(ZkController zkController,
                             CoreContainer cc,
                             String collection,
                             String shardId,
                             ZkCoreNodeProps nodeProps,
                             int maxTries,
                             CoreDescriptor leaderCd)

RecoveryStrategy(CoreContainer cc,
                CoreDescriptor cd,
                RecoveryStrategy.RecoveryListener recoveryListener)

SyncStrategy(CoreContainer cc)

ZkController(CoreContainer cc,
            String zkServerAddress,
            int zkClientConnectTimeout,
            CloudConfig cloudConfig,
            CurrentCoreDescriptorProvider registerOnReconnect)

Uses of CoreContainer in org.apache.solr.cloud.rule

Methods in org.apache.solr.cloud.rule that return CoreContainer

Modifier and Type
Method and Description

abstract CoreContainer
SnitchContext.SnitchInfo.getCoreContainer()

Methods in org.apache.solr.cloud.rule with parameters of type CoreContainer

Modifier and Type
Method and Description

static void
ReplicaAssigner.verifySnitchConf(CoreContainer cc,
                List snitchConf)

Constructors in org.apache.solr.cloud.rule with parameters of type CoreContainer

Constructor and Description

ReplicaAssigner(List<Rule> rules,
               Map<String,Integer> shardVsReplicaCount,
               List snitches,
               Map<String,Map<String,Integer>> shardVsNodes,
               List<String> liveNodes,
               CoreContainer cc,
               ClusterState clusterState)

Uses of CoreContainer in org.apache.solr.core

Methods in org.apache.solr.core that return CoreContainer

Modifier and Type
Method and Description

static CoreContainer
CoreContainer.createAndLoad(Path solrHome)

static CoreContainer
CoreContainer.createAndLoad(Path solrHome,
             Path configFile)

Create a new CoreContainer and load its cores

CoreContainer
CoreDescriptor.getCoreContainer()

Methods in org.apache.solr.core with parameters of type CoreContainer

Modifier and Type
Method and Description

protected CoreDescriptor
CorePropertiesLocator.buildCoreDescriptor(Path propertiesFile,
                   CoreContainer cc)

void
CorePropertiesLocator.create(CoreContainer cc,
      CoreDescriptor... coreDescriptors)

void
CoresLocator.create(CoreContainer cc,
      CoreDescriptor... coreDescriptors)

Make new cores available for discovery

void
CorePropertiesLocator.delete(CoreContainer cc,
      CoreDescriptor... coreDescriptors)

void
CoresLocator.delete(CoreContainer cc,
      CoreDescriptor... coreDescriptors)

Ensure that the core definitions from the passed in CoreDescriptors
 are not available for discovery

List<CoreDescriptor>
CorePropertiesLocator.discover(CoreContainer cc)

List<CoreDescriptor>
CoresLocator.discover(CoreContainer cc)

Load all the CoreDescriptors from persistence store

void
ZkContainer.initZooKeeper(CoreContainer cc,
             String solrHome,
             CloudConfig config)

CoreAdminHandler
SolrResourceLoader.newAdminHandlerInstance(CoreContainer coreContainer,
                       String cname,
                       String... subpackages)

void
CorePropertiesLocator.persist(CoreContainer cc,
       CoreDescriptor... coreDescriptors)

void
CoresLocator.persist(CoreContainer cc,
       CoreDescriptor... coreDescriptors)

Ensure that the core definitions from the passed in CoreDescriptors
 will persist across container restarts.

void
CorePropertiesLocator.rename(CoreContainer cc,
      CoreDescriptor oldCD,
      CoreDescriptor newCD)

void
CoresLocator.rename(CoreContainer cc,
      CoreDescriptor oldCD,
      CoreDescriptor newCD)

Persist the new name of a renamed core

void
CorePropertiesLocator.swap(CoreContainer cc,
    CoreDescriptor cd1,
    CoreDescriptor cd2)

void
CoresLocator.swap(CoreContainer cc,
    CoreDescriptor cd1,
    CoreDescriptor cd2)

Swap two core definitions

Constructors in org.apache.solr.core with parameters of type CoreContainer

Constructor and Description

CoreDescriptor(CoreContainer container,
              String name,
              Path instanceDir)

Create a new CoreDescriptor with a given name and instancedir

CoreDescriptor(CoreContainer container,
              String name,
              Path instanceDir,
              Map<String,String> coreProps)

Create a new CoreDescriptor.

CoreDescriptor(CoreContainer container,
              String name,
              Path instanceDir,
              String... properties)

JarRepository(CoreContainer coreContainer)

Uses of CoreContainer in org.apache.solr.handler.admin

Fields in org.apache.solr.handler.admin declared as CoreContainer

Modifier and Type
Field and Description

protected CoreContainer
ConfigSetsHandler.coreContainer

protected CoreContainer
InfoHandler.coreContainer

protected CoreContainer
CollectionsHandler.coreContainer

protected CoreContainer
CoreAdminHandler.coreContainer

Methods in org.apache.solr.handler.admin that return CoreContainer

Modifier and Type
Method and Description

CoreContainer
InfoHandler.getCoreContainer()

The instance of CoreContainer this handler handles.

CoreContainer
CollectionsHandler.getCoreContainer()

The instance of CoreContainer this handler handles.

CoreContainer
CoreAdminHandler.getCoreContainer()

The instance of CoreContainer this handler handles.

Methods in org.apache.solr.handler.admin with parameters of type CoreContainer

Modifier and Type
Method and Description

static void
CollectionsHandler.verifyRuleParams(CoreContainer cc,
                Map<String,Object> m)

Constructors in org.apache.solr.handler.admin with parameters of type CoreContainer

Constructor and Description

CollectionsHandler(CoreContainer coreContainer)

Overloaded ctor to inject CoreContainer into the handler.

ConfigSetsHandler(CoreContainer coreContainer)

Overloaded ctor to inject CoreContainer into the handler.

CoreAdminHandler(CoreContainer coreContainer)

Overloaded ctor to inject CoreContainer into the handler.

InfoHandler(CoreContainer coreContainer)

Overloaded ctor to inject CoreContainer into the handler.

LoggingHandler(CoreContainer cc)

SecurityConfHandler(CoreContainer coreContainer)

SystemInfoHandler(CoreContainer cc)

ZookeeperInfoHandler(CoreContainer cc)

Uses of CoreContainer in org.apache.solr.logging

Methods in org.apache.solr.logging with parameters of type CoreContainer

Modifier and Type
Method and Description

static void
MDCLoggingContext.setNode(CoreContainer cc)

Uses of CoreContainer in org.apache.solr.search.join

Methods in org.apache.solr.search.join with parameters of type CoreContainer

Modifier and Type
Method and Description

static String
ScoreJoinQParserPlugin.getCoreName(String fromIndex,
           CoreContainer container)

Returns an String with the name of a core.

Uses of CoreContainer in org.apache.solr.security

Constructors in org.apache.solr.security with parameters of type CoreContainer

Constructor and Description

KerberosPlugin(CoreContainer coreContainer)

PKIAuthenticationPlugin(CoreContainer cores,
                       String nodeName)

Uses of CoreContainer in org.apache.solr.servlet

Fields in org.apache.solr.servlet declared as CoreContainer

Modifier and Type
Field and Description

protected CoreContainer
HttpSolrCall.cores

protected CoreContainer
SolrDispatchFilter.cores

Methods in org.apache.solr.servlet that return CoreContainer

Modifier and Type
Method and Description

protected CoreContainer
SolrDispatchFilter.createCoreContainer(Path solrHome,
                   Properties extraProperties)

Override this to change CoreContainer initialization

CoreContainer
SolrDispatchFilter.getCores()

Constructors in org.apache.solr.servlet with parameters of type CoreContainer

Constructor and Description

HttpSolrCall(SolrDispatchFilter solrDispatchFilter,
            CoreContainer cores,
            javax.servlet.http.HttpServletRequest request,
            javax.servlet.http.HttpServletResponse response,
            boolean retry)

Uses of CoreContainer in org.apache.solr.update

Methods in org.apache.solr.update with parameters of type CoreContainer

Modifier and Type
Method and Description

void
DefaultSolrCoreState.doRecovery(CoreContainer cc,
          CoreDescriptor cd)

abstract void
SolrCoreState.doRecovery(CoreContainer cc,
          CoreDescriptor cd)

Uses of CoreContainer in org.apache.solr.util

Methods in org.apache.solr.util with parameters of type CoreContainer

Modifier and Type
Method and Description

static boolean
TestInjection.injectNonGracefullClose(CoreContainer cc)

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

          Copyright © 2000-2016 Apache Software Foundation.  All Rights Reserved.