private static void InitPowerUps()
 {
     powerUps = new PowerUp[3];
     powerUps[0] = new AdditionalMove();
     powerUps[1] = new Expand();
     powerUps[2] = new Extend();
 }
 public ForecastIORequest(string apiKey, float latF, float longF, Unit unit, Extend[] extend = null, Exclude[] exclude = null)
 {
     _apiKey = apiKey;
     _latitude = latF.ToString(CultureInfo.InvariantCulture);
     _longitude = longF.ToString(CultureInfo.InvariantCulture);
     _unit = Enum.GetName(typeof(Unit), unit);
     _extend = (extend != null) ? RequestHelpers.FormatExtendString(extend) : "";
     _exclude = (exclude != null) ? RequestHelpers.FormatExcludeString(exclude) : "";
 }
 public ForecastIORequest(string _apiKey, float _lat, float _long, Unit _unit, Extend[] _extend = null, Exclude[] _exclude = null)
 {
     apiKey = _apiKey;
     latitude = _lat.ToString(CultureInfo.InvariantCulture);
     longitude = _long.ToString(CultureInfo.InvariantCulture);
     unit = Enum.GetName(typeof(Unit), _unit);
     extend = (_extend != null) ? RequestHelpers.FormatExtendString(_extend) : "";
     exclude = (_exclude != null) ? RequestHelpers.FormatExcludeString(_exclude) : "";
 }
 public ForecastIORequest(string apiKey, float latF, float longF, DateTime time, Unit unit, Language? lang = null, Extend[] extend = null, Exclude[] exclude = null)
 {
     _apiKey = apiKey;
     _latitude = latF.ToString(CultureInfo.InvariantCulture);
     _longitude = longF.ToString(CultureInfo.InvariantCulture);
     _time = time.ToUTCString();
     _unit = Enum.GetName(typeof(Unit), unit);
     _extend = (extend != null) ? RequestHelpers.FormatExtendString(extend) : "";
     _exclude = (exclude != null) ? RequestHelpers.FormatExcludeString(exclude) : "";
     _lang = (lang != null) ? RequestHelpers.FormatLanguageEnum(lang) : Language.en.ToString();
 }
Beispiel #5
0
 public static extern Status cairo_pattern_set_extend (IntPtr pattern, Extend extend);
		internal static extern void cairo_pattern_set_extend (IntPtr pattern, Extend extend);
Beispiel #7
0
 public Extender(Selector baseSelector, Extend extend) : this(baseSelector)
 {
     Extend = extend;
 }
Beispiel #8
0
        /// <summary>
        /// Optimises BGPs in the Algebra to use Filter() and Extend() rather than the embedded FILTER and BIND
        /// </summary>
        /// <param name="algebra">Algebra to optimise</param>
        /// <returns></returns>
        public ISparqlAlgebra Optimise(ISparqlAlgebra algebra)
        {
            if (algebra is IAbstractJoin)
            {
                return(((IAbstractJoin)algebra).Transform(this));
            }
            else if (algebra is IUnaryOperator)
            {
                return(((IUnaryOperator)algebra).Transform(this));
            }
            else if (algebra is IBgp)
            {
                //Don't integerfer with other optimisers which have added custom BGP implementations
                if (!(algebra is Bgp))
                {
                    return(algebra);
                }

                IBgp current = (IBgp)algebra;
                if (current.PatternCount == 0)
                {
                    return(current);
                }
                else
                {
                    ISparqlAlgebra        result   = new Bgp();
                    List <ITriplePattern> patterns = new List <ITriplePattern>();
                    List <ITriplePattern> ps       = new List <ITriplePattern>(current.TriplePatterns.ToList());
                    for (int i = 0; i < current.PatternCount; i++)
                    {
                        //Can't split the BGP if there are Blank Nodes present
                        if (!ps[i].HasNoBlankVariables)
                        {
                            return(current);
                        }

                        if (!(ps[i] is TriplePattern))
                        {
                            //First ensure that if we've found any other Triple Patterns up to this point
                            //we dump this into a BGP and join with the result so far
                            if (patterns.Count > 0)
                            {
                                result = Join.CreateJoin(result, new Bgp(patterns));
                                patterns.Clear();
                            }

                            //Then generate the appropriate strict algebra operator
                            if (ps[i] is FilterPattern)
                            {
                                result = new Filter(result, ((FilterPattern)ps[i]).Filter);
                            }
                            else if (ps[i] is BindPattern)
                            {
                                BindPattern bind = (BindPattern)ps[i];
                                result = new Extend(result, bind.AssignExpression, bind.VariableName);
                            }
                            else if (ps[i] is LetPattern)
                            {
                                LetPattern let = (LetPattern)ps[i];
                                result = new Extend(result, let.AssignExpression, let.VariableName);
                            }
                            else if (ps[i] is SubQueryPattern)
                            {
                                SubQueryPattern sq = (SubQueryPattern)ps[i];
                                result = Join.CreateJoin(result, new SubQuery(sq.SubQuery));
                            }
                            else if (ps[i] is PropertyPathPattern)
                            {
                                PropertyPathPattern pp = (PropertyPathPattern)ps[i];
                                result = Join.CreateJoin(result, new PropertyPath(pp.Subject, pp.Path, pp.Object));
                            }
                        }
                        else
                        {
                            patterns.Add(ps[i]);
                        }
                    }

                    if (patterns.Count == current.PatternCount)
                    {
                        //If count of remaining patterns same as original pattern count there was no optimisation
                        //to do so return as is
                        return(current);
                    }
                    else if (patterns.Count > 0)
                    {
                        //If any patterns left at end join as a BGP with result so far
                        result = Join.CreateJoin(result, new Bgp(patterns));
                        return(result);
                    }
                    else
                    {
                        return(result);
                    }
                }
            }
            else if (algebra is ITerminalOperator)
            {
                return(algebra);
            }
            else
            {
                return(algebra);
            }
        }
        internal void FromRun(Run r)
        {
            this.SetAllNull();

            using (OpenXmlReader oxr = OpenXmlReader.Create(r))
            {
                while (oxr.Read())
                {
                    if (oxr.ElementType == typeof(Text))
                    {
                        this.Text = ((Text)oxr.LoadCurrentElement()).Text;
                    }
                    else if (oxr.ElementType == typeof(RunFont))
                    {
                        RunFont rft = (RunFont)oxr.LoadCurrentElement();
                        if (rft.Val != null)
                        {
                            this.Font.FontName = rft.Val.Value;
                        }
                    }
                    else if (oxr.ElementType == typeof(RunPropertyCharSet))
                    {
                        RunPropertyCharSet rpcs = (RunPropertyCharSet)oxr.LoadCurrentElement();
                        if (rpcs.Val != null)
                        {
                            this.Font.CharacterSet = rpcs.Val.Value;
                        }
                    }
                    else if (oxr.ElementType == typeof(FontFamily))
                    {
                        FontFamily ff = (FontFamily)oxr.LoadCurrentElement();
                        if (ff.Val != null)
                        {
                            this.Font.FontFamily = ff.Val.Value;
                        }
                    }
                    else if (oxr.ElementType == typeof(Bold))
                    {
                        Bold b = (Bold)oxr.LoadCurrentElement();
                        if (b.Val != null)
                        {
                            this.Font.Bold = b.Val.Value;
                        }
                        else
                        {
                            this.Font.Bold = true;
                        }
                    }
                    else if (oxr.ElementType == typeof(Italic))
                    {
                        Italic itlc = (Italic)oxr.LoadCurrentElement();
                        if (itlc.Val != null)
                        {
                            this.Font.Italic = itlc.Val.Value;
                        }
                        else
                        {
                            this.Font.Italic = true;
                        }
                    }
                    else if (oxr.ElementType == typeof(Strike))
                    {
                        Strike strk = (Strike)oxr.LoadCurrentElement();
                        if (strk.Val != null)
                        {
                            this.Font.Strike = strk.Val.Value;
                        }
                        else
                        {
                            this.Font.Strike = true;
                        }
                    }
                    else if (oxr.ElementType == typeof(Outline))
                    {
                        Outline outln = (Outline)oxr.LoadCurrentElement();
                        if (outln.Val != null)
                        {
                            this.Font.Outline = outln.Val.Value;
                        }
                        else
                        {
                            this.Font.Outline = true;
                        }
                    }
                    else if (oxr.ElementType == typeof(Shadow))
                    {
                        Shadow shdw = (Shadow)oxr.LoadCurrentElement();
                        if (shdw.Val != null)
                        {
                            this.Font.Shadow = shdw.Val.Value;
                        }
                        else
                        {
                            this.Font.Shadow = true;
                        }
                    }
                    else if (oxr.ElementType == typeof(Condense))
                    {
                        Condense cdns = (Condense)oxr.LoadCurrentElement();
                        if (cdns.Val != null)
                        {
                            this.Font.Condense = cdns.Val.Value;
                        }
                        else
                        {
                            this.Font.Condense = true;
                        }
                    }
                    else if (oxr.ElementType == typeof(Extend))
                    {
                        Extend ext = (Extend)oxr.LoadCurrentElement();
                        if (ext.Val != null)
                        {
                            this.Font.Extend = ext.Val.Value;
                        }
                        else
                        {
                            this.Font.Extend = true;
                        }
                    }
                    else if (oxr.ElementType == typeof(Color))
                    {
                        this.Font.clrFontColor.FromSpreadsheetColor((Color)oxr.LoadCurrentElement());
                        this.Font.HasFontColor = !this.Font.clrFontColor.IsEmpty();
                    }
                    else if (oxr.ElementType == typeof(FontSize))
                    {
                        FontSize ftsz = (FontSize)oxr.LoadCurrentElement();
                        if (ftsz.Val != null)
                        {
                            this.Font.FontSize = ftsz.Val.Value;
                        }
                    }
                    else if (oxr.ElementType == typeof(Underline))
                    {
                        Underline und = (Underline)oxr.LoadCurrentElement();
                        if (und.Val != null)
                        {
                            this.Font.Underline = und.Val.Value;
                        }
                        else
                        {
                            this.Font.Underline = UnderlineValues.Single;
                        }
                    }
                    else if (oxr.ElementType == typeof(VerticalTextAlignment))
                    {
                        VerticalTextAlignment vta = (VerticalTextAlignment)oxr.LoadCurrentElement();
                        if (vta.Val != null)
                        {
                            this.Font.VerticalAlignment = vta.Val.Value;
                        }
                    }
                    else if (oxr.ElementType == typeof(FontScheme))
                    {
                        FontScheme ftsch = (FontScheme)oxr.LoadCurrentElement();
                        if (ftsch.Val != null)
                        {
                            this.Font.FontScheme = ftsch.Val.Value;
                        }
                    }
                }
            }
        }
Beispiel #10
0
 /// <summary>
 /// Processes an Extend
 /// </summary>
 /// <param name="extend">Extend</param>
 /// <param name="context">SPARQL Evaluation Context</param>
 public override BaseMultiset ProcessExtend(Extend extend, SparqlEvaluationContext context)
 {
     return(this.ExplainAndEvaluate <Extend>(extend, context, base.ProcessExtend));
 }
Beispiel #11
0
 public static bool HasFamily(System.IO.Stream stream, string family)
 {
     return(Noesis_HasFamily(Extend.GetInstanceHandle(stream).Handle, family));
 }
        public static MetricOrgValue List(int ValueCount, DateTime BaseDate, Guid ScoreCardMetricID, MetricTrac.Bll.ScoreCardMetric.CalcStringFormula Calculator)
        {
            LinqMicajahDataContext dc = new LinqMicajahDataContext();
            var r = from cm in dc.ScoreCardMetric
                    join _m in dc.Metric on new { LinqMicajahDataContext.InstanceId, cm.MetricID, Status = (bool?)true } equals new { _m.InstanceId, MetricID = (Guid?)_m.MetricID, _m.Status } into __m
            join o in dc.ViewnameOrgLocation on new { InstanceId = (Guid?)cm.InstanceId, cm.OrgLocationID } equals new { o.InstanceId, o.OrgLocationID }
            join _u in dc.MetricOrgLocationUoM on new { LinqMicajahDataContext.InstanceId, cm.MetricID, cm.OrgLocationID } equals new { _u.InstanceId, MetricID = (Guid?)_u.MetricID, OrgLocationID = (Guid?)_u.OrgLocationID } into __u
            join _pi in dc.PerformanceIndicator on new { LinqMicajahDataContext.InstanceId, cm.PerformanceIndicatorId, Status = (bool?)true } equals new { _pi.InstanceId, PerformanceIndicatorId = (Guid?)_pi.PerformanceIndicatorID, _pi.Status } into __pi

            from m in __m.DefaultIfEmpty()
            from u in __u.DefaultIfEmpty()
            from pi in __pi.DefaultIfEmpty()

            where cm.InstanceId == LinqMicajahDataContext.InstanceId && cm.ScoreCardMetricID == ScoreCardMetricID && cm.Status == true
                select new MetricOrgValue
            {
                Name = cm.MetricID == null ? pi.Name : m.Name,
                OrgLocationFullName    = o.FullName,
                MetricID               = cm.MetricID == null ? Guid.Empty : (Guid)cm.MetricID,
                OrgLocationID          = cm.OrgLocationID == null ? Guid.Empty : (Guid)cm.OrgLocationID,                     //o.EntityNodeId, !!!! TODO fix this
                FrequencyID            = m.MetricID == null ? 3 : m.FrequencyID,
                InputUnitOfMeasureID   = u.MetricOrgLocationUoMID == null ? m.InputUnitOfMeasureID : u.InputUnitOfMeasureID, //u.InputUnitOfMeasureID == null ? m.InputUnitOfMeasureID : u.InputUnitOfMeasureID,
                UnitOfMeasureID        = cm.MetricID == null ? pi.UnitOfMeasureID : m.UnitOfMeasureID,
                NODecPlaces            = m.NODecPlaces,
                PerformanceIndicatorID = cm.PerformanceIndicatorId == null || pi.PerformanceIndicatorID == Guid.Empty ? null : (Guid?)pi.PerformanceIndicatorID
            };
            var mo = r.FirstOrNull();

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

            DateTime EndDate = Frequency.GetNormalizedDate(mo.FrequencyID, BaseDate);


            ScoreCardMetric.Extend e = new ScoreCardMetric.Extend()
            {
                InstanceId             = LinqMicajahDataContext.InstanceId,
                ScoreCardMetricID      = ScoreCardMetricID,
                MetricID               = mo.MetricID,
                OrgLocationID          = mo.OrgLocationID,
                ScoreCardPeriodID      = 1,
                MetricFrequencyID      = mo.FrequencyID,
                PerformanceIndicatorId = mo.PerformanceIndicatorID,
                UomID = mo.UnitOfMeasureID
            };

            mo.MetricValues = new List <Extend>();
            for (int i = ValueCount - 1; i >= 0; i--)
            {
                DateTime dtBegin = Frequency.AddPeriod(EndDate, mo.FrequencyID, -i);
                DateTime dtEnd   = Frequency.AddPeriod(dtBegin, mo.FrequencyID, 1);
                if (e.MetricID != null && e.MetricID != Guid.Empty)
                {
                    e.CurrentValue = ScoreCardMetric.CalculateTotalValue(dc, LinqMicajahDataContext.OrganizationId, LinqMicajahDataContext.InstanceId, (Guid)e.MetricID, e.OrgLocationID, e.UomID, dtBegin, dtEnd, true, ScoreCardMetric.enTotalValueType.Sum, false);
                }
                else if (e.PerformanceIndicatorId != null)
                {
                    var    f = PerformanceIndicator.GetFormulasWithRealValues(dc, dtBegin, dtEnd, (new Guid[] { e.OrgLocationID == null ? Guid.Empty : (Guid)e.OrgLocationID }).ToList(), (Guid)e.PerformanceIndicatorId, e.UomID == null?Guid.Empty:(Guid)e.UomID);
                    double v = Calculator(f);
                    if (v != 0)
                    {
                        e.CurrentValue = v;
                    }
                    //e.PerformanceIndicatorId;
                }

                Extend mv = new Extend()
                {
                    InstanceId           = mo.InstanceId,
                    MetricID             = mo.MetricID,
                    FrequencyID          = mo.FrequencyID,
                    Date                 = dtBegin,
                    UnitOfMeasureID      = e.UomID,
                    InputUnitOfMeasureID = e.UomID,
                    MetricDataTypeID     = 1,
                    DValue               = e.CurrentValue,
                    OrgLocationID        = mo.OrgLocationID,
                    Period               = Frequency.GetPeriodName(dtBegin, mo.FrequencyID, true)
                };

                mo.MetricValues.Add(mv);
                mo.UnitOfMeasureID = e.UomID;
            }
            return(mo);
        }
Beispiel #13
0
        public JsonResult WeChatMobileChange(string SECURITYKEY, string pushparam)
        {
            ExecutionResult result = new ExecutionResult();

            try
            {
                if (API_Authentication(SECURITYKEY))
                {
                    string             accessToken   = Common.WeChatPush.WeChatTools.GetAccessoken(true);
                    U_WeChatRegistered user          = Extend.JsonToModel <U_WeChatRegistered>(pushparam);
                    UserInfoLogic      userInfoLogic = new UserInfoLogic();
                    var muser = userInfoLogic.GetPerson(user.idcard);
                    if (muser != null)
                    {
                        userInfoLogic.UpdatePhoneNumber(muser.UserID, user.mobile);
                        //userInfoLogic.DeleteUserInfo(new string[] { muser.Vguid.ToString() });
                        string pushResult   = WeChatTools.DeleteUser(accessToken, muser.UserID);
                        var    wechatResult = Extend.JsonToModel <U_WechatResult>(pushResult);
                        if (wechatResult.errcode != "0")
                        {
                            result.Message = pushResult;
                        }
                        else
                        {
                            UserInfoLogic logic       = new UserInfoLogic();
                            var           allTrainers = logic.GetTrainers(user);
                            if (allTrainers != null)
                            {
                                user.userid = allTrainers.IDCard;
                                user.name   = allTrainers.Name;
                                user.gender = allTrainers.Gender.ToString();
                                //string pushResult = WeChatTools.WeChatMobileChange(accessToken, muser.UserID, user.mobile);

                                pushResult   = WeChatTools.CreateUser(accessToken, user);
                                wechatResult = Extend.JsonToModel <U_WechatResult>(pushResult);
                                if (wechatResult.errcode == "0")
                                {
                                    logic.UpdateTrainers(user);
                                    result.Success = true;
                                }
                                result.Message = pushResult;
                            }
                            else
                            {
                                result.Message = string.Format("该身份证号码:{0} 用户在培训注册表中不存在!", user.idcard);
                            }
                        }
                    }
                    else
                    {
                        result.Message = string.Format("该身份证号码:{0} 用户不存在", user.idcard);
                    }
                }
                else
                {
                    result.Message = "SECURITYKEY 无效!";
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
                LogHelper.WriteLog(ex.Message);
            }
            ExecHistry("WeChatRegistered", pushparam, JsonHelper.ModelToJson(result));
            return(Json(result));
        }
Beispiel #14
0
        /// <summary>
        /// Optimises the algebra so that all Node terms are virtualised
        /// </summary>
        /// <param name="algebra">Algebra</param>
        /// <returns></returns>
        public ISparqlAlgebra Optimise(ISparqlAlgebra algebra)
        {
            if (algebra is IAbstractJoin)
            {
                return(((IAbstractJoin)algebra).Transform(this));
            }
            else if (algebra is IUnaryOperator)
            {
                return(((IUnaryOperator)algebra).Transform(this));
            }
            else if (algebra is IBgp)
            {
                IBgp current = (IBgp)algebra;
                if (current.PatternCount == 0)
                {
                    return(current);
                }
                else
                {
                    ISparqlAlgebra        result   = new Bgp();
                    List <ITriplePattern> patterns = new List <ITriplePattern>();
                    List <ITriplePattern> ps       = new List <ITriplePattern>(current.TriplePatterns.ToList());
                    TNodeID nullID = this._provider.NullID;

                    for (int i = 0; i < current.PatternCount; i++)
                    {
                        if (ps[i] is FilterPattern || ps[i] is BindPattern)
                        {
                            //First ensure that if we've found any other Triple Patterns up to this point
                            //we dump this into a BGP and join with the result so far
                            if (patterns.Count > 0)
                            {
                                result = Join.CreateJoin(result, new Bgp(patterns));
                                patterns.Clear();
                            }
                            if (ps[i] is FilterPattern)
                            {
                                result = new Filter(result, ((FilterPattern)ps[i]).Filter);
                            }
                            else
                            {
                                BindPattern bind = (BindPattern)ps[i];
                                result = new Extend(result, bind.AssignExpression, bind.VariableName);
                            }
                        }
                        else
                        {
                            //Convert Terms in the Pattern into Virtual Nodes
                            TriplePattern tp = (TriplePattern)ps[i];
                            PatternItem   subj, pred, obj;
                            if (tp.Subject is NodeMatchPattern)
                            {
                                TNodeID id = this._provider.GetID(((NodeMatchPattern)tp.Subject).Node);
                                if (id == null || id.Equals(nullID))
                                {
                                    result = new NullOperator(current.Variables);
                                    break;
                                }
                                else
                                {
                                    subj = new NodeMatchPattern(this.CreateVirtualNode(id, ((NodeMatchPattern)tp.Subject).Node));
                                }
                            }
                            else
                            {
                                subj = tp.Subject;
                            }
                            if (tp.Predicate is NodeMatchPattern)
                            {
                                TNodeID id = this._provider.GetID(((NodeMatchPattern)tp.Predicate).Node);
                                if (id == null || id.Equals(nullID))
                                {
                                    result = new NullOperator(current.Variables);
                                    break;
                                }
                                else
                                {
                                    pred = new NodeMatchPattern(this.CreateVirtualNode(id, ((NodeMatchPattern)tp.Predicate).Node));
                                }
                            }
                            else
                            {
                                pred = tp.Predicate;
                            }
                            if (tp.Object is NodeMatchPattern)
                            {
                                TNodeID id = this._provider.GetID(((NodeMatchPattern)tp.Object).Node);
                                if (id == null || id.Equals(nullID))
                                {
                                    result = new NullOperator(current.Variables);
                                    break;
                                }
                                else
                                {
                                    obj = new NodeMatchPattern(this.CreateVirtualNode(id, ((NodeMatchPattern)tp.Object).Node));
                                }
                            }
                            else
                            {
                                obj = tp.Object;
                            }
                            patterns.Add(new TriplePattern(subj, pred, obj));
                        }
                    }

                    if (result is NullOperator)
                    {
                        return(result);
                    }
                    else if (patterns.Count == current.PatternCount)
                    {
                        //If count of remaining patterns same as original pattern count there was no optimisation
                        //to do so return as is
                        return(current);
                    }
                    else if (patterns.Count > 0)
                    {
                        //If any patterns left at end join as a BGP with result so far
                        result = Join.CreateJoin(result, new Bgp(patterns));
                        return(result);
                    }
                    else
                    {
                        return(result);
                    }
                }
            }
            else if (algebra is ITerminalOperator)
            {
                return(algebra);
            }
            else
            {
                return(algebra);
            }
        }
Beispiel #15
0
        public JsonResult WeChatRegistered(string SECURITYKEY, string pushparam)
        {
            ExecutionResult result = new ExecutionResult();

            try
            {
                if (API_Authentication(SECURITYKEY))
                {
                    //if (!APICount())
                    //{
                    //    result.Message = "删除微信官方通讯录次数已经用完!";
                    //}
                    //else
                    //{

                    string             accessToken = WeChatTools.GetAccessoken(true);
                    U_WeChatRegistered user        = Extend.JsonToModel <U_WeChatRegistered>(pushparam);

                    string pushResult   = WeChatTools.CreateUser(accessToken, user);
                    var    wechatResult = Extend.JsonToModel <U_WechatResult>(pushResult);
                    if (wechatResult.errcode == "0")
                    {
                        UserInfoLogic logic = new UserInfoLogic();
                        logic.InsertTrainers(user);
                        result.Success = true;
                    }
                    result.Message = pushResult;


                    //string accessToken = WeChatTools.GetAccessoken(true);
                    //U_WeChatRegistered user = Extend.JsonToModel<U_WeChatRegistered>(pushparam);
                    //var wResult = WeChatTools.GetUserInfoByUserID(accessToken, user.idcard);
                    //var wechatResult = Extend.JsonToModel<U_WechatResult>(wResult);
                    //if (wechatResult.errcode == "0")
                    //{
                    //    WeChatTools.DeleteUser(accessToken, user.idcard);
                    //}
                    //wResult = WeChatTools.GetUserId(accessToken, user.mobile);
                    //Dictionary<string, string> dicReuslt = Extend.JsonToModel<Dictionary<string, string>>(wResult);
                    //if (dicReuslt["errcode"] == "0")
                    //{
                    //    string userid = dicReuslt["userid"];
                    //    WeChatTools.DeleteUser(accessToken, userid);
                    //}

                    //string pushResult = WeChatTools.CreateUser(accessToken, user);
                    //wechatResult = Extend.JsonToModel<U_WechatResult>(pushResult);
                    //if (wechatResult.errcode == "0")
                    //{
                    //    UserInfoLogic logic = new UserInfoLogic();
                    //    logic.InsertTrainers(user);
                    //    result.Success = true;
                    //}
                    //result.Message = pushResult;
                    //}
                }
                else
                {
                    result.Message = "SECURITYKEY 无效!";
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
                LogHelper.WriteLog(ex.Message);
            }
            ExecHistry("WeChatRegistered", pushparam, JsonHelper.ModelToJson(result));
            return(Json(result));
        }
Beispiel #16
0
        public JsonResult WeChatRegistrationVerification(string SECURITYKEY, string pushparam)
        {
            ExecutionResult result = new ExecutionResult();

            try
            {
                if (API_Authentication(SECURITYKEY))
                {
                    U_WeChatRegistered  user        = Extend.JsonToModel <U_WeChatRegistered>(pushparam);
                    string              accessToken = WeChatTools.GetAccessoken(true);
                    string              pushResult  = WeChatTools.GetUserInfo(accessToken);
                    U_WechatUsersResult usersResult = Extend.JsonToModel <U_WechatUsersResult>(pushResult);

                    var fuser = usersResult.userlist.Find(c => c.userid == c.mobile && c.mobile == user.mobile);
                    if (fuser != null)
                    {
                        result.Success = true;
                        result.Message = string.Format("存在微信USERID为{0},手机号码为{1}的用户!", fuser.userid, fuser.mobile);
                        result.Result  = 1;//USERID为手机号,手机号一致
                        return(Json(result));
                    }
                    fuser = usersResult.userlist.Find(c => c.userid == user.idcard && c.mobile == user.mobile);
                    if (fuser != null)
                    {
                        result.Success = true;
                        result.Message = string.Format("存在微信USERID为{0},手机号码为{1}的用户!", fuser.userid, fuser.mobile);
                        result.Result  = 2;//USERID为身份证号,手机号一致
                        return(Json(result));
                    }
                    fuser = usersResult.userlist.Find(c => c.userid == user.mobile);
                    if (fuser != null)
                    {
                        result.Success = true;
                        result.Message = string.Format("存在微信USERID为{0},手机号码为{1}的用户!", fuser.userid, fuser.mobile);
                        result.Result  = 3;//USERID为手机号,手机号不一致
                        return(Json(result));
                    }
                    fuser = usersResult.userlist.Find(c => c.userid == user.idcard);
                    if (fuser != null)
                    {
                        result.Success = true;
                        result.Message = string.Format("存在微信USERID为{0},手机号码为{1}的用户!", fuser.userid, fuser.mobile);
                        result.Result  = 4;//USERID为身份证号,手机号不一致
                        return(Json(result));
                    }
                    fuser = usersResult.userlist.Find(c => c.mobile == user.mobile);
                    if (fuser != null)
                    {
                        result.Success = true;
                        result.Message = string.Format("存在微信USERID为{0},手机号码为{1}的用户!", fuser.userid, fuser.mobile);
                        result.Result  = 5;//手机号一致,USERID不一致
                        return(Json(result));
                    }
                    result.Success = true;
                    result.Message = "微信不存在该用户!";
                    result.Result  = 0;//
                    return(Json(result));
                }
            }

            catch (Exception ex)
            {
                result.Message = ex.Message;
                LogHelper.WriteLog(ex.Message);
            }
            return(Json(result));
        }
Beispiel #17
0
        public JsonResult TextPush(string SECURITYKEY, string pushparam)
        {
            ExecutionResult result = new ExecutionResult();

            try
            {
                if (API_Authentication(SECURITYKEY))
                {
                    PushParamModel textPush = Extend.JsonToModel <PushParamModel>(pushparam);
                    U_PushMsg      pushMsg  = new U_PushMsg();
                    pushMsg.VGUID            = Guid.NewGuid();
                    pushMsg.PushType         = 1;
                    pushMsg.MessageType      = 1;
                    pushMsg.Title            = textPush.Title;
                    pushMsg.Message          = textPush.Message;
                    pushMsg.PushPeople       = textPush.founder;
                    pushMsg.CreatedUser      = "******";
                    pushMsg.CreatedDate      = DateTime.Now;
                    pushMsg.PeriodOfValidity = DateTime.Now.AddMonths(1);
                    UserInfoLogic userInfoLogic = new UserInfoLogic();
                    if (textPush.PushPeople.Count == 0)
                    {
                        result.Message = "推送人员不能为空!";
                        ExecHistry("TextPush", pushparam, JsonHelper.ModelToJson(result));
                        return(Json(result));
                    }
                    foreach (string item in textPush.PushPeople)
                    {
                        var user = userInfoLogic.GetPerson(item);
                        if (user != null && user.UserID != null && user.UserID != "")
                        {
                            pushMsg.PushPeople += user.UserID + "|";
                            pushMsg.PushObject += user.UserID + "|";
                        }
                        else
                        {
                            result.Message += item + "|";
                        }
                    }
                    if (!string.IsNullOrEmpty(result.Message))
                    {
                        result.Message = result.Message.Remove(result.Message.Length - 1, 1);
                        result.Message = "不存在身份证号码:" + result.Message;
                        ExecHistry("TextPush", pushparam, JsonHelper.ModelToJson(result));
                        return(Json(result));
                    }
                    DraftInfoLogic logic = new DraftInfoLogic();
                    Guid           vguid = Guid.Empty;
                    result.Success = logic.APISavePushMsg(pushMsg);
                    result.Result  = new { Uniquekey = pushMsg.VGUID };
                }
                else
                {
                    result.Message = "SECURITYKEY 无效!";
                }
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
                LogHelper.WriteLog(ex.Message);
            }
            ExecHistry("TextPush", pushparam, JsonHelper.ModelToJson(result));
            return(Json(result));
        }
Beispiel #18
0
        public override async Task <MoeItems> GetRealPageImagesAsync(SearchPara para, CancellationToken token)
        {
            Net = Net == null ? new NetOperator(Settings, HomeUrl) : Net.CloneWithOldCookie();

            if (!IsLogin)
            {
                Extend.ShowMessage("MiniTokyo 正在自动登录中……", null, Extend.MessagePos.Searching);
                var accIndex = new Random().Next(0, _user.Length);
                var content  = new FormUrlEncodedContent(new Pairs
                {
                    { "username", _user[accIndex] },
                    { "password", _pass[accIndex] }
                });
                var p = await Net.Client.PostAsync("http://my.minitokyo.net/login", content, token);

                if (p.IsSuccessStatusCode)
                {
                    IsLogin = true;
                }
            }

            var    imgs = new MoeItems();
            string query;

            if (para.Keyword.IsEmpty()) // by new
            {
                // recent:
                // wall http://gallery.minitokyo.net/wallpapers?display=thumbnails&order=id&page=2
                // mobile http://gallery.minitokyo.net/mobile?order=id&display=thumbnails&page=2
                // indy http://gallery.minitokyo.net/indy-art?order=id&display=thumbnails&page=2
                // scan  http://gallery.minitokyo.net/scans?order=id&display=thumbnails&page=2

                // popular
                // wall http://gallery.minitokyo.net/wallpapers?order=favorites&display=thumbnails&page=2
                // scan http://gallery.minitokyo.net/scans?display=thumbnails&order=favorites&page=2
                query = $"{HomeGalleryUrl}/{GetSort(para)}?order={GetOrder(para)}&display=thumbnails&page={para.PageIndex}";
            }
            else
            {
                var q   = $"{HomeUrl}/search?q={para.Keyword}";
                var net = Net.CloneWithOldCookie();
                net.SetReferer(HomeUrl);
                net.HttpClientHandler.AllowAutoRedirect = false;
                var res = await net.Client.GetAsync(q, token);

                var loc303 = res.Headers.Location.OriginalString;
                var net2   = Net.CloneWithOldCookie();
                var doc1   = await net2.GetHtmlAsync($"{HomeUrl}{loc303}", token);

                var tabnodes = doc1.DocumentNode.SelectNodes("*//ul[@id='tabs']//a");
                var url      = tabnodes[1].Attributes["href"]?.Value;
                var reg      = new Regex(@"(?:^|\?|&)tid=(\d*)(?:&|$)");
                var tid      = reg.Match(url ?? "").Groups[0].Value;
                var indexs   = new [] { 1, 3, 1, 2 };
                query = $"{HomeBrowseUrl}/gallery{tid}index={indexs[para.SubMenuIndex]}&order={GetOrder(para)}&display=thumbnails";
            }

            var doc = await Net.GetHtmlAsync(query, token);

            var docnode = doc.DocumentNode;
            var empty   = docnode.SelectSingleNode("*//p[@class='empty']")?.InnerText.ToLower().Trim();

            if (empty == "no items to display")
            {
                return(imgs);
            }
            var wallNode = docnode.SelectSingleNode("*//ul[@class='scans']");
            var imgNodes = wallNode.SelectNodes(".//li");

            if (imgNodes == null)
            {
                return(imgs);
            }

            foreach (var node in imgNodes)
            {
                var img       = new MoeItem(this, para);
                var detailUrl = node.SelectSingleNode("a").Attributes["href"].Value;
                img.DetailUrl = detailUrl;
                img.Id        = detailUrl.Substring(detailUrl.LastIndexOf('/') + 1).ToInt();
                var imgHref   = node.SelectSingleNode(".//img");
                var sampleUrl = imgHref.Attributes["src"].Value;
                img.Urls.Add(1, sampleUrl, HomeUrl);
                //http://static2.minitokyo.net/thumbs/24/25/583774.jpg preview
                //http://static2.minitokyo.net/view/24/25/583774.jpg   sample
                //http://static.minitokyo.net/downloads/24/25/583774.jpg   full
                const string api2       = "http://static2.minitokyo.net";
                const string api        = "http://static.minitokyo.net";
                var          previewUrl = $"{api2}/view{sampleUrl.Substring(sampleUrl.IndexOf('/', sampleUrl.IndexOf(".net/", StringComparison.Ordinal) + 5))}";
                var          fileUrl    = $"{api}/downloads{previewUrl.Substring(previewUrl.IndexOf('/', previewUrl.IndexOf(".net/", StringComparison.Ordinal) + 5))}";
                img.Urls.Add(4, fileUrl, HomeUrl);
                img.Title    = node.SelectSingleNode("./p/a").InnerText.Trim();
                img.Uploader = node.SelectSingleNode("./p").InnerText.Delete("by ").Trim();
                var res  = node.SelectSingleNode("./a/img").Attributes["title"].Value;
                var resi = res?.Split('x');
                if (resi?.Length == 2)
                {
                    img.Width  = resi[0].ToInt();
                    img.Height = resi[1].ToInt();
                }
                img.OriginString = node.OuterHtml;
                imgs.Add(img);
            }
            token.ThrowIfCancellationRequested();
            return(imgs);
        }
Beispiel #19
0
        public static void InsertOrUpdate(Extend DataRule)
        {
            using (LinqMicajahDataContext dc = new LinqMicajahDataContext())
            {
                DataRule dr =(from r in dc.DataRule
                             where
                                r.InstanceId == LinqMicajahDataContext.InstanceId &&
                                r.DataRuleID == DataRule.DataRuleID
                             select r).FirstOrNull();
                bool InsertMode = (dr == null);
                Guid DataRuleID = DataRule.DataRuleID;
                if (dr == null)
                {
                    DataRule NewRule = new DataRule();
                    NewRule.DataRuleID = DataRuleID = Guid.NewGuid();
                    NewRule.Description = DataRule.Description;
                    NewRule.UserId = DataRule.UserId;
                    NewRule.GroupId = DataRule.GroupId;
                    NewRule.DataRuleTypeID = DataRule.DataRuleTypeID;
                    NewRule.GroupCategoryAspectID = DataRule.GroupCategoryAspectID;
                    dc.DataRule.InsertOnSubmit(NewRule);
                }
                else
                {                    
                    dr.Description = DataRule.Description;
                    dr.UserId = DataRule.UserId;
                    dr.GroupId = DataRule.GroupId;
                    dr.GroupCategoryAspectID = DataRule.GroupCategoryAspectID;
                }
                dc.SubmitChanges();
                // save related entities
                if (!InsertMode)
                {
                    IQueryable<DataRuleOrgLocation> OldDataRuleOrgLocation
                        = from drol in dc.DataRuleOrgLocation
                          where drol.InstanceId == LinqMicajahDataContext.InstanceId && drol.DataRuleID == DataRuleID
                          select drol;

                    IQueryable<DataRulePerformanceIndicator> OldDataRulePerformanceIndicator
                        = from drpi in dc.DataRulePerformanceIndicator
                          where drpi.InstanceId == LinqMicajahDataContext.InstanceId && drpi.DataRuleID == DataRuleID
                          select drpi;
                    IQueryable<DataRuleMetric> OldDataRuleMetric
                        = from drm in dc.DataRuleMetric
                          where drm.InstanceId == LinqMicajahDataContext.InstanceId && drm.DataRuleID == DataRuleID
                          select drm;
                    dc.DataRuleOrgLocation.DeleteAllOnSubmit(OldDataRuleOrgLocation);
                    dc.DataRulePerformanceIndicator.DeleteAllOnSubmit(OldDataRulePerformanceIndicator);
                    dc.DataRuleMetric.DeleteAllOnSubmit(OldDataRuleMetric);
                    dc.SubmitChanges();
                }
                foreach (Guid? NewOrgLocationID in DataRule.DataRuleOrgLocation)
                {
                    DataRuleOrgLocation NewOrgLocation = new DataRuleOrgLocation();
                    NewOrgLocation.InstanceId = LinqMicajahDataContext.InstanceId;
                    NewOrgLocation.DataRuleID = DataRuleID;
                    NewOrgLocation.OrgLocationID = (Guid)NewOrgLocationID;
                    NewOrgLocation.DataRuleOrgLocationID = Guid.NewGuid();
                    dc.DataRuleOrgLocation.InsertOnSubmit(NewOrgLocation);
                }
                foreach (Guid? NewPIID in DataRule.DataRulePI)
                {
                    DataRulePerformanceIndicator NewOrgLocation = new DataRulePerformanceIndicator();
                    NewOrgLocation.InstanceId = LinqMicajahDataContext.InstanceId;
                    NewOrgLocation.DataRuleID = DataRuleID;
                    NewOrgLocation.PerformanceIndicatorID = (Guid)NewPIID;
                    NewOrgLocation.DataRulePerformanceIndicatorID = Guid.NewGuid();
                    dc.DataRulePerformanceIndicator.InsertOnSubmit(NewOrgLocation);
                }
                foreach (Guid? NewMetricID in DataRule.DataRuleMetric)
                {
                    DataRuleMetric NewOrgLocation = new DataRuleMetric();
                    NewOrgLocation.InstanceId = LinqMicajahDataContext.InstanceId;
                    NewOrgLocation.DataRuleID = DataRuleID;
                    NewOrgLocation.MetricID = (Guid)NewMetricID;
                    NewOrgLocation.DataRuleMetricID = Guid.NewGuid();
                    dc.DataRuleMetric.InsertOnSubmit(NewOrgLocation);
                }
                dc.SubmitChanges();
                UpdateD_DataRule(dc);
            }
            return;
        }
        private Selector GetSelector(IEnumerable <LessParser.SelectorElementContext> selectorElements, Extend extend = null)
        {
            IEnumerable <SelectorElement> GetElements()
            {
                foreach (var element in selectorElements)
                {
                    yield return((SelectorElement)element.Accept(this));
                }
            }

            return(new Selector(GetElements(), extend));
        }
Beispiel #21
0
        /// <summary>
        /// Optimises the algebra so that all Node terms are virtualised.
        /// </summary>
        /// <param name="algebra">Algebra.</param>
        /// <returns></returns>
        public ISparqlAlgebra Optimise(ISparqlAlgebra algebra)
        {
            if (algebra is IAbstractJoin)
            {
                return(((IAbstractJoin)algebra).Transform(this));
            }
            else if (algebra is IUnaryOperator)
            {
                return(((IUnaryOperator)algebra).Transform(this));
            }
            else if (algebra is IBgp)
            {
                IBgp current = (IBgp)algebra;
                if (current.PatternCount == 0)
                {
                    return(current);
                }
                else
                {
                    ISparqlAlgebra        result   = new Bgp();
                    List <ITriplePattern> patterns = new List <ITriplePattern>();
                    List <ITriplePattern> ps       = new List <ITriplePattern>(current.TriplePatterns.ToList());
                    TNodeID nullID = _provider.NullID;

                    for (int i = 0; i < current.PatternCount; i++)
                    {
                        if (ps[i].PatternType == TriplePatternType.Filter || ps[i].PatternType == TriplePatternType.BindAssignment || ps[i].PatternType == TriplePatternType.LetAssignment)
                        {
                            // First ensure that if we've found any other Triple Patterns up to this point
                            // we dump this into a BGP and join with the result so far
                            if (patterns.Count > 0)
                            {
                                result = Join.CreateJoin(result, new Bgp(patterns));
                                patterns.Clear();
                            }
                            if (ps[i].PatternType == TriplePatternType.Filter)
                            {
                                result = new Filter(result, new UnaryExpressionFilter(Transform(((IFilterPattern)ps[i]).Filter.Expression)));
                            }
                            else
                            {
                                IAssignmentPattern bind = (IAssignmentPattern)ps[i];
                                result = new Extend(result, Transform(bind.AssignExpression), bind.VariableName);
                            }
                        }
                        else if (ps[i].PatternType == TriplePatternType.Match)
                        {
                            // Convert Terms in the Pattern into Virtual Nodes
                            IMatchTriplePattern tp = (IMatchTriplePattern)ps[i];
                            PatternItem         subj, pred, obj;
                            if (tp.Subject is NodeMatchPattern)
                            {
                                TNodeID id = _provider.GetID(((NodeMatchPattern)tp.Subject).Node);
                                if (id == null || id.Equals(nullID))
                                {
                                    result = new NullOperator(current.Variables);
                                    break;
                                }
                                else
                                {
                                    subj = new NodeMatchPattern(CreateVirtualNode(id, ((NodeMatchPattern)tp.Subject).Node));
                                }
                            }
                            else
                            {
                                subj = tp.Subject;
                            }
                            if (tp.Predicate is NodeMatchPattern)
                            {
                                TNodeID id = _provider.GetID(((NodeMatchPattern)tp.Predicate).Node);
                                if (id == null || id.Equals(nullID))
                                {
                                    result = new NullOperator(current.Variables);
                                    break;
                                }
                                else
                                {
                                    pred = new NodeMatchPattern(CreateVirtualNode(id, ((NodeMatchPattern)tp.Predicate).Node));
                                }
                            }
                            else
                            {
                                pred = tp.Predicate;
                            }
                            if (tp.Object is NodeMatchPattern)
                            {
                                TNodeID id = _provider.GetID(((NodeMatchPattern)tp.Object).Node);
                                if (id == null || id.Equals(nullID))
                                {
                                    result = new NullOperator(current.Variables);
                                    break;
                                }
                                else
                                {
                                    obj = new NodeMatchPattern(CreateVirtualNode(id, ((NodeMatchPattern)tp.Object).Node));
                                }
                            }
                            else
                            {
                                obj = tp.Object;
                            }
                            patterns.Add(new TriplePattern(subj, pred, obj));
                        }
                        else
                        {
                            // Can't optimize if other pattern types involved
                            return(current);
                        }
                    }

                    if (result is NullOperator)
                    {
                        return(result);
                    }
                    else if (patterns.Count > 0)
                    {
                        // If any patterns left at end join as a BGP with result so far
                        result = Join.CreateJoin(result, new Bgp(patterns));
                        return(result);
                    }
                    else
                    {
                        return(result);
                    }
                }
            }
            else if (algebra is ITerminalOperator)
            {
                return(algebra);
            }
            else
            {
                return(algebra);
            }
        }
 protected override void OnInit()
 {
     Extend <TransformationNamespace> .With <TranslationServicesMethods>();
 }
Beispiel #23
0
        /// <summary>
        /// Gets the Algebra representation of the Graph Pattern.
        /// </summary>
        /// <returns></returns>
        public ISparqlAlgebra ToAlgebra()
        {
            if (_isUnion)
            {
                // If this Graph Pattern represents a UNION of Graph Patterns turn into a series of UNIONs
                ISparqlAlgebra union = new Union(_graphPatterns[0].ToAlgebra(), _graphPatterns[1].ToAlgebra());
                if (_graphPatterns.Count > 2)
                {
                    for (int i = 2; i < _graphPatterns.Count; i++)
                    {
                        union = new Union(union, _graphPatterns[i].ToAlgebra());
                    }
                }
                // Apply Inline Data
                if (HasInlineData)
                {
                    union = Join.CreateJoin(union, new Bindings(_data));
                }
                // If there's a FILTER apply it over the Union
                if (_isFiltered && (_filter != null || _unplacedFilters.Count > 0))
                {
                    return(new Filter(union, Filter));
                }
                return(union);
            }

            // Terminal graph pattern
            if (_graphPatterns.Count == 0)
            {
                // If there are no Child Graph Patterns then this is a BGP
                ISparqlAlgebra bgp = new Bgp(_triplePatterns);
                if (_unplacedAssignments.Count > 0)
                {
                    // If we have any unplaced LETs these get Extended onto the BGP
                    foreach (IAssignmentPattern p in _unplacedAssignments)
                    {
                        bgp = new Extend(bgp, p.AssignExpression, p.VariableName);
                    }
                }
                if (IsGraph)
                {
                    bgp = Algebra.Graph.ApplyGraph(bgp, GraphSpecifier);
                }
                else if (IsService)
                {
                    bgp = new Service(GraphSpecifier, this, IsSilent);
                }

                // Apply Inline Data
                if (HasInlineData)
                {
                    bgp = Join.CreateJoin(bgp, new Bindings(_data));
                }
                if (_isFiltered && (_filter != null || _unplacedFilters.Count > 0))
                {
                    if (_isOptional && !(_isExists || _isNotExists))
                    {
                        // If we contain an unplaced FILTER and we're an OPTIONAL then the FILTER
                        // applies over the LEFT JOIN and will have been added elsewhere in the Algebra transform
                        return(bgp);
                    }

                    // If we contain an unplaced FILTER and we're not an OPTIONAL the FILTER
                    // applies here
                    return(new Filter(bgp, Filter));
                }
                // We're not filtered (or all FILTERs were placed in the BGP) so we're just a BGP
                return(bgp);
            }

            // Create a basic BGP to start with
            ISparqlAlgebra complex = new Bgp();

            if (_triplePatterns.Count > 0)
            {
                complex = new Bgp(_triplePatterns);
            }

            // Apply Inline Data
            // If this Graph Pattern had child patterns before this Graph Pattern then we would
            // have broken the BGP and not added the Inline Data here so it's always safe to apply this here
            if (HasInlineData)
            {
                complex = Join.CreateJoin(complex, new Bindings(_data));
            }

            // Then Join each of the Graph Patterns as appropriate
            foreach (GraphPattern gp in _graphPatterns)
            {
                if (gp.IsGraph)
                {
                    // A GRAPH clause means a Join of the current pattern to a Graph clause
                    ISparqlAlgebra gpAlgebra = gp.ToAlgebra();
                    complex = Join.CreateJoin(complex, Algebra.Graph.ApplyGraph(gpAlgebra, gp.GraphSpecifier));
                }
                else if (gp.IsOptional)
                {
                    if (gp.IsExists || gp.IsNotExists)
                    {
                        // An EXISTS/NOT EXISTS means an Exists Join of the current pattern to the EXISTS/NOT EXISTS clause
                        complex = new ExistsJoin(complex, gp.ToAlgebra(), gp.IsExists);
                    }
                    else
                    {
                        // An OPTIONAL means a Left Join of the current pattern to the OPTIONAL clause
                        // with a possible FILTER applied over the LeftJoin
                        if (gp.IsFiltered && gp.Filter != null)
                        {
                            // If the OPTIONAL clause has an unplaced FILTER it applies over the Left Join
                            complex = new LeftJoin(complex, gp.ToAlgebra(), gp.Filter);
                        }
                        else
                        {
                            complex = new LeftJoin(complex, gp.ToAlgebra());
                        }
                    }
                }
                else if (gp.IsMinus)
                {
                    // Always introduce a Minus here even if the Minus is disjoint since during evaluation we'll choose
                    // not to execute it if it's disjoint
                    complex = new Minus(complex, gp.ToAlgebra());
                }
                else if (gp.IsService)
                {
                    complex = Join.CreateJoin(complex, new Service(gp.GraphSpecifier, gp, gp.IsSilent));
                }
                else
                {
                    // Otherwise we just join the pattern to the existing pattern
                    complex = Join.CreateJoin(complex, gp.ToAlgebra());
                }
            }
            if (_unplacedAssignments.Count > 0)
            {
                // Unplaced assignments get Extended over the algebra so far here
                // complex = Join.CreateJoin(complex, new Bgp(this._unplacedAssignments.OfType<ITriplePattern>()));
                foreach (IAssignmentPattern p in _unplacedAssignments)
                {
                    complex = new Extend(complex, p.AssignExpression, p.VariableName);
                }
            }
            if (IsGraph)
            {
                complex = Algebra.Graph.ApplyGraph(complex, GraphSpecifier);
            }
            if (_isFiltered && (_filter != null || _unplacedFilters.Count > 0))
            {
                if (_isOptional && !(_isExists || _isNotExists))
                {
                    // If there's an unplaced FILTER and we're an OPTIONAL then the FILTER will
                    // apply over the LeftJoin and is applied elsewhere in the Algebra transform
                    return(complex);
                }
                else
                {
                    if (_filter != null || _unplacedFilters.Count > 0)
                    {
                        // If there's an unplaced FILTER and we're not an OPTIONAL pattern we apply
                        // the FILTER here
                        return(new Filter(complex, Filter));
                    }
                    else
                    {
                        return(complex);
                    }
                }
            }
            else
            {
                // If no FILTER just return the transform
                return(complex);
            }
        }
Beispiel #24
0
 internal static extern void cairo_pattern_set_extend(IntPtr pattern, Extend extend);
Beispiel #25
0
 public PartialExtender(Selector baseSelector, Extend extend) : base(baseSelector, extend)
 {
 }
Beispiel #26
0
        public async Task SearchByNewOrHot(SearchPara para, CancellationToken token, MoeItems imgs)
        {
            const string api   = "https://api.vc.bilibili.com/link_draw/v2";
            var          type  = para.Lv3MenuIndex == 0 ? "new" : "hot";
            var          count = para.Count > 20 ? 20 : para.Count;
            var          api2  = "";

            switch (para.SubMenuIndex)
            {
            case 0:
                api2 = $"{api}/Doc/list";
                break;

            case 1:
            case 2:
                api2 = $"{api}/Photo/list";
                break;
            }
            var net  = new NetOperator(Settings);
            var json = await net.GetJsonAsync(api2, token, new Pairs
            {
                { "category", para.SubMenuIndex == 0 ? "all" : (para.SubMenuIndex == 1 ? "cos" : "sifu") },
                { "type", type },
                { "page_num", $"{para.PageIndex - 1}" },
                { "page_size", $"{count}" }
            });


            foreach (var item in Extend.GetList(json?.data?.items))
            {
                var cat = para.SubMenuIndex == 0 ? "/d" : "/p";
                var img = new MoeItem(this, para)
                {
                    Uploader = $"{item.user?.name}",
                    Id       = $"{item.item?.doc_id}".ToInt(),
                };
                img.DetailUrl = $"https://h.bilibili.com/{img.Id}";
                var i0 = item.item?.pictures[0];
                img.Width  = $"{i0?.img_width}".ToInt();
                img.Height = $"{i0?.img_height}".ToInt();
                img.Date   = $"{item.item?.upload_time}".ToDateTime();
                img.Urls.Add(1, $"{i0?.img_src}@336w_336h_1e_1c.jpg", HomeUrl + cat);
                img.Urls.Add(2, $"{i0?.img_src}@1024w_768h.jpg");
                img.Urls.Add(4, $"{i0?.img_src}");
                img.Title = $"{item.item?.title}";
                var list = item.item?.pictures as JArray;
                if (list?.Count > 1)
                {
                    foreach (var pic in item.item.pictures)
                    {
                        var child = new MoeItem(this, para);
                        child.Urls.Add(1, $"{pic.img_src}@336w_336h_1e_1c.jpg", HomeUrl + cat);
                        child.Urls.Add(2, $"{pic.img_src}@1024w_768h.jpg", HomeUrl + cat);
                        child.Urls.Add(4, $"{pic.img_src}");
                        child.Width  = $"{pic.img_width}".ToInt();
                        child.Height = $"{pic.img_height}".ToInt();
                        img.ChildrenItems.Add(child);
                    }
                }
                img.GetDetailTaskFunc = async() => await GetSearchByNewOrHotDetailTask(img, token, para);

                img.OriginString = $"{item}";
                imgs.Add(img);
            }

            var c = $"{json?.data.total_count}".ToInt();

            Extend.ShowMessage($"共搜索到{c}张,已加载至{para.PageIndex}页,共{c / para.Count}页", null, Extend.MessagePos.InfoBar);
        }
Beispiel #27
0
        static public void Fill(Extend m)
        {
            string UomName = null;

            if (m.UomID != null)
            {
                UomName = Micajah.Common.Bll.MeasureUnit.GetMeasureUnitName((Guid)m.UomID, Micajah.Common.Bll.MeasureUnitName.SingularAbbreviation);
            }
            m.CurrentValueStr  = GetValueStr(m.CurrentValue, m.MetricNODecPlaces, UomName);
            m.PreviousValueStr = GetValueStr(m.PreviousValue, m.MetricNODecPlaces, UomName);

            if (m.UomID != null && m.AltUomID != null)
            {
                UomName = Micajah.Common.Bll.MeasureUnit.GetMeasureUnitName((Guid)m.AltUomID, Micajah.Common.Bll.MeasureUnitName.SingularAbbreviation);
                double?AltVal;
                string AltStr;
                if (m.CurrentValue != null)
                {
                    AltVal = MetricTrac.Bll.Mc_UnitsOfMeasure.ConvertValue((double)m.CurrentValue, (Guid)m.UomID, (Guid)m.AltUomID, LinqMicajahDataContext.OrganizationId);
                    AltStr = GetValueStr(AltVal, m.MetricNODecPlaces, UomName);
                    if (!string.IsNullOrEmpty(AltStr))
                    {
                        if (!string.IsNullOrEmpty(m.CurrentValueStr))
                        {
                            m.CurrentValueStr += " = ";
                        }
                        m.CurrentValueStr += AltStr;
                    }
                }
                if (m.PreviousValue != null)
                {
                    AltVal = MetricTrac.Bll.Mc_UnitsOfMeasure.ConvertValue((double)m.PreviousValue, (Guid)m.UomID, (Guid)m.AltUomID, LinqMicajahDataContext.OrganizationId);
                    AltStr = GetValueStr(AltVal, m.MetricNODecPlaces, UomName);
                    if (!string.IsNullOrEmpty(AltStr))
                    {
                        if (!string.IsNullOrEmpty(m.PreviousValueStr))
                        {
                            m.PreviousValueStr += " = ";
                        }
                        m.PreviousValueStr += AltStr;
                    }
                }
            }

            if (m.CurrentValue != null && m.PreviousValue != null)
            {
                if (m.PreviousValue == 0)
                {
                    m.ChangeValue    = double.PositiveInfinity;
                    m.ChangeValueStr = "~";
                }
                else
                {
                    try
                    {
                        m.ChangeValue     = (m.CurrentValue - m.PreviousValue) / m.PreviousValue * 100;//  (1 - m.CurrentValue / m.PreviousValue) * 100;
                        m.ChangeValueStr  = ((double)m.ChangeValue).ToString("#0");
                        m.ChangeValueStr += "%";
                    }
                    catch
                    {
                        m.ChangeValueStr = "~";
                    }
                }
            }
        }
Beispiel #28
0
 public ExactExtender(Selector baseSelector, Extend extend) : base(baseSelector, extend)
 {
 }
Beispiel #29
0
        private ForecastIOResponse GetWeatherInfo(string address, bool extendHourly)
        {
            // Get Latitude and Longitude for given address
            Address addressInfo = GetGeoInfo(address);
            ForecastIOResponse response = null;

            // If the address was found (had Latitude and Longitude)
            if (addressInfo != null)
            {
                ForecastIORequest request;
                if (extendHourly)
                {
                    Extend[] extendBlocks = new Extend[]
                    { Extend.hourly };
                    request = new ForecastIORequest(_weatherApiKey, Convert.ToSingle(addressInfo.Coordinates.Latitude), Convert.ToSingle(addressInfo.Coordinates.Longitude), Unit.us, extendBlocks);
                    response = request.Get();
                }
                else
                {
                    // Get weather info from forecast API
                    request = new ForecastIORequest(_weatherApiKey, Convert.ToSingle(addressInfo.Coordinates.Latitude), Convert.ToSingle(addressInfo.Coordinates.Longitude), Unit.us);
                    response = request.Get();
                }
            }

            return response;
        }
Beispiel #30
0
        /// <summary>
        /// 异步加载图片
        /// </summary>
        public async Task <Exception> LoadImageAsync()
        {
            // client
            var net = ImageItem.Net ?? new NetDocker(Settings);

            net.SetTimeOut(15);
            net.SetReferer(ImageItem.ThumbnailUrlInfo.Referer);
            Exception loadEx = null;

            try
            {
                var cts      = new CancellationTokenSource(TimeSpan.FromSeconds(15));
                var response = await net.Client.GetAsync(ImageItem.ThumbnailUrlInfo.Url, cts.Token);

                using (var stream = await response.Content.ReadAsStreamAsync())
                {
                    var source = await Task.Run(() =>
                    {
                        try
                        {
                            var bitimg           = new BitmapImage();
                            bitimg.CacheOption   = BitmapCacheOption.OnLoad;
                            bitimg.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                            bitimg.BeginInit();
                            bitimg.StreamSource = stream;
                            bitimg.EndInit();
                            bitimg.Freeze();
                            return(bitimg);
                        }
                        catch (IOException)
                        {
                            try
                            {
                                var bitmap = new Bitmap(stream);
                                var ms     = new MemoryStream();
                                bitmap.Save(ms, ImageFormat.Png);
                                var bitimg           = new BitmapImage();
                                bitimg.CacheOption   = BitmapCacheOption.OnLoad;
                                bitimg.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                                bitimg.BeginInit();
                                bitimg.StreamSource = ms;
                                bitimg.EndInit();
                                bitimg.Freeze();
                                //ms.Dispose();
                                return(bitimg);
                            }
                            catch (Exception e)
                            {
                                loadEx = e;
                                return(null);
                            }
                        }
                        catch (Exception ex)
                        {
                            loadEx = ex;
                            return(null);
                        }
                    }, cts.Token);

                    if (source != null)
                    {
                        PreviewImage.Source = source;
                    }
                }
            }
            catch (Exception ex)
            {
                loadEx = ex;
            }

            if (loadEx == null)
            {
                this.Sb("LoadedImageSb").Begin();
            }
            else
            {
                this.Sb("LoadFailSb").Begin();
                Extend.Log(loadEx.Message, loadEx.StackTrace);
                Extend.Log($"{ImageItem.ThumbnailUrlInfo.Url} 图片加载失败");
            }

            return(loadEx);
        }
Beispiel #31
0
        public override async Task <MoeItems> GetRealPageImagesAsync(SearchPara para, CancellationToken token)
        {
            // logon
            if (!IsLogon)
            {
                Login(token);
            }
            if (!IsLogon)
            {
                return(new MoeItems());
            }

            // get page source
            string pageString;
            var    url = $"{HomeUrl}{(para.Keyword.Length > 0 ? $"/search?q={para.Keyword}&" : "/?")}p={para.PageIndex}";

            if (!_beforeWord.Equals(para.Keyword, StringComparison.CurrentCultureIgnoreCase))
            {
                // 301
                var respose = await Net.Client.GetAsync(url, token);

                if (respose.IsSuccessStatusCode)
                {
                    _beforeUrl = respose.Headers.Location.AbsoluteUri;
                }
                else
                {
                    Extend.ShowMessage("搜索失败,请检查您输入的关键词");
                    return(new MoeItems());
                }

                pageString = await respose.Content.ReadAsStringAsync();

                _beforeWord = para.Keyword;
            }
            else
            {
                url = para.Keyword.IsEmpty() ? url : $"{_beforeUrl}?p={para.PageIndex}";
                var res = await Net.Client.GetAsync(url, token);

                pageString = await res.Content.ReadAsStringAsync();
            }

            // images
            var imgs = new MoeItems();
            var doc  = new HtmlDocument();

            doc.LoadHtml(pageString);
            HtmlNodeCollection nodes;

            try
            {
                nodes = doc.DocumentNode.SelectSingleNode("//ul[@id='thumbs2']").SelectNodes(".//li");
            }
            catch { return(new MoeItems {
                    Message = "没有搜索到图片"
                }); }

            foreach (var imgNode in nodes)
            {
                var img = new MoeItem(this, para);
                var mo  = imgNode.SelectSingleNode(".//b")?.InnerText?.Trim();
                if (mo?.ToLower().Trim().Contains("members only") == true)
                {
                    continue;
                }
                var strId = imgNode.SelectSingleNode("a").Attributes["href"].Value;
                var fav   = imgNode.SelectSingleNode("a/span")?.InnerText;
                if (!fav.IsEmpty())
                {
                    img.Score = Regex.Replace(fav, @"[^0-9]+", "")?.ToInt() ?? 0;
                }
                var imgHref    = imgNode.SelectSingleNode(".//img");
                var previewUrl = imgHref?.Attributes["src"]?.Value;
                //http://s3.zerochan.net/Morgiana.240.1355397.jpg   preview
                //http://s3.zerochan.net/Morgiana.600.1355397.jpg    sample
                //http://static.zerochan.net/Morgiana.full.1355397.jpg   full
                //先加前一个,再加后一个  范围都是00-49
                //string folder = (id % 2500 % 50).ToString("00") + "/" + (id % 2500 / 50).ToString("00");
                var sampleUrl = "";
                var fileUrl   = "";
                if (!previewUrl.IsEmpty())
                {
                    sampleUrl = previewUrl?.Replace("240", "600");
                    fileUrl   = Regex.Replace(previewUrl, "^(.+?)zerochan.net/", "https://static.zerochan.net/").Replace("240", "full");
                }

                var resAndFileSize = imgHref?.Attributes["title"]?.Value;
                if (!resAndFileSize.IsEmpty())
                {
                    foreach (var s in resAndFileSize.Split(' '))
                    {
                        if (!s.Contains("x"))
                        {
                            continue;
                        }
                        var res = s.Split('x');
                        if (res.Length != 2)
                        {
                            continue;
                        }
                        img.Width  = res[0].ToInt();
                        img.Height = res[1].ToInt();
                    }
                }

                var title = imgHref?.Attributes["alt"]?.Value;

                //convert relative url to absolute
                if (!fileUrl.IsEmpty() && fileUrl.StartsWith("/"))
                {
                    fileUrl = $"{HomeUrl}{fileUrl}";
                }
                if (sampleUrl != null && sampleUrl.StartsWith("/"))
                {
                    sampleUrl = HomeUrl + sampleUrl;
                }

                img.Description = title;
                img.Title       = title;
                img.Id          = strId.Substring(1).ToInt();

                img.Urls.Add(1, previewUrl, HomeUrl);
                img.Urls.Add(2, sampleUrl, HomeUrl);
                img.Urls.Add(4, fileUrl, img.DetailUrl);
                img.DetailUrl = $"{HomeUrl}/{img.Id}";

                img.OriginString = imgNode.OuterHtml;
                imgs.Add(img);
            }
            token.ThrowIfCancellationRequested();
            return(imgs);
        }
Beispiel #32
0
        /// <summary>
        /// Converts the Query into it's SPARQL Algebra representation (as represented in the Leviathan API)
        /// </summary>
        /// <returns></returns>
        public ISparqlAlgebra ToAlgebra()
        {
            //Depending on how the query gets built we may not have had graph pattern optimization applied
            //which we should do here if query optimization is enabled
            if (!this.IsOptimised && Options.QueryOptimisation)
            {
                this.Optimise();
            }

            //Firstly Transform the Root Graph Pattern to SPARQL Algebra
            ISparqlAlgebra algebra;

            if (this._rootGraphPattern != null)
            {
                if (Options.AlgebraOptimisation)
                {
                    //If using Algebra Optimisation may use a special algebra in some cases
                    switch (this.SpecialType)
                    {
                    case SparqlSpecialQueryType.DistinctGraphs:
                        algebra = new SelectDistinctGraphs(this.Variables.First(v => v.IsResultVariable).Name);
                        break;

                    case SparqlSpecialQueryType.AskAnyTriples:
                        algebra = new AskAnyTriples();
                        break;

                    case SparqlSpecialQueryType.NotApplicable:
                    default:
                        //If not just use the standard transform
                        algebra = this._rootGraphPattern.ToAlgebra();
                        break;
                    }
                }
                else
                {
                    //If not using Algebra Optimisation just use the standard transform
                    algebra = this._rootGraphPattern.ToAlgebra();
                }
            }
            else
            {
                //No root graph pattern means empty BGP
                algebra = new Bgp();
            }

            //If we have a top level VALUES clause then we'll add it into the algebra here
            if (this._bindings != null)
            {
                algebra = Join.CreateJoin(algebra, new Bindings(this._bindings));
            }

            //Then we apply any optimisers followed by relevant solution modifiers
            switch (this._type)
            {
            case SparqlQueryType.Ask:
                //Apply Algebra Optimisation is enabled
                if (Options.AlgebraOptimisation)
                {
                    algebra = this.ApplyAlgebraOptimisations(algebra);
                }
                return(new Ask(algebra));

            case SparqlQueryType.Construct:
            case SparqlQueryType.Describe:
            case SparqlQueryType.DescribeAll:
            case SparqlQueryType.Select:
            case SparqlQueryType.SelectAll:
            case SparqlQueryType.SelectAllDistinct:
            case SparqlQueryType.SelectAllReduced:
            case SparqlQueryType.SelectDistinct:
            case SparqlQueryType.SelectReduced:
                //Apply Algebra Optimisation if enabled
                if (Options.AlgebraOptimisation)
                {
                    algebra = this.ApplyAlgebraOptimisations(algebra);
                }

                //GROUP BY is the first thing applied
                //This applies if there is a GROUP BY or if there are aggregates
                //With no GROUP BY it produces a single group of all results
                if (this._groupBy != null || this._vars.Any(v => v.IsAggregate))
                {
                    algebra = new GroupBy(algebra, this._groupBy, this._vars.Where(v => v.IsAggregate));
                }

                //After grouping we do projection
                //We introduce an Extend for each Project Expression
                foreach (SparqlVariable var in this._vars)
                {
                    if (var.IsProjection)
                    {
                        algebra = new Extend(algebra, var.Projection, var.Name);
                    }
                }

                //Add HAVING clause after the projection
                if (this._having != null)
                {
                    algebra = new Having(algebra, this._having);
                }

                //We can then Order our results
                //We do ordering before we do Select but after Project so we can order by any of
                //the project expressions/aggregates and any variable in the results even if
                //it won't be output as a result variable
                if (this._orderBy != null)
                {
                    algebra = new OrderBy(algebra, this._orderBy);
                }

                //After Ordering we apply Select
                //Select effectively trims the results so only result variables are left
                //This doesn't apply to CONSTRUCT since any variable may be used in the Construct Template
                //so we don't want to eliminate anything
                if (this._type != SparqlQueryType.Construct)
                {
                    algebra = new Select(algebra, this.Variables);
                }

                //If we have a Distinct/Reduced then we'll apply those after Selection
                if (this._type == SparqlQueryType.SelectAllDistinct || this._type == SparqlQueryType.SelectDistinct)
                {
                    algebra = new Distinct(algebra);
                }
                else if (this._type == SparqlQueryType.SelectAllReduced || this._type == SparqlQueryType.SelectReduced)
                {
                    algebra = new Reduced(algebra);
                }

                //Finally we can apply any limit and/or offset
                if (this._limit >= 0 || this._offset > 0)
                {
                    algebra = new Slice(algebra, this._limit, this._offset);
                }

                return(algebra);

            default:
                throw new RdfQueryException("Unable to convert unknown Query Types to SPARQL Algebra");
            }
        }
Beispiel #33
0
 /// <summary>
 /// Registers translation services methods.
 /// </summary>
 public override void Init()
 {
     Extend <TransformationNamespace> .With <TranslationServicesMethods>();
 }
 public static string FormatExtendString(Extend[] input)
 {
     return string.Join(",", input.Select(i => Enum.GetName(typeof(Extend), i)));
 }
Beispiel #35
0
        // Generates content of workbookStylesPart1.
        private void GenerateWorkbookStylesPart1Content(WorkbookStylesPart workbookStylesPart1)
        {
            Stylesheet stylesheet1 = new Stylesheet();

            Fonts fonts1 = new Fonts() { Count = (UInt32Value)1U };

            Font font1 = new Font();
            FontSize fontSize1 = new FontSize() { Val = 11D };
            Color color1 = new Color() { Theme = (UInt32Value)1U };
            FontName fontName1 = new FontName() { Val = "Calibri" };
            FontFamilyNumbering fontFamilyNumbering1 = new FontFamilyNumbering() { Val = 2 };
            FontScheme fontScheme1 = new FontScheme() { Val = FontSchemeValues.Minor };

            font1.Append(fontSize1);
            font1.Append(color1);
            font1.Append(fontName1);
            font1.Append(fontFamilyNumbering1);
            font1.Append(fontScheme1);

            fonts1.Append(font1);

            Fills fills1 = new Fills() { Count = (UInt32Value)2U };

            Fill fill1 = new Fill();
            PatternFill patternFill1 = new PatternFill() { PatternType = PatternValues.None };

            fill1.Append(patternFill1);

            Fill fill2 = new Fill();
            PatternFill patternFill2 = new PatternFill() { PatternType = PatternValues.Gray125 };

            fill2.Append(patternFill2);

            fills1.Append(fill1);
            fills1.Append(fill2);

            Borders borders1 = new Borders() { Count = (UInt32Value)1U };

            Border border1 = new Border();
            LeftBorder leftBorder1 = new LeftBorder();
            RightBorder rightBorder1 = new RightBorder();
            TopBorder topBorder1 = new TopBorder();
            BottomBorder bottomBorder1 = new BottomBorder();
            DiagonalBorder diagonalBorder1 = new DiagonalBorder();

            border1.Append(leftBorder1);
            border1.Append(rightBorder1);
            border1.Append(topBorder1);
            border1.Append(bottomBorder1);
            border1.Append(diagonalBorder1);

            borders1.Append(border1);

            CellStyleFormats cellStyleFormats1 = new CellStyleFormats() { Count = (UInt32Value)1U };
            CellFormat cellFormat1 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U };

            cellStyleFormats1.Append(cellFormat1);

            CellFormats cellFormats1 = new CellFormats() { Count = (UInt32Value)1U };
            CellFormat cellFormat2 = new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U };

            cellFormats1.Append(cellFormat2);

            CellStyles cellStyles1 = new CellStyles() { Count = (UInt32Value)1U };
            CellStyle cellStyle1 = new CellStyle() { Name = "Normal", FormatId = (UInt32Value)0U, BuiltinId = (UInt32Value)0U };

            cellStyles1.Append(cellStyle1);

            DifferentialFormats differentialFormats1 = new DifferentialFormats() { Count = (UInt32Value)3U };

            DifferentialFormat differentialFormat1 = new DifferentialFormat();

            Font font2 = new Font();
            Condense condense1 = new Condense() { Val = false };
            Extend extend1 = new Extend() { Val = false };
            Color color2 = new Color() { Rgb = "FF9C0006" };

            font2.Append(condense1);
            font2.Append(extend1);
            font2.Append(color2);

            Fill fill3 = new Fill();

            PatternFill patternFill3 = new PatternFill();
            BackgroundColor backgroundColor1 = new BackgroundColor() { Rgb = "FFFFC7CE" };

            patternFill3.Append(backgroundColor1);

            fill3.Append(patternFill3);

            differentialFormat1.Append(font2);
            differentialFormat1.Append(fill3);

            DifferentialFormat differentialFormat2 = new DifferentialFormat();

            Font font3 = new Font();
            Condense condense2 = new Condense() { Val = false };
            Extend extend2 = new Extend() { Val = false };
            Color color3 = new Color() { Rgb = "FF006100" };

            font3.Append(condense2);
            font3.Append(extend2);
            font3.Append(color3);

            Fill fill4 = new Fill();

            PatternFill patternFill4 = new PatternFill();
            BackgroundColor backgroundColor2 = new BackgroundColor() { Rgb = "FFC6EFCE" };

            patternFill4.Append(backgroundColor2);

            fill4.Append(patternFill4);

            differentialFormat2.Append(font3);
            differentialFormat2.Append(fill4);

            DifferentialFormat differentialFormat3 = new DifferentialFormat();

            Font font4 = new Font();
            Condense condense3 = new Condense() { Val = false };
            Extend extend3 = new Extend() { Val = false };
            Color color4 = new Color() { Rgb = "FF006100" };

            font4.Append(condense3);
            font4.Append(extend3);
            font4.Append(color4);

            Fill fill5 = new Fill();

            PatternFill patternFill5 = new PatternFill();
            BackgroundColor backgroundColor3 = new BackgroundColor() { Rgb = "FFC6EFCE" };

            patternFill5.Append(backgroundColor3);

            fill5.Append(patternFill5);

            differentialFormat3.Append(font4);
            differentialFormat3.Append(fill5);

            differentialFormats1.Append(differentialFormat1);
            differentialFormats1.Append(differentialFormat2);
            differentialFormats1.Append(differentialFormat3);
            TableStyles tableStyles1 = new TableStyles() { Count = (UInt32Value)0U, DefaultTableStyle = "TableStyleMedium9", DefaultPivotStyle = "PivotStyleLight16" };

            stylesheet1.Append(fonts1);
            stylesheet1.Append(fills1);
            stylesheet1.Append(borders1);
            stylesheet1.Append(cellStyleFormats1);
            stylesheet1.Append(cellFormats1);
            stylesheet1.Append(cellStyles1);
            stylesheet1.Append(differentialFormats1);
            stylesheet1.Append(tableStyles1);

            workbookStylesPart1.Stylesheet = stylesheet1;
        }
Beispiel #36
0
        public override async Task <MoeItems> GetRealPageImagesAsync(SearchPara para, CancellationToken token)
        {
            var          imgs = new MoeItems();
            const string api  = "https://capi-v2.sankakucomplex.com";
            const string beta = "https://beta.sankakucomplex.com";

            if (Net == null)
            {
                Net = new NetOperator(Settings, api);
                var cc = GetCookies();

                if (cc != null)
                {
                    Net.SetCookie(cc);
                }
            }
            else
            {
                Net.CloneWithOldCookie();
            }

            Net.SetReferer(beta);
            var pairs = new Pairs
            {
                { "lang", "en" },
                { "next", $"{para.NextPagePara}" },
                { "limit", $"{para.Count}" },
                { "hide_posts_in_books", "in-larger-tags" },
                { "default_threshold", "1" },
                { "tags", para.Keyword.ToEncodedUrl() }
            };
            var json = await Net.GetJsonAsync($"{api}/posts/keyset", token, pairs);

            para.NextPagePara = $"{json.meta.next}";
            foreach (var jitem in Extend.GetList(json.data))
            {
                var img = new MoeItem(this, para)
                {
                    Net    = Net.CloneWithOldCookie(),
                    Id     = $"{jitem.id}".ToInt(),
                    Width  = $"{jitem.width}".ToInt(),
                    Height = $"{jitem.height}".ToInt(),
                    Score  = $"{jitem.total_score}".ToInt()
                };
                img.Urls.Add(1, $"{jitem.preview_url}", beta);
                img.Urls.Add(2, $"{jitem.sample_url}", beta);
                img.Urls.Add(4, $"{jitem.file_url}", $"{beta}/post/show/{img.Id}");
                img.IsExplicit = $"{jitem.rating}" != "s";
                img.Date       = $"{jitem.created_at?.s}".ToDateTime();
                img.Uploader   = $"{jitem.author?.name}";
                img.DetailUrl  = $"{beta}/post/show/{img.Id}";
                if ($"{jitem.redirect_to_signup}".ToLower() == "true")
                {
                    img.Tip = "此图片需要登录查看";
                }
                foreach (var tag in Extend.GetList(jitem.tags))
                {
                    img.Tags.Add($"{tag.name_en}");
                }

                img.OriginString = $"{jitem}";
                imgs.Add(img);
            }

            return(imgs);
        }
Beispiel #37
0
        /// <summary>
        ///     将值转换成类型对象的值
        /// </summary>
        /// <param name="sourceValue">原值</param>
        /// <param name="returnType">要转换的对象的类型</param>
        public static object ConvertType(object sourceValue, Type returnType)
        {
            if (sourceValue == null)
            {
                return(null);
            }
            // 获取非nullable类型
            if (returnType.GetTypeInfo().IsGenericType&& returnType.GetGenericTypeDefinition() == typeof(Nullable <>))
            {
                returnType = Nullable.GetUnderlyingType(returnType);
            }

            var objString = sourceValue.ToString();

            // 对  List 类型处理
            if (returnType.GetTypeInfo().IsGenericType&& returnType.GetGenericTypeDefinition() != typeof(Nullable <>))
            {
                var returnGenericType = Extend.GetGenericType(returnType);
                // List参数类型
                switch (Type.GetTypeCode(returnGenericType))
                {
                case TypeCode.Boolean: { return(StringHelper.ToList(objString, false)); }

                case TypeCode.DateTime: { return(StringHelper.ToList(objString, DateTime.MinValue)); }

                case TypeCode.Decimal:
                case TypeCode.Double:
                case TypeCode.Single: { return(StringHelper.ToList(objString, 0m)); }

                case TypeCode.Byte:
                case TypeCode.SByte:
                case TypeCode.UInt16: { return(StringHelper.ToList <ushort>(objString)); }

                case TypeCode.UInt32: { return(StringHelper.ToList <uint>(objString)); }

                case TypeCode.UInt64: { return(StringHelper.ToList <ulong>(objString)); }

                case TypeCode.Int16: { return(StringHelper.ToList <short>(objString)); }

                case TypeCode.Int64: { return(StringHelper.ToList <long>(objString)); }

                case TypeCode.Int32: { return(StringHelper.ToList(objString, 0)); }

                case TypeCode.Empty:
                case TypeCode.Char:
                case TypeCode.String: { return(StringHelper.ToList(objString, "")); }
                }
            }

            // 枚举处理
            if (returnType.GetTypeInfo().IsEnum)
            {
                if (sourceValue is bool)
                {
                    sourceValue = ((bool)sourceValue) ? 1 : 0;
                    objString   = sourceValue.ToString();
                }
                return(sourceValue is int?Enum.ToObject(returnType, int.Parse(objString)) : Enum.Parse(returnType, objString, true));
            }

            // 简单类型转换
            var returnTypeCode = Type.GetTypeCode(returnType);
            var val            = ConvertSimple(sourceValue, objString, returnType, returnTypeCode);

            if (val != null)
            {
                return(val);
            }

            try { return(Convert.ChangeType(sourceValue, returnType)); }
            catch
            {
                return(null);
            }
        }
        /// <summary>
        /// Optimises BGPs in the Algebra to use Filter() and Extend() rather than the embedded FILTER and BIND.
        /// </summary>
        /// <param name="algebra">Algebra to optimise.</param>
        /// <returns></returns>
        public ISparqlAlgebra Optimise(ISparqlAlgebra algebra)
        {
            if (algebra is IAbstractJoin)
            {
                return(((IAbstractJoin)algebra).Transform(this));
            }
            else if (algebra is IUnaryOperator)
            {
                return(((IUnaryOperator)algebra).Transform(this));
            }
            else if (algebra is IBgp)
            {
                // Don't integerfer with other optimisers which have added custom BGP implementations
                if (!(algebra is Bgp))
                {
                    return(algebra);
                }

                IBgp current = (IBgp)algebra;
                if (current.PatternCount == 0)
                {
                    return(current);
                }
                else
                {
                    ISparqlAlgebra        result   = new Bgp();
                    List <ITriplePattern> patterns = new List <ITriplePattern>();
                    List <ITriplePattern> ps       = new List <ITriplePattern>(current.TriplePatterns.ToList());
                    for (int i = 0; i < current.PatternCount; i++)
                    {
                        // Can't split the BGP if there are Blank Nodes present
                        if (!ps[i].HasNoBlankVariables)
                        {
                            return(current);
                        }

                        if (ps[i].PatternType != TriplePatternType.Match)
                        {
                            // First ensure that if we've found any other Triple Patterns up to this point
                            // we dump this into a BGP and join with the result so far
                            if (patterns.Count > 0)
                            {
                                result = Join.CreateJoin(result, new Bgp(patterns));
                                patterns.Clear();
                            }

                            // Then generate the appropriate strict algebra operator
                            switch (ps[i].PatternType)
                            {
                            case TriplePatternType.Filter:
                                result = new Filter(result, ((IFilterPattern)ps[i]).Filter);
                                break;

                            case TriplePatternType.BindAssignment:
                            case TriplePatternType.LetAssignment:
                                IAssignmentPattern assignment = (IAssignmentPattern)ps[i];
                                result = new Extend(result, assignment.AssignExpression, assignment.VariableName);
                                break;

                            case TriplePatternType.SubQuery:
                                ISubQueryPattern sq = (ISubQueryPattern)ps[i];
                                result = Join.CreateJoin(result, new SubQuery(sq.SubQuery));
                                break;

                            case TriplePatternType.Path:
                                IPropertyPathPattern pp = (IPropertyPathPattern)ps[i];
                                result = Join.CreateJoin(result, new PropertyPath(pp.Subject, pp.Path, pp.Object));
                                break;

                            case TriplePatternType.PropertyFunction:
                                IPropertyFunctionPattern pf = (IPropertyFunctionPattern)ps[i];
                                result = new PropertyFunction(result, pf.PropertyFunction);
                                break;

                            default:
                                throw new RdfQueryException("Cannot apply strict algebra form to a BGP containing a unknown triple pattern type");
                            }
                        }
                        else
                        {
                            patterns.Add(ps[i]);
                        }
                    }

                    if (patterns.Count == current.PatternCount)
                    {
                        // If count of remaining patterns same as original pattern count there was no optimisation
                        // to do so return as is
                        return(current);
                    }
                    else if (patterns.Count > 0)
                    {
                        // If any patterns left at end join as a BGP with result so far
                        result = Join.CreateJoin(result, new Bgp(patterns));
                        return(result);
                    }
                    else
                    {
                        return(result);
                    }
                }
            }
            else if (algebra is ITerminalOperator)
            {
                return(algebra);
            }
            else
            {
                return(algebra);
            }
        }
Beispiel #39
0
 public virtual void Exit( )
 {
     Extend.ClosePrompt();
     RemoveListeners();
 }