/// <summary>Construct Geodesic Ellipse sample control</summary> public GeodesicEllipse() { InitializeComponent(); _pinSymbol = layoutGrid.Resources["PointSymbol"] as Symbol; _sectorSymbol = layoutGrid.Resources["SectorSymbol"] as Symbol; }
public virtual void define(Symbol symbol) { if(m_symbols.ContainsKey(symbol.getName())) { throw new ProgrammingLanguageNr1.Error("Program already contains a symbol called " + symbol.getName()); } m_symbols.Add(symbol.getName(), symbol); }
/// <summary> /// Initializes a new instance of the <see cref="HistoryRequest"/> class from the specified parameters /// </summary> /// <param name="startTimeUtc">The start time for this request,</param> /// <param name="endTimeUtc">The start time for this request</param> /// <param name="dataType">The data type of the output data</param> /// <param name="symbol">The symbol to request data for</param> /// <param name="securityType">The security type of the symbol</param> /// <param name="resolution">The requested data resolution</param> /// <param name="market">The market this data belongs to</param> /// <param name="exchangeHours">The exchange hours used in fill forward processing</param> /// <param name="fillForwardResolution">The requested fill forward resolution for this request</param> /// <param name="includeExtendedMarketHours">True to include data from pre/post market hours</param> /// <param name="isCustomData">True for custom user data, false for normal QC data</param> public HistoryRequest(DateTime startTimeUtc, DateTime endTimeUtc, Type dataType, Symbol symbol, SecurityType securityType, Resolution resolution, string market, SecurityExchangeHours exchangeHours, Resolution? fillForwardResolution, bool includeExtendedMarketHours, bool isCustomData ) { StartTimeUtc = startTimeUtc; EndTimeUtc = endTimeUtc; Symbol = symbol; ExchangeHours = exchangeHours; Resolution = resolution; FillForwardResolution = fillForwardResolution; IncludeExtendedMarketHours = includeExtendedMarketHours; DataType = dataType; SecurityType = securityType; Market = market; IsCustomData = isCustomData; TimeZone = exchangeHours.TimeZone; }
/// <summary> /// Creates an <see cref="IntegerType"/> instance. /// </summary> /// <param name="module"></param> /// <param name="name"></param> /// <param name="enumerator"></param> public IntegerType(IModule module, string name, Symbol type, ISymbolEnumerator symbols) : base (module, name) { Types? t = GetExactType(type); type.Assert(t.HasValue, "Unknown symbol for unsigned type!"); _type = t.Value; _isEnumeration = false; Symbol current = symbols.NextNonEOLSymbol(); if (current == Symbol.OpenBracket) { _isEnumeration = true; symbols.PutBack(current); _map = Lexer.DecodeEnumerations(symbols); } else if (current == Symbol.OpenParentheses) { symbols.PutBack(current); _ranges = Lexer.DecodeRanges(symbols); current.Assert(!_ranges.IsSizeDeclaration, "SIZE keyword is not allowed for ranges of integer types!"); } else { symbols.PutBack(current); } }
private TypeMap WithAlphaRename(ImmutableArray<TypeParameterSymbol> oldTypeParameters, Symbol newOwner, out ImmutableArray<TypeParameterSymbol> newTypeParameters) { if (oldTypeParameters.Length == 0) { newTypeParameters = ImmutableArray<TypeParameterSymbol>.Empty; return this; } // Note: the below assertion doesn't hold while rewriting async lambdas defined inside generic methods. // The async rewriter adds a synthesized struct inside the lambda frame and construct a typemap from // the lambda frame's substituted type parameters. // Debug.Assert(!oldTypeParameters.Any(tp => tp is SubstitutedTypeParameterSymbol)); // warning: we expose result to the SubstitutedTypeParameterSymbol constructor, below, even before it's all filled in. TypeMap result = new TypeMap(this.Mapping); ArrayBuilder<TypeParameterSymbol> newTypeParametersBuilder = ArrayBuilder<TypeParameterSymbol>.GetInstance(); // The case where it is "synthesized" is when we're creating type parameters for a synthesized (generic) // class or method for a lambda appearing in a generic method. bool synthesized = !ReferenceEquals(oldTypeParameters[0].ContainingSymbol.OriginalDefinition, newOwner.OriginalDefinition); foreach (var tp in oldTypeParameters) { var newTp = synthesized ? new SynthesizedSubstitutedTypeParameterSymbol(newOwner, result, tp) : new SubstitutedTypeParameterSymbol(newOwner, result, tp); result.Mapping.Add(tp, new TypeWithModifiers(newTp)); newTypeParametersBuilder.Add(newTp); } newTypeParameters = newTypeParametersBuilder.ToImmutableAndFree(); return result; }
private SubstitutedParameterSymbol(Symbol containingSymbol, TypeMap map, ParameterSymbol originalParameter) : base(originalParameter) { Debug.Assert(originalParameter.IsDefinition); _containingSymbol = containingSymbol; _mapOrType = map; }
/// <summary> /// This method checks to see if the given symbol is Obsolete or if any symbol in the parent hierarchy is Obsolete. /// </summary> /// <returns> /// True if some symbol in the parent hierarchy is known to be Obsolete. Unknown if any /// symbol's Obsoleteness is Unknown. False, if we are certain that no symbol in the parent /// hierarchy is Obsolete. /// </returns> internal static ThreeState GetObsoleteContextState(Symbol symbol, bool forceComplete = false) { if ((object)symbol == null) return ThreeState.False; // For Property or Event accessors, check the associated property or event instead. if (symbol.IsAccessor()) { symbol = ((MethodSymbol)symbol).AssociatedSymbol; } // If this is the backing field of an event, look at the event instead. else if (symbol.Kind == SymbolKind.Field && (object)((FieldSymbol)symbol).AssociatedSymbol != null) { symbol = ((FieldSymbol)symbol).AssociatedSymbol; } if (forceComplete) { symbol.ForceCompleteObsoleteAttribute(); } if (symbol.ObsoleteState != ThreeState.False) { return symbol.ObsoleteState; } return GetObsoleteContextState(symbol.ContainingSymbol, forceComplete); }
public FieldList(Position pos, Symbol name, Symbol type, FieldList tail) { Pos = pos; Name = name; Type = type; Tail = tail; }
protected static Rule Rule(string name, Pred contents, Symbol mode = null, int k = 0) { var rule = Pred.Rule(name, contents, (mode ?? Start) == Start, mode == Token, k); if (mode == Private) rule.IsPrivate = true; return rule; }
public void SurvivesRoundtripSerializationWithTypeNameHandling() { var expected = new Symbol("sid", "value"); var json = JsonConvert.SerializeObject(expected, Settings); var actual = JsonConvert.DeserializeObject<Symbol>(json); Assert.AreEqual(expected, actual); }
public FieldExpressionList(Position pos, Symbol name, Expression init, FieldExpressionList tail) { Pos = pos; Name = name; Init = init; Tail = tail; }
public LocalFunctionSymbol( Binder binder, Symbol containingSymbol, LocalFunctionStatementSyntax syntax) { _syntax = syntax; _containingSymbol = containingSymbol; _declarationModifiers = DeclarationModifiers.Private | DeclarationModifiers.Static | syntax.Modifiers.ToDeclarationModifiers(); var diagnostics = DiagnosticBag.GetInstance(); if (_syntax.TypeParameterList != null) { binder = new WithMethodTypeParametersBinder(this, binder); _typeParameters = MakeTypeParameters(diagnostics); } else { _typeParameters = ImmutableArray<TypeParameterSymbol>.Empty; } if (IsExtensionMethod) { diagnostics.Add(ErrorCode.ERR_BadExtensionAgg, Locations[0]); } _binder = binder; _refKind = (syntax.ReturnType.Kind() == SyntaxKind.RefType) ? RefKind.Ref : RefKind.None; _diagnostics = diagnostics.ToReadOnlyAndFree(); }
public decimal CalculateLastTradePandL(Symbol symbol) { var matchedTrade = Trades.LastOrDefault(p => p.Symbol == symbol); if (matchedTrade != null) return matchedTrade.GainOrLoss; return 0; }
public AnonymousTypeParameterSymbol(Symbol container, int ordinal, string name) { Debug.Assert((object)container != null && !String.IsNullOrEmpty(name)); this.container = container; this.ordinal = ordinal; this.name = name; }
public ArrayExpression(Position pos, Symbol type, Expression size, Expression init) { Pos = pos; Type = type; Size = size; Init = init; }
/// <summary> /// Creates a new <see cref="Indicators.CandlestickPatterns.ThreeInside"/> pattern indicator. /// The indicator will be automatically updated on the given resolution. /// </summary> /// <param name="symbol">The symbol whose pattern we seek</param> /// <param name="resolution">The resolution.</param> /// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to casting the input value to a TradeBar</param> /// <returns>The pattern indicator for the requested symbol.</returns> public ThreeInside ThreeInside(Symbol symbol, Resolution? resolution = null, Func<BaseData, TradeBar> selector = null) { var name = _algorithm.CreateIndicatorName(symbol, "THREEINSIDE", resolution); var pattern = new ThreeInside(name); _algorithm.RegisterIndicator(symbol, pattern, resolution, selector); return pattern; }
/// <summary>Construct Distance From Geometry sample control</summary> public DistanceFromGeometry() { InitializeComponent(); _lineSymbol = layoutGrid.Resources["LineSymbol"] as Symbol; _pointSymbol = layoutGrid.Resources["PointSymbol"] as Symbol; }
public IListSource<LNode> Parse(IListSource<Token> input, ISourceFile file, IMessageSink msgs, Symbol inputType = null) { // For efficiency we'd prefer to re-use our _parser object, but // when parsing lazily, we can't re-use it because another parsing // operation could start before this one is finished. To force // greedy parsing, we can call ParseStmtsGreedy(), but the caller may // prefer lazy parsing, especially if the input is large. As a // compromise I'll check if the source file is larger than a // certain arbitrary size. Also, ParseExprs() is always greedy // so we can always re-use _parser in that case. bool exprMode = inputType == ParsingService.Exprs; char _ = '\0'; if (inputType == ParsingService.Exprs || file.Text.TryGet(255, ref _)) { EcsParser parser = _parser; if (parser == null) _parser = parser = new EcsParser(input, file, msgs); else { parser.ErrorSink = msgs ?? MessageSink.Current; parser.Reset(input, file); } if (inputType == ParsingService.Exprs) return parser.ParseExprs(); else return parser.ParseStmtsGreedy(); } else { var parser = new EcsParser(input, file, msgs); return parser.ParseStmtsLazy().Buffered(); } }
/// <summary> /// Creates a new <see cref="Indicators.CandlestickPatterns.ThreeBlackCrows"/> pattern indicator. /// The indicator will be automatically updated on the given resolution. /// </summary> /// <param name="symbol">The symbol whose pattern we seek</param> /// <param name="resolution">The resolution.</param> /// <param name="selector">Selects a value from the BaseData to send into the indicator, if null defaults to casting the input value to a TradeBar</param> /// <returns>The pattern indicator for the requested symbol.</returns> public ThreeBlackCrows ThreeBlackCrows(Symbol symbol, Resolution? resolution = null, Func<BaseData, TradeBar> selector = null) { var name = _algorithm.CreateIndicatorName(symbol, "THREEBLACKCROWS", resolution); var pattern = new ThreeBlackCrows(name); _algorithm.RegisterIndicator(symbol, pattern, resolution, selector); return pattern; }
internal OldTypeArgumentBinderContext(TypeArgumentSyntax declaration, Symbol genericSymbol, WithTypeParametersBaseBinderContext next) : base(next.Location(declaration), genericSymbol, next) { this.declaration = declaration; this.genericSymbol = genericSymbol; this.enclosing = next; }
public SymbolViewModel(Symbol s, OnSymbolVMSelectedDelegate onSymbolSelected) { Symbol = s; _IsSelected = false; _OnSymbolVMSelected = onSymbolSelected; _Symbols = new List<SymbolViewModel>(); }
/// <summary> /// Gets a <see cref="FactorFile"/> instance for the specified symbol, or null if not found /// </summary> /// <param name="symbol">The security's symbol whose factor file we seek</param> /// <returns>The resolved factor file, or null if not found</returns> public FactorFile Get(Symbol symbol) { FactorFile factorFile; if (_cache.TryGetValue(symbol, out factorFile)) { return factorFile; } var market = symbol.ID.Market; // we first need to resolve the map file to get a permtick, that's how the factor files are stored var mapFileResolver = _mapFileProvider.Get(market); if (mapFileResolver == null) { return GetFactorFile(symbol, symbol.Value, market); } var mapFile = mapFileResolver.ResolveMapFile(symbol.ID.Symbol, symbol.ID.Date); if (mapFile.IsNullOrEmpty()) { return GetFactorFile(symbol, symbol.Value, market); } return GetFactorFile(symbol, mapFile.Permtick, market); }
// saves chosenSymbol into session state and returns partial view with asking for name form public ActionResult AskName(int gameId, Symbol chosenSymbol) { Session["ChosenSymbol"] = chosenSymbol; ViewBag.GameId = gameId; return PartialView("~/Views/NewLayout/AskName.cshtml", chosenSymbol); }
/// <summary> /// The static Select method is the recommended way to create the SelectDevice /// dialog. /// </summary> /// <remarks> /// This method will display the SelectDevice dialog and block until a /// selection has been made. /// </remarks> /// <param name="Title">A string that will be displayed as the title to the /// SelectDevice dialog.</param> /// <param name="AvailableDevices">An array of available Symbol.Device objects. /// </param> /// <returns>The selected device object.</returns> public static Symbol.Barcode2.Device Select( string Title, Symbol.Barcode2.Device[] AvailableDevices) { OurAvailableDevices = AvailableDevices; if ( OurAvailableDevices.Length == 0 ) { return null; } if ( OurAvailableDevices.Length == 1 ) { return OurAvailableDevices[0]; } OurTitle = Title; DefaultIndex = 0; int nSelection = new SelectDevice().Selection; if ( nSelection < 0 ) { return null; } return OurAvailableDevices[nSelection]; }
public static Answer MakeNew(string text, Symbol sym) { Answer a = new Answer(); a.Text = text; a.Sym = sym; return a; }
public Symbol GetNext() { var currentSymbol = String.Empty; while(_CurrentIndex <= _EndIndex) { var currentChar = _Tweet.text[_CurrentIndex]; if(currentChar == ' ') { _CurrentIndex++; if(_IsSymbol(currentSymbol)) { break; } currentSymbol = String.Empty; continue; } currentSymbol += currentChar; _CurrentIndex++; } CurrentSymbol = _GetSymbol(currentSymbol); return CurrentSymbol; }
/// <summary> /// Creats a new instance of the <c>LRStateAction</c> class. /// </summary> /// <param name="index">Index of the LR state action.</param> /// <param name="symbol">Symbol associated with the action.</param> /// <param name="action">Action type.</param> /// <param name="value">Action value.</param> public LRStateAction(int index, Symbol symbol, LRAction action, int value) { m_index = index; m_symbol = symbol; m_action = action; m_value = value; }
public MissingNamespaceSymbol(MissingModuleSymbol containingModule) { Debug.Assert((object)containingModule != null); _containingSymbol = containingModule; _name = string.Empty; }
internal static NormalizedName NameNormalizer(EFElement parent, string refName) { Debug.Assert(parent != null, "parent should not be null"); if (refName == null) { return null; } // cast the parameter to what this really is var end = parent as AssociationSetEnd; Debug.Assert(end != null, "parent should be an AssociationSetEnd"); // get the assoc set var set = end.Parent as AssociationSet; Debug.Assert(set != null, "association set end parent should be an AssociationSet"); // get the entity container name string entityContainerName = null; var ec = set.Parent as BaseEntityContainer; if (ec != null) { entityContainerName = ec.EntityContainerName; } Debug.Assert(ec != null, "AssociationSet parent should be a subclass of BaseEntityContainer"); // the normalized name for an EnitySet is 'EntityContainerName + # + EntitySetName' var symbol = new Symbol(entityContainerName, refName); var normalizedName = new NormalizedName(symbol, null, null, refName); return normalizedName; }
public InvokeExpr(string source, IPersistentMap spanMap, Symbol tag, Expr fexpr, IPersistentVector args) { _source = source; _spanMap = spanMap; _fexpr = fexpr; _args = args; VarExpr varFexpr = fexpr as VarExpr; if (varFexpr != null) { Var fvar = varFexpr.Var; Var pvar = (Var)RT.get(fvar.meta(), Compiler.ProtocolKeyword); if (pvar != null && Compiler.ProtocolCallsitesVar.isBound) { _isProtocol = true; _siteIndex = Compiler.RegisterProtocolCallsite(fvar); Object pon = RT.get(pvar.get(), _onKey); _protocolOn = HostExpr.MaybeType(pon, false); if (_protocolOn != null) { IPersistentMap mmap = (IPersistentMap)RT.get(pvar.get(), _methodMapKey); Keyword mmapVal = (Keyword)mmap.valAt(Keyword.intern(fvar.sym)); if (mmapVal == null) { throw new ArgumentException(String.Format("No method of interface: {0} found for function: {1} of protocol: {2} (The protocol method may have been defined before and removed.)", _protocolOn.FullName, fvar.Symbol, pvar.Symbol)); } String mname = Compiler.munge(mmapVal.Symbol.ToString()); IList<MethodBase> methods = Reflector.GetMethods(_protocolOn, mname, null, args.count() - 1, false); if (methods.Count != 1) throw new ArgumentException(String.Format("No single method: {0} of interface: {1} found for function: {2} of protocol: {3}", mname, _protocolOn.FullName, fvar.Symbol, pvar.Symbol)); _onMethod = (MethodInfo) methods[0]; } } } if (tag != null) _tag = tag; else if (varFexpr != null) { object arglists = RT.get(RT.meta(varFexpr.Var), Compiler.ArglistsKeyword); object sigTag = null; for (ISeq s = RT.seq(arglists); s != null; s = s.next()) { APersistentVector sig = (APersistentVector)s.first(); int restOffset = sig.IndexOf(Compiler.AmpersandSym); if (args.count() == sig.count() || (restOffset > -1 && args.count() >= restOffset)) { sigTag = Compiler.TagOf(sig); break; } } _tag = sigTag ?? varFexpr.Tag; } else _tag = null; }
/// <summary> /// Gets the Future Option's expiry from the Future Symbol provided /// </summary> /// <param name="futureSymbol">Future (non-canonical) Symbol</param> /// <returns>Future Option Expiry for the Future with the same contract month</returns> public static DateTime GetFutureOptionExpiryFromFutureExpiry(Symbol futureSymbol, Symbol canonicalFutureOption = null) { var futureContractMonthDelta = FuturesExpiryUtilityFunctions.GetDeltaBetweenContractMonthAndContractExpiry(futureSymbol.ID.Symbol, futureSymbol.ID.Date); var futureContractMonth = new DateTime( futureSymbol.ID.Date.Year, futureSymbol.ID.Date.Month, 1) .AddMonths(futureContractMonthDelta); if (canonicalFutureOption == null) { canonicalFutureOption = Symbol.CreateOption( Symbol.Create(futureSymbol.ID.Symbol, SecurityType.Future, futureSymbol.ID.Market), futureSymbol.ID.Market, default(OptionStyle), default(OptionRight), default(decimal), SecurityIdentifier.DefaultDate); } return(FuturesOptionExpiry(canonicalFutureOption, futureContractMonth)); }
internal static bool ReportDefaultParameterErrors( Binder binder, Symbol owner, ParameterSyntax parameterSyntax, SourceParameterSymbol parameter, BoundExpression defaultExpression, DiagnosticBag diagnostics) { bool hasErrors = false; // SPEC VIOLATION: The spec says that the conversion from the initializer to the // parameter type is required to be either an identity or a nullable conversion, but // that is not right: // // void M(short myShort = 10) {} // * not an identity or nullable conversion but should be legal // // void M(object obj = (dynamic)null) {} // * an identity conversion, but should be illegal // // void M(MyStruct? myStruct = default(MyStruct)) {} // * a nullable conversion, but must be illegal because we cannot generate metadata for it // // Even if the expression is thoroughly illegal, we still want to bind it and // stick it in the parameter because we want to be able to analyze it for // IntelliSense purposes. TypeSymbol parameterType = parameter.Type.TypeSymbol; HashSet <DiagnosticInfo> useSiteDiagnostics = null; Conversion conversion = binder.Conversions.ClassifyImplicitConversionFromExpression(defaultExpression, parameterType, ref useSiteDiagnostics); diagnostics.Add(defaultExpression.Syntax, useSiteDiagnostics); var extendedTypeSyntax = parameterSyntax.Type as ExtendedTypeSyntax; RefKind refKind = parameterSyntax.Type.GetRefKind(); SyntaxToken refnessKeyword = default; GetModifiers(extendedTypeSyntax?.Modifiers, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword); // CONSIDER: We are inconsistent here regarding where the error is reported; is it // CONSIDER: reported on the parameter name, or on the value of the initializer? // CONSIDER: Consider making this consistent. if (refKind == RefKind.Ref || refKind == RefKind.Out) { // error CS1741: A ref or out parameter cannot have a default value diagnostics.Add(ErrorCode.ERR_RefOutDefaultValue, refnessKeyword.GetLocation()); hasErrors = true; } else if (paramsKeyword.Kind() == SyntaxKind.ParamsKeyword) { // error CS1751: Cannot specify a default value for a parameter array diagnostics.Add(ErrorCode.ERR_DefaultValueForParamsParameter, paramsKeyword.GetLocation()); hasErrors = true; } else if (thisKeyword.Kind() == SyntaxKind.ThisKeyword) { // Only need to report CS1743 for the first parameter. The caller will // have reported CS1100 if 'this' appeared on another parameter. if (parameter.Ordinal == 0) { // error CS1743: Cannot specify a default value for the 'this' parameter diagnostics.Add(ErrorCode.ERR_DefaultValueForExtensionParameter, thisKeyword.GetLocation()); hasErrors = true; } } else if (!defaultExpression.HasAnyErrors && !IsValidDefaultValue(defaultExpression)) { // error CS1736: Default parameter value for '{0}' must be a compile-time constant diagnostics.Add(ErrorCode.ERR_DefaultValueMustBeConstant, parameterSyntax.Default.Value.Location, parameterSyntax.Identifier.ValueText); hasErrors = true; } else if (!conversion.Exists || conversion.IsUserDefined || conversion.IsIdentity && parameterType.SpecialType == SpecialType.System_Object && defaultExpression.Type.IsDynamic()) { // If we had no implicit conversion, or a user-defined conversion, report an error. // // Even though "object x = (dynamic)null" is a legal identity conversion, we do not allow it. // CONSIDER: We could. Doesn't hurt anything. // error CS1750: A value of type '{0}' cannot be used as a default parameter because there are no standard conversions to type '{1}' diagnostics.Add(ErrorCode.ERR_NoConversionForDefaultParam, parameterSyntax.Identifier.GetLocation(), defaultExpression.Display, parameterType); hasErrors = true; } else if (conversion.IsReference && (parameterType.SpecialType == SpecialType.System_Object || parameterType.Kind == SymbolKind.DynamicType) && (object)defaultExpression.Type != null && defaultExpression.Type.SpecialType == SpecialType.System_String || conversion.IsBoxing) { // We don't allow object x = "hello", object x = 123, dynamic x = "hello", etc. // error CS1763: '{0}' is of type '{1}'. A default parameter value of a reference type other than string can only be initialized with null diagnostics.Add(ErrorCode.ERR_NotNullRefDefaultParameter, parameterSyntax.Identifier.GetLocation(), parameterSyntax.Identifier.ValueText, parameterType); hasErrors = true; } else if (conversion.IsNullable && !defaultExpression.Type.IsNullableType() && !(parameterType.GetNullableUnderlyingType().IsEnumType() || parameterType.GetNullableUnderlyingType().IsIntrinsicType())) { // We can do: // M(int? x = default(int)) // M(int? x = default(int?)) // M(MyEnum? e = default(enum)) // M(MyEnum? e = default(enum?)) // M(MyStruct? s = default(MyStruct?)) // // but we cannot do: // // M(MyStruct? s = default(MyStruct)) // error CS1770: // A value of type '{0}' cannot be used as default parameter for nullable parameter '{1}' because '{0}' is not a simple type diagnostics.Add(ErrorCode.ERR_NoConversionForNubDefaultParam, parameterSyntax.Identifier.GetLocation(), defaultExpression.Type, parameterSyntax.Identifier.ValueText); hasErrors = true; } // Certain contexts allow default parameter values syntactically but they are ignored during // semantic analysis. They are: // 1. Explicitly implemented interface methods; since the method will always be called // via the interface, the defaults declared on the implementation will not // be seen at the call site. // // UNDONE: 2. The "actual" side of a partial method; the default values are taken from the // UNDONE: "declaring" side of the method. // // UNDONE: 3. An indexer with only one formal parameter; it is illegal to omit every argument // UNDONE: to an indexer. // // 4. A user-defined operator; it is syntactically impossible to omit the argument. if (owner.IsExplicitInterfaceImplementation() || owner.IsPartialImplementation() || owner.IsOperator()) { // CS1066: The default value specified for parameter '{0}' will have no effect because it applies to a // member that is used in contexts that do not allow optional arguments diagnostics.Add(ErrorCode.WRN_DefaultValueForUnconsumedLocation, parameterSyntax.Identifier.GetLocation(), parameterSyntax.Identifier.ValueText); } return(hasErrors); }
public static ImmutableArray <ParameterSymbol> MakeParameters( Binder binder, Symbol owner, BaseParameterListSyntax syntax, out SyntaxToken arglistToken, DiagnosticBag diagnostics, bool allowRefOrOut, bool allowThis, bool addRefReadOnlyModifier) { arglistToken = default(SyntaxToken); int parameterIndex = 0; int firstDefault = -1; var builder = ArrayBuilder <ParameterSymbol> .GetInstance(); var mustBeLastParameter = (ParameterSyntax)null; foreach (var parameterSyntax in syntax.Parameters) { var extendedParameterType = parameterSyntax.Type as ExtendedTypeSyntax; if (mustBeLastParameter == null) { if (extendedParameterType != null && extendedParameterType.Modifiers.Any(SyntaxKind.ParamsKeyword) || parameterSyntax.Identifier.Kind() == SyntaxKind.ArgListKeyword) { mustBeLastParameter = parameterSyntax; } } CheckParameterModifiers(parameterSyntax, diagnostics); RefKind refKind = parameterSyntax.Type.GetRefKind(); SyntaxToken refnessKeyword = default; GetModifiers(extendedParameterType?.Modifiers, out SyntaxToken paramsKeyword, out SyntaxToken thisKeyword); if (thisKeyword.Kind() != SyntaxKind.None && !allowThis) { diagnostics.Add(ErrorCode.ERR_ThisInBadContext, thisKeyword.GetLocation()); } if (parameterSyntax.IsArgList) { arglistToken = parameterSyntax.Identifier; // The native compiler produces "Expected type" here, in the parser. Roslyn produces // the somewhat more informative "arglist not valid" error. if (paramsKeyword.Kind() != SyntaxKind.None || refnessKeyword.Kind() != SyntaxKind.None || thisKeyword.Kind() != SyntaxKind.None) { // CS1669: __arglist is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, arglistToken.GetLocation()); } continue; } if (parameterSyntax.Default != null && firstDefault == -1) { firstDefault = parameterIndex; } Debug.Assert(parameterSyntax.Type != null); var parameterType = binder.BindType(parameterSyntax.Type, diagnostics); if (!allowRefOrOut && (refKind == RefKind.Ref || refKind == RefKind.Out)) { Debug.Assert(refnessKeyword.Kind() != SyntaxKind.None); // error CS0631: ref and out are not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalRefParam, refnessKeyword.GetLocation()); } var parameter = SourceParameterSymbol.Create( binder, owner, parameterType, parameterSyntax, refKind, parameterSyntax.Identifier, parameterIndex, (paramsKeyword.Kind() != SyntaxKind.None), parameterIndex == 0 && thisKeyword.Kind() != SyntaxKind.None, addRefReadOnlyModifier, diagnostics); ReportParameterErrors(owner, parameterSyntax, parameter, thisKeyword, paramsKeyword, firstDefault, diagnostics); builder.Add(parameter); ++parameterIndex; } if (mustBeLastParameter != null && mustBeLastParameter != syntax.Parameters.Last()) { diagnostics.Add( mustBeLastParameter.Identifier.Kind() == SyntaxKind.ArgListKeyword ? ErrorCode.ERR_VarargsLast : ErrorCode.ERR_ParamsLast, mustBeLastParameter.GetLocation()); } ImmutableArray <ParameterSymbol> parameters = builder.ToImmutableAndFree(); var methodOwner = owner as MethodSymbol; var typeParameters = (object)methodOwner != null ? methodOwner.TypeParameters : default(ImmutableArray <TypeParameterSymbol>); Debug.Assert(methodOwner?.MethodKind != MethodKind.LambdaMethod); bool allowShadowingNames = binder.Compilation.IsFeatureEnabled(MessageID.IDS_FeatureNameShadowingInNestedFunctions) && methodOwner?.MethodKind == MethodKind.LocalFunction; binder.ValidateParameterNameConflicts(typeParameters, parameters, allowShadowingNames, diagnostics); return(parameters); }
public FxcmStopMarketOrderTestParameters(Symbol symbol, decimal highLimit, decimal lowLimit) : base(symbol, highLimit, lowLimit) { }
public static SourceParameterSymbol Create( Binder context, Symbol owner, TypeWithAnnotations parameterType, ParameterSyntax syntax, RefKind refKind, SyntaxToken identifier, int ordinal, bool isParams, bool isExtensionMethodThis, bool addRefReadOnlyModifier, DiagnosticBag declarationDiagnostics) { var name = identifier.ValueText; var locations = ImmutableArray.Create <Location>(new SourceLocation(identifier)); if (isParams) { // touch the constructor in order to generate proper use-site diagnostics Binder.ReportUseSiteDiagnosticForSynthesizedAttribute(context.Compilation, WellKnownMember.System_ParamArrayAttribute__ctor, declarationDiagnostics, identifier.Parent.GetLocation()); } if (addRefReadOnlyModifier && refKind == RefKind.In) { var modifierType = context.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_InAttribute, declarationDiagnostics, syntax); return(new SourceComplexParameterSymbolWithCustomModifiersPrecedingByRef( owner, ordinal, parameterType, refKind, ImmutableArray.Create(CSharpCustomModifier.CreateRequired(modifierType)), name, locations, syntax.GetReference(), ConstantValue.Unset, isParams, isExtensionMethodThis)); } if (!isParams && !isExtensionMethodThis && (syntax.Default == null) && (syntax.AttributeLists.Count == 0) && !owner.IsPartialMethod()) { return(new SourceSimpleParameterSymbol(owner, parameterType, ordinal, refKind, name, locations)); } return(new SourceComplexParameterSymbol( owner, ordinal, parameterType, refKind, name, locations, syntax.GetReference(), ConstantValue.Unset, isParams, isExtensionMethodThis)); }
private void AddIfCaptured(Symbol symbol, SyntaxNode syntax) { Debug.Assert( symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Parameter || symbol.Kind == SymbolKind.Method); if (_currentClosure == null) { // Can't be captured if we're not in a closure return; } if (symbol is LocalSymbol local && local.IsConst) { // consts aren't captured since they're inlined return; } if (symbol is MethodSymbol method && _currentClosure.OriginalMethodSymbol == method) { // Is this recursion? If so there's no capturing return; } if (symbol.ContainingSymbol != _currentClosure.OriginalMethodSymbol) { // Restricted types can't be hoisted, so they are not permitted to be captured AddDiagnosticIfRestrictedType(symbol, syntax); // Record the captured variable where it's captured var scope = _currentScope; var closure = _currentClosure; while (closure != null && symbol.ContainingSymbol != closure.OriginalMethodSymbol) { closure.CapturedVariables.Add(symbol); // Also mark captured in enclosing scopes while (scope.ContainingClosureOpt == closure) { scope = scope.Parent; } closure = scope.ContainingClosureOpt; } // Also record where the captured variable lives // No need to record where local functions live: that was recorded // in the Closures list in each scope if (symbol.Kind == SymbolKind.Method) { return; } if (_localToScope.TryGetValue(symbol, out var declScope)) { declScope.DeclaredVariables.Add(symbol); } else { #if DEBUG // Parameters and locals from expression tree lambdas // are free variables Debug.Assert(_freeVariables.Contains(symbol)); #endif } } }
/// <summary> /// For Trading that terminates on the 4th last business day of the month prior to the contract month. /// If the 4th last business day occurs on a Friday or the day before a holiday, trading terminates on the /// prior business day. This applies to some NYMEX (with fridays), all COMEX. /// </summary> /// <param name="underlyingFuture">Underlying Future Symbol</param> /// <param name="expiryMonth">Contract expiry month</param> /// <param name="hour">Hour the contract expires at</param> /// <param name="minutes">Minute the contract expires at</param> /// <param name="noFridays">Exclude Friday expiration dates from consideration</param> /// <returns>Expiry DateTime of the Future Option</returns> private static DateTime FourthLastBusinessDayInPrecedingMonthFromContractMonth(Symbol underlyingFuture, DateTime expiryMonth, int hour, int minutes, bool noFridays = true) { var holidays = _mhdb.GetEntry(underlyingFuture.ID.Market, underlyingFuture, SecurityType.Future) .ExchangeHours .Holidays; var expiryMonthPreceding = expiryMonth.AddMonths(-1); var fourthLastBusinessDay = FuturesExpiryUtilityFunctions.NthLastBusinessDay(expiryMonthPreceding, 4, holidays); if (noFridays) { while (fourthLastBusinessDay.DayOfWeek == DayOfWeek.Friday || holidays.Contains(fourthLastBusinessDay.AddDays(1))) { fourthLastBusinessDay = FuturesExpiryUtilityFunctions.AddBusinessDays(fourthLastBusinessDay, -1, false, holidays); } } return(fourthLastBusinessDay.AddHours(hour).AddMinutes(minutes)); }
/// <summary> /// Creates a new insight for predicting the percent change in price over the specified period /// </summary> /// <param name="symbol">The symbol this insight is for</param> /// <param name="expiryFunc">Func that defines the expiry time</param> /// <param name="direction">The predicted direction</param> /// <param name="magnitude">The predicted magnitude as a percent change</param> /// <param name="confidence">The confidence in this insight</param> /// <param name="sourceModel">The model generating this insight</param> /// <returns>A new insight object for the specified parameters</returns> public static Insight Price(Symbol symbol, Func <DateTime, DateTime> expiryFunc, InsightDirection direction, double?magnitude = null, double?confidence = null, string sourceModel = null) { return(new Insight(symbol, expiryFunc, InsightType.Price, direction, magnitude, confidence, sourceModel)); }
/// <summary> /// Initializes a new instance of the <see cref="Insight"/> class /// </summary> /// <param name="symbol">The symbol this insight is for</param> /// <param name="expiryFunc">Func that defines the expiry time</param> /// <param name="type">The type of insight, price/volatility</param> /// <param name="direction">The predicted direction</param> /// <param name="magnitude">The predicted magnitude as a percentage change</param> /// <param name="confidence">The confidence in this insight</param> /// <param name="sourceModel">An identifier defining the model that generated this insight</param> public Insight(Symbol symbol, Func <DateTime, DateTime> expiryFunc, InsightType type, InsightDirection direction, double?magnitude, double?confidence, string sourceModel = null) : this(symbol, new FuncPeriodSpecification(expiryFunc), type, direction, magnitude, confidence) { }
private bool UsedBySomeAlpha(Symbol asset) { return(_symbolsPerAlpha.Any(pair => pair.Value.Contains(asset))); }
/// <summary> /// Initializes a new instance of the <see cref="Insight"/> class /// </summary> /// <param name="symbol">The symbol this insight is for</param> /// <param name="period">The period over which the prediction will come true</param> /// <param name="type">The type of insight, price/volatility</param> /// <param name="direction">The predicted direction</param> public Insight(Symbol symbol, TimeSpan period, InsightType type, InsightDirection direction) : this(symbol, period, type, direction, null, null) { }
/// <summary> /// Initializes a new instance of the <see cref="Insight"/> class. /// This constructor is provided mostly for testing purposes. When running inside an algorithm, /// the generated and close times are set based on the algorithm's time. /// </summary> /// <param name="generatedTimeUtc">The time this insight was generated in utc</param> /// <param name="symbol">The symbol this insight is for</param> /// <param name="period">The period over which the prediction will come true</param> /// <param name="type">The type of insight, price/volatility</param> /// <param name="direction">The predicted direction</param> /// <param name="magnitude">The predicted magnitude as a percentage change</param> /// <param name="confidence">The confidence in this insight</param> /// <param name="sourceModel">An identifier defining the model that generated this insight</param> public Insight(DateTime generatedTimeUtc, Symbol symbol, TimeSpan period, InsightType type, InsightDirection direction, double?magnitude, double?confidence, string sourceModel = null) : this(symbol, period, type, direction, magnitude, confidence, sourceModel) { GeneratedTimeUtc = generatedTimeUtc; CloseTimeUtc = generatedTimeUtc + period; }
private void ConvertMinuteFuturesData(Symbol canonical, TickType tickType, Resolution outputResolution, Resolution inputResolution = Resolution.Minute) { var timeSpans = new Dictionary <Resolution, TimeSpan>() { { Resolution.Daily, TimeSpan.FromHours(24) }, { Resolution.Hour, TimeSpan.FromHours(1) }, }; var timeSpan = timeSpans[outputResolution]; var tickTypeConsolidatorMap = new Dictionary <TickType, Func <IDataConsolidator> >() { { TickType.Quote, () => new QuoteBarConsolidator(timeSpan) }, { TickType.OpenInterest, () => new OpenInterestConsolidator(timeSpan) }, { TickType.Trade, () => new TradeBarConsolidator(timeSpan) } }; var consolidators = new Dictionary <string, IDataConsolidator>(); var configs = new Dictionary <string, SubscriptionDataConfig>(); var outputFiles = new Dictionary <string, StringBuilder>(); var futures = new Dictionary <string, Symbol>(); var date = _fromDate; while (date <= _toDate) { var futureChain = LoadFutureChain(canonical, date, tickType, inputResolution); foreach (var future in futureChain) { if (!futures.ContainsKey(future.Value)) { futures[future.Value] = future; var config = new SubscriptionDataConfig(LeanData.GetDataType(outputResolution, tickType), future, inputResolution, TimeZones.NewYork, TimeZones.NewYork, false, false, false, false, tickType); configs[future.Value] = config; consolidators[future.Value] = tickTypeConsolidatorMap[tickType].Invoke(); var sb = new StringBuilder(); outputFiles[future.Value] = sb; consolidators[future.Value].DataConsolidated += (sender, bar) => { sb.Append(LeanData.GenerateLine(bar, SecurityType.Future, outputResolution) + Environment.NewLine); }; } var leanDataReader = new LeanDataReader(configs[future.Value], future, inputResolution, date, _dataDirectory); var consolidator = consolidators[future.Value]; foreach (var bar in leanDataReader.Parse()) { consolidator.Update(bar); } } date = date.AddDays(1); } //write all results foreach (var consolidator in consolidators.Values) { consolidator.Scan(date); } var zip = LeanData.GenerateRelativeZipFilePath(canonical, _fromDate, outputResolution, tickType); var zipPath = Path.Combine(_dataDirectory, zip); var fi = new FileInfo(zipPath); if (!fi.Directory.Exists) { fi.Directory.Create(); } foreach (var future in futures.Values) { var zipEntry = LeanData.GenerateZipEntryName(future, _fromDate, outputResolution, tickType); var sb = outputFiles[future.Value]; //Uncomment to write zip files //QuantConnect.Compression.ZipCreateAppendData(zipPath, zipEntry, sb.ToString()); Assert.IsTrue(sb.Length > 0); } }
/// <summary> /// Initializes a new instance of the <see cref="Insight"/> class /// </summary> /// <param name="symbol">The symbol this insight is for</param> /// <param name="expiryFunc">Func that defines the expiry time</param> /// <param name="type">The type of insight, price/volatility</param> /// <param name="direction">The predicted direction</param> public Insight(Symbol symbol, Func <DateTime, DateTime> expiryFunc, InsightType type, InsightDirection direction) : this(symbol, expiryFunc, type, direction, null, null) { }
private static void Main(string[] args) { var isUpdate = false; if (args.Length == 1) { if (args[0] == "all" || args[0] == "update") { if (args[0] == "update") { isUpdate = true; } args = new[] { "EURUSD,USDJPY,GBPUSD,USDCHF,EURCHF,AUDUSD,USDCAD,NZDUSD,EURGBP,EURJPY,GBPJPY,EURAUD,EURCAD,AUDJPY", "All", "20100101", DateTime.Today.ToString("yyyyMMdd") }; } } if (args.Length != 4) { Console.WriteLine("Usage:\n\t" + "FxcmVolumeDownloader all\t will download data for all available pair for the three resolutions.\n\t" + "FxcmVolumeDownloader update\t will download just last day data for all pair and resolutions already downloaded."); Console.WriteLine("Usage: FxcmVolumeDownloader SYMBOLS RESOLUTION FROMDATE TODATE"); Console.WriteLine("SYMBOLS = eg EURUSD,USDJPY\n" + "\tAvailable pairs:\n" + "\tEURUSD, USDJPY, GBPUSD, USDCHF, EURCHF, AUDUSD, USDCAD,\n" + "\tNZDUSD, EURGBP, EURJPY, GBPJPY, EURAUD, EURCAD, AUDJPY"); Console.WriteLine("RESOLUTION = Minute/Hour/Daily/All"); Console.WriteLine("FROMDATE = yyyymmdd"); Console.WriteLine("TODATE = yyyymmdd"); Environment.Exit(exitCode: 1); } try { Log.DebuggingEnabled = true; Log.LogHandler = new CompositeLogHandler(new ConsoleLogHandler(), new FileLogHandler("FxcmFxVolumeDownloader.log", useTimestampPrefix: false)); // Load settings from command line var tickers = args[0].Split(','); var resolutions = new[] { Resolution.Daily }; if (args[1].ToLower() == "all") { resolutions = new[] { Resolution.Daily, Resolution.Hour, Resolution.Minute }; } else { resolutions[0] = (Resolution)Enum.Parse(typeof(Resolution), args[1]); } var startDate = DateTime.ParseExact(args[2], "yyyyMMdd", CultureInfo.InvariantCulture); var endDate = DateTime.ParseExact(args[3], "yyyyMMdd", CultureInfo.InvariantCulture); // Load settings from config.json var dataDirectory = Config.Get("data-directory", "../../../Data"); var downloader = new FxcmVolumeDownloader(dataDirectory); foreach (var ticker in tickers) { var symbol = Symbol.Create(ticker, SecurityType.Base, Market.FXCM); foreach (var resolution in resolutions) { downloader.Run(symbol, resolution, startDate, endDate, isUpdate); } } } catch (Exception err) { Log.Error(err); } }
public SlippageTestSystem(QREBridgeBase bridge, Symbol symbol) : base(bridge, symbol) { }
public EnumeratorHandler(Symbol symbol, IEnumerator <BaseData> enumerator, EnqueueableEnumerator <BaseData> enqueueable) : base(symbol, enumerator, true) { _enqueueable = enqueueable; }
public static ImmutableArray <ParameterSymbol> MakeParameters( Binder binder, Symbol owner, BaseParameterListSyntax syntax, bool allowRefOrOut, out SyntaxToken arglistToken, DiagnosticBag diagnostics, bool beStrict) { arglistToken = default(SyntaxToken); int parameterIndex = 0; int firstDefault = -1; var builder = ArrayBuilder <ParameterSymbol> .GetInstance(); ImmutableArray <ParameterSymbol> parameters; foreach (var parameterSyntax in syntax.Parameters) { SyntaxToken outKeyword; SyntaxToken refKeyword; SyntaxToken paramsKeyword; SyntaxToken thisKeyword; var refKind = GetModifiers(parameterSyntax.Modifiers, out outKeyword, out refKeyword, out paramsKeyword, out thisKeyword); if (parameterSyntax.IsArgList) { arglistToken = parameterSyntax.Identifier; // The native compiler produces "Expected type" here, in the parser. Roslyn produces // the somewhat more informative "arglist not valid" error. if (paramsKeyword.Kind() != SyntaxKind.None || outKeyword.Kind() != SyntaxKind.None || refKeyword.Kind() != SyntaxKind.None || thisKeyword.Kind() != SyntaxKind.None) { // CS1669: __arglist is not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, arglistToken.GetLocation()); } continue; } if (parameterSyntax.Default != null && firstDefault == -1) { firstDefault = parameterIndex; } Debug.Assert(parameterSyntax.Type != null); var parameterType = binder.BindType(parameterSyntax.Type, diagnostics); if (!allowRefOrOut && (refKind != RefKind.None)) { var outOrRefKeyword = (outKeyword.Kind() != SyntaxKind.None) ? outKeyword : refKeyword; Debug.Assert(outOrRefKeyword.Kind() != SyntaxKind.None); // error CS0631: ref and out are not valid in this context diagnostics.Add(ErrorCode.ERR_IllegalRefParam, outOrRefKeyword.GetLocation()); } var parameter = SourceParameterSymbol.Create( binder, owner, parameterType, parameterSyntax, refKind, parameterSyntax.Identifier, parameterIndex, (paramsKeyword.Kind() != SyntaxKind.None), parameterIndex == 0 && thisKeyword.Kind() != SyntaxKind.None, diagnostics, beStrict); ReportParameterErrors(owner, parameterSyntax, parameter, firstDefault, diagnostics); builder.Add(parameter); ++parameterIndex; } parameters = builder.ToImmutableAndFree(); var methodOwner = owner as MethodSymbol; var typeParameters = (object)methodOwner != null ? methodOwner.TypeParameters : default(ImmutableArray <TypeParameterSymbol>); binder.ValidateParameterNameConflicts(typeParameters, parameters, diagnostics); return(parameters); }
public override ImmutableArray <Symbol> GetMembers() { Symbol constructor = this.Constructor; return((object)constructor == null ? ImmutableArray <Symbol> .Empty : ImmutableArray.Create(constructor)); }
/// <summary> /// Get the benchmark for this model /// </summary> /// <param name="securities">SecurityService to create the security with if needed</param> /// <returns>The benchmark for this brokerage</returns> public override IBenchmark GetBenchmark(SecurityManager securities) { var symbol = Symbol.Create("BTCUSDC", SecurityType.Crypto, Market.Binance); return(SecurityBenchmark.CreateInstance(securities, symbol)); }
public ErrorDiagnostic FunctionDoesNotExistInNamespace(Symbol namespaceSymbol, string name) => new ErrorDiagnostic( TextSpan, "BCP107", $"The function \"{name}\" does not exist in namespace \"{namespaceSymbol.Name}\".");
private PEParameterSymbol( PEModuleSymbol moduleSymbol, Symbol containingSymbol, int ordinal, bool isByRef, TypeWithAnnotations typeWithAnnotations, ParameterHandle handle, Symbol nullableContext, int countOfCustomModifiers, out bool isBad) { Debug.Assert((object)moduleSymbol != null); Debug.Assert((object)containingSymbol != null); Debug.Assert(ordinal >= 0); Debug.Assert(typeWithAnnotations.HasType); isBad = false; _moduleSymbol = moduleSymbol; _containingSymbol = containingSymbol; _ordinal = (ushort)ordinal; _handle = handle; RefKind refKind = RefKind.None; if (handle.IsNil) { refKind = isByRef ? RefKind.Ref : RefKind.None; typeWithAnnotations = TupleTypeSymbol.TryTransformToTuple(typeWithAnnotations.Type, out TupleTypeSymbol tuple) ? TypeWithAnnotations.Create(tuple) : typeWithAnnotations; byte?value = nullableContext.GetNullableContextValue(); if (value.HasValue) { typeWithAnnotations = NullableTypeDecoder.TransformType(typeWithAnnotations, value.GetValueOrDefault(), default); } _lazyCustomAttributes = ImmutableArray <CSharpAttributeData> .Empty; _lazyHiddenAttributes = ImmutableArray <CSharpAttributeData> .Empty; _lazyDefaultValue = ConstantValue.NotAvailable; _lazyIsParams = ThreeState.False; } else { try { moduleSymbol.Module.GetParamPropsOrThrow(handle, out _name, out _flags); } catch (BadImageFormatException) { isBad = true; } if (isByRef) { ParameterAttributes inOutFlags = _flags & (ParameterAttributes.Out | ParameterAttributes.In); if (inOutFlags == ParameterAttributes.Out) { refKind = RefKind.Out; } else if (moduleSymbol.Module.HasIsReadOnlyAttribute(handle)) { refKind = RefKind.In; } else { refKind = RefKind.Ref; } } var typeSymbol = DynamicTypeDecoder.TransformType(typeWithAnnotations.Type, countOfCustomModifiers, handle, moduleSymbol, refKind); typeWithAnnotations = typeWithAnnotations.WithTypeAndModifiers(typeSymbol, typeWithAnnotations.CustomModifiers); // Decode nullable before tuple types to avoid converting between // NamedTypeSymbol and TupleTypeSymbol unnecessarily. // The containing type is passed to NullableTypeDecoder.TransformType to determine access // for property parameters because the property does not have explicit accessibility in metadata. var accessSymbol = containingSymbol.Kind == SymbolKind.Property ? containingSymbol.ContainingSymbol : containingSymbol; typeWithAnnotations = NullableTypeDecoder.TransformType(typeWithAnnotations, handle, moduleSymbol, accessSymbol: accessSymbol, nullableContext: nullableContext); typeWithAnnotations = TupleTypeDecoder.DecodeTupleTypesIfApplicable(typeWithAnnotations, handle, moduleSymbol); } _typeWithAnnotations = typeWithAnnotations; bool hasNameInMetadata = !string.IsNullOrEmpty(_name); if (!hasNameInMetadata) { // As was done historically, if the parameter doesn't have a name, we give it the name "value". _name = "value"; } _packedFlags = new PackedFlags(refKind, attributesAreComplete: handle.IsNil, hasNameInMetadata: hasNameInMetadata); Debug.Assert(refKind == this.RefKind); Debug.Assert(hasNameInMetadata == this.HasNameInMetadata); }
static void Main(string[] args) { // A ski jumper leaves the ski track moving in the horizontal // direction with a speed of 25.0 m/s, as shown in Figure 4.14. // The landing incline below him falls off with a slope of 35.0°. // Where does he land on the incline? var thA = new Symbol("thA"); // angle at point A var vA = new Symbol("vA"); // velocity at point A var g = new Symbol("g"); // magnitude of gravity var _g = new Point(0, -g); // gravity vector var th = new Symbol("th"); // angle of incline var objA = new Obj() { position = new Point(0, 0), velocity = Point.FromAngle(thA, vA), acceleration = _g, time = 0 }; Func <MathObject, MathObject> numeric = obj => obj .Substitute(vA, 25) .Substitute(thA, 0.0) .Substitute(th, (-35).ToRadians()) .Substitute(Trig.Pi, 3.14159) .Substitute(g, 9.8); var intersection = objA.ProjectileInclineIntersection(th); Action nl = () => "".Disp(); "Where does he land on the incline?".Disp(); nl(); "x position (symbolic):".Disp(); intersection.x.Disp(); nl(); "y position (symbolic):".Disp(); intersection.y.Disp(); nl(); "x position (numeric):".Disp(); numeric(intersection.x).Disp(); nl(); "y position (numeric):".Disp(); numeric(intersection.y).Disp(); nl(); var objB = new Obj() { position = intersection, acceleration = _g }; "Determine how long the jumper is airborne".Disp(); nl(); "symbolic:".Disp(); var timeB = Calc.Time(objA, objB, 1); timeB.Disp(); nl(); "numeric:".Disp(); numeric(timeB).Disp(); nl(); objB = objA.AtTime(timeB); "Determine his vertical component of velocity just before he lands".Disp(); nl(); "symbolic:".Disp(); objB.velocity.y.Disp(); nl(); "numeric:".Disp(); numeric(objB.velocity.y).Disp(); Console.ReadLine(); }
public FixableErrorDiagnostic FunctionDoesNotExistInNamespaceWithSuggestion(Symbol namespaceSymbol, string name, string suggestedName) => new FixableErrorDiagnostic( TextSpan, "BCP108", $"The function \"{name}\" does not exist in namespace \"{namespaceSymbol.Name}\". Did you mean \"{suggestedName}\"?", new CodeFix($"Change \"{name}\" to \"{suggestedName}\"", true, CodeManipulator.Replace(TextSpan, suggestedName)));
public override JSValue Evaluate(Context context) { var res = JSObject.CreateObject(); if (_fieldNames.Length == 0 && _computedProperties.Length == 0) { return(res); } res._fields = JSObject.getFieldsContainer(); for (int i = 0; i < _fieldNames.Length; i++) { var val = _values[i].Evaluate(context); val = val.CloneImpl(false); val._attributes = JSValueAttributesInternal.None; if (_fieldNames[i] == "__proto__") { res.__proto__ = val._oValue as JSObject; } else { res._fields[_fieldNames[i]] = val; } } for (var i = 0; i < _computedProperties.Length; i++) { var key = _computedProperties[i].Key.Evaluate(context).CloneImpl(false); var value = _computedProperties[i].Value.Evaluate(context).CloneImpl(false); JSValue existedValue; Symbol symbolKey = null; string stringKey = null; if (key.Is <Symbol>()) { symbolKey = key.As <Symbol>(); if (res._symbols == null) { res._symbols = new Dictionary <Symbol, JSValue>(); } if (!res._symbols.TryGetValue(symbolKey, out existedValue)) { res._symbols[symbolKey] = existedValue = value; } } else { stringKey = key.As <string>(); if (!res._fields.TryGetValue(stringKey, out existedValue)) { res._fields[stringKey] = existedValue = value; } } if (existedValue != value) { if (existedValue.Is(JSValueType.Property) && value.Is(JSValueType.Property)) { var egs = existedValue.As <Core.PropertyPair>(); var ngs = value.As <Core.PropertyPair>(); egs.getter = ngs.getter ?? egs.getter; egs.setter = ngs.setter ?? egs.setter; } else { if (key.Is <Symbol>()) { res._symbols[symbolKey] = value; } else { res._fields[stringKey] = value; } } } } return(res); }
private void ParseNextSymbol() { _parsing = true; int index = 0; string currentString = _currentString; Symbol symbol = Symbol.None; while (symbol == Symbol.None) { switch (currentString[index]) { case '%': index++; if (currentString[index] == 'w') { string num = ""; index++; while (symbol == Symbol.None) { switch (currentString[index]) { case '0': num += '0'; index++; break; case '1': num += '1'; index++; break; case '2': num += '2'; index++; break; case '3': num += '3'; index++; break; case '4': num += '4'; index++; break; case '5': num += '5'; index++; break; case '6': num += '6'; index++; break; case '7': num += '7'; index++; break; case '8': num += '8'; index++; break; case '9': num += '9'; index++; break; default: symbol = Symbol.Wait; index++; waitTime = Int32.Parse(num); break; } if (index >= currentString.Count()) { symbol = Symbol.Wait; waitTime = Int32.Parse(num); break; } } } else if (currentString[index] == 'c') { symbol = Symbol.Click; index++; } break; default: symbol = Symbol.Char; _drawString += _currentString[index]; index++; break; } } _currentString = currentString.Remove(0, index); _currentSymbol = symbol; _parsing = false; }
private static void GenerateEvent(ScriptGenerator generator, string typeName, EventSymbol eventSymbol) { ScriptTextWriter writer = generator.Writer; ParameterSymbol valueParameter = eventSymbol.Parameters[0]; string eventName = eventSymbol.GeneratedName; string fieldName = eventName; if (eventSymbol.DefaultImplementation) { fieldName = "__" + Utility.CreateCamelCaseName(eventSymbol.Name); Debug.Assert(eventSymbol.Parent.Type == SymbolType.Class); Symbol fieldSymbol = ((ClassSymbol)eventSymbol.Parent).GetMember(fieldName); Debug.Assert((fieldSymbol != null) && (fieldSymbol.Type == SymbolType.Field)); fieldName = fieldSymbol.GeneratedName; } string fieldReference; if ((eventSymbol.Visibility & MemberVisibility.Static) == 0) { fieldReference = "this."; } else { fieldReference = typeName + "."; } fieldReference += fieldName; bool instanceMember = true; if ((eventSymbol.Visibility & MemberVisibility.Static) != 0) { instanceMember = false; writer.Write(typeName); writer.Write("."); } writer.Write("add_"); writer.Write(eventName); if (instanceMember) { writer.Write(": "); } else { writer.Write(" = "); } writer.Write("function("); writer.Write(valueParameter.GeneratedName); writer.WriteLine(") {"); writer.Indent++; if (generator.Options.EnableDocComments) { DocCommentGenerator.GenerateComment(generator, eventSymbol); } if (eventSymbol.DefaultImplementation) { writer.Write(fieldReference); writer.Write(" = ss.bindAdd("); writer.Write(fieldReference); writer.Write(", "); writer.Write(valueParameter.GeneratedName); writer.WriteLine(");"); } else { CodeGenerator.GenerateScript(generator, eventSymbol, /* add */ true); } writer.Indent--; writer.Write("}"); if (instanceMember == false) { writer.WriteLine(";"); } if (instanceMember) { writer.WriteLine(","); } else { writer.Write(typeName); writer.Write("."); } writer.Write("remove_"); writer.Write(eventName); if (instanceMember) { writer.Write(": "); } else { writer.Write(" = "); } writer.Write("function("); writer.Write(valueParameter.GeneratedName); writer.WriteLine(") {"); writer.Indent++; if (generator.Options.EnableDocComments) { DocCommentGenerator.GenerateComment(generator, eventSymbol); } if (eventSymbol.DefaultImplementation) { writer.Write(fieldReference); writer.Write(" = ss.bindSub("); writer.Write(fieldReference); writer.Write(", "); writer.Write(valueParameter.GeneratedName); writer.WriteLine(");"); } else { CodeGenerator.GenerateScript(generator, eventSymbol, /* add */ false); } writer.Indent--; writer.Write("}"); if (instanceMember == false) { writer.WriteLine(";"); } }
//Select statement public List <string>[] Select() { string query = "SELECT * FROM opensignal"; //Create a list to store the result List <string>[] list = new List <string> [9]; string[][] arr = new string[20][]; for (int x = 0; x < arr.Length; x++) { arr[x] = new string[8]; } list[0] = new List <string>(); list[1] = new List <string>(); list[2] = new List <string>(); list[3] = new List <string>(); list[4] = new List <string>(); list[5] = new List <string>(); list[6] = new List <string>(); list[7] = new List <string>(); list[8] = new List <string>(); MySqlCommand cmd = new MySqlCommand(query, connection); MySqlDataReader dataReader = cmd.ExecuteReader(); int nr = 0; while (dataReader.Read()) { // Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0), reader.GetString(1)); /// SET POSITION HERE DONT INSERT IN ARRAY /// create file with position or check is exist position with label in history or open positions arr[nr][0] = "" + dataReader["id"]; arr[nr][1] = "" + dataReader["symbol"]; arr[nr][2] = "" + dataReader["volume"]; arr[nr][3] = "" + dataReader["type"]; arr[nr][4] = "" + dataReader["opent"]; arr[nr][5] = "" + dataReader["openp"]; arr[nr][6] = "" + dataReader["sl"]; arr[nr][7] = "" + dataReader["tp"]; if (!CreateFile("" + dataReader["id"])) { Symbol sym = MarketData.GetSymbol("" + dataReader["symbol"]); //ExecuteMarketOrder(TradeType.Buy, sym, (Int32)dataReader["volume"], (string)dataReader["id"]); Print("Utwórz pozycję" + dataReader["id"]); } //Print(arr[nr][1]); nr++; //Print(dataReader["id"]); list[0].Add(dataReader["id"] + ""); list[1].Add(dataReader["symbol"] + ""); list[2].Add(dataReader["volume"] + ""); list[3].Add(dataReader["type"] + ""); list[4].Add(dataReader["opent"] + ""); list[5].Add(dataReader["sl"] + ""); list[6].Add(dataReader["tp"] + ""); list[7].Add(dataReader["time"] + ""); list[8].Add(dataReader["account"] + ""); } dataReader.Close(); foreach (string[] dd in arr) { if (dd[0] != null) { Print("POS " + dd[0]); } } // Loop over list elements using foreach-loop. foreach (List <string> element in list) { //Print("ELEMENT " + element); string line = string.Join(",", element.ToArray()); //Print("POZYCJA ============================= " + line); //Print(element.ElementAt(0)); foreach (string pos in element) { //Print(pos); } } return(list); }
public ShellNavigationItem(string label, Symbol symbol, string viewModelName) : this(label, viewModelName) { Symbol = symbol; }
public void SetContainer(Symbol container) { _container = container; }