Exemple #1
0
 public TermDetails(Terms.Term term)
 {
     this.term = term;
     this.properties = term.Properties;
     this.children = term.Childen;
     this.parents = term.Parents;
     this.connectedTerms = term.GetConnectedTerms();
 }
Exemple #2
0
        public override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
        {
            TermsEnum tenum = terms.Iterator(null);

            if (Prefix_Renamed.Bytes().Length == 0)
            {
                // no prefix -- match all terms for this field:
                return tenum;
            }
            return new PrefixTermsEnum(tenum, Prefix_Renamed.Bytes());
        }
Exemple #3
0
        /// <summary>
        /// Formats an action for display in the view.
        /// </summary>
        /// <param name="start">Optional start action with input arguments.</param>
        /// <param name="finish">Optional finish action with output arguments and return value.</param>
        /// <returns>A nicely formatted string representing the action(s).</returns>
        static string GetActionLabel(Terms.CompoundTerm/*?*/ start, Terms.CompoundTerm/*?*/ finish)
        {
            if (start != null && finish != null && finish.Arguments.Count > 0)
                return string.Format((IFormatProvider)null,
                    "{0}({1}) / {2}",
                    start.Symbol.Name.Replace("_Start",""),
                    GetArgumentLabel(start.Arguments),
                    GetArgumentLabel(finish.Arguments));

            if (start != null)
                return string.Format((IFormatProvider)null,
                    "{0}({1})",
                    start.Symbol.Name,
                    GetArgumentLabel(start.Arguments));

            if (finish != null)
                return string.Format((IFormatProvider)null,
                    "{0}({1})",
                    finish.Symbol.Name,
                    GetArgumentLabel(finish.Arguments));

            return "";
        }
Exemple #4
0
 public BloomFilteredTermsEnum(Terms delegateTerms, TermsEnum reuseDelegate, FuzzySet filter)
 {
     _delegateTerms = delegateTerms;
     _reuseDelegate = reuseDelegate;
     this.filter    = filter;
 }
 public override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
 {
     return new SimplePrefixTermsEnum(this, terms.Iterator(null), Prefix);
 }
    private TERMS.Business.Centers.SalesCenter.Hotel ConvertRooms(TERMS.Business.Centers.SalesCenter.Hotel hotel, Terms.Sales.Business.HotelSearchCondition searchCondtion)
    {
        List<MVRoom> rooms = new List<MVRoom>();

        for (int index = 0; index < searchCondtion.RoomSearchConditions.Count; index++)
        {
            //������
            int iAdult = searchCondtion.RoomSearchConditions[index].Passengers[TERMS.Common.PassengerType.Adult];
            //����
            int iChild = searchCondtion.RoomSearchConditions[index].Passengers[TERMS.Common.PassengerType.Child];

            int MaxNumber = 0;

            MVRoom mvroom = new MVRoom((TERMS.Business.Centers.SalesCenter.HotelProfile)((TERMS.Business.Centers.SalesCenter.HotelProfile)hotel.Profile).Clone());
            mvroom.Profile.AdultNumber = iAdult;
            mvroom.Profile.ChildNumber = iChild;

            for (int j = 0; j < hotel.Items.Count; j++)
            {
                //�жϷ��������Ƿ����
                HotelMaterial room = (HotelMaterial)hotel.Items[j];

                if (string.IsNullOrEmpty(room.Room.Name))
                    room.Room.Name = room.Room.Description;

                MaxNumber = room.Room.Capacity + room.Room.MaxExtraBed + room.Room.MaxShareBed;

                if ((iAdult + iChild) > MaxNumber)
                {
                    continue;
                }
                else
                {
                    if (iChild > 0)
                    {
                        if ((iAdult + iChild) == room.Room.Capacity)
                        {
                            if (iAdult == 2 && iChild == 1)
                            {
                                if (room.Room.Code == "TR")
                                {
                                    continue;
                                }
                            }

                            AddRoomSort(mvroom, room);
                            continue;
                        }

                        if ((room.Room.MaxExtraBed + room.Room.MaxShareBed) >= iChild && iAdult == room.Room.Capacity)
                        {
                            if (iAdult == 2 && iChild == 1)
                            {
                                if (room.Room.Code == "TR")
                                {
                                    continue;
                                }
                            }

                            AddRoomSort(mvroom, room);
                            continue;
                        }

                        if (iAdult == 1 && iChild == 2)
                        {
                            if (room.Room.Code == "DB" || room.Room.Code == "TB")
                            {
                                if (room.Room.MaxExtraBed == 1)
                                {
                                    AddRoomSort(mvroom, room);
                                    continue;
                                }
                            }
                        }
                    }
                    else
                    {
                        if (iAdult == room.Room.Capacity && (room.Room.MaxExtraBed + room.Room.MaxShareBed) == iChild)
                        {
                            if (iAdult == 2 && iChild == 1)
                            {
                                if (room.Room.Code == "TR")
                                {
                                    continue;
                                }
                            }

                            AddRoomSort(mvroom, room);
                            continue;
                        }
                    }

                    //mvroom.Items.Add(room);

                }
            }

            if (mvroom.Items.Count > 0)
                rooms.Add(mvroom);
        }

        if (rooms.Count == searchCondtion.RoomSearchConditions.Count)
        {
            hotel.Items.Clear();

            for (int j = 0; j < rooms.Count; j++)
            {
                hotel.Items.Add(rooms[j]);
            }

            return hotel;
        }
        else
        {
            return null;
        }
    }
        private void DuellReaders(CompositeReader other, AtomicReader memIndexReader)
        {
            AtomicReader competitor = SlowCompositeReaderWrapper.Wrap(other);
            Fields       memFields  = memIndexReader.Fields;

            foreach (string field in competitor.Fields)
            {
                Terms memTerms = memFields.GetTerms(field);
                Terms iwTerms  = memIndexReader.GetTerms(field);
                if (iwTerms == null)
                {
                    assertNull(memTerms);
                }
                else
                {
                    NumericDocValues normValues    = competitor.GetNormValues(field);
                    NumericDocValues memNormValues = memIndexReader.GetNormValues(field);
                    if (normValues != null)
                    {
                        // mem idx always computes norms on the fly
                        assertNotNull(memNormValues);
                        assertEquals(normValues.Get(0), memNormValues.Get(0));
                    }

                    assertNotNull(memTerms);
                    assertEquals(iwTerms.DocCount, memTerms.DocCount);
                    assertEquals(iwTerms.SumDocFreq, memTerms.SumDocFreq);
                    assertEquals(iwTerms.SumTotalTermFreq, memTerms.SumTotalTermFreq);
                    TermsEnum iwTermsIter  = iwTerms.GetIterator(null);
                    TermsEnum memTermsIter = memTerms.GetIterator(null);
                    if (iwTerms.HasPositions)
                    {
                        bool offsets = iwTerms.HasOffsets && memTerms.HasOffsets;

                        while (iwTermsIter.Next() != null)
                        {
                            assertNotNull(memTermsIter.Next());
                            assertEquals(iwTermsIter.Term, memTermsIter.Term);
                            DocsAndPositionsEnum iwDocsAndPos  = iwTermsIter.DocsAndPositions(null, null);
                            DocsAndPositionsEnum memDocsAndPos = memTermsIter.DocsAndPositions(null, null);
                            while (iwDocsAndPos.NextDoc() != DocsAndPositionsEnum.NO_MORE_DOCS)
                            {
                                assertEquals(iwDocsAndPos.DocID, memDocsAndPos.NextDoc());
                                assertEquals(iwDocsAndPos.Freq, memDocsAndPos.Freq);
                                for (int i = 0; i < iwDocsAndPos.Freq; i++)
                                {
                                    assertEquals("term: " + iwTermsIter.Term.Utf8ToString(), iwDocsAndPos.NextPosition(), memDocsAndPos.NextPosition());
                                    if (offsets)
                                    {
                                        assertEquals(iwDocsAndPos.StartOffset, memDocsAndPos.StartOffset);
                                        assertEquals(iwDocsAndPos.EndOffset, memDocsAndPos.EndOffset);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        while (iwTermsIter.Next() != null)
                        {
                            assertEquals(iwTermsIter.Term, memTermsIter.Term);
                            DocsEnum iwDocsAndPos  = iwTermsIter.Docs(null, null);
                            DocsEnum memDocsAndPos = memTermsIter.Docs(null, null);
                            while (iwDocsAndPos.NextDoc() != DocsAndPositionsEnum.NO_MORE_DOCS)
                            {
                                assertEquals(iwDocsAndPos.DocID, memDocsAndPos.NextDoc());
                                assertEquals(iwDocsAndPos.Freq, memDocsAndPos.Freq);
                            }
                        }
                    }
                }
            }
        }
    public InsuranceMaterial SearchInsurance(Terms.Sales.Business.InsuranceSearchCondition insuranceCondition)
    {
        TERMS.Common.Search.InsuranceSearchCondition Condition = new TERMS.Common.Search.InsuranceSearchCondition();

        Condition.InsuranceType = insuranceCondition.InsuranceType;

        Condition.Trip = new TERMS.Common.Trip();

        Condition.Trip.DepartureDate = insuranceCondition.DepartureDate;
        Condition.Trip.ReturnDate = insuranceCondition.ReturnDate;
        Condition.Trip.InitialTripDepositDate = DateTime.Now;

        List<TERMS.Common.Traveler> list = new List<TERMS.Common.Traveler>();

        for (int i = 0; i < insuranceCondition.TravelerCount; i++)
        {
            TERMS.Common.Traveler t = new TERMS.Common.Traveler();

            t.BirthDate = DateTime.Now.AddYears(-10);

            t.TripCost = Convert.ToDouble(insuranceCondition.TotalTripCost / insuranceCondition.TravelerCount);

            list.Add(t);
        }

        Condition.Travelers = list.ToArray();

        InsuranceProductSearcher INs = new InsuranceProductSearcher();
        IList<InsuranceProduct> products = null;
        try
        {
            products = INs.Search(Condition);
        }
        catch
        {
            return null;
        }

        if (products != null && products.Count > 0)
        {
            return ((TERMS.Business.Centers.ProductCenter.Components.InsuranceMaterial)((TERMS.Core.Product.ComponentGroup)products[0].Items[0]).Items[0]);
        }
        else
        {
            return null;
        }
    }
    //public TourMerchandise SearchTour(Terms.Sales.Business.TourSearchCondition searchCondition, List<string> citys, string Language)
    //{
    //    searchCondition.UserInfo = UserInfo;
    //    //��Cache�в��ҽ�
    //    TourMerchandise tourMerchandise = (TourMerchandise)MVMerchandisePool.Find(citys);
    //    if (tourMerchandise == null)
    //    {
    //        TourProductSearcher searcher = new TourProductSearcher();
    //        TERMS.Common.Search.TourSearchCondition tourSearchCondition = new TERMS.Common.Search.TourSearchCondition();
    //        tourSearchCondition.SetCity(searchCondition.City);
    //        tourSearchCondition.SetRegion(searchCondition.Region);
    //        tourSearchCondition.SetCountry(searchCondition.Counrty);
    //        tourSearchCondition.IsLandOnly = searchCondition.IsLandOnly;
    //        tourSearchCondition.TravelDaysFrom = searchCondition.TravelDaysFrom;
    //        tourSearchCondition.TravelDaysTo = searchCondition.TravelDaysTo;
    //        tourSearchCondition.PriceType = searchCondition.PriceType;
    //        tourSearchCondition.SetDepartureRange(searchCondition.TravelBeginDate.AddDays(-7), searchCondition.TravelBeginDate.AddDays(300));
    //        IList<TourProduct> tps = new List<TourProduct>();
    //        tps = searcher.Search(tourSearchCondition, citys, userInfo.Entity);
    //        if (tps != null && tps.Count > 0)
    //        {
    //            TourMerchandise tourMerchandiseNew = new TourMerchandise((List<TourProduct>)tps);
    //            if (Utility.IsSubAgent)
    //            {
    //                GetSpecialTourPrice(tourMerchandise, searchCondition.IsLandOnly);
    //            }
    //            MVMerchandisePool.Cache(citys, tourMerchandiseNew); //Cache
    //            tourMerchandise = tourMerchandiseNew;
    //        }
    //        else
    //            return null;
    //    }
    //    tourMerchandise.LanguageFlag = Language;
    //    return tourMerchandise;
    //}
    public TourMerchandise SearchTour(Terms.Sales.Business.TourSearchCondition searchCondition, List<string> citys, string Language)
    {
        //searchCondition.UserInfo = UserInfo;

        TourMerchandise tourMerchandise = null;

        TourMerchandise tourMerchandiseAll = null;

        if (Utility.IsSubAgent)
            tourMerchandiseAll = (TourMerchandise)MVMerchandisePool.Find("SUBTour");
        else
            tourMerchandiseAll = (TourMerchandise)MVMerchandisePool.Find("Tour");

        if (tourMerchandiseAll == null)
        {
            tourMerchandiseAll = SearchTour(Language);
        }

        if (tourMerchandiseAll != null)
        {
            tourMerchandise = new TourMerchandise();

            tourMerchandise.TourProductList = tourMerchandiseAll.TourProductList;

            for (int i = 0; i < tourMerchandiseAll.Items.Count; i++)
            {
                TourMaterial tourMaterial = (TourMaterial)tourMerchandiseAll.Items[i];
                TourMaterial tourMaterialCN = (TourMaterial)tourMerchandiseAll.TourMCN[i];

                TourProfile tourprofile = (TourProfile)tourMaterial.Profile;

                TERMS.Common.City StartCity = tourprofile.StartCity;
                TERMS.Common.City EndCity = tourprofile.EndCity;
                List<TERMS.Common.City> PassCities = (List<TERMS.Common.City>)tourprofile.PassCities;

                if (searchCondition.TravelDaysFrom != 0 && searchCondition.TravelDaysTo != 0 &&
                (tourprofile.Days < searchCondition.TravelDaysFrom || tourprofile.Days > searchCondition.TravelDaysTo))
                {
                    continue;
                }

                if (citys.Contains(StartCity.Code))
                {
                    tourMerchandise.Add(tourMaterial);
                    tourMerchandise.TourMCN.Add(tourMaterialCN);
                    continue;
                }
                if (citys.Contains(EndCity.Code))
                {
                    tourMerchandise.Add(tourMaterial);
                    tourMerchandise.TourMCN.Add(tourMaterialCN);
                    continue;
                }
                for (int index = 0; index < PassCities.Count; index++)
                {
                    if (citys.Contains(PassCities[index].Code))
                    {
                        tourMerchandise.Add(tourMaterial);
                        tourMerchandise.TourMCN.Add(tourMaterialCN);

                        break;
                    }
                }
            }
        }
        else
            return null;

        //tourMerchandise.Items.Sort(CompareByStartFromLandOnlyFareAndTourCode);

        tourMerchandise.LanguageFlag = Language;

        return tourMerchandise;
    }
Exemple #10
0
        public IEnumerable <Substitution> GetSubstitutions(IEnumerable <Segment> segments)
        {
            yield return(new Substitution(position, Terms.Constant(0)));

            yield return(new Substitution(value, Terms.Constant(Enumerable.Repeat(0.0, value.Dimension))));

            foreach (int segmentIndex in Enumerable.Range(0, segments.Count()))
            {
                yield return(new Substitution(segmentWeights.ElementAt(segmentIndex), Terms.Constant(0)));
            }
        }
Exemple #11
0
        public IEnumerable <Substitution> GetSubstitutions(IEnumerable <Segment> segments, double specificationPosition, ValueTerm substitutionPosition, ValueTerm substitutionValue)
        {
            yield return(new Substitution(position, substitutionPosition));

            yield return(new Substitution(value, substitutionValue));

            foreach (int segmentIndex in Enumerable.Range(0, segments.Count()))
            {
                Segment segment       = segments.ElementAt(segmentIndex);
                double  segmentWeight = segment.Contains(specificationPosition) ? 1 : 0;

                yield return(new Substitution(segmentWeights.ElementAt(segmentIndex), Terms.Constant(segmentWeight)));
            }
        }
Exemple #12
0
        // we need to guarantee that if several threads call this concurrently, only
        // one executes it, and after it returns, the cache is updated and is either
        // complete or not.
        private void PerhapsFillCache()
        {
            lock (this)
            {
                if (cacheMisses < cacheMissesUntilFill)
                {
                    return;
                }

                if (!shouldFillCache)
                {
                    // we already filled the cache once, there's no need to re-fill it
                    return;
                }
                shouldFillCache = false;

                InitReaderManager();

                bool            aborted = false;
                DirectoryReader reader  = readerManager.Acquire();
                try
                {
                    TermsEnum termsEnum = null;
                    DocsEnum  docsEnum  = null;
                    foreach (AtomicReaderContext ctx in reader.Leaves)
                    {
                        Terms terms = ctx.AtomicReader.GetTerms(Consts.FULL);
                        if (terms != null) // cannot really happen, but be on the safe side
                        {
                            termsEnum = terms.GetIterator(termsEnum);
                            while (termsEnum.Next() != null)
                            {
                                if (!cache.IsFull)
                                {
                                    BytesRef t = termsEnum.Term;
                                    // Since we guarantee uniqueness of categories, each term has exactly
                                    // one document. Also, since we do not allow removing categories (and
                                    // hence documents), there are no deletions in the index. Therefore, it
                                    // is sufficient to call next(), and then doc(), exactly once with no
                                    // 'validation' checks.
                                    FacetLabel cp = new FacetLabel(FacetsConfig.StringToPath(t.Utf8ToString()));
                                    docsEnum = termsEnum.Docs(null, docsEnum, DocsFlags.NONE);
                                    bool res = cache.Put(cp, docsEnum.NextDoc() + ctx.DocBase);
                                    Debug.Assert(!res, "entries should not have been evicted from the cache");
                                }
                                else
                                {
                                    // the cache is full and the next put() will evict entries from it, therefore abort the iteration.
                                    aborted = true;
                                    break;
                                }
                            }
                        }
                        if (aborted)
                        {
                            break;
                        }
                    }
                }
                finally
                {
                    readerManager.Release(reader);
                }

                cacheIsComplete = !aborted;
                if (cacheIsComplete)
                {
                    lock (this)
                    {
                        // everything is in the cache, so no need to keep readerManager open.
                        // this block is executed in a sync block so that it works well with
                        // initReaderManager called in parallel.
                        readerManager.Dispose();
                        readerManager            = null;
                        initializedReaderManager = false;
                    }
                }
            }
        }
Exemple #13
0
        public static SpecificationTemplate CreateCurvatureSpecificationTemplate(IEnumerable <Segment> segments, ValueTerm speed, int index)
        {
            ValueTerm position  = Terms.Variable(string.Format("c_{0}_position", index));
            ValueTerm curvature = Terms.Variable(string.Format("c_{0}_curvature", index), 1);
            IEnumerable <ValueTerm> segmentWeights =
                (
                    from segmentIndex in Enumerable.Range(0, segments.Count())
                    select Terms.Variable(string.Format("c_{0}_segment_weight_{1}", index, segmentIndex))
                )
                .ToArray();
            Constraint <ValueTerm> constraint = Constraints.CreateZero
                                                (
                Terms.Sum
                (
                    Enumerable.Zip
                    (
                        segments,
                        segmentWeights,
                        (segment, segmentWeight) => Terms.Scaling
                        (
                            segmentWeight,
                            Terms.Difference
                            (
                                Terms.Scaling
                                (
                                    Terms.Exponentiation(speed, Terms.Constant(-3)),
                                    Terms.DotProduct(segment.GlobalCurve.Acceleration.Apply(position), Terms.Normal(segment.GlobalCurve.Velocity.Apply(position)))
                                ),
                                curvature
                            )
                        )
                    )
                )
                                                );

            return(new SpecificationTemplate(position, curvature, segmentWeights, constraint));
        }
Exemple #14
0
        /// <summary>
        /// Look up the given category in the cache and/or the on-disk storage,
        /// returning the category's ordinal, or a negative number in case the
        /// category does not yet exist in the taxonomy.
        /// </summary>
        protected virtual int FindCategory(FacetLabel categoryPath)
        {
            lock (this)
            {
                // If we can find the category in the cache, or we know the cache is
                // complete, we can return the response directly from it
                int res = cache.Get(categoryPath);
                if (res >= 0 || cacheIsComplete)
                {
                    return(res);
                }

                cacheMisses.IncrementAndGet();
                // After a few cache misses, it makes sense to read all the categories
                // from disk and into the cache. The reason not to do this on the first
                // cache miss (or even when opening the writer) is that it will
                // significantly slow down the case when a taxonomy is opened just to
                // add one category. The idea only spending a long time on reading
                // after enough time was spent on cache misses is known as an "online
                // algorithm".
                PerhapsFillCache();
                res = cache.Get(categoryPath);
                if (res >= 0 || cacheIsComplete)
                {
                    // if after filling the cache from the info on disk, the category is in it
                    // or the cache is complete, return whatever cache.get returned.
                    return(res);
                }

                // if we get here, it means the category is not in the cache, and it is not
                // complete, and therefore we must look for the category on disk.

                // We need to get an answer from the on-disk index.
                InitReaderManager();

                int             doc    = -1;
                DirectoryReader reader = readerManager.Acquire();
                try
                {
                    BytesRef  catTerm   = new BytesRef(FacetsConfig.PathToString(categoryPath.Components, categoryPath.Length));
                    TermsEnum termsEnum = null; // reuse
                    DocsEnum  docs      = null; // reuse
                    foreach (AtomicReaderContext ctx in reader.Leaves)
                    {
                        Terms terms = ctx.AtomicReader.GetTerms(Consts.FULL);
                        if (terms != null)
                        {
                            termsEnum = terms.GetIterator(termsEnum);
                            if (termsEnum.SeekExact(catTerm))
                            {
                                // liveDocs=null because the taxonomy has no deletes
                                docs = termsEnum.Docs(null, docs, 0); // freqs not required
                                // if the term was found, we know it has exactly one document.
                                doc = docs.NextDoc() + ctx.DocBase;
                                break;
                            }
                        }
                    }
                }
                finally
                {
                    readerManager.Release(reader);
                }
                if (doc > 0)
                {
                    AddToCache(categoryPath, doc);
                }
                return(doc);
            }
        }
Exemple #15
0
 private DbUpdateStatement GetQuery_UpdateQuery(Terms _obj)
 {
     return(DbMgr.CreateUpdateClause("Terms", GetFields(_obj), "TermsID", _obj.TermsID));
 }
Exemple #16
0
        private DbInsertStatement GetQuery_InsertQuery(Terms _obj)
        {
            Dictionary <string, DbFieldEntry> fields = GetFields(_obj);

            return(DbMgr.CreateInsertClause("Terms", fields));
        }
    private AirMerchandise SearchAir(Terms.Sales.Business.AirSearchCondition searchCondition)
    {
        searchCondition.UserInfo = UserInfo;
        //bool isOpenCommNetFareTicket = false;
        bool isOpenAllFareTypeAir = false;
        bool isOnlyShowPubFareTicket = true;
        bool hasMajorAirlinesForAvailable = false;
        bool hasMajorAirlinesForSelect = false;
        bool isAvailableOnly = false;

        if (ConfigurationManager.AppSettings.Get("IsOpenAllFareTypeAir") != null)
            isOpenAllFareTypeAir = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("IsOpenAllFareTypeAir").ToString());

        if (ConfigurationManager.AppSettings.Get("IsOnlyShowPubFareTicket") != null)
            isOnlyShowPubFareTicket = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("IsOnlyShowPubFareTicket").ToString());

        if (ConfigurationManager.AppSettings.Get("HasMajorAirlinesForAvailable") != null)
            hasMajorAirlinesForAvailable = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("HasMajorAirlinesForAvailable").ToString());

        if (ConfigurationManager.AppSettings.Get("HasMajorAirlinesForSelect") != null)
            hasMajorAirlinesForSelect = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("HasMajorAirlinesForSelect").ToString());

        if (ConfigurationManager.AppSettings.Get("IsAvailableOnly") != null)
            isAvailableOnly = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("IsAvailableOnly").ToString());

        //by cjc, ��ʱ��ʾ���еĻ�Ʊ

        searchCondition.IsLogin = Utility.IsLogin;

        //��Cache�в��ҽ��
        AirMerchandise airMerchandise = (AirMerchandise)MVMerchandisePool.Find(searchCondition);

        if (airMerchandise == null)
        {
            DateTime SearchingBeginningTime = DateTime.Now;

            AirProductSearcher searcher = new AirProductSearcher();

            DateTime depDate = searchCondition.GetAddTripCondition()[0].DepartureDate;
            DateTime rtnDate = new DateTime();
            string fromAirportCode = searchCondition.GetAddTripCondition()[0].Departure.Code;
            string toAirportCode = searchCondition.GetAddTripCondition()[0].Destination.Code;
            string rtnFromAirportCode = string.Empty;
            string rtnToAirportCode = string.Empty;
            int adultNumber = searchCondition.GetPassengerNumber(TERMS.Common.PassengerType.Adult);
            int childNumber = searchCondition.GetPassengerNumber(TERMS.Common.PassengerType.Child);
            IList<AirProduct> airs = new List<AirProduct>();
            DateTime dtBeginTime = new DateTime();

            //log begin 20090312 Leon
            try
            {
                dtBeginTime = System.DateTime.Now;
                log.Info(m_LogRandomID + " >Search  From Terms Product Begin Start time : " + dtBeginTime);

                if (searchCondition.FlightType.ToLower().Equals("oneway"))
                    log.Info(m_LogRandomID + " >===================== OneWay =====================");
                else if (searchCondition.FlightType.ToLower().Equals("roundtrip"))
                    log.Info(m_LogRandomID + " >===================== Roundtrip =====================");
                else
                    log.Info(m_LogRandomID + " >===================== OpenJW =====================");
            }
            catch
            { }

            //ת����ѯ����
            TERMS.Common.Search.AirSearchCondition termsSearchCondition;

            if (searchCondition.FlightType.ToLower().Equals("oneway"))
            {
                termsSearchCondition = new TERMS.Common.Search.AirSearchCondition(fromAirportCode, true, toAirportCode, true, depDate, true, adultNumber, childNumber, 0);
            }
            else if (searchCondition.FlightType.ToLower().Equals("roundtrip"))
            {
                rtnDate = searchCondition.GetAddTripCondition()[1].DepartureDate;
                termsSearchCondition = new TERMS.Common.Search.AirSearchCondition(fromAirportCode, true, toAirportCode, true, depDate, true, rtnDate, true, adultNumber, childNumber, 0);
            }
            else  //Open Jaw
            {
                rtnDate = searchCondition.GetAddTripCondition()[1].DepartureDate;
                rtnFromAirportCode = searchCondition.GetAddTripCondition()[1].Departure.Code;
                rtnToAirportCode = searchCondition.GetAddTripCondition()[1].Destination.Code;
                termsSearchCondition = new TERMS.Common.Search.AirSearchCondition(fromAirportCode, true, toAirportCode, true, depDate, true, rtnFromAirportCode, true, rtnToAirportCode, true, rtnDate, true, adultNumber, childNumber, 0);
            }

            //ָ�����չ�˾
            if (searchCondition.Airlines != null && searchCondition.Airlines.Length > 0)
                termsSearchCondition.AddAirlines(searchCondition.Airlines);

            //�ƶ��յ�
            for (int i = 0; i < termsSearchCondition.Trips.Count; i++)
                termsSearchCondition.Trips[i].Cabin = searchCondition.AirTripCondition[i].Cabin;

            //��������ָ����ѯ��ʾ����
            if (!isOpenAllFareTypeAir)
            {
                //if isOpenAllFareTypeAir is false ,  un-login condition come into effect.
                if (!Utility.IsLogin)
                {
                    termsSearchCondition.HasMajorAirlinesForAvailable = hasMajorAirlinesForAvailable;
                    termsSearchCondition.HasMajorAirlinesForSelect = hasMajorAirlinesForSelect;
                    termsSearchCondition.IsAvailableOnly = isAvailableOnly;

                    //if un-login and only show PUB fare
                    if (isOnlyShowPubFareTicket)
                    {
                        termsSearchCondition.HasMajorAirlinesForAvailable = true;
                        termsSearchCondition.HasMajorAirlinesForSelect = true;
                        termsSearchCondition.FareType = TERMS.Common.AirFareType.Published;
                        termsSearchCondition.IsAvailableOnly = true;
                    }
                    else
                    {
                        termsSearchCondition.FareType = TERMS.Common.AirFareType.All;
                    }
                }
                else
                {
                    //��¼����ʾ���л�Ʊ����
                    termsSearchCondition.HasMajorAirlinesForAvailable = true;
                    termsSearchCondition.HasMajorAirlinesForSelect = true;
                    termsSearchCondition.FareType = TERMS.Common.AirFareType.All;
                    termsSearchCondition.IsAvailableOnly = false;
                }
            }
            else
            {
                //��ʾ���л�Ʊ����
                termsSearchCondition.HasMajorAirlinesForAvailable = true;
                termsSearchCondition.HasMajorAirlinesForSelect = true;
                termsSearchCondition.FareType = TERMS.Common.AirFareType.All;
                termsSearchCondition.IsAvailableOnly = false;
            }

            //ִ�в�ѯ
            airs = searcher.Search(termsSearchCondition, UserInfo.Entity);

            log.Info(m_LogRandomID + " >Search From Terms Product End time : " + ((TimeSpan)System.DateTime.Now.Subtract(dtBeginTime)).ToString());
            dtBeginTime = System.DateTime.Now;

            if (airs.Count == 0 || airs[0].Items == null) return null;
            TERMS.Business.Centers.ProductCenter.Profiles.AirProfile oldProfile = (TERMS.Business.Centers.ProductCenter.Profiles.AirProfile)airs[0].Profile;
            oldProfile.SetParam("ADULT_NUMBER", adultNumber);
            oldProfile.SetParam("CHILD_NUMBER", childNumber);
            oldProfile.SetParam("IS_LOGIN", Utility.IsLogin);

            //log begin 20090312 Leon
            try
            {
                log.Info(m_LogRandomID + " >Become Merchandise Begin Begin Start time : " + dtBeginTime);

                if (airMerchandise != null && airMerchandise.Items != null)
                    log.Info(m_LogRandomID + " > " + airs[0].ItemGetter.Log.Text);
                else
                    log.Info(m_LogRandomID + " >No Result");

                log.Info(m_LogRandomID + " >Become Merchandise Begin End time : " + ((TimeSpan)System.DateTime.Now.Subtract(dtBeginTime)).ToString());
            }
            catch
            { }

            airMerchandise = new AirMerchandise(oldProfile, airs[0]);
            MVMerchandisePool.Cache(searchCondition.Clone(), airMerchandise); //Cache

            //��¼Searchʱ��
            DateTime SearchingEndingTime = DateTime.Now;
            SearchingLogger searchingLogger = new SearchingLogger();
            searchingLogger.Log(SearchingBeginningTime, SearchingEndingTime, searchCondition);
        }

        return airMerchandise;
    }
 public override void Run()
 {
     if (Verbose)
     {
         Console.WriteLine(Thread.CurrentThread.Name + ": launch search thread");
     }
     while (J2N.Time.NanoTime() / J2N.Time.MillisecondsPerNanosecond < stopTimeMS) // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results
     {
         try
         {
             IndexSearcher s = outerInstance.GetCurrentSearcher();
             try
             {
                 // Verify 1) IW is correctly setting
                 // diagnostics, and 2) segment warming for
                 // merged segments is actually happening:
                 foreach (AtomicReaderContext sub in s.IndexReader.Leaves)
                 {
                     SegmentReader segReader = (SegmentReader)sub.Reader;
                     IDictionary <string, string> diagnostics = segReader.SegmentInfo.Info.Diagnostics;
                     assertNotNull(diagnostics);
                     diagnostics.TryGetValue("source", out string source);
                     assertNotNull(source);
                     if (source.Equals("merge", StringComparison.Ordinal))
                     {
                         assertTrue("sub reader " + sub + " wasn't warmed: warmed=" + outerInstance.warmed + " diagnostics=" + diagnostics + " si=" + segReader.SegmentInfo,
                                    // LUCENENET: ConditionalWeakTable doesn't have ContainsKey, so we normalize to TryGetValue
                                    !outerInstance.m_assertMergedSegmentsWarmed || outerInstance.warmed.TryGetValue(segReader.core, out BooleanRef _));
                     }
                 }
                 if (s.IndexReader.NumDocs > 0)
                 {
                     outerInstance.SmokeTestSearcher(s);
                     Fields fields = MultiFields.GetFields(s.IndexReader);
                     if (fields == null)
                     {
                         continue;
                     }
                     Terms terms = fields.GetTerms("body");
                     if (terms == null)
                     {
                         continue;
                     }
                     TermsEnum termsEnum     = terms.GetEnumerator();
                     int       seenTermCount = 0;
                     int       shift;
                     int       trigger;
                     if (totTermCount < 30)
                     {
                         shift   = 0;
                         trigger = 1;
                     }
                     else
                     {
                         trigger = totTermCount / 30;
                         shift   = Random.Next(trigger);
                     }
                     while (J2N.Time.NanoTime() / J2N.Time.MillisecondsPerNanosecond < stopTimeMS) // LUCENENET: Use NanoTime() rather than CurrentTimeMilliseconds() for more accurate/reliable results
                     {
                         if (!termsEnum.MoveNext())
                         {
                             totTermCount.Value = seenTermCount;
                             break;
                         }
                         seenTermCount++;
                         // search 30 terms
                         if ((seenTermCount + shift) % trigger == 0)
                         {
                             //if (VERBOSE) {
                             //System.out.println(Thread.currentThread().getName() + " now search body:" + term.Utf8ToString());
                             //}
                             totHits.AddAndGet(outerInstance.RunQuery(s, new TermQuery(new Term("body", termsEnum.Term))));
                         }
                     }
                     //if (VERBOSE) {
                     //System.out.println(Thread.currentThread().getName() + ": search done");
                     //}
                 }
             }
             finally
             {
                 outerInstance.ReleaseSearcher(s);
             }
         }
         catch (Exception t) when(t.IsThrowable())
         {
             Console.WriteLine(Thread.CurrentThread.Name + ": hit exc");
             outerInstance.m_failed.Value = (true);
             Console.WriteLine(t.ToString());
             throw RuntimeException.Create(t);
         }
     }
 }
    private PackageMerchandise SearchPackage(Terms.Sales.Business.PackageSearchCondition searchCondition)
    {
        searchCondition.UserInfo = UserInfo;
        searchCondition.AirSearchCondition.UserInfo = UserInfo;
        searchCondition.HotelSearchCondition.UserInfo = UserInfo;

        if (searchCondition.HotelSearchCondition2 != null)
            searchCondition.HotelSearchCondition2.UserInfo = UserInfo;

        //��Cache�в��ҽ�
        PackageMerchandise packageMerchandise = (PackageMerchandise)MVMerchandisePool.Find(searchCondition);

        if (packageMerchandise == null)
        {
            DateTime SearchingBeginningTime = DateTime.Now;

            Utility.Transaction.Difference.To = "OnSearch1 End";
            Utility.Transaction.Difference.EndTime = DateTime.Now;
            Utility.Transaction.Difference.From = "Search Package By Find";
            Utility.Transaction.Difference.StarTime = DateTime.Now;

            PackageProductSearcher searcher = new PackageProductSearcher();
            TERMS.Common.Search.PackageSearchCondition pkgCondition = new TERMS.Common.Search.PackageSearchCondition();
            DateTime depDate = searchCondition.AirSearchCondition.GetAddTripCondition()[0].DepartureDate;
            DateTime rtnDate = new DateTime();
            string fromAirportCode = searchCondition.AirSearchCondition.GetAddTripCondition()[0].Departure.Code;
            string toAirportCode = searchCondition.AirSearchCondition.GetAddTripCondition()[0].Destination.Code;
            string rtnFromAirportCode = string.Empty;
            string rtnToAirportCode = string.Empty;
            int adultNumber = searchCondition.AirSearchCondition.GetPassengerNumber(TERMS.Common.PassengerType.Adult);

            int childNumber = searchCondition.AirSearchCondition.GetPassengerNumber(TERMS.Common.PassengerType.Child);
            IList<PackageProduct> pkgs = new List<PackageProduct>();
            if (searchCondition.AirSearchCondition.FlightType.ToLower().Equals("oneway"))
            {
                //û��
            }
            else if (searchCondition.AirSearchCondition.FlightType.ToLower().Equals("roundtrip"))
            {
                rtnDate = searchCondition.AirSearchCondition.GetAddTripCondition()[1].DepartureDate;
                pkgCondition.AirCondition = new TERMS.Common.Search.AirSearchCondition(fromAirportCode, true, toAirportCode, true, depDate, true, rtnDate, true, adultNumber, childNumber, 0);
            }
            else
            {
                rtnDate = searchCondition.AirSearchCondition.GetAddTripCondition()[1].DepartureDate;
                rtnFromAirportCode = searchCondition.AirSearchCondition.GetAddTripCondition()[1].Departure.Code;
                rtnToAirportCode = searchCondition.AirSearchCondition.GetAddTripCondition()[1].Destination.Code;
                pkgCondition.AirCondition = new TERMS.Common.Search.AirSearchCondition(fromAirportCode, true, toAirportCode, true, depDate, true, rtnFromAirportCode, true, rtnToAirportCode, true, rtnDate, true, adultNumber, childNumber, 0);
            }

            if (ConfigurationManager.AppSettings.Get("IsOpenCommNetFareTicket") != null)
                pkgCondition.AirCondition.IsAvailableOnly = Convert.ToBoolean(ConfigurationManager.AppSettings.Get("IsOpenCommNetFareTicket").ToString());

            //����Airlines
            if (searchCondition.AirSearchCondition.Airlines != null && searchCondition.AirSearchCondition.Airlines.Length > 0)
                pkgCondition.AirCondition.AddAirlines(searchCondition.AirSearchCondition.Airlines);

            //����Cabin
            for (int i = 0; i < pkgCondition.AirCondition.Trips.Count; i++)
                pkgCondition.AirCondition.Trips[i].Cabin = searchCondition.AirSearchCondition.AirTripCondition[i].Cabin;

            //ת��Hotel Search Condition
            pkgCondition.HotelCondition = ConvertHotelSearchCondition(searchCondition.HotelSearchCondition);

            pkgs = searcher.Search(pkgCondition);

            //Ϊ�̷߳�����Ӳ��� package
            PackageProduct pkg = package = pkgs[0];
            Utility.Transaction.Difference.To = "Intel Search Over";
            Utility.Transaction.Difference.EndTime = DateTime.Now;
            Utility.Transaction.Difference.From = "Return AIRItem Start";
            Utility.Transaction.Difference.StarTime = DateTime.Now;

            //�����߳� ͬʱ��ѯ Air �� Hotel
            PackageThreadStar();

            //IList<TERMS.Core.Product.Component> aa = pkg.AirGroup.Items;

            if (packageair == null || packageair.Count == 0)
            {
                m_Error = "Searching is not available in Web Searching now. Please choose another travel date or destination.(pa1)";
                return null;
            }

            Utility.Transaction.Difference.To = "Return AIRItem End";
            Utility.Transaction.Difference.EndTime = DateTime.Now;
            Utility.Transaction.Difference.From = "Return HotelItem Start";
            Utility.Transaction.Difference.StarTime = DateTime.Now;

            //IList<TERMS.Core.Product.Component> BB = pkg.HotelGroup.Items;

            if (packagehotel == null || packagehotel.Count == 0)
            {
                m_Error = "Searching is not available in Web Searching now. Please choose another travel date or destination.(ph1)";
                return null;
            }

            Utility.Transaction.Difference.To = "Return HotelItem End";
            Utility.Transaction.Difference.EndTime = DateTime.Now;
            Utility.Transaction.Difference.From = "Convert Start";
            Utility.Transaction.Difference.StarTime = DateTime.Now;

            TERMS.Business.Centers.ProductCenter.Profiles.PackageProfile packageProfile = (TERMS.Business.Centers.ProductCenter.Profiles.PackageProfile)pkg.Profile;

            packageProfile.SetParam("ADULT_NUMBER", adultNumber);
            packageProfile.SetParam("CHILD_NUMBER", childNumber);
            packageProfile.SetParam("CheckIn", searchCondition.HotelSearchCondition.CheckIn);
            packageProfile.SetParam("CheckOut", searchCondition.HotelSearchCondition.CheckOut);
            packageProfile.SetParam("Location", searchCondition.HotelSearchCondition.Location);
            try
            {
                packageMerchandise = new PackageMerchandise(packageProfile, pkg);

                if (packageMerchandise.Items[1] == null || ((HotelMerchandise)packageMerchandise.Items[1]).Items == null || ((HotelMerchandise)packageMerchandise.Items[1]).Items.Count == 0)
                {
                    m_Error = "Searching is not available in Web Searching now. Please choose another travel date or destination.";
                    return null;
                }

                for (int i = 1; i < packageMerchandise.Items.Count; i++)
                {
                    HotelMerchandise hotelMerchandise = (HotelMerchandise)packageMerchandise.Items[i];
                    hotelMerchandise.Profile.CheckInDate = searchCondition.HotelSearchCondition.CheckIn;
                    hotelMerchandise.Profile.CheckOutDate = searchCondition.HotelSearchCondition.CheckOut;//
                    hotelMerchandise = ConvertHotelToMVHotel(searchCondition.HotelSearchCondition, hotelMerchandise);
                }
                //�ж�
                if (packageMerchandise.Items[1] == null || ((HotelMerchandise)packageMerchandise.Items[1]).Items == null || ((HotelMerchandise)packageMerchandise.Items[1]).Items.Count == 0)
                {
                    m_Error = "Searching is not available in Web Searching now. Please choose another travel date or destination.";
                    return null;
                }

                MVMerchandisePool.Cache(searchCondition.Clone(), packageMerchandise); //Cache

                if (searchCondition.OptionalHotelSearchConditions.Count > 0)
                {
                    for (int j = 0; j < searchCondition.OptionalHotelSearchConditions.Count; j++)
                    {
                        packageMerchandise.Items.Add(SearchHotel(searchCondition.OptionalHotelSearchConditions[j]));
                    }
                    packageMerchandise.ReSetPMItems();    // �趨��Ĭ����������
                }
                packageMerchandise.Reset();//��Ϊ��ʼ��packageMerchandise �е� CurrentItem
            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message);
            }

            //��¼Searchʱ��
            DateTime SearchingEndingTime = DateTime.Now;
            SearchingLogger searchingLogger = new SearchingLogger();
            searchingLogger.Log(SearchingBeginningTime, SearchingEndingTime, searchCondition);
        }
        else
        {
            if (searchCondition.OptionalHotelSearchConditions.Count == packageMerchandise.CurrentItems.Count - 3)
            {
                packageMerchandise.Items.RemoveAt(packageMerchandise.Items.Count - 1);
                packageMerchandise.CurrentItems.RemoveAt(packageMerchandise.CurrentItems.Count - 1);

                packageMerchandise.CurrentHotelListNumber = 0;
                packageMerchandise.Reset();
                packageMerchandise.ReSetPMItems();
            }

            if (searchCondition.IsReset) //����packageMerchandise �е� CurrentItem
            {
                for (int i = 2; i < packageMerchandise.Items.Count; i++)
                {
                    packageMerchandise.Items.Remove(packageMerchandise.Items[i]);
                }
                packageMerchandise.CurrentHotelListNumber = 0;
                packageMerchandise.Reset();
                packageMerchandise.ReSetPMItems();
            }
        }

        List<int> searchFaildHotelIndexs = new List<int>();

        for (int i = 0; i < searchCondition.OptionalHotelSearchConditions.Count; i++)
        {
            HotelMerchandise hotelMerchandise = (HotelMerchandise)MVMerchandisePool.Find(searchCondition.OptionalHotelSearchConditions[i]);
            if (hotelMerchandise == null)
            {
                hotelMerchandise = SearchHotel(searchCondition.OptionalHotelSearchConditions[i]);

                if (hotelMerchandise == null) //Search Hotelʧ��
                    searchFaildHotelIndexs.Add(i);

                packageMerchandise.Items.Add(hotelMerchandise);
                packageMerchandise.Reset(i + 2);
                packageMerchandise.ReSetPMItems();
            }
            else
            {
                if ((packageMerchandise.Items.Count - 1) >= (i + 2))//�ж��±�(i+2),��Items �����Ƿ����
                    packageMerchandise.Items[i + 2] = hotelMerchandise;
                else
                {
                    packageMerchandise.Items.Add(hotelMerchandise);
                    packageMerchandise.Reset(i + 2);
                    packageMerchandise.ReSetPMItems();
                }
                if (searchCondition.IsReset) //����packageMerchandise �е� CurrentItem[i+2]
                    packageMerchandise.Reset(i + 2);
            }

        }

        if (searchFaildHotelIndexs.Count > 0) //Search Hotelʧ��
        {
            for (int i = 0; i < searchFaildHotelIndexs.Count; i++)
            {
                //���Searchʧ�ܵ�Hotel Search Condition
                searchCondition.OptionalHotelSearchConditions.RemoveAt(searchFaildHotelIndexs[i] - i);
                packageMerchandise.Items.RemoveAt(searchFaildHotelIndexs[i] + 2 - i);
                packageMerchandise.CurrentItems.RemoveAt(searchFaildHotelIndexs[i] + 2 - i);
            }

            packageMerchandise.ReSetPMItems();

            return null;
        }

        searchCondition.IsReset = false;

        Utility.Transaction.Difference.To = "Convert End";
        Utility.Transaction.Difference.EndTime = DateTime.Now;

        Utility.Transaction.Difference.From = "Search End";
        Utility.Transaction.Difference.StarTime = DateTime.Now;

        packageMerchandise.UserInfo = UserInfo.User.UserName;

        return packageMerchandise;
    }
 public SettingsKeyAnalyzers(Terms reportTerms) : base(reportTerms)
 {
 }
    public InsuranceMaterial SearchInsuranceByB2B(Terms.Sales.Business.InsuranceSearchCondition insuranceCondition)
    {
        TERMS.Common.Search.InsuranceSearchCondition Condition = new TERMS.Common.Search.InsuranceSearchCondition();

        Condition.InsuranceType = insuranceCondition.InsuranceType;

        Condition.Trip = new TERMS.Common.Trip();

        Condition.Trip.DepartureDate = insuranceCondition.DepartureDate;
        Condition.Trip.ReturnDate = insuranceCondition.ReturnDate;
        Condition.Trip.InitialTripDepositDate = DateTime.Now;

        List<TERMS.Common.Traveler> list = new List<TERMS.Common.Traveler>();

        for (int i = 0; i < insuranceCondition.TravelerCount; i++)
        {
            TERMS.Common.Traveler t = new TERMS.Common.Traveler();

            t.BirthDate = DateTime.Now.AddYears(-10);

            t.TripCost = Convert.ToDouble(insuranceCondition.TotalTripCost / insuranceCondition.TravelerCount);

            list.Add(t);
        }

        Condition.Travelers = list.ToArray();

        InsuranceProductSearcher INs = new InsuranceProductSearcher();

        try
        {
            IList<InsuranceProduct> products = INs.Search(Condition);

            if (products != null && products.Count > 0)
            {
                return ((TERMS.Business.Centers.ProductCenter.Components.InsuranceMaterial)((TERMS.Core.Product.ComponentGroup)products[0].Items[0]).Items[0]);
            }
            else
            {
                InsuranceMaterial insurance = new InsuranceMaterial(new TERMS.Core.Profiles.Profile("insurance"));

                insurance.PolicyQuote = new TERMS.Common.PolicyQuote();

                insurance.PolicyQuote.Status = new TERMS.Common.Status();

                insurance.PolicyQuote.Status.IsSuccess = false;

                insurance.PolicyQuote.Status.ErrorDescription = "None Insurance products";

                return insurance;
            }
        }
        catch (Exception ex)
        {
            InsuranceMaterial insurance = new InsuranceMaterial(new TERMS.Core.Profiles.Profile("insurance"));

            insurance.PolicyQuote = new TERMS.Common.PolicyQuote();

            insurance.PolicyQuote.Status = new TERMS.Common.Status();

            insurance.PolicyQuote.Status.IsSuccess = false;

            insurance.PolicyQuote.Status.ErrorDescription = ex.Message;

            return insurance;
        }
    }
Exemple #22
0
 public TermsEnum TermsEnum(Terms terms)
 {
     return terms.Iterator(null);
 }
    private TERMS.Common.Search.HotelSearchCondition ConvertHotelSearchCondition(Terms.Sales.Business.HotelSearchCondition searchCondition)
    {
        hotelSearchHotelByZyl.Debug("UserInfo Start :" + DateTime.Now.ToLongTimeString());
        searchCondition.UserInfo = UserInfo;
        hotelSearchHotelByZyl.Debug("UserInfo End :" + DateTime.Now.ToLongTimeString());
        //ת��Search����
        List<TERMS.Common.Search.RoomCondition> termsRoomSCs = new List<TERMS.Common.Search.RoomCondition>();

        for (int i = 0; i < searchCondition.RoomSearchConditions.Count; i++)
        {
            Terms.Sales.Business.RoomSearchCondition mvRoomSC = searchCondition.RoomSearchConditions[i];
            TERMS.Common.Search.RoomCondition termsRoomSC;

            if (mvRoomSC.ChildNumber > 0)
            {
                List<DateTime> childrenBirthday = new List<DateTime>();

                for (int childIndex = 0; childIndex < mvRoomSC.ChildNumber; childIndex++)
                    childrenBirthday.Add(DateTime.Now.AddYears(-3));    //С��Ĭ��Ϊ2��

                termsRoomSC = new TERMS.Common.Search.RoomCondition(mvRoomSC.AdultNumber, mvRoomSC.ChildNumber, childrenBirthday.ToArray());
            }
            else
            {
                termsRoomSC = new TERMS.Common.Search.RoomCondition(mvRoomSC.AdultNumber, mvRoomSC.ChildNumber);
            }

            termsRoomSCs.Add(termsRoomSC);
        }

        TERMS.Common.Search.HotelSearchCondition termsHotelSC = new TERMS.Common.Search.HotelSearchCondition(
            searchCondition.Location, searchCondition.CheckIn, searchCondition.CheckOut, string.Empty, searchCondition.RoomSearchConditions.Count,
            termsRoomSCs.ToArray());

        City city = CommCityDao.FindCityByCode(searchCondition.Location);

        if (city != null)
        {
            termsHotelSC.Destination.CityCode_Travco = city.CityCode_Travco;
            termsHotelSC.Destination.Name = city.Name;
            termsHotelSC.Destination.ProvinceName = city.ProvinceName;
            termsHotelSC.Destination.Country = new TERMS.Common.Country();
            termsHotelSC.Destination.Country.Code = city.Country.Code;
            termsHotelSC.Destination.Country.Code3 = city.Country.Code3;
            termsHotelSC.Destination.Country.CallingCode = city.Country.CallingCode;
            termsHotelSC.Destination.Country.FullName = city.Country.FullName;
            termsHotelSC.Destination.Country.Name = city.Country.Name;
        }

        return termsHotelSC;
    }
Exemple #24
0
 public override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
 {
     if (MaxEdits_Renamed == 0 || PrefixLength_Renamed >= Term_Renamed.Text().Length) // can only match if it's exact
     {
         return new SingleTermsEnum(terms.Iterator(null), Term_Renamed.Bytes());
     }
     return new FuzzyTermsEnum(terms, atts, Term, MaxEdits_Renamed, PrefixLength_Renamed, Transpositions_Renamed);
 }
Exemple #25
0
        public BigBookingCalendar() : base()
        {
            // since this control will be used for displaying
            // events, set these properties as a default
            config = hapConfig.Current;

            this.SelectionMode = CalendarSelectionMode.Day;
            this.maxday        = config.BookingSystem.MaxDays;
            foreach (AdvancedBookingRight right in HAP.BookingSystem.BookingSystem.BookingRights)
            {
                if (right.Username == HttpContext.Current.User.Identity.Name)
                {
                    this.maxday = 7 * right.Weeksahead;
                }
            }

            Terms terms = new Terms();

            if (Terms.getTerm(DateTime.Now).Name == null)
            {
                int y = 0;
                for (int x = terms.Count - 1; x >= 0; x--)
                {
                    if (terms[x].StartDate > DateTime.Now)
                    {
                        y = x;
                    }
                }


                if (DateTime.Now < terms[y].StartDate)
                {
                    this.maxday += (terms[y].StartDate - DateTime.Now).Days;
                }
            }
            else
            {
                Term term = Terms.getTerm(DateTime.Now);
                int  y    = 0;
                for (int x = 0; x < terms.Count; x++)
                {
                    if (terms[x].Equals(term))
                    {
                        y = x + 1;
                    }
                }
                if (y == terms.Count)
                {
                    y = terms.Count - 1;
                }
                if (DateTime.Now.AddDays(this.maxday) < terms[y].StartDate && DateTime.Now.AddDays(this.maxday) > term.EndDate)
                {
                    this.maxday += (terms[y].StartDate - DateTime.Now).Days - 7;
                }
                int dow = 0;
                switch (DateTime.Now.DayOfWeek)
                {
                case DayOfWeek.Monday: this.maxday += 7; dow = 7; break;

                case DayOfWeek.Tuesday: this.maxday += 6; dow = 6; break;

                case DayOfWeek.Wednesday: this.maxday += 5; dow = 5; break;

                case DayOfWeek.Thursday: this.maxday += 4; dow = 4; break;

                case DayOfWeek.Friday: this.maxday += 3; dow = 3; break;

                case DayOfWeek.Saturday: this.maxday += 2; dow = 2; break;

                case DayOfWeek.Sunday: this.maxday += 1; dow = 1; break;
                }

                if (DateTime.Now.AddDays(dow) >= term.HalfTerm.StartDate && DateTime.Now.AddDays(dow) <= term.HalfTerm.EndDate)
                {
                    this.maxday += 7;
                }
                if (DateTime.Now.AddDays(7 + dow) >= term.HalfTerm.StartDate && DateTime.Now.AddDays(7 + dow) <= term.HalfTerm.EndDate)
                {
                    this.maxday += 7;
                }
            }
        }
Exemple #26
0
 internal void Reset(Terms delegateTerms, TermsEnum reuseDelegate)
 {
     _delegateTerms    = delegateTerms;
     _reuseDelegate    = reuseDelegate;
     delegateTermsEnum = null;
 }
Exemple #27
0
 public override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
 {
     return Compiled.GetTermsEnum(terms);
 }
        private void AssertTermsSeeking(Terms leftTerms, Terms rightTerms)
        {
            TermsEnum leftEnum  = null;
            TermsEnum rightEnum = null;

            // just an upper bound
            int    numTests = AtLeast(20);
            Random random   = Random();

            // collect this number of terms from the left side
            HashSet <BytesRef> tests = new HashSet <BytesRef>();
            int numPasses            = 0;

            while (numPasses < 10 && tests.Count < numTests)
            {
                leftEnum = leftTerms.GetIterator(leftEnum);
                BytesRef term = null;
                while ((term = leftEnum.Next()) != null)
                {
                    int code = random.Next(10);
                    if (code == 0)
                    {
                        // the term
                        tests.Add(BytesRef.DeepCopyOf(term));
                    }
                    else if (code == 1)
                    {
                        // truncated subsequence of term
                        term = BytesRef.DeepCopyOf(term);
                        if (term.Length > 0)
                        {
                            // truncate it
                            term.Length = random.Next(term.Length);
                        }
                    }
                    else if (code == 2)
                    {
                        // term, but ensure a non-zero offset
                        var newbytes = new byte[term.Length + 5];
                        Array.Copy(term.Bytes, term.Offset, newbytes, 5, term.Length);
                        tests.Add(new BytesRef(newbytes, 5, term.Length));
                    }
                }
                numPasses++;
            }

            List <BytesRef> shuffledTests = new List <BytesRef>(tests);

            Collections.Shuffle(shuffledTests);

            foreach (BytesRef b in shuffledTests)
            {
                leftEnum  = leftTerms.GetIterator(leftEnum);
                rightEnum = rightTerms.GetIterator(rightEnum);

                Assert.AreEqual(leftEnum.SeekExact(b), rightEnum.SeekExact(b));
                Assert.AreEqual(leftEnum.SeekExact(b), rightEnum.SeekExact(b));

                SeekStatus leftStatus;
                SeekStatus rightStatus;

                leftStatus  = leftEnum.SeekCeil(b);
                rightStatus = rightEnum.SeekCeil(b);
                Assert.AreEqual(leftStatus, rightStatus);
                if (leftStatus != SeekStatus.END)
                {
                    Assert.AreEqual(leftEnum.Term, rightEnum.Term);
                }

                leftStatus  = leftEnum.SeekCeil(b);
                rightStatus = rightEnum.SeekCeil(b);
                Assert.AreEqual(leftStatus, rightStatus);
                if (leftStatus != SeekStatus.END)
                {
                    Assert.AreEqual(leftEnum.Term, rightEnum.Term);
                }
            }
        }
        /// <summary>
        /// Constructor for enumeration of all terms from specified <code>reader</code> which share a prefix of
        /// length <code>prefixLength</code> with <code>term</code> and which have a fuzzy similarity &gt;
        /// <code>minSimilarity</code>.
        /// <p>
        /// After calling the constructor the enumeration is already pointing to the first
        /// valid term if such a term exists.
        /// </summary>
        /// <param name="terms"> Delivers terms. </param>
        /// <param name="atts"> <seealso cref="AttributeSource"/> created by the rewrite method of <seealso cref="MultiTermQuery"/>
        /// thats contains information about competitive boosts during rewrite. It is also used
        /// to cache DFAs between segment transitions. </param>
        /// <param name="term"> Pattern term. </param>
        /// <param name="minSimilarity"> Minimum required similarity for terms from the reader. Pass an integer value
        ///        representing edit distance. Passing a fraction is deprecated. </param>
        /// <param name="prefixLength"> Length of required common prefix. Default value is 0. </param>
        /// <exception cref="IOException"> if there is a low-level IO error </exception>
        public FuzzyTermsEnum(Terms terms, AttributeSource atts, Term term, float minSimilarity, int prefixLength, bool transpositions)
        {
            if (!InstanceFieldsInitialized)
            {
                InitializeInstanceFields();
                InstanceFieldsInitialized = true;
            }
            if (minSimilarity >= 1.0f && minSimilarity != (int)minSimilarity)
            {
                throw new System.ArgumentException("fractional edit distances are not allowed");
            }
            if (minSimilarity < 0.0f)
            {
                throw new System.ArgumentException("minimumSimilarity cannot be less than 0");
            }
            if (prefixLength < 0)
            {
                throw new System.ArgumentException("prefixLength cannot be less than 0");
            }
            this.Terms = terms;
            this.Term_Renamed = term;

            // convert the string into a utf32 int[] representation for fast comparisons
            string utf16 = term.Text();
            //LUCENE TO-DO
            //this.TermText = new int[utf16.codePointCount(0, utf16.Length)];
            this.TermText = new int[utf16.Length];
            for (int cp, i = 0, j = 0; i < utf16.Length; i += Character.CharCount(cp))
            {
                TermText[j++] = cp = Character.CodePointAt(utf16, i);
            }
            this.TermLength = TermText.Length;
            this.DfaAtt = atts.AddAttribute<ILevenshteinAutomataAttribute>();

            //The prefix could be longer than the word.
            //It's kind of silly though.  It means we must match the entire word.
            this.RealPrefixLength = prefixLength > TermLength ? TermLength : prefixLength;
            // if minSimilarity >= 1, we treat it as number of edits
            if (minSimilarity >= 1f)
            {
                this.MinSimilarity_Renamed = 0; // just driven by number of edits
                MaxEdits = (int)minSimilarity;
                Raw = true;
            }
            else
            {
                this.MinSimilarity_Renamed = minSimilarity;
                // calculate the maximum k edits for this similarity
                MaxEdits = InitialMaxDistance(this.MinSimilarity_Renamed, TermLength);
                Raw = false;
            }
            if (transpositions && MaxEdits > LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE)
            {
                throw new System.NotSupportedException("with transpositions enabled, distances > " + LevenshteinAutomata.MAXIMUM_SUPPORTED_DISTANCE + " are not supported ");
            }
            this.Transpositions = transpositions;
            this.Scale_factor = 1.0f / (1.0f - this.MinSimilarity_Renamed);

            this.MaxBoostAtt = atts.AddAttribute<IMaxNonCompetitiveBoostAttribute>();
            Bottom = MaxBoostAtt.MaxNonCompetitiveBoost;
            BottomTerm = MaxBoostAtt.CompetitiveTerm;
            BottomChanged(null, true);
        }
        /// <summary>
        /// Build the suggest index, using up to the specified
        ///  amount of temporary RAM while building.  Note that
        ///  the weights for the suggestions are ignored.
        /// </summary>
        public virtual void Build(InputIterator iterator, double ramBufferSizeMB)
        {
            if (iterator.HasPayloads())
            {
                throw new System.ArgumentException("this suggester doesn't support payloads");
            }
            if (iterator.HasContexts())
            {
                throw new System.ArgumentException("this suggester doesn't support contexts");
            }

            string prefix    = this.GetType().Name;
            var    directory = OfflineSorter.DefaultTempDir();
            // TODO: messy ... java7 has Files.createTempDirectory
            // ... but 4.x is java6:
            File   tempIndexPath = null;
            Random random        = new Random();

            while (true)
            {
                tempIndexPath = new File(directory, prefix + ".index." + random.Next(int.MaxValue));
                if (tempIndexPath.mkdir())
                {
                    break;
                }
            }

            Directory dir = FSDirectory.Open(tempIndexPath);

            IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_CURRENT, indexAnalyzer);

            iwc.OpenMode        = IndexWriterConfig.OpenMode.CREATE;
            iwc.RAMBufferSizeMB = ramBufferSizeMB;
            IndexWriter writer = new IndexWriter(dir, iwc);

            FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);

            // TODO: if only we had IndexOptions.TERMS_ONLY...
            ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS;
            ft.OmitNorms    = true;
            ft.Freeze();

            Document doc   = new Document();
            Field    field = new Field("body", "", ft);

            doc.Add(field);

            totTokens = 0;
            IndexReader reader = null;

            bool success = false;

            count = 0;
            try
            {
                while (true)
                {
                    BytesRef surfaceForm = iterator.Next();
                    if (surfaceForm == null)
                    {
                        break;
                    }
                    field.StringValue = surfaceForm.Utf8ToString();
                    writer.AddDocument(doc);
                    count++;
                }
                reader = DirectoryReader.Open(writer, false);

                Terms terms = MultiFields.GetTerms(reader, "body");
                if (terms == null)
                {
                    throw new System.ArgumentException("need at least one suggestion");
                }

                // Move all ngrams into an FST:
                TermsEnum termsEnum = terms.Iterator(null);

                Outputs <long?> outputs = PositiveIntOutputs.Singleton;
                Builder <long?> builder = new Builder <long?>(FST.INPUT_TYPE.BYTE1, outputs);

                IntsRef scratchInts = new IntsRef();
                while (true)
                {
                    BytesRef term = termsEnum.next();
                    if (term == null)
                    {
                        break;
                    }
                    int ngramCount = countGrams(term);
                    if (ngramCount > grams)
                    {
                        throw new System.ArgumentException("tokens must not contain separator byte; got token=" + term + " but gramCount=" + ngramCount + ", which is greater than expected max ngram size=" + grams);
                    }
                    if (ngramCount == 1)
                    {
                        totTokens += termsEnum.TotalTermFreq();
                    }

                    builder.Add(Util.ToIntsRef(term, scratchInts), encodeWeight(termsEnum.TotalTermFreq()));
                }

                fst = builder.Finish();
                if (fst == null)
                {
                    throw new System.ArgumentException("need at least one suggestion");
                }
                //System.out.println("FST: " + fst.getNodeCount() + " nodes");

                /*
                 * PrintWriter pw = new PrintWriter("/x/tmp/out.dot");
                 * Util.toDot(fst, pw, true, true);
                 * pw.close();
                 */

                success = true;
            }
            finally
            {
                try
                {
                    if (success)
                    {
                        IOUtils.Close(writer, reader);
                    }
                    else
                    {
                        IOUtils.CloseWhileHandlingException(writer, reader);
                    }
                }
                finally
                {
                    foreach (string file in dir.ListAll())
                    {
                        File path = new File(tempIndexPath, file);
                        if (path.Delete() == false)
                        {
                            throw new InvalidOperationException("failed to remove " + path);
                        }
                    }

                    if (tempIndexPath.Delete() == false)
                    {
                        throw new InvalidOperationException("failed to remove " + tempIndexPath);
                    }

                    dir.Dispose();
                }
            }
        }
Exemple #31
0
    public InsuranceMaterial OnSearchInsuranceByB2B(Terms.Sales.Business.InsuranceSearchCondition Condition)
    {
        if (Condition is Terms.Sales.Business.InsuranceSearchCondition)
        {
            MVMerchandiseSearcher searcher = new MVMerchandiseSearcher();

            return searcher.SearchInsuranceByB2B(Condition);
        }
        else
        {
            InsuranceMaterial insurance = new InsuranceMaterial(new TERMS.Core.Profiles.Profile("insurance"));

            insurance.PolicyQuote = new TERMS.Common.PolicyQuote();

            insurance.PolicyQuote.Status = new TERMS.Common.Status();

            insurance.PolicyQuote.Status.IsSuccess = false;

            insurance.PolicyQuote.Status.ErrorDescription = "SearchCondition Type Error";

            return insurance;

        }
    }
Exemple #32
0
        private void initObjectModels()
        {
            // initializing blog objects
            allPosts      = new AllPosts(browser);
            conferences   = new Conferences(browser);
            engineering   = new Engineering(browser);
            enterprise    = new Enterprise(browser);
            featured      = new Featured(browser);
            meetups       = new Meetups(browser);
            newFeatures   = new NewFeatures(browser);
            newHires      = new NewHires(browser);
            blogSearchBar = new pageObjectModels.blog.SearchBar(browser);
            watercooler   = new Watercooler(browser);

            // initializing explore objects
            integrations = new Integrations(browser);
            showcases    = new Showcases(browser);
            trending     = new Trending(browser);

            // initializing footer objects
            about         = new About(browser);
            api           = new API(browser);
            footerBlog    = new pageObjectModels.footer.Blog(browser);
            contactGitHub = new ContactGitHub(browser);
            help          = new Help(browser);
            footerLogo    = new pageObjectModels.footer.Logo(browser);
            privacy       = new Privacy(browser);
            security      = new Security(browser);
            shop          = new Shop(browser);
            status        = new Status(browser);
            terms         = new Terms(browser);
            training      = new Training(browser);

            // initializing header objects
            headerBlog      = new pageObjectModels.header.Blog(browser);
            business        = new Business(browser);
            explore         = new Explore(browser);
            headerLogo      = new pageObjectModels.header.Logo(browser);
            openSource      = new OpenSource(browser);
            personal        = new Personal(browser);
            pricing         = new Pricing(browser);
            headerSearchBar = new pageObjectModels.header.SearchBar(browser);
            signIn          = new SignIn(browser);
            signUp          = new SignUp(browser);
            support         = new Support(browser);

            // initializing main objects
            signUpEmail     = new SignUpEmail(browser);
            signUpForGitHub = new SignUpForGitHubButton(browser);
            signUpPassword  = new SignUpPassword(browser);
            signUpSubmit    = new SignUpSubmit(browser);
            signUpUsername  = new SignUpUsername(browser);

            // initializing pricing objects
            createOrganization   = new CreateOrganization(browser);
            joinGitHubForFree    = new JoinGitHubForFree(browser);
            startEnterpriseTrial = new StartEnterpriseTrial(browser);
            upgradeAccount       = new UpgradeAccount(browser);

            // initializing support objects
            beSocial         = new BeSocial(browser);
            contactSupport   = new ContactSupport(browser);
            createARepo      = new CreateARepo(browser);
            forkARepo        = new ForkARepo(browser);
            setUpGit         = new SetUpGit(browser);
            supportSearchBar = new pageObjectModels.support.SearchBar(browser);
        }
    public TERMS.Business.Centers.ProductCenter.Components.TransferProduct SearchTransfer(Terms.Sales.Business.TransferSearchCondition transferSearchCondition)
    {
        //if (this.IsSearchConditionNull)
        //{
            return null;
        //}
        //else
        //{
        //    if (Utility.Transaction.CurrentSearchConditions is Terms.Sales.Business.AirSearchCondition)
        //    {
        //        return null;
        //    }
        //    else
        //    {
        //        MVMerchandiseSearcher searcher = new MVMerchandiseSearcher();

        //        return searcher.SearchTransfer(transferSearchCondition);
        //    }
        //}
    }
Exemple #34
0
 protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
 {
     return(new TermRangeTermsEnumAnonymousInnerClassHelper(this, terms.GetIterator(null), new BytesRef("2"), new BytesRef("7")));
 }
        // TODO: should this take startTerm too?  this way
        // Terms.intersect could forward to this method if type !=
        // NORMAL:
        public virtual TermsEnum GetTermsEnum(Terms terms)
        {
            switch (Type)
            {
                case Lucene.Net.Util.Automaton.CompiledAutomaton.AUTOMATON_TYPE.NONE:
                    return TermsEnum.EMPTY;

                case Lucene.Net.Util.Automaton.CompiledAutomaton.AUTOMATON_TYPE.ALL:
                    return terms.Iterator(null);

                case Lucene.Net.Util.Automaton.CompiledAutomaton.AUTOMATON_TYPE.SINGLE:
                    return new SingleTermsEnum(terms.Iterator(null), Term);

                case Lucene.Net.Util.Automaton.CompiledAutomaton.AUTOMATON_TYPE.PREFIX:
                    // TODO: this is very likely faster than .intersect,
                    // but we should test and maybe cutover
                    return new PrefixTermsEnum(terms.Iterator(null), Term);

                case Lucene.Net.Util.Automaton.CompiledAutomaton.AUTOMATON_TYPE.NORMAL:
                    return terms.Intersect(this, null);

                default:
                    // unreachable
                    throw new Exception("unhandled case");
            }
        }
 public SortingTerms(Terms input, IndexOptions indexOptions, Sorter.DocMap docMap)
     : base(input)
 {
     this.docMap       = docMap;
     this.indexOptions = indexOptions;
 }
    private HotelMerchandise SearchHotel(Terms.Sales.Business.HotelSearchCondition searchCondition)
    {
        hotelSearchHotelByZyl.Debug("Hotel UserInfo Start :" + DateTime.Now.ToLongTimeString());
        searchCondition.UserInfo = UserInfo;
        hotelSearchHotelByZyl.Debug("Hotel UserInfo End :" + DateTime.Now.ToLongTimeString());

        //��Cache�в��ҽ��
        HotelMerchandise hotelMerchandise = (HotelMerchandise)MVMerchandisePool.Find(searchCondition);

        if (hotelMerchandise == null)
        {
            DateTime SearchingBeginningTime = DateTime.Now;

            //log zyl
            hotelSearchHotelByZyl.Debug("Search Hotel Start :" + DateTime.Now.ToLongTimeString());

            TERMS.Common.Search.HotelSearchCondition termsHotelSC = ConvertHotelSearchCondition(searchCondition);

            DateTime dtBeginTime = new DateTime();

            //log begin 20090312 Leon
            dtBeginTime = System.DateTime.Now;
            hotelLog.Info(m_LogRandomID + " >Search From Terms Product Begin Start time : " + dtBeginTime);

            IList<HotelProduct> products = new List<HotelProduct>();

            //��ѯ�õ�Hotel Product
            DateTime dtNow = DateTime.Now;
            hotelSearchHotelByZyl.Debug("MV_B2C Hotel GetProductFrame Start :" + dtNow.ToString("HH:mm:ss") + ":" + dtNow.Millisecond);
            products = new TERMS.Business.Centers.ProductCenter.Search.HotelProductSearcher().Search(termsHotelSC, UserInfo.Entity);
            dtNow = DateTime.Now;
            hotelSearchHotelByZyl.Debug("MV_B2C Hotel GetProductFrame Conclusion :" + dtNow.ToString("HH:mm:ss") + ":" + dtNow.Millisecond);

            //log
            hotelLog.Info(m_LogRandomID + " >Search From Terms Product End time : " + ((TimeSpan)System.DateTime.Now.Subtract(dtBeginTime)).ToString());
            dtBeginTime = System.DateTime.Now;
            hotelLog.Info(m_LogRandomID + " >TERMS Search hotel Begin time : " + dtBeginTime);

            HotelProduct hotelProduct = products[0];

            dtNow = DateTime.Now;
            hotelSearchHotelByZyl.Debug("MV_B2C Hotel GetProductItems Start :" + dtNow.ToString("HH:mm:ss") + ":" + dtNow.Millisecond);
            IList<TERMS.Core.Product.Component> hotels = hotelProduct.Items;
            dtNow = DateTime.Now;
            hotelSearchHotelByZyl.Debug("MV_B2C Hotel GetProductItems Conclusion :" + dtNow.ToString("HH:mm:ss") + ":" + dtNow.Millisecond);
            if (hotels.Count == 0)
            {
                m_Error = "Searching is not available in Web Searching now. Please choose another travel date or destination.(h1)";
                return null;
            }

            //log begin 20090312 Leon
            try
            {
                if (hotelProduct.ItemGetter != null && hotelProduct.ItemGetter.Log != null)
                    hotelLog.Info(m_LogRandomID + " > " + hotelProduct.ItemGetter.Log.Text);

                hotelLog.Info(m_LogRandomID + " >TERMS Search hotel End time : " + ((TimeSpan)System.DateTime.Now.Subtract(dtBeginTime)).ToString());
                dtBeginTime = System.DateTime.Now;
                hotelLog.Info(m_LogRandomID + " >Create Hotel Merchandise Begin time : " + dtBeginTime);
            }
            catch
            { }

            //����Hotel Merchandise
            TERMS.Business.Centers.SalesCenter.HotelProfile hotelProfile = new TERMS.Business.Centers.SalesCenter.HotelProfile("mv");
            hotelProfile.CheckInDate = searchCondition.CheckIn;
            hotelProfile.CheckOutDate = searchCondition.CheckOut;
            hotelProfile.Location = searchCondition.Location;

            hotelMerchandise = new HotelMerchandise(hotelProfile, hotelProduct);

            //log
            hotelLog.Info(m_LogRandomID + " >Create Hotel Merchandise End time : " + ((TimeSpan)System.DateTime.Now.Subtract(dtBeginTime)).ToString());

            if (hotelMerchandise == null || hotelMerchandise.Items == null || hotelMerchandise.Items.Count == 0)
            {
                m_Error = "Searching is not available in Web Searching now. Please choose another travel date or destination.(h1)";
                return null;
            }

            //log
            dtBeginTime = System.DateTime.Now;
            hotelLog.Info(m_LogRandomID + " >Convert Hotel to MV Hotel Begin time : " + dtBeginTime);

            hotelMerchandise = ConvertHotelToMVHotel(searchCondition, hotelMerchandise);

            //log
            hotelLog.Info(m_LogRandomID + " >Convert Hotel to MV Hotel End time : " + ((TimeSpan)System.DateTime.Now.Subtract(dtBeginTime)).ToString());

            if (hotelMerchandise == null || hotelMerchandise.Items == null || hotelMerchandise.Items.Count == 0)
            {
                m_Error = "Searching is not available in Web Searching now. Please choose another travel date or destination.(h1)";
                return null;
            }

            hotelSearchHotelByZyl.Info("MV_B2C Hotel Count :" + hotelMerchandise.Items.Count);

            MVMerchandisePool.Cache(searchCondition.Clone(), hotelMerchandise); //Cache

            hotelSearchHotelByZyl.Debug("Search Hotel End :" + DateTime.Now.ToLongTimeString());

            //��¼Searchʱ��
            DateTime SearchingEndingTime = DateTime.Now;
            SearchingLogger searchingLogger = new SearchingLogger();
            searchingLogger.Log(SearchingBeginningTime, SearchingEndingTime, searchCondition);
        }

        return hotelMerchandise;
        //return null;
    }
Exemple #38
0
        public virtual T AsCriteria <T>(string catalog, ISearchFilter[] filters) where T : CatalogItemSearchCriteria, new()
        {
            var criteria = new T();

            criteria.Currency          = Currency;
            criteria.Pricelists        = PriceLists;
            criteria.SearchPhrase      = SearchPhrase;
            criteria.Locale            = Locale;
            criteria.StartingRecord    = Skip;
            criteria.RecordsToRetrieve = Take;

            // add outline
            if (!string.IsNullOrEmpty(Outline))
            {
                criteria.Outlines.Add(string.Format("{0}/{1}", catalog, Outline));
            }
            else
            {
                criteria.Outlines.Add(string.Format("{0}*", catalog));
            }

            // Add all filters
            foreach (var filter in filters)
            {
                criteria.Add(filter);
            }

            #region Filters

            var terms = Terms.AsKeyValues();
            if (terms.Any())
            {
                var filtersWithValues = filters
                                        .Where(x => (!(x is PriceRangeFilter) || ((PriceRangeFilter)x).Currency.Equals(Currency, StringComparison.OrdinalIgnoreCase)))
                                        .Select(x => new { Filter = x, Values = x.GetValues() })
                                        .ToList();

                foreach (var term in terms)
                {
                    var filter = filters.SingleOrDefault(x => x.Key.Equals(term.Key, StringComparison.OrdinalIgnoreCase) &&
                                                         (!(x is PriceRangeFilter) || ((PriceRangeFilter)x).Currency.Equals(criteria.Currency, StringComparison.OrdinalIgnoreCase)));

                    // handle special filter term with a key = "tags", it contains just values and we need to determine which filter to use
                    if (filter == null && term.Key == "tags")
                    {
                        foreach (var termValue in term.Values)
                        {
                            // try to find filter by value
                            var foundFilter = filtersWithValues.FirstOrDefault(x => x.Values.Any(y => y.Id.Equals(termValue)));

                            if (foundFilter != null)
                            {
                                filter = foundFilter.Filter;

                                var appliedFilter = BrowseFilterHelper.Convert(filter, term.Values);
                                criteria.Apply(appliedFilter);
                            }
                        }
                    }
                    else if (filter != null) // predefined filter
                    {
                        var attributeFilter = filter as AttributeFilter;
                        if (attributeFilter != null && attributeFilter.Values == null)
                        {
                            filter = new AttributeFilter
                            {
                                Key          = attributeFilter.Key,
                                Values       = BrowseFilterHelper.CreateAttributeFilterValues(term.Values),
                                IsLocalized  = attributeFilter.IsLocalized,
                                DisplayNames = attributeFilter.DisplayNames,
                            };
                        }

                        var appliedFilter = BrowseFilterHelper.Convert(filter, term.Values);
                        criteria.Apply(appliedFilter);
                    }
                    else // custom term
                    {
                        if (!term.Key.StartsWith("_")) // ignore system terms, we can't filter by them
                        {
                            var attr = new AttributeFilter {
                                Key = term.Key, Values = BrowseFilterHelper.CreateAttributeFilterValues(term.Values)
                            };
                            criteria.Apply(attr);
                        }
                    }
                }
            }

            #endregion

            #region Sorting

            var categoryId        = Outline.AsCategoryId();
            var sorts             = Sort.AsSortInfoes();
            var sortFields        = new List <SearchSortField>();
            var priorityFieldName = string.Format(CultureInfo.InvariantCulture, "priority_{0}_{1}", catalog, categoryId).ToLower();

            if (!sorts.IsNullOrEmpty())
            {
                foreach (var sortInfo in sorts)
                {
                    var fieldName    = sortInfo.SortColumn.ToLowerInvariant();
                    var isDescending = sortInfo.SortDirection == SortDirection.Descending;

                    switch (fieldName)
                    {
                    case "price":
                        if (criteria.Pricelists != null)
                        {
                            sortFields.AddRange(
                                criteria.Pricelists.Select(
                                    priceList =>
                                    new SearchSortField(string.Format(CultureInfo.InvariantCulture, "price_{0}_{1}", criteria.Currency.ToLower(), priceList.ToLower()))
                            {
                                IgnoredUnmapped = true,
                                IsDescending    = isDescending,
                                DataType        = SearchSortField.DOUBLE
                            })
                                .ToArray());
                        }
                        break;

                    case "priority":
                        sortFields.Add(new SearchSortField(priorityFieldName, isDescending)
                        {
                            IgnoredUnmapped = true
                        });
                        sortFields.Add(new SearchSortField("priority", isDescending));
                        break;

                    case "name":
                    case "title":
                        sortFields.Add(new SearchSortField("name", isDescending));
                        break;

                    default:
                        sortFields.Add(new SearchSortField(fieldName, isDescending));
                        break;
                    }
                }
            }

            if (!sortFields.Any())
            {
                sortFields.Add(new SearchSortField(priorityFieldName, true)
                {
                    IgnoredUnmapped = true
                });
                sortFields.Add(new SearchSortField("priority", true));
                sortFields.AddRange(CatalogItemSearchCriteria.DefaultSortOrder.GetSort());
            }

            criteria.Sort = new SearchSort(sortFields.ToArray());

            #endregion

            return(criteria);
        }
    private VehcileMerchandise SearchVehcile(Terms.Sales.Business.VehcileSearchCondition searchCondition)
    {
        //searchCondition.UserInfo = UserInfo;

        //��Cache�в��ҽ��
        VehcileMerchandise hotelMerchandise = (VehcileMerchandise)MVMerchandisePool.Find(searchCondition);

        if (hotelMerchandise == null)
        {
            //log zyl
            try
            {
                TERMS.Common.Search.VehcileSearchCondition termsHotelSC = searchCondition.CarSearchCondition ;

                IList<VehcileProduct> products = new List<VehcileProduct>();

                hotelLog.Info(" Search Car : " + UserInfo.Entity.Name);
                //��ѯ�õ�Hotel Product
                products = new TERMS.Business.Centers.ProductCenter.Search.VehcileProductSearcher().Search(termsHotelSC, UserInfo.Entity);

                hotelLog.Info(" Search Car 1: " + products.Count.ToString());

                VehcileProduct hotelProduct = products[0];

                //IList<TERMS.Core.Product.Component> hotels = hotelProduct.Items;
                if (products[0].Items.Count == 0)
                {
                    m_Error = "Searching is not available in Web Searching now. Please choose another travel date or destination.(h1)";
                    return null;
                }

                //����Hotel Merchandise
                VehcileProfile hotelProfile = new VehcileProfile("car");

                hotelMerchandise = new VehcileMerchandise(hotelProfile, hotelProduct);

                //log

                MVMerchandisePool.Cache(searchCondition, hotelMerchandise); //Cache
            }
            catch(Exception ex)
            {
                hotelLog.Info(" Search Car 1: " + ex.Message );

                if (ex.InnerException != null)
                {
                    hotelLog.Info(" Search Car 2: " + ex.InnerException.Message);
                }

                m_Error = "Searching is not available in Web Searching now. Please choose another travel date or destination.";
                return null;
            }
        }

        return hotelMerchandise;
    }
Exemple #40
0
            public override Scorer Scorer(AtomicReaderContext context, Bits acceptDocs)
            {
                Debug.Assert(OuterInstance.Terms_Renamed.Count > 0);
                AtomicReader reader   = context.AtomicReader;
                Bits         liveDocs = acceptDocs;

                PostingsAndFreq[] postingsFreqs = new PostingsAndFreq[OuterInstance.Terms_Renamed.Count];

                Terms fieldTerms = reader.Terms(OuterInstance.Field);

                if (fieldTerms == null)
                {
                    return(null);
                }

                // Reuse single TermsEnum below:
                TermsEnum te = fieldTerms.Iterator(null);

                for (int i = 0; i < OuterInstance.Terms_Renamed.Count; i++)
                {
                    Term      t     = OuterInstance.Terms_Renamed[i];
                    TermState state = States[i].Get(context.Ord);
                    if (state == null) // term doesnt exist in this segment
                    {
                        Debug.Assert(TermNotInReader(reader, t), "no termstate found but term exists in reader");
                        return(null);
                    }
                    te.SeekExact(t.Bytes(), state);
                    DocsAndPositionsEnum postingsEnum = te.DocsAndPositions(liveDocs, null, DocsEnum.FLAG_NONE);

                    // PhraseQuery on a field that did not index
                    // positions.
                    if (postingsEnum == null)
                    {
                        Debug.Assert(te.SeekExact(t.Bytes()), "termstate found but no term exists in reader");
                        // term does exist, but has no positions
                        throw new InvalidOperationException("field \"" + t.Field() + "\" was indexed without position data; cannot run PhraseQuery (term=" + t.Text() + ")");
                    }
                    postingsFreqs[i] = new PostingsAndFreq(postingsEnum, te.DocFreq(), (int)OuterInstance.Positions_Renamed[i], t);
                }

                // sort by increasing docFreq order
                if (OuterInstance.Slop_Renamed == 0)
                {
                    ArrayUtil.TimSort(postingsFreqs);
                }

                if (OuterInstance.Slop_Renamed == 0) // optimize exact case
                {
                    ExactPhraseScorer s = new ExactPhraseScorer(this, postingsFreqs, Similarity.DoSimScorer(Stats, context));
                    if (s.NoDocs)
                    {
                        return(null);
                    }
                    else
                    {
                        return(s);
                    }
                }
                else
                {
                    return(new SloppyPhraseScorer(this, postingsFreqs, OuterInstance.Slop_Renamed, Similarity.DoSimScorer(Stats, context)));
                }
            }
    public SightSeeingMaterial SearchInsurance(Terms.Sales.Business.SightSeeingSearchCondition sightSeeingSearchCondition)
    {
        TERMS.Common.Search.SightSeeingSearchCondition searchCondition = new TERMS.Common.Search.SightSeeingSearchCondition();

        searchCondition.Adults = sightSeeingSearchCondition.Adults;

        searchCondition.ChildrenAges = sightSeeingSearchCondition.ChildrenAges.ToArray();

        searchCondition.DestinationCode = sightSeeingSearchCondition.City;
        searchCondition.DestinationType = sightSeeingSearchCondition.SearchType;
        searchCondition.TourDate = sightSeeingSearchCondition.ServiceDate;

        searchCondition.TypeCodes = sightSeeingSearchCondition.Types.ToArray();

        SightSeeingProductSearcher searcher = new SightSeeingProductSearcher();

        IList<SightSeeingProduct> Products = searcher.Search(searchCondition);

        if (Products != null)
        {
            return ((TERMS.Business.Centers.ProductCenter.Components.SightSeeingMaterial)((TERMS.Core.Product.ComponentGroup)Products[0].Items[0]).Items[0]);
        }
        else
        {
            return null;
        }
    }
 protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
 {
     return(new SimpleAutomatonTermsEnum(this, terms.GetIterator(null)));
 }
    public TourMerchandise SearchTour(Terms.Sales.Business.TourSearchCondition searchCondition, string Language)
    {
        //searchCondition.UserInfo = UserInfo;
        ////��Cache�в��ҽ�
        //TourMerchandise tourMerchandise = null;
        //if (Utility.IsSubAgent)
        //    tourMerchandise = (TourMerchandise)MVMerchandisePool.FindB2BTour(searchCondition);
        //else
        //    tourMerchandise = (TourMerchandise)MVMerchandisePool.Find(searchCondition);

        //if (tourMerchandise == null)
        //{
        TourProductSearcher searcher = new TourProductSearcher();

        TERMS.Common.Search.TourSearchCondition tourSearchCondition = new TERMS.Common.Search.TourSearchCondition();
        tourSearchCondition.SetCity(searchCondition.City);
        tourSearchCondition.SetRegion(searchCondition.Region);
        tourSearchCondition.SetCountry(searchCondition.Counrty);
        tourSearchCondition.IsLandOnly = searchCondition.IsLandOnly;
        tourSearchCondition.TravelDaysFrom = searchCondition.TravelDaysFrom;
        tourSearchCondition.TravelDaysTo = searchCondition.TravelDaysTo;
        tourSearchCondition.PriceType = searchCondition.PriceType;
        tourSearchCondition.SetDepartureRange(searchCondition.TravelBeginDate.AddDays(-7), searchCondition.TravelBeginDate.AddDays(7));

        List<string> citys = new List<string>();

        citys.Add(searchCondition.City);

        return SearchTour(searchCondition, citys, Language);

        //    IList<TourProduct> tps = new List<TourProduct>();

        //    tps = searcher.Search(tourSearchCondition, UserInfo.Entity);

        //    if (tps != null && tps.Count > 0)
        //    {
        //        tourMerchandise = new TourMerchandise((List<TourProduct>)tps);

        //        if (Utility.IsSubAgent)
        //        {
        //            GetSpecialTourPrice(tourMerchandise, searchCondition.IsLandOnly);
        //        }

        //        MVMerchandisePool.Cache(searchCondition.Clone(), tourMerchandise); //Cache
        //    }
        //    else
        //        return null;
        //}

        //tourMerchandise.LanguageFlag = Language;

        //return tourMerchandise;
    }
            public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs)
            {
                if (Debugging.AssertsEnabled)
                {
                    Debugging.Assert(outerInstance.termArrays.Count > 0);
                }
                AtomicReader reader   = (context.AtomicReader);
                IBits        liveDocs = acceptDocs;

                PhraseQuery.PostingsAndFreq[] postingsFreqs = new PhraseQuery.PostingsAndFreq[outerInstance.termArrays.Count];

                Terms fieldTerms = reader.GetTerms(outerInstance.field);

                if (fieldTerms == null)
                {
                    return(null);
                }

                // Reuse single TermsEnum below:
                TermsEnum termsEnum = fieldTerms.GetIterator(null);

                for (int pos = 0; pos < postingsFreqs.Length; pos++)
                {
                    Term[] terms = outerInstance.termArrays[pos];

                    DocsAndPositionsEnum postingsEnum;
                    int docFreq;

                    if (terms.Length > 1)
                    {
                        postingsEnum = new UnionDocsAndPositionsEnum(liveDocs, context, terms, termContexts, termsEnum);

                        // coarse -- this overcounts since a given doc can
                        // have more than one term:
                        docFreq = 0;
                        for (int termIdx = 0; termIdx < terms.Length; termIdx++)
                        {
                            Term      term      = terms[termIdx];
                            TermState termState = termContexts[term].Get(context.Ord);
                            if (termState == null)
                            {
                                // Term not in reader
                                continue;
                            }
                            termsEnum.SeekExact(term.Bytes, termState);
                            docFreq += termsEnum.DocFreq;
                        }

                        if (docFreq == 0)
                        {
                            // None of the terms are in this reader
                            return(null);
                        }
                    }
                    else
                    {
                        Term      term      = terms[0];
                        TermState termState = termContexts[term].Get(context.Ord);
                        if (termState == null)
                        {
                            // Term not in reader
                            return(null);
                        }
                        termsEnum.SeekExact(term.Bytes, termState);
                        postingsEnum = termsEnum.DocsAndPositions(liveDocs, null, DocsAndPositionsFlags.NONE);

                        if (postingsEnum == null)
                        {
                            // term does exist, but has no positions
                            if (Debugging.AssertsEnabled)
                            {
                                Debugging.Assert(termsEnum.Docs(liveDocs, null, DocsFlags.NONE) != null, () => "termstate found but no term exists in reader");
                            }
                            throw new InvalidOperationException("field \"" + term.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + term.Text() + ")");
                        }

                        docFreq = termsEnum.DocFreq;
                    }

                    postingsFreqs[pos] = new PhraseQuery.PostingsAndFreq(postingsEnum, docFreq, (int)outerInstance.positions[pos], terms);
                }

                // sort by increasing docFreq order
                if (outerInstance.slop == 0)
                {
                    ArrayUtil.TimSort(postingsFreqs);
                }

                if (outerInstance.slop == 0)
                {
                    ExactPhraseScorer s = new ExactPhraseScorer(this, postingsFreqs, similarity.GetSimScorer(stats, context));
                    if (s.noDocs)
                    {
                        return(null);
                    }
                    else
                    {
                        return(s);
                    }
                }
                else
                {
                    return(new SloppyPhraseScorer(this, postingsFreqs, outerInstance.slop, similarity.GetSimScorer(stats, context)));
                }
            }
    public TERMS.Business.Centers.ProductCenter.Components.TransferProduct SearchTransfer(Terms.Sales.Business.TransferSearchCondition transferSearchCondition)
    {
        TERMS.Common.Search.TransferSearchCondition searchCondition = new TERMS.Common.Search.TransferSearchCondition();

        searchCondition.CurrencyCode = transferSearchCondition.CurrencyCode;
        searchCondition.CountryCode = transferSearchCondition.Country;
        searchCondition.PreferredLanguage = transferSearchCondition.PreferredLanguage;

        searchCondition.PickupCityCode = transferSearchCondition.PickupCityCode;
        searchCondition.PickupCode = transferSearchCondition.PickupCode;
        searchCondition.PickupPointCode = transferSearchCondition.PickupPoint;

        searchCondition.DropOffCityCode = transferSearchCondition.DropOffCityCode;
        searchCondition.DropOffCode = transferSearchCondition.DropOffCode;

        searchCondition.TransferDate = transferSearchCondition.TransferDate;
        searchCondition.AlternateLanguage = transferSearchCondition.AlternateLanguage;
        searchCondition.Passengers = transferSearchCondition.Passengers;

        TransferProductSearcher searcher = new TransferProductSearcher();
        IList<TransferProduct> Products = searcher.Search(searchCondition);

        if (Products != null && Products.Count > 0)
        {
            return (TERMS.Business.Centers.ProductCenter.Components.TransferProduct)Products[0];
        }
        else
        {
            return null;
        }
    }
Exemple #46
0
 public SingleDocValuesAnonymousInnerClassHelper(TFValueSource outerInstance, TFValueSource @this, Terms terms, TFIDFSimilarity similarity)
     : base(@this)
 {
     this.outerInstance = outerInstance;
     this.terms         = terms;
     this.similarity    = similarity;
     lastDocRequested   = -1;
     Reset();
 }
    private HotelMerchandise ConvertHotelToMVHotel(Terms.Sales.Business.HotelSearchCondition searchCondition, HotelMerchandise hotelMerchandise)
    {
        if (hotelMerchandise.Items == null) return null;
        if (hotelMerchandise.Items.Count == 0) return null;

        //��Hotel Merchandise�Ľṹ���ɣ�HotelMerchandise -> MVHotel -> MVRoom -> HotelMaterial
        for (int i = hotelMerchandise.Items.Count - 1; i >= 0; i--)
        {
            TERMS.Business.Centers.SalesCenter.Hotel hotel = ConvertRooms(hotelMerchandise.Items[i], searchCondition);

            if (hotel == null)
                hotelMerchandise.Items.RemoveAt(i);
            else
            {
                hotelMerchandise.Items[i] = new MVHotel(hotelMerchandise.Items[i]);

                hotelMerchandise.Items[i].Profile.CheckInDate = hotelMerchandise.Profile.CheckInDate;
                hotelMerchandise.Items[i].Profile.CheckOutDate = hotelMerchandise.Profile.CheckOutDate;

                if (((MVHotel)hotelMerchandise.Items[i]).Items != null)
                {
                    foreach (MVRoom room in ((MVHotel)hotelMerchandise.Items[i]).Items)
                    {
                        room.Profile.CheckInDate = hotelMerchandise.Profile.CheckInDate;
                        room.Profile.CheckOutDate = hotelMerchandise.Profile.CheckOutDate;
                    }
                }

                try
                {
                    decimal dec = hotelMerchandise.Items[i].RoomPrice;
                }
                catch
                {
                    hotelMerchandise.Items.RemoveAt(i);
                    continue;
                }

                //��Map�ĵ�ַ��ֵ
                if (hotelMerchandise.Items[i].HotelInformation.Images.Count > 0)
                {
                    if (hotelMerchandise.Items[i].Source == "GTA")
                    {
                        for (int index = 0; index < hotelMerchandise.Items[i].HotelInformation.Images.Count; index++)
                        {
                            if (string.IsNullOrEmpty(hotelMerchandise.Items[i].HotelInformation.Images[index].Name))
                            {
                                hotelMerchandise.Items[i].HotelInformation.MapUrl = hotelMerchandise.Items[i].HotelInformation.Images[index].Filename;

                                hotelMerchandise.Items[i].HotelInformation.Images.RemoveAt(index);

                                continue;
                            }
                        }
                    }
                    if (hotelMerchandise.Items[i].Source == "TRAVCO")
                    {
                        for (int index = 0; index < hotelMerchandise.Items[i].HotelInformation.Images.Count; index++)
                        {
                            if (hotelMerchandise.Items[i].HotelInformation.Images[index].Name.Trim().ToUpper() == "MAP".Trim().ToUpper())
                            {
                                hotelMerchandise.Items[i].HotelInformation.MapUrl = hotelMerchandise.Items[i].HotelInformation.Images[index].Filename;

                                hotelMerchandise.Items[i].HotelInformation.Images.RemoveAt(index);

                                continue;
                            }
                        }
                    }

                    //add zyl 2009-8-19 ��hotel�� localʱ �� webconfig�е����õ�·���滻ͼƬ·���е� "~/" ��ΪͼƬ�ϴ�ʱ���ϴ���TERMS��
                    if (hotelMerchandise.Items[i].Source == "LOCAL")
                    {
                        string imgHand = string.Empty;

                        if (System.Configuration.ConfigurationManager.AppSettings["URL.Head"] != null)
                            imgHand = System.Configuration.ConfigurationManager.AppSettings["URL.Head"];

                        for (int index = 0; index < hotelMerchandise.Items[i].HotelInformation.Images.Count; index++)
                        {
                            if (!string.IsNullOrEmpty(imgHand))
                            {
                                hotelMerchandise.Items[i].HotelInformation.Images[index].Filename =
                                    hotelMerchandise.Items[i].HotelInformation.Images[index].Filename.Trim().Replace("~/", imgHand);
                            }
                        }
                    }
                }
                else
                {
                    //add zyl 2009-9-2 ��hotel�� localʱ ���û��ͼƬ��Ϣ�Ͳ�Ҫ��ʾ��ǰ̨
                    if (hotelMerchandise.Items[i].Source == "LOCAL")
                    {
                        hotelMerchandise.Items.RemoveAt(i);
                        continue;
                    }
                }
            }
        }

        return hotelMerchandise;
    }
Exemple #48
0
            public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs)
            {
                if (Debugging.AssertsEnabled)
                {
                    Debugging.Assert(outerInstance.terms.Count > 0);
                }
                AtomicReader reader   = context.AtomicReader;
                IBits        liveDocs = acceptDocs;

                PostingsAndFreq[] postingsFreqs = new PostingsAndFreq[outerInstance.terms.Count];

                Terms fieldTerms = reader.GetTerms(outerInstance.field);

                if (fieldTerms == null)
                {
                    return(null);
                }

                // Reuse single TermsEnum below:
                TermsEnum te = fieldTerms.GetIterator(null);

                for (int i = 0; i < outerInstance.terms.Count; i++)
                {
                    Term      t     = outerInstance.terms[i];
                    TermState state = states[i].Get(context.Ord);
                    if (state == null) // term doesnt exist in this segment
                    {
                        if (Debugging.AssertsEnabled)
                        {
                            Debugging.Assert(TermNotInReader(reader, t), "no termstate found but term exists in reader");
                        }
                        return(null);
                    }
                    te.SeekExact(t.Bytes, state);
                    DocsAndPositionsEnum postingsEnum = te.DocsAndPositions(liveDocs, null, DocsAndPositionsFlags.NONE);

                    // PhraseQuery on a field that did not index
                    // positions.
                    if (postingsEnum == null)
                    {
                        if (Debugging.AssertsEnabled)
                        {
                            Debugging.Assert(te.SeekExact(t.Bytes), "termstate found but no term exists in reader");
                        }
                        // term does exist, but has no positions
                        throw new InvalidOperationException("field \"" + t.Field + "\" was indexed without position data; cannot run PhraseQuery (term=" + t.Text() + ")");
                    }
                    postingsFreqs[i] = new PostingsAndFreq(postingsEnum, te.DocFreq, (int)outerInstance.positions[i], t);
                }

                // sort by increasing docFreq order
                if (outerInstance.slop == 0)
                {
                    ArrayUtil.TimSort(postingsFreqs);
                }

                if (outerInstance.slop == 0) // optimize exact case
                {
                    ExactPhraseScorer s = new ExactPhraseScorer(this, postingsFreqs, similarity.GetSimScorer(stats, context));
                    if (s.noDocs)
                    {
                        return(null);
                    }
                    else
                    {
                        return(s);
                    }
                }
                else
                {
                    return(new SloppyPhraseScorer(this, postingsFreqs, outerInstance.slop, similarity.GetSimScorer(stats, context)));
                }
            }
 /// <summary>
 /// Construct the enumeration to be used, expanding the
 /// pattern term.  this method should only be called if
 /// the field exists (ie, implementations can assume the
 /// field does exist).  this method should not return null
 /// (should instead return <see cref="TermsEnum.EMPTY"/> if no
 /// terms match).  The <see cref="TermsEnum"/> must already be
 /// positioned to the first matching term.
 /// The given <see cref="AttributeSource"/> is passed by the <see cref="RewriteMethod"/> to
 /// provide attributes, the rewrite method uses to inform about e.g. maximum competitive boosts.
 /// this is currently only used by <see cref="TopTermsRewrite{Q}"/>.
 /// </summary>
 protected abstract TermsEnum GetTermsEnum(Terms terms, AttributeSource atts);
 /// <summary>
 /// Convenience method, if no attributes are needed:
 /// this simply passes empty attributes and is equal to:
 /// <code>GetTermsEnum(terms, new AttributeSource())</code>
 /// </summary>
 public TermsEnum GetTermsEnum(Terms terms)
 {
     return(GetTermsEnum(terms, new AttributeSource()));
 }
Exemple #51
0
        public override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
        {
            if (LowerTerm_Renamed != null && UpperTerm_Renamed != null && LowerTerm_Renamed.CompareTo(UpperTerm_Renamed) > 0)
            {
                return TermsEnum.EMPTY;
            }

            TermsEnum tenum = terms.Iterator(null);

            if ((LowerTerm_Renamed == null || (IncludeLower && LowerTerm_Renamed.Length == 0)) && UpperTerm_Renamed == null)
            {
                return tenum;
            }
            return new TermRangeTermsEnum(tenum, LowerTerm_Renamed, UpperTerm_Renamed, IncludeLower, IncludeUpper);
        }
 /// <summary>
 /// Returns the <see cref="MultiTermQuery"/>s <see cref="TermsEnum"/> </summary>
 /// <seealso cref="MultiTermQuery.GetTermsEnum(Terms, AttributeSource)"/>
 protected virtual TermsEnum GetTermsEnum(MultiTermQuery query, Terms terms, AttributeSource atts)
 {
     return(query.GetTermsEnum(terms, atts)); // allow RewriteMethod subclasses to pull a TermsEnum from the MTQ
 }
            public DirectField(SegmentReadState state, string field, Terms termsIn, int minSkipCount, int lowFreqCutoff)
            {
                FieldInfo fieldInfo = state.FieldInfos.FieldInfo(field);

                sumTotalTermFreq = termsIn.SumTotalTermFreq;
                sumDocFreq = termsIn.SumDocFreq;
                docCount = termsIn.DocCount;

                int numTerms = (int) termsIn.Size();
                if (numTerms == -1)
                {
                    throw new System.ArgumentException("codec does not provide Terms.size()");
                }
                terms = new TermAndSkip[numTerms];
                termOffsets = new int[1 + numTerms];

                byte[] termBytes = new byte[1024];

                this.minSkipCount = minSkipCount;

                hasFreq = fieldInfo.FieldIndexOptions.Value.CompareTo(IndexOptions.DOCS_ONLY) > 0;
                hasPos = fieldInfo.FieldIndexOptions.Value.CompareTo(IndexOptions.DOCS_AND_FREQS) > 0;
                hasOffsets_Renamed = fieldInfo.FieldIndexOptions.Value.CompareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) > 0;
                hasPayloads_Renamed = fieldInfo.HasPayloads();

                BytesRef term;
                DocsEnum docsEnum = null;
                DocsAndPositionsEnum docsAndPositionsEnum = null;
                TermsEnum termsEnum = termsIn.Iterator(null);
                int termOffset = 0;

                IntArrayWriter scratch = new IntArrayWriter();

                // Used for payloads, if any:
                RAMOutputStream ros = new RAMOutputStream();

                // if (DEBUG) {
                //   System.out.println("\nLOAD terms seg=" + state.segmentInfo.name + " field=" + field + " hasOffsets=" + hasOffsets + " hasFreq=" + hasFreq + " hasPos=" + hasPos + " hasPayloads=" + hasPayloads);
                // }

                while ((term = termsEnum.Next()) != null)
                {
                    int docFreq = termsEnum.DocFreq();
                    long totalTermFreq = termsEnum.TotalTermFreq();

                    // if (DEBUG) {
                    //   System.out.println("  term=" + term.utf8ToString());
                    // }

                    termOffsets[count] = termOffset;

                    if (termBytes.Length < (termOffset + term.Length))
                    {
                        termBytes = ArrayUtil.Grow(termBytes, termOffset + term.Length);
                    }
                    Array.Copy(term.Bytes, term.Offset, termBytes, termOffset, term.Length);
                    termOffset += term.Length;
                    termOffsets[count + 1] = termOffset;

                    if (hasPos)
                    {
                        docsAndPositionsEnum = termsEnum.DocsAndPositions(null, docsAndPositionsEnum);
                    }
                    else
                    {
                        docsEnum = termsEnum.Docs(null, docsEnum);
                    }

                    TermAndSkip ent;

                    DocsEnum docsEnum2;
                    docsEnum2 = hasPos ? docsAndPositionsEnum : docsEnum;

                    int docID;

                    if (docFreq <= lowFreqCutoff)
                    {

                        ros.Reset();

                        // Pack postings for low-freq terms into a single int[]:
                        while ((docID = docsEnum2.NextDoc()) != DocsEnum.NO_MORE_DOCS)
                        {
                            scratch.Add(docID);
                            if (hasFreq)
                            {
                                int freq = docsEnum2.Freq();
                                scratch.Add(freq);
                                if (hasPos)
                                {
                                    for (int pos = 0; pos < freq; pos++)
                                    {
                                        scratch.Add(docsAndPositionsEnum.NextPosition());
                                        if (hasOffsets_Renamed)
                                        {
                                            scratch.Add(docsAndPositionsEnum.StartOffset());
                                            scratch.Add(docsAndPositionsEnum.EndOffset());
                                        }
                                        if (hasPayloads_Renamed)
                                        {
                                            BytesRef payload = docsAndPositionsEnum.Payload;
                                            if (payload != null)
                                            {
                                                scratch.Add(payload.Length);
                                                ros.WriteBytes(payload.Bytes, payload.Offset, payload.Length);
                                            }
                                            else
                                            {
                                                scratch.Add(0);
                                            }
                                        }
                                    }
                                }
                            }
                        }


                        byte[] payloads;
                        if (hasPayloads_Renamed)
                        {
                            ros.Flush();
                            payloads = new byte[(int) ros.Length];
                            ros.WriteTo(payloads, 0);
                        }
                        else
                        {
                            payloads = null;
                        }

                        int[] postings = scratch.Get();

                        ent = new LowFreqTerm(postings, payloads, docFreq, (int) totalTermFreq);
                    }
                    else
                    {
                        var docs = new int[docFreq];
                        int[] freqs;
                        int[][] positions;
                        byte[][][] payloads;

                        if (hasFreq)
                        {
                            freqs = new int[docFreq];
                            if (hasPos)
                            {
                                positions = new int[docFreq][];
                                if (hasPayloads_Renamed)
                                {
                                    payloads = new byte[docFreq][][];
                                }
                                else
                                {
                                    payloads = null;
                                }
                            }
                            else
                            {
                                positions = null;
                                payloads = null;
                            }
                        }
                        else
                        {
                            freqs = null;
                            positions = null;
                            payloads = null;
                        }

                        // Use separate int[] for the postings for high-freq
                        // terms:
                        int upto = 0;
                        while ((docID = docsEnum2.NextDoc()) != DocsEnum.NO_MORE_DOCS)
                        {
                            docs[upto] = docID;
                            if (hasFreq)
                            {
                                int freq = docsEnum2.Freq();
                                freqs[upto] = freq;
                                if (hasPos)
                                {
                                    int mult;
                                    if (hasOffsets_Renamed)
                                    {
                                        mult = 3;
                                    }
                                    else
                                    {
                                        mult = 1;
                                    }
                                    if (hasPayloads_Renamed)
                                    {
                                        payloads[upto] = new byte[freq][];
                                    }
                                    positions[upto] = new int[mult*freq];
                                    int posUpto = 0;
                                    for (int pos = 0; pos < freq; pos++)
                                    {
                                        positions[upto][posUpto] = docsAndPositionsEnum.NextPosition();
                                        if (hasPayloads_Renamed)
                                        {
                                            BytesRef payload = docsAndPositionsEnum.Payload;
                                            if (payload != null)
                                            {
                                                var payloadBytes = new byte[payload.Length];
                                                Array.Copy(payload.Bytes, payload.Offset, payloadBytes, 0,
                                                    payload.Length);
                                                payloads[upto][pos] = payloadBytes;
                                            }
                                        }
                                        posUpto++;
                                        if (hasOffsets_Renamed)
                                        {
                                            positions[upto][posUpto++] = docsAndPositionsEnum.StartOffset();
                                            positions[upto][posUpto++] = docsAndPositionsEnum.EndOffset();
                                        }
                                    }
                                }
                            }

                            upto++;
                        }
                        Debug.Assert(upto == docFreq);
                        ent = new HighFreqTerm(docs, freqs, positions, payloads, totalTermFreq);
                    }

                    terms[count] = ent;
                    SetSkips(count, termBytes);
                    count++;
                }

                // End sentinel:
                termOffsets[count] = termOffset;

                FinishSkips();

                //System.out.println(skipCount + " skips: " + field);

                this.termBytes = new byte[termOffset];
                Array.Copy(termBytes, 0, this.termBytes, 0, termOffset);

                // Pack skips:
                this.skips = new int[skipCount];
                this.skipOffsets = new int[1 + numTerms];

                int skipOffset = 0;
                for (int i = 0; i < numTerms; i++)
                {
                    int[] termSkips = terms[i].skips;
                    skipOffsets[i] = skipOffset;
                    if (termSkips != null)
                    {
                        Array.Copy(termSkips, 0, skips, skipOffset, termSkips.Length);
                        skipOffset += termSkips.Length;
                        terms[i].skips = null;
                    }
                }
                this.skipOffsets[numTerms] = skipOffset;
                Debug.Assert(skipOffset == skipCount);
            }
        private IDictionary <int, object> HighlightField(string field, string[] contents, BreakIterator bi, BytesRef[] terms, int[] docids, IList <AtomicReaderContext> leaves, int maxPassages, Query query)
        {
            IDictionary <int, object> highlights = new Dictionary <int, object>();

            PassageFormatter fieldFormatter = GetFormatter(field);

            if (fieldFormatter == null)
            {
                throw new NullReferenceException("PassageFormatter cannot be null");
            }

            // check if we should do any multiterm processing
            Analyzer analyzer = GetIndexAnalyzer(field);

            CharacterRunAutomaton[] automata = new CharacterRunAutomaton[0];
            if (analyzer != null)
            {
                automata = MultiTermHighlighting.ExtractAutomata(query, field);
            }

            // resize 'terms', where the last term is the multiterm matcher
            if (automata.Length > 0)
            {
                BytesRef[] newTerms = new BytesRef[terms.Length + 1];
                System.Array.Copy(terms, 0, newTerms, 0, terms.Length);
                terms = newTerms;
            }

            // we are processing in increasing docid order, so we only need to reinitialize stuff on segment changes
            // otherwise, we will just advance() existing enums to the new document in the same segment.
            DocsAndPositionsEnum[] postings = null;
            TermsEnum termsEnum             = null;
            int       lastLeaf = -1;

            for (int i = 0; i < docids.Length; i++)
            {
                string content = contents[i];
                if (content.Length == 0)
                {
                    continue; // nothing to do
                }
                bi.SetText(content);
                int doc  = docids[i];
                int leaf = ReaderUtil.SubIndex(doc, leaves);
                AtomicReaderContext subContext = leaves[leaf];
                AtomicReader        r          = subContext.AtomicReader;

                Debug.Assert(leaf >= lastLeaf); // increasing order

                // if the segment has changed, we must initialize new enums.
                if (leaf != lastLeaf)
                {
                    Terms t = r.GetTerms(field);
                    if (t != null)
                    {
                        termsEnum = t.GetIterator(null);
                        postings  = new DocsAndPositionsEnum[terms.Length];
                    }
                }
                if (termsEnum == null)
                {
                    continue; // no terms for this field, nothing to do
                }

                // if there are multi-term matches, we have to initialize the "fake" enum for each document
                if (automata.Length > 0)
                {
                    DocsAndPositionsEnum dp = MultiTermHighlighting.GetDocsEnum(analyzer.GetTokenStream(field, content), automata);
                    dp.Advance(doc - subContext.DocBase);
                    postings[terms.Length - 1] = dp; // last term is the multiterm matcher
                }

                Passage[] passages = HighlightDoc(field, terms, content.Length, bi, doc - subContext.DocBase, termsEnum, postings, maxPassages);

                if (passages.Length == 0)
                {
                    // no passages were returned, so ask for a default summary
                    passages = GetEmptyHighlight(field, bi, maxPassages);
                }

                if (passages.Length > 0)
                {
                    highlights[doc] = fieldFormatter.Format(passages, content);
                }

                lastLeaf = leaf;
            }

            return(highlights);
        }
 //JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
 //ORIGINAL LINE: public SortingTerms(final org.apache.lucene.index.Terms in, org.apache.lucene.index.FieldInfo.IndexOptions indexOptions, final Sorter.DocMap docMap)
 public SortingTerms(Terms @in, IndexOptions indexOptions, Sorter.DocMap docMap)
     : base(@in)
 {
     this.docMap = docMap;
       this.indexOptions = indexOptions;
 }
Exemple #56
0
 public TermsEnum TermsEnum(Terms terms)
 {
     return(terms.GetEnumerator());
 }
 public override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
 {
     return new TermRangeTermsEnumAnonymousInnerClassHelper(this, terms.Iterator(null), new BytesRef("2"), new BytesRef("7"));
 }
Exemple #58
0
    public InsuranceMaterial OnSearchInsurance(Terms.Sales.Business.InsuranceSearchCondition Condition)
    {
        if (this.IsSearchConditionNull)
        {
            return null;
        }
        else
        {
            if (Utility.Transaction.CurrentSearchConditions is Terms.Sales.Business.HotelSearchCondition)
            {
                return null;
            }
            else
            {
                MVMerchandiseSearcher searcher = new MVMerchandiseSearcher();

                return searcher.SearchInsurance(Condition);
            }
        }
    }
 public override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts)
 {
     return new SimpleAutomatonTermsEnum(this, terms.Iterator(null));
 }
Exemple #60
0
 public BloomFilteredTerms(Terms terms, FuzzySet filter)
 {
     _delegateTerms = terms;
     _filter        = filter;
 }