content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Linq;
using HotChocolate.Data.Filters;
using HotChocolate.Data.Projections;
using HotChocolate.Data.Sorting;
using HotChocolate.Language;
using HotChocolate.Resolvers;
using HotChocolate.Types;
namespace HotChocolate.Data
{
internal static class ErrorHelper
{
public static IError CreateNonNullError<T>(
IFilterField field,
IValueNode value,
IFilterVisitorContext<T> context)
{
IFilterInputType filterType = context.Types.OfType<IFilterInputType>().First();
return ErrorBuilder.New()
.SetMessage(
DataResources.ErrorHelper_CreateNonNullError,
context.Operations.Peek().Name,
filterType.Visualize())
.AddLocation(value)
.SetExtension("expectedType", new NonNullType(field.Type).Visualize())
.SetExtension("filterType", filterType.Visualize())
.Build();
}
public static IError SortingVisitor_ListValues(ISortField field, ListValueNode node) =>
ErrorBuilder.New()
.SetMessage(
DataResources.SortingVisitor_ListInput_AreNotSuported,
field.DeclaringType.Name,
field.Name)
.AddLocation(node)
.SetExtension(nameof(field), field)
.Build();
public static IError CreateNonNullError<T>(
ISortField field,
IValueNode value,
ISortVisitorContext<T> context)
{
ISortInputType sortType = context.Types.OfType<ISortInputType>().First();
return ErrorBuilder.New()
.SetMessage(
DataResources.ErrorHelper_CreateNonNullError,
context.Fields.Peek().Name,
sortType.Visualize())
.AddLocation(value)
.SetExtension("expectedType", new NonNullType(field.Type).Visualize())
.SetExtension("sortType", sortType.Visualize())
.Build();
}
public static ISchemaError ProjectionConvention_UnableToCreateFieldHandler(
IProjectionProvider convention,
Type fieldHandler) =>
SchemaErrorBuilder.New()
.SetMessage(
DataResources.FilterProvider_UnableToCreateFieldHandler,
fieldHandler.FullName ?? fieldHandler.Name,
convention.GetType().FullName ?? convention.GetType().Name)
.SetExtension(nameof(convention), convention)
.SetExtension(nameof(fieldHandler), fieldHandler)
.Build();
public static IError ProjectionProvider_CreateMoreThanOneError(IResolverContext context) =>
ErrorBuilder.New()
.SetMessage(DataResources.ProjectionProvider_CreateMoreThanOneError)
.SetCode("SELECTIONS_SINGLE_MORE_THAN_ONE")
.SetPath(context.Path)
.AddLocation(context.Selection.SyntaxNode)
.Build();
public static IError ProjectionProvider_CreateMoreThanOneError() =>
ErrorBuilder.New()
.SetMessage(DataResources.ProjectionProvider_CreateMoreThanOneError)
.SetCode("SELECTIONS_SINGLE_MORE_THAN_ONE")
.Build();
public static IError ProjectionProvider_CouldNotProjectFiltering(
IValueNode node) =>
ErrorBuilder.New()
.SetMessage(DataResources.ProjectionProvider_CouldNotProjectFiltering)
.AddLocation(node)
.Build();
public static IError ProjectionProvider_CouldNotProjectSorting(
IValueNode node) =>
ErrorBuilder.New()
.SetMessage(DataResources.ProjectionProvider_CouldNotProjectSorting)
.AddLocation(node)
.Build();
}
}
| 39.584158 | 99 | 0.602051 | [
"MIT"
] | alexandercarls/hotchocolate | src/HotChocolate/Data/src/Data/ErrorHelper.cs | 3,998 | C# |
#region BSD License
/*
*
* Original BSD 3-Clause License (https://github.com/ComponentFactory/Krypton/blob/master/LICENSE)
* © Component Factory Pty Ltd, 2006 - 2016, (Version 4.5.0.0) All rights reserved.
*
* New BSD 3-Clause License (https://github.com/Krypton-Suite/Standard-Toolkit/blob/master/LICENSE)
* Modifications by Peter Wagner(aka Wagnerp) & Simon Coghlan(aka Smurf-IV), et al. 2017 - 2022. All rights reserved.
*
*/
#endregion
namespace Krypton.Toolkit
{
/// <summary>
/// Details for palette layout events.
/// </summary>
public class PaletteLayoutEventArgs : NeedLayoutEventArgs
{
#region Instance Fields
#endregion
#region Identity
/// <summary>
/// Initialize a new instance of the PaletteLayoutEventArgs class.
/// </summary>
/// <param name="needLayout">Does the layout need regenerating.</param>
/// <param name="needColorTable">Have the color table values changed?</param>
public PaletteLayoutEventArgs(bool needLayout,
bool needColorTable)
: base(needLayout) =>
NeedColorTable = needColorTable;
#endregion
#region Public
/// <summary>
/// Gets a value indicating if the color table needs to be reprocessed.
/// </summary>
public bool NeedColorTable { get; }
#endregion
}
}
| 31.130435 | 119 | 0.625 | [
"BSD-3-Clause"
] | Krypton-Suite/Standard-Toolkit | Source/Krypton Components/Krypton.Toolkit/EventArgs/PaletteLayoutEventArgs.cs | 1,435 | C# |
/**
Copyright (c) 2018-present, Walmart Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using Newtonsoft.Json;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
namespace Walmart.Sdk.Base.Primitive
{
public class BasePayload : IPayload
{
public XmlSerializerNamespaces Xmlns { get; set; } = new XmlSerializerNamespaces();
}
}
| 30.15625 | 92 | 0.762694 | [
"Apache-2.0"
] | GaryWayneSmith/partnerapi_sdk_dotnet | Source/Walmart.Sdk.Base/Primitive/BasePayload.cs | 967 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
using System.Web;
using DotNetNuke.Common;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Users;
namespace Dnn.PersonaBar.Prompt.Components.Models
{
public class HostModel
{
// DNN Platform for example
public string Product { get; set; }
public string Version { get; set; }
public bool UpgradeAvailable { get; set; }
// .NET Framework: 4.6 for example
public string Framework { get; set; }
// Could be IPv6
public string IpAddress { get; set; }
// ReflectionPermission, WebPermission, AspNetHostingPermission, etc.
public string Permissions { get; set; }
// prompt.com
public string Site { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public string Email { get; set; }
public string Theme { get; set; }
public string Container { get; set; }
public string EditTheme { get; set; }
public string EditContainer { get; set; }
public int PortalCount { get; set; }
public static HostModel Current()
{
var application = DotNetNuke.Application.DotNetNukeContext.Current.Application;
var controlBarController = DotNetNuke.Web.Components.Controllers.ControlBarController.Instance;
var request = HttpContext.Current.Request;
var upgradeIndicator = controlBarController.GetUpgradeIndicator(application.Version, request.IsLocal, request.IsSecureConnection);
var hostName = System.Net.Dns.GetHostName();
var hostPortal = DotNetNuke.Entities.Portals.PortalController.Instance.GetPortal(Host.HostPortalID);
var portalCount = DotNetNuke.Entities.Portals.PortalController.Instance.GetPortals().Count;
var isHost = UserController.Instance.GetCurrentUserInfo()?.IsSuperUser ?? false;
var hostModel = new HostModel
{
Version = "v." + Globals.FormatVersion(application.Version, true),
Product = application.Description,
UpgradeAvailable = upgradeIndicator != null,
Framework = isHost ? Globals.NETFrameworkVersion.ToString(2) : string.Empty,
IpAddress = System.Net.Dns.GetHostEntry(hostName).AddressList[0].ToString(),
Permissions = DotNetNuke.Framework.SecurityPolicy.Permissions,
Site = hostPortal.PortalName,
Title = Host.HostTitle,
Url = Host.HostURL,
Email = Host.HostEmail,
Theme = Utilities.FormatSkinName(Host.DefaultPortalSkin),
EditTheme = Utilities.FormatSkinName(Host.DefaultAdminSkin),
Container = Utilities.FormatContainerName(Host.DefaultPortalContainer),
EditContainer = Utilities.FormatContainerName(Host.DefaultAdminContainer),
PortalCount = portalCount
};
return hostModel;
}
}
}
| 47.220588 | 142 | 0.646528 | [
"MIT"
] | MaiklT/Dnn.Platform | Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Components/Prompt/Models/HostModel.cs | 3,213 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace KantaiHelper.Views
{
/// <summary>
/// MainWindow.xaml에 대한 상호 작용 논리
/// </summary>
public partial class ToolView : UserControl
{
public ToolView()
{
InitializeComponent();
}
}
}
| 20.241379 | 44 | 0.764906 | [
"MIT"
] | CirnoV/KantaiHelper | KantaiHelper/KantaiHelper/Views/ToolView.xaml.cs | 607 | C# |
using System;
using System.Windows.Forms;
namespace AutoUpdaterDotNET
{
internal partial class RemindLaterForm : Form
{
public RemindLaterFormat RemindLaterFormat { get; private set; }
public int RemindLaterAt { get; private set; }
public RemindLaterForm()
{
InitializeComponent();
}
private void RemindLaterFormLoad(object sender, EventArgs e)
{
comboBoxRemindLater.SelectedIndex = 0;
radioButtonYes.Checked = true;
}
private void ButtonOkClick(object sender, EventArgs e)
{
if (radioButtonYes.Checked)
{
switch (comboBoxRemindLater.SelectedIndex)
{
case 0:
RemindLaterFormat = RemindLaterFormat.Minutes;
RemindLaterAt = 30;
break;
case 1:
RemindLaterFormat = RemindLaterFormat.Hours;
RemindLaterAt = 12;
break;
case 2:
RemindLaterFormat = RemindLaterFormat.Days;
RemindLaterAt = 1;
break;
case 3:
RemindLaterFormat = RemindLaterFormat.Days;
RemindLaterAt = 2;
break;
case 4:
RemindLaterFormat = RemindLaterFormat.Days;
RemindLaterAt = 4;
break;
case 5:
RemindLaterFormat = RemindLaterFormat.Days;
RemindLaterAt = 8;
break;
case 6:
RemindLaterFormat = RemindLaterFormat.Days;
RemindLaterAt = 10;
break;
}
DialogResult = DialogResult.OK;
}
else
{
DialogResult = DialogResult.Abort;
}
}
private void RadioButtonYesCheckedChanged(object sender, EventArgs e)
{
comboBoxRemindLater.Enabled = radioButtonYes.Checked;
}
}
} | 32.833333 | 78 | 0.445008 | [
"MIT"
] | AjuPrince/AutoUpdater.NET | AutoUpdater.NET/RemindLaterForm.cs | 2,366 | C# |
// Copyright 2019 Cohesity Inc.
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Cohesity.Model
{
/// <summary>
/// ADObjectRestoreParam
/// </summary>
[DataContract]
public partial class ADObjectRestoreParam : IEquatable<ADObjectRestoreParam>
{
/// <summary>
/// Initializes a new instance of the <see cref="ADObjectRestoreParam" /> class.
/// </summary>
/// <param name="credentials">credentials.</param>
/// <param name="guidVec">Array of AD object guids to restore either from recycle bin or from AD snapshot. The guid should not exist in production AD. If it exits, then kDuplicate error is output in status..</param>
/// <param name="optionFlags">Restore option flags of type ADObjectRestoreOptionFlags..</param>
/// <param name="ouPath">Distinguished name(DN) of the target Organization Unit (OU) to restore non-OU object. This can be empty, in which case objects are restored to their original OU. The 'credential' specified must have privileges to add objects to this OU. Example: 'OU=SJC,OU=EngOU,DC=contoso,DC=com'. This parameter is ignored for OU objects..</param>
public ADObjectRestoreParam(Credentials credentials = default(Credentials), List<string> guidVec = default(List<string>), int? optionFlags = default(int?), string ouPath = default(string))
{
this.GuidVec = guidVec;
this.OptionFlags = optionFlags;
this.OuPath = ouPath;
this.Credentials = credentials;
this.GuidVec = guidVec;
this.OptionFlags = optionFlags;
this.OuPath = ouPath;
}
/// <summary>
/// Gets or Sets Credentials
/// </summary>
[DataMember(Name="credentials", EmitDefaultValue=false)]
public Credentials Credentials { get; set; }
/// <summary>
/// Array of AD object guids to restore either from recycle bin or from AD snapshot. The guid should not exist in production AD. If it exits, then kDuplicate error is output in status.
/// </summary>
/// <value>Array of AD object guids to restore either from recycle bin or from AD snapshot. The guid should not exist in production AD. If it exits, then kDuplicate error is output in status.</value>
[DataMember(Name="guidVec", EmitDefaultValue=true)]
public List<string> GuidVec { get; set; }
/// <summary>
/// Restore option flags of type ADObjectRestoreOptionFlags.
/// </summary>
/// <value>Restore option flags of type ADObjectRestoreOptionFlags.</value>
[DataMember(Name="optionFlags", EmitDefaultValue=true)]
public int? OptionFlags { get; set; }
/// <summary>
/// Distinguished name(DN) of the target Organization Unit (OU) to restore non-OU object. This can be empty, in which case objects are restored to their original OU. The 'credential' specified must have privileges to add objects to this OU. Example: 'OU=SJC,OU=EngOU,DC=contoso,DC=com'. This parameter is ignored for OU objects.
/// </summary>
/// <value>Distinguished name(DN) of the target Organization Unit (OU) to restore non-OU object. This can be empty, in which case objects are restored to their original OU. The 'credential' specified must have privileges to add objects to this OU. Example: 'OU=SJC,OU=EngOU,DC=contoso,DC=com'. This parameter is ignored for OU objects.</value>
[DataMember(Name="ouPath", EmitDefaultValue=true)]
public string OuPath { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString() { return ToJson(); }
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ADObjectRestoreParam);
}
/// <summary>
/// Returns true if ADObjectRestoreParam instances are equal
/// </summary>
/// <param name="input">Instance of ADObjectRestoreParam to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ADObjectRestoreParam input)
{
if (input == null)
return false;
return
(
this.Credentials == input.Credentials ||
(this.Credentials != null &&
this.Credentials.Equals(input.Credentials))
) &&
(
this.GuidVec == input.GuidVec ||
this.GuidVec != null &&
input.GuidVec != null &&
this.GuidVec.SequenceEqual(input.GuidVec)
) &&
(
this.OptionFlags == input.OptionFlags ||
(this.OptionFlags != null &&
this.OptionFlags.Equals(input.OptionFlags))
) &&
(
this.OuPath == input.OuPath ||
(this.OuPath != null &&
this.OuPath.Equals(input.OuPath))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Credentials != null)
hashCode = hashCode * 59 + this.Credentials.GetHashCode();
if (this.GuidVec != null)
hashCode = hashCode * 59 + this.GuidVec.GetHashCode();
if (this.OptionFlags != null)
hashCode = hashCode * 59 + this.OptionFlags.GetHashCode();
if (this.OuPath != null)
hashCode = hashCode * 59 + this.OuPath.GetHashCode();
return hashCode;
}
}
}
}
| 45.269737 | 402 | 0.595408 | [
"Apache-2.0"
] | chandrashekar-cohesity/cohesity-powershell-module | src/Cohesity.Powershell.Models/ADObjectRestoreParam.cs | 6,881 | C# |
namespace SharemundoBulgaria.Areas.Identity.Pages.Account
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using SharemundoBulgaria.Models.User;
[AllowAnonymous]
public class LoginModel : PageModel
{
private readonly UserManager<ApplicationUser> userManager;
private readonly SignInManager<ApplicationUser> signInManager;
private readonly ILogger<LoginModel> logger;
public LoginModel(
SignInManager<ApplicationUser> signInManager,
ILogger<LoginModel> logger,
UserManager<ApplicationUser> userManager)
{
this.userManager = userManager;
this.signInManager = signInManager;
this.logger = logger;
}
[BindProperty]
public InputModel Input { get; set; }
public IList<AuthenticationScheme> ExternalLogins { get; set; }
public string ReturnUrl { get; set; }
[TempData]
public string ErrorMessage { get; set; }
public async Task OnGetAsync(string returnUrl = null)
{
if (!string.IsNullOrEmpty(this.ErrorMessage))
{
this.ModelState.AddModelError(string.Empty, this.ErrorMessage);
}
returnUrl = returnUrl ?? this.Url.Content("~/");
// Clear the existing external cookie to ensure a clean login process
await this.HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
this.ExternalLogins = (await this.signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
this.ReturnUrl = returnUrl;
}
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? this.Url.Content("~/");
if (this.ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await this.signInManager.PasswordSignInAsync(
this.Input.UserName,
this.Input.Password,
this.Input.RememberMe,
lockoutOnFailure: false);
if (result.Succeeded)
{
this.logger.LogInformation("User logged in.");
return this.LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return this.RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = this.Input.RememberMe });
}
if (result.IsLockedOut)
{
this.logger.LogWarning("User account locked out.");
return this.RedirectToPage("./Lockout");
}
else
{
this.ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return this.Page();
}
}
// If we got this far, something failed, redisplay form
return this.Page();
}
public class InputModel
{
[Required]
[Display(Name = "Username")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
}
} | 34.810345 | 132 | 0.582714 | [
"MIT"
] | indieza/Sharemundo.bg | SharemundoBulgaria/SharemundoBulgaria/Areas/Identity/Pages/Account/Login.cshtml.cs | 4,040 | C# |
/*************************************************
Copyright (c) 2021 Undersoft
System.Instant.Mathset.CompilerContext.cs
@project: Undersoft.Vegas.Sdk
@stage: Development
@author: Dariusz Hanc
@date: (05.06.2021)
@licence MIT
*************************************************/
namespace System.Instant.Mathset
{
using System;
using System.Reflection.Emit;
#region Delegates
/// <summary>
/// The Evaluator.
/// </summary>
public delegate void Evaluator();
#endregion
/// <summary>
/// Defines the <see cref="CompilerContext" />.
/// </summary>
[Serializable]
public class CompilerContext
{
#region Fields
[NonSerialized] internal int indexVariableCount;
[NonSerialized] internal int[] indexVariables;
[NonSerialized] internal int paramCount;
[NonSerialized] internal IFigures[] paramTables = new IFigures[10];
[NonSerialized] internal int pass = 0;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="CompilerContext"/> class.
/// </summary>
public CompilerContext()
{
indexVariableCount = 0;
}
#endregion
#region Properties
/// <summary>
/// Gets the Count.
/// </summary>
public int Count
{
get { return paramCount; }
}
/// <summary>
/// Gets the ParamCards.
/// </summary>
public IFigures[] ParamCards
{
get { return paramTables; }
}
#endregion
#region Methods
/// <summary>
/// The GenLocalLoad.
/// </summary>
/// <param name="g">The g<see cref="ILGenerator"/>.</param>
/// <param name="a">The a<see cref="int"/>.</param>
public static void GenLocalLoad(ILGenerator g, int a)
{
switch (a)
{
case 0: g.Emit(OpCodes.Ldloc_0); break;
case 1: g.Emit(OpCodes.Ldloc_1); break;
case 2: g.Emit(OpCodes.Ldloc_2); break;
case 3: g.Emit(OpCodes.Ldloc_3); break;
default:
g.Emit(OpCodes.Ldloc, a);
break;
}
}
/// <summary>
/// The GenLocalStore.
/// </summary>
/// <param name="g">The g<see cref="ILGenerator"/>.</param>
/// <param name="a">The a<see cref="int"/>.</param>
public static void GenLocalStore(ILGenerator g, int a)
{
switch (a)
{
case 0: g.Emit(OpCodes.Stloc_0); break;
case 1: g.Emit(OpCodes.Stloc_1); break;
case 2: g.Emit(OpCodes.Stloc_2); break;
case 3: g.Emit(OpCodes.Stloc_3); break;
default:
g.Emit(OpCodes.Stloc, a);
break;
}
}
/// <summary>
/// The Add.
/// </summary>
/// <param name="v">The v<see cref="IFigures"/>.</param>
/// <returns>The <see cref="int"/>.</returns>
public int Add(IFigures v)
{
int index = GetIndexOf(v);
if (index < 0)
{
paramTables[paramCount] = v;
return indexVariableCount + paramCount++;
}
return index;
}
/// <summary>
/// The AllocIndexVariable.
/// </summary>
/// <returns>The <see cref="int"/>.</returns>
public int AllocIndexVariable()
{
return indexVariableCount++;
}
/// <summary>
/// The GenerateLocalInit.
/// </summary>
/// <param name="g">The g<see cref="ILGenerator"/>.</param>
public void GenerateLocalInit(ILGenerator g)
{
// declare indexes
for (int i = 0; i < indexVariableCount; i++)
g.DeclareLocal(typeof(int));
// declare parameters
string paramFieldName = "DataParameters";
for (int i = 0; i < paramCount; i++)
g.DeclareLocal(typeof(IFigures));
for (int i = 0; i < paramCount; i++)
g.DeclareLocal(typeof(IFigure));
g.DeclareLocal(typeof(double));
// load the parameters from parameters array
for (int i = 0; i < paramCount; i++)
{
// simple this.paramTables[i]
g.Emit(OpCodes.Ldarg_0); //this
g.Emit(OpCodes.Ldfld, typeof(CombinedMathset).GetField(paramFieldName));
g.Emit(OpCodes.Ldc_I4, i);
g.Emit(OpCodes.Ldelem_Ref);
g.Emit(OpCodes.Stloc, indexVariableCount + i);
}
}
/// <summary>
/// The GetBufforIndexOf.
/// </summary>
/// <param name="v">The v<see cref="IFigures"/>.</param>
/// <returns>The <see cref="int"/>.</returns>
public int GetBufforIndexOf(IFigures v)
{
for (int i = 0; i < paramCount; i++)
if (paramTables[i] == v) return indexVariableCount + i + paramCount + 1;
return -1;
}
/// <summary>
/// The GetIndexOf.
/// </summary>
/// <param name="v">The v<see cref="IFigures"/>.</param>
/// <returns>The <see cref="int"/>.</returns>
public int GetIndexOf(IFigures v)
{
for (int i = 0; i < paramCount; i++)
if (paramTables[i] == v) return indexVariableCount + i;
return -1;
}
// index access by variable number
/// <summary>
/// The GetIndexVariable.
/// </summary>
/// <param name="number">The number<see cref="int"/>.</param>
/// <returns>The <see cref="int"/>.</returns>
public int GetIndexVariable(int number)
{
return indexVariables[number];
}
/// <summary>
/// The GetSubIndexOf.
/// </summary>
/// <param name="v">The v<see cref="IFigures"/>.</param>
/// <returns>The <see cref="int"/>.</returns>
public int GetSubIndexOf(IFigures v)
{
for (int i = 0; i < paramCount; i++)
if (paramTables[i] == v) return indexVariableCount + i + paramCount;
return -1;
}
/// <summary>
/// The IsFirstPass.
/// </summary>
/// <returns>The <see cref="bool"/>.</returns>
public bool IsFirstPass()
{
return pass == 0;
}
/// <summary>
/// The NextPass.
/// </summary>
public void NextPass()
{
pass++;
// local variables array
indexVariables = new int[indexVariableCount];
for (int i = 0; i < indexVariableCount; i++)
indexVariables[i] = i;
}
/// <summary>
/// The SetIndexVariable.
/// </summary>
/// <param name="number">The number<see cref="int"/>.</param>
/// <param name="value">The value<see cref="int"/>.</param>
public void SetIndexVariable(int number, int value)
{
indexVariables[number] = value;
}
#endregion
}
}
| 29.062992 | 88 | 0.482525 | [
"MIT"
] | undersoft-org/NET.Undersoft.Sdk.Devel | NET.Undersoft.Vegas.Sdk/Undersoft.System.Instant.Mathset/Compiler/CompilerContext.cs | 7,384 | C# |
using System.Threading.Tasks;
using Abp.Configuration;
using Abp.Zero.Configuration;
using Jewellery.Authorization.Accounts.Dto;
using Jewellery.Authorization.Users;
namespace Jewellery.Authorization.Accounts
{
public class AccountAppService : JewelleryAppServiceBase, IAccountAppService
{
// from: http://regexlib.com/REDetails.aspx?regexp_id=1923
public const string PasswordRegex = "(?=^.{8,}$)(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\\s)[0-9a-zA-Z!@#$%^&*()]*$";
private readonly UserRegistrationManager _userRegistrationManager;
public AccountAppService(
UserRegistrationManager userRegistrationManager)
{
_userRegistrationManager = userRegistrationManager;
}
public async Task<IsTenantAvailableOutput> IsTenantAvailable(IsTenantAvailableInput input)
{
var tenant = await TenantManager.FindByTenancyNameAsync(input.TenancyName);
if (tenant == null)
{
return new IsTenantAvailableOutput(TenantAvailabilityState.NotFound);
}
if (!tenant.IsActive)
{
return new IsTenantAvailableOutput(TenantAvailabilityState.InActive);
}
return new IsTenantAvailableOutput(TenantAvailabilityState.Available, tenant.Id);
}
public async Task<RegisterOutput> Register(RegisterInput input)
{
var user = await _userRegistrationManager.RegisterAsync(
input.Name,
input.Surname,
input.EmailAddress,
input.UserName,
input.Password,
true // Assumed email address is always confirmed. Change this if you want to implement email confirmation.
);
var isEmailConfirmationRequiredForLogin = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin);
return new RegisterOutput
{
CanLogin = user.IsActive && (user.IsEmailConfirmed || !isEmailConfirmationRequiredForLogin)
};
}
}
}
| 37.275862 | 174 | 0.642923 | [
"MIT"
] | dedavidsilwal/JewelleryAbp | aspnet-core/src/Jewellery.Application/Authorization/Accounts/AccountAppService.cs | 2,162 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using DirectX12GameEngine.Core.Assets;
using DirectX12GameEngine.Graphics;
using DirectX12GameEngine.Rendering;
using DirectX12GameEngine.Rendering.Materials;
using Microsoft.Extensions.DependencyInjection;
namespace DirectX12GameEngine.Assets
{
[AssetContentType(typeof(Model))]
public class ModelAsset : AssetWithSource<Model>
{
public IList<Material> Materials { get; } = new List<Material>();
public async override Task CreateAssetAsync(Model model, IServiceProvider services)
{
IContentManager contentManager = services.GetRequiredService<IContentManager>();
GraphicsDevice device = services.GetRequiredService<GraphicsDevice>();
if (device is null) throw new InvalidOperationException();
string extension = Path.GetExtension(Source);
if (extension == ".glb")
{
model.Materials.Clear();
model.Meshes.Clear();
using Stream stream = await contentManager.FileProvider.OpenStreamAsync(Source, FileMode.Open, FileAccess.Read);
GltfModelLoader modelLoader = await GltfModelLoader.CreateAsync(device, stream);
var meshes = await modelLoader.GetMeshesAsync();
foreach (Mesh mesh in meshes)
{
model.Meshes.Add(mesh);
}
if (Materials.Count > 0)
{
foreach (Material material in Materials)
{
model.Materials.Add(material);
}
}
else
{
foreach (MaterialAttributes attributes in await modelLoader.GetMaterialAttributesAsync())
{
Material material = await Material.CreateAsync(device, new MaterialDescriptor { Id = Id, Attributes = attributes }, contentManager);
model.Materials.Add(material);
}
}
}
else
{
throw new NotSupportedException("This file type is not supported.");
}
}
}
}
| 35.353846 | 156 | 0.582245 | [
"MIT"
] | jjh2v2/DirectX12GameEngine | DirectX12GameEngine.Assets/ModelAsset.cs | 2,300 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.Encryption
{
/// <summary>
/// Encryption algorithms supported for data encryption.
/// </summary>
public static class DataEncryptionAlgorithm
{
/// <summary>
/// Represents the authenticated encryption algorithm with associated data as described in
/// http://tools.ietf.org/html/draft-mcgrew-aead-aes-cbc-hmac-sha2-05.
/// </summary>
public const string AeadAes256CbcHmacSha256 = "AEAD_AES_256_CBC_HMAC_SHA256";
}
}
| 37.105263 | 98 | 0.560284 | [
"MIT"
] | Azure/azure-cosmos-dotnet | Microsoft.Azure.Cosmos.Encryption/src/DataEncryptionAlgorithm.cs | 707 | C# |
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT. See LICENSE in the project root for license information.
using System;
using System.Data;
using System.Data.Common;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Utilities;
using MySqlConnector;
// ReSharper disable once CheckNamespace
namespace Microsoft.EntityFrameworkCore
{
// TODO: Rename to MySqlDbContextOptionsBuilderExtensions for .NET Core 5.0, which is in line with Npgsql, but
// not with SqlServer.
public static class MySqlDbContextOptionsExtensions
{
public static DbContextOptionsBuilder UseMySql(
[NotNull] this DbContextOptionsBuilder optionsBuilder,
[NotNull] string connectionString,
[CanBeNull] Action<MySqlDbContextOptionsBuilder> mySqlOptionsAction = null)
{
Check.NotNull(optionsBuilder, nameof(optionsBuilder));
Check.NotEmpty(connectionString, nameof(connectionString));
var csb = new MySqlConnectionStringBuilder(connectionString)
{
AllowUserVariables = true,
UseAffectedRows = false
};
connectionString = csb.ConnectionString;
var extension = (MySqlOptionsExtension)GetOrCreateExtension(optionsBuilder).WithConnectionString(connectionString);
((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension);
ConfigureWarnings(optionsBuilder);
mySqlOptionsAction?.Invoke(new MySqlDbContextOptionsBuilder(optionsBuilder));
return optionsBuilder;
}
public static DbContextOptionsBuilder UseMySql(
[NotNull] this DbContextOptionsBuilder optionsBuilder,
[NotNull] DbConnection connection,
[CanBeNull] Action<MySqlDbContextOptionsBuilder> mySqlOptionsAction = null)
{
Check.NotNull(optionsBuilder, nameof(optionsBuilder));
Check.NotNull(connection, nameof(connection));
var csb = new MySqlConnectionStringBuilder(connection.ConnectionString);
if (csb.AllowUserVariables != true || csb.UseAffectedRows)
{
try
{
csb.AllowUserVariables = true;
csb.UseAffectedRows = false;
if (connection.State != ConnectionState.Open)
{
connection.ConnectionString = csb.ConnectionString;
}
}
catch (MySqlException e)
{
throw new InvalidOperationException("The MySql Connection string used with Pomelo.EntityFrameworkCore.MySql " +
"must contain \"AllowUserVariables=true;UseAffectedRows=false\"", e);
}
}
var extension = (MySqlOptionsExtension)GetOrCreateExtension(optionsBuilder).WithConnection(connection);
((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension);
ConfigureWarnings(optionsBuilder);
mySqlOptionsAction?.Invoke(new MySqlDbContextOptionsBuilder(optionsBuilder));
return optionsBuilder;
}
public static DbContextOptionsBuilder<TContext> UseMySql<TContext>(
[NotNull] this DbContextOptionsBuilder<TContext> optionsBuilder,
[NotNull] string connectionString,
[CanBeNull] Action<MySqlDbContextOptionsBuilder> mySqlOptionsAction = null)
where TContext : DbContext
=> (DbContextOptionsBuilder<TContext>)UseMySql(
(DbContextOptionsBuilder)optionsBuilder, connectionString, mySqlOptionsAction);
public static DbContextOptionsBuilder<TContext> UseMySql<TContext>(
[NotNull] this DbContextOptionsBuilder<TContext> optionsBuilder,
[NotNull] DbConnection connection,
[CanBeNull] Action<MySqlDbContextOptionsBuilder> mySqlOptionsAction = null)
where TContext : DbContext
=> (DbContextOptionsBuilder<TContext>)UseMySql(
(DbContextOptionsBuilder)optionsBuilder, connection, mySqlOptionsAction);
private static MySqlOptionsExtension GetOrCreateExtension(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.Options.FindExtension<MySqlOptionsExtension>()
?? new MySqlOptionsExtension();
private static void ConfigureWarnings(DbContextOptionsBuilder optionsBuilder)
{
var coreOptionsExtension
= optionsBuilder.Options.FindExtension<CoreOptionsExtension>()
?? new CoreOptionsExtension();
coreOptionsExtension = coreOptionsExtension.WithWarningsConfiguration(
coreOptionsExtension.WarningsConfiguration.TryWithExplicit(
RelationalEventId.AmbientTransactionWarning, WarningBehavior.Throw));
((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(coreOptionsExtension);
}
}
}
| 46.743363 | 131 | 0.679856 | [
"MIT"
] | paviad/Pomelo.EntityFrameworkCore.MySql | src/EFCore.MySql/Extensions/MySqlDbContextOptionsExtensions.cs | 5,282 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using NuScien.Security;
using Trivial.Collection;
using Trivial.Data;
using Trivial.Net;
using Trivial.Reflection;
using Trivial.Security;
using Trivial.Text;
namespace NuScien.Data
{
/// <summary>
/// The base resource entity accessing service.
/// </summary>
/// <typeparam name="T">The type of the resouce entity.</typeparam>
public abstract class OnPremisesResourceEntityProvider<T> : IResourceEntityProvider<T> where T : BaseResourceEntity
{
/// <summary>
/// The save handler.
/// </summary>
private readonly Func<CancellationToken, Task<int>> saveHandler;
/// <summary>
/// Initializes a new instance of the OnPremisesResourceEntityProvider class.
/// </summary>
/// <param name="client">The resource access client.</param>
/// <param name="set">The database set.</param>
/// <param name="save">The entity save handler.</param>
public OnPremisesResourceEntityProvider(OnPremisesResourceAccessClient client, DbSet<T> set, Func<CancellationToken, Task<int>> save)
{
CoreResources = client ?? new OnPremisesResourceAccessClient(null);
Set = set;
saveHandler = save ?? DbResourceEntityExtensions.SaveChangesFailureAsync;
}
/// <summary>
/// Initializes a new instance of the OnPremisesResourceEntityProvider class.
/// </summary>
/// <param name="dataProvider">The resource data provider.</param>
/// <param name="set">The database set.</param>
/// <param name="save">The entity save handler.</param>
public OnPremisesResourceEntityProvider(IAccountDataProvider dataProvider, DbSet<T> set, Func<CancellationToken, Task<int>> save)
{
CoreResources = new OnPremisesResourceAccessClient(dataProvider);
Set = set;
saveHandler = save ?? DbResourceEntityExtensions.SaveChangesFailureAsync;
}
/// <summary>
/// Adds or removes the event handler on save.
/// </summary>
public event ChangeEventHandler<T> Saved;
/// <summary>
/// Gets the resource access client.
/// </summary>
protected DbSet<T> Set { get; }
/// <summary>
/// Gets the resource access client.
/// </summary>
protected OnPremisesResourceAccessClient CoreResources { get; }
/// <summary>
/// Gets the current user information.
/// </summary>
protected Users.UserEntity User => CoreResources.User;
/// <summary>
/// Gets the current user identifier.
/// </summary>
protected string UserId => CoreResources?.User?.Id;
/// <summary>
/// Gets the current client identifier.
/// </summary>
protected string ClientId => CoreResources.ClientId;
/// <summary>
/// Gets a value indicating whether the access token is null, empty or consists only of white-space characters.
/// </summary>
protected bool IsTokenNullOrEmpty => CoreResources.IsTokenNullOrEmpty;
/// <summary>
/// Gets the resource access client.
/// </summary>
BaseResourceAccessClient IResourceEntityProvider<T>.CoreResources => CoreResources;
/// <summary>
/// Gets by a specific entity identifier.
/// </summary>
/// <param name="id">The identifier of the entity to get.</param>
/// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param>
/// <returns>An entity instance.</returns>
public Task<T> GetAsync(string id, CancellationToken cancellationToken = default) => GetAsync(id, false, cancellationToken);
/// <summary>
/// Gets by a specific entity identifier.
/// </summary>
/// <param name="id">The identifier of the entity to get.</param>
/// <param name="includeAllStates">true if includes all states but not only normal one; otherwise, false.</param>
/// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param>
/// <returns>An entity instance.</returns>
public virtual Task<T> GetAsync(string id, bool includeAllStates, CancellationToken cancellationToken = default)
{
return Set.GetByIdAsync(id, includeAllStates, cancellationToken);
}
/// <summary>
/// Searches.
/// </summary>
/// <param name="q">The query arguments.</param>
/// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param>
/// <returns>A collection of entity.</returns>
public virtual async Task<CollectionResult<T>> SearchAsync(QueryArgs q, CancellationToken cancellationToken = default)
{
return new CollectionResult<T>(await Set.ListEntities(q).ToListAsync(cancellationToken), q?.Offset ?? 0);
}
/// <summary>
/// Searches.
/// </summary>
/// <param name="q">The query arguments.</param>
/// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param>
/// <returns>A collection of entity.</returns>
public virtual Task<CollectionResult<T>> SearchAsync(QueryData q, CancellationToken cancellationToken = default)
{
return DbResourceEntityExtensions.SearchAsync(Set, q, MapQuery, cancellationToken);
}
/// <summary>
/// Saves.
/// </summary>
/// <param name="value">The entity to add or update.</param>
/// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param>
/// <returns>The change method.</returns>
public virtual async Task<ChangingResultInfo> SaveAsync(T value, CancellationToken cancellationToken = default)
{
if (value == null) return new ChangingResultInfo(ChangeMethods.Unchanged);
var isNew = value.IsNew;
if (isNew) OnAdd(value);
else OnUpdate(value);
try
{
var result = await DbResourceEntityExtensions.SaveAsync(Set, SaveChangesAsync, value, cancellationToken);
Saved?.Invoke(this, new ChangeEventArgs<T>(isNew ? null : value, value, result));
if (ResourceEntityExtensions.IsSuccessful(result))
return new ChangingResultInfo<T>(result, value, $"{result} {typeof(T).Name} entity.");
return result;
}
catch (Exception ex)
{
var err = DbResourceEntityExtensions.TryCatch(ex);
if (err != null) return err;
throw;
}
}
/// <summary>
/// Saves.
/// </summary>
/// <param name="id">The entity identifier.</param>
/// <param name="delta">The data to change.</param>
/// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param>
/// <returns>The change method.</returns>
public virtual async Task<ChangingResultInfo> SaveAsync(string id, JsonObject delta, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(id))
{
if (delta == null) return null;
try
{
var newEntity = delta.Deserialize<T>();
return await SaveAsync(newEntity, cancellationToken) ?? new ChangingResultInfo(ChangeErrorKinds.Service, "No response.");
}
catch (System.Text.Json.JsonException)
{
return new ChangingResultInfo(ChangeErrorKinds.Argument, "Failed to convert the JSON object."); ;
}
}
var entity = await GetAsync(id, true, cancellationToken);
if (delta == null || delta.Count == 0) return new ChangingResultInfo<T>(ChangeMethods.Unchanged, entity, "Update properties."); ;
entity.SetProperties(delta);
await SaveAsync(entity, cancellationToken);
return new ChangingResultInfo<T>(ChangeMethods.MemberModify, entity, "Update properties.");
}
/// <summary>
/// Updates the entity state.
/// </summary>
/// <param name="id">The identifier of the entity.</param>
/// <param name="state">The state.</param>
/// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param>
/// <returns>The change method.</returns>
public async Task<T> UpdateStateAsync(string id, ResourceEntityStates state, CancellationToken cancellationToken = default)
{
var entity = await GetAsync(id, true, cancellationToken);
if (entity == null) return null;
if (entity.State == state) return entity;
entity.State = state;
await SaveAsync(entity, cancellationToken);
return entity;
}
/// <summary>
/// Searches.
/// </summary>
/// <param name="predication">The query predication.</param>
/// <returns>The result.</returns>
protected abstract void MapQuery(QueryPredication<T> predication);
/// <summary>
/// Tests if the new entity is valid.
/// </summary>
/// <param name="value">The entity to add.</param>
/// <returns>true if it is valid; otherwise, false.</returns>
protected virtual void OnAdd(T value)
{
}
/// <summary>
/// Tests if the new entity is valid.
/// </summary>
/// <param name="value">The entity to add.</param>
/// <returns>true if it is valid; otherwise, false.</returns>
protected virtual void OnUpdate(T value)
{
}
/// <summary>
/// Saves all changes made in this context to the database.
/// This method will automatically call Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.DetectChanges
/// to discover any changes to entity instances before saving to the underlying database.
/// This can be disabled via Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker.AutoDetectChangesEnabled.
/// Multiple active operations on the same context instance are not supported. Use
/// 'await' to ensure that any asynchronous operations have completed before calling
/// another method on this context.
/// </summary>
/// <param name="cancellationToken">The optional token to monitor for cancellation requests.</param>
/// <returns>A number of state entries written to the database.</returns>
/// <exception cref="DbUpdateException">An error is encountered while saving to the database.</exception>
protected virtual Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
return saveHandler?.Invoke(cancellationToken) ?? Task.FromResult(0);
}
/// <summary>
/// Tests if contains any of the specific permission item.
/// </summary>
/// <param name="siteId">The site identifier.</param>
/// <param name="value">The permission item to test.</param>
/// <returns>true if contains; otherwise, false.</returns>
protected async Task<bool> HasPermissionAsync(string siteId, string value)
{
if (CoreResources == null) return false;
return await CoreResources.HasPermissionAsync(siteId, value);
}
/// <summary>
/// Tests if contains any of the specific permission item.
/// </summary>
/// <param name="siteId">The site identifier.</param>
/// <param name="value">The permission item to test.</param>
/// <param name="otherValues">Other permission items to test.</param>
/// <returns>true if contains; otherwise, false.</returns>
protected async Task<bool> HasAnyPermissionAsync(string siteId, string value, params string[] otherValues)
{
if (CoreResources == null) return false;
return await CoreResources.HasAnyPermissionAsync(siteId, value, otherValues);
}
/// <summary>
/// Tests if contains any of the specific permission item.
/// </summary>
/// <param name="siteId">The site identifier.</param>
/// <param name="values">The permission items to test.</param>
/// <returns>true if contains; otherwise, false.</returns>
protected async Task<bool> HasAnyPermissionAsync(string siteId, IEnumerable<string> values)
{
if (CoreResources == null) return false;
return await CoreResources.HasAnyPermissionAsync(siteId, values);
}
}
}
| 44.615646 | 141 | 0.618968 | [
"MIT"
] | nuscien/nuscien | OnPremises/Data/ResourceEntityProvider.cs | 13,119 | C# |
using System;
using WatiN.Core;
using WatiN.Core.Interfaces;
using WatiN.Core.Native.InternetExplorer;
using WatiN.Core.Native.Windows;
namespace Coypu.Drivers.Watin
{
public class IEWithDialogWaiter : IE
{
private HasDialogHandler hasDialogHandler;
public override void WaitForComplete(int waitForCompleteTimeOut)
{
if (hasDialogHandler == null)
{
hasDialogHandler = new HasDialogHandler();
DialogWatcher.Add(hasDialogHandler);
}
WaitForComplete(new IEWaitForCompleteWithDialogs((IEBrowser)NativeBrowser, waitForCompleteTimeOut, hasDialogHandler.HasDialog));
}
private class HasDialogHandler : IDialogHandler
{
private Window lastSeenWindow;
public bool HandleDialog(Window window)
{
return false;
}
public bool CanHandleDialog(Window window, IntPtr mainWindowHwnd)
{
lastSeenWindow = window;
return false;
}
public bool HasDialog()
{
return lastSeenWindow != null && lastSeenWindow.Exists();
}
}
}
} | 26.978261 | 140 | 0.592264 | [
"MIT",
"Unlicense"
] | citizenmatt/coypu | src/Coypu.Drivers.Watin/IEWithDialogWaiter.cs | 1,241 | C# |
// -----------------------------------------------------------------------
// <copyright file="Repository.cs" company="Niklas Karl">
// Copyright (c) Niklas Karl. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using KitHub.Core;
using Newtonsoft.Json.Linq;
namespace KitHub
{
/// <summary>
/// A repository hosted on GitHub.
/// </summary>
public sealed class Repository : RefreshableModelBase
{
private static readonly IDictionary<RepositoryKey, Repository> Cache = new Dictionary<RepositoryKey, Repository>();
private RepositoryKey _key;
private Repository(RepositoryKey key)
: base(key.Session)
{
_key = key;
}
/// <summary>
/// Gets the owner of the repository.
/// </summary>
[ModelProperty("owner")]
public User Owner { get => _key.Owner; }
/// <summary>
/// Gets the name of the repository.
/// </summary>
public string Name { get => _key.Name; }
/// <summary>
/// Gets the id of the repository.
/// </summary>
[ModelProperty("id")]
public long? Id
{
get => GetProperty() as long?;
internal set => SetProperty(value);
}
/// <summary>
/// Gets the description of the repository.
/// </summary>
[ModelProperty("description")]
public string Description
{
get => GetProperty() as string;
private set => SetProperty(value);
}
/// <summary>
/// Gets a value indicating whether the repository is private or not.
/// </summary>
[ModelProperty("private")]
public bool? IsPrivate
{
get => GetProperty() as bool?;
private set => SetProperty(value);
}
/// <summary>
/// Gets a value indicating whether the repository is fork of another repository or not..
/// </summary>
[ModelProperty("fork")]
public bool? IsFork
{
get => GetProperty() as bool?;
private set => SetProperty(value);
}
/// <summary>
/// Gets the main programming language of the repository.
/// </summary>
[ModelProperty("language")]
public string Language
{
get => GetProperty() as string;
private set => SetProperty(value);
}
/// <summary>
/// Gets the number of forks of the repository.
/// </summary>
[ModelProperty("forks_count")]
public int? ForksCount
{
get => GetProperty() as int?;
private set => SetProperty(value);
}
/// <summary>
/// Gets the number of stargazers of the repository.
/// </summary>
[ModelProperty("stargazers_count")]
public int? StargazersCount
{
get => GetProperty() as int?;
private set => SetProperty(value);
}
/// <summary>
/// Gets the number of users watching this repository.
/// </summary>
[ModelProperty("watchers_count")]
public int? WatchersCount
{
get => GetProperty() as int?;
private set => SetProperty(value);
}
/// <summary>
/// Gets the size of the repository.
/// </summary>
[ModelProperty("size")]
public int? Size
{
get => GetProperty() as int?;
private set => SetProperty(value);
}
/// <summary>
/// Gets the name of the default branch.
/// </summary>
[ModelProperty("default_branch")]
public string DefaultBranch
{
get => GetProperty() as string;
private set => SetProperty(value);
}
/// <summary>
/// Gets the number of open issues.
/// </summary>
[ModelProperty("open_issues_count")]
public int? OpenIssuesCount
{
get => GetProperty() as int?;
private set => SetProperty(value);
}
/// <summary>
/// Gets a value indicating whether the repository has an issues section or not.
/// </summary>
[ModelProperty("has_issues")]
public bool? HasIssues
{
get => GetProperty() as bool?;
private set => SetProperty(value);
}
/// <summary>
/// Gets a value indicating whether the repository has a wiki or not.
/// </summary>
[ModelProperty("has_wiki")]
public bool? HasWiki
{
get => GetProperty() as bool?;
private set => SetProperty(value);
}
/// <summary>
/// Gets a value indicating whether the repository has github.io pages or not.
/// </summary>
[ModelProperty("has_pages")]
public bool? HasPages
{
get => GetProperty() as bool?;
private set => SetProperty(value);
}
/// <summary>
/// Gets a value indicating whether the repository has downloads or not.
/// </summary>
[ModelProperty("has_downloads")]
public bool? HasDownloads
{
get => GetProperty() as bool?;
private set => SetProperty(value);
}
/// <summary>
/// Gets the timestamp at which the repository was last pushed.
/// </summary>
[ModelProperty("pushed_at")]
public DateTimeOffset? PushedAt
{
get => GetProperty() as DateTime?;
private set => SetProperty(value);
}
/// <summary>
/// Gets the timestamp at which the repository was created.
/// </summary>
[ModelProperty("created_at")]
public DateTimeOffset? CreatedAt
{
get => GetProperty() as DateTime?;
private set => SetProperty(value);
}
/// <summary>
/// Gets the timestamp at which the repository was last updated.
/// </summary>
[ModelProperty("updated_at")]
public DateTimeOffset? UpdatedAt
{
get => GetProperty() as DateTime?;
private set => SetProperty(value);
}
/// <summary>
/// Gets the browser url to the repository.
/// </summary>
public Uri HtmlUrl
{
get => new Uri(Session.Client.BaseUri, new Uri($"/{Owner.Login}/{Name}", UriKind.Relative));
}
/// <inheritdoc/>
protected override Uri Uri => new Uri($"/repos/{Owner.Login}/{Name}", UriKind.Relative);
private RepositoryKey Key { get => _key; }
internal static Repository Create(KitHubSession session, JToken data)
{
if (data == null || data.Type == JTokenType.Null)
{
return null;
}
if (data is JObject repository && repository.TryGetValue("owner", out JToken owner))
{
return Create(session, User.Create(session, owner), data);
}
throw new KitHubDataException("The repository object is invalid.", data);
}
internal static Repository Create(KitHubSession session, User owner, JToken data)
{
if (data == null)
{
return null;
}
string name = data.Value<string>("name");
Repository repository = GetOrCreate(session, owner, name);
repository.SetFromData(data);
return repository;
}
internal static Repository GetOrCreate(KitHubSession session, User owner, string name)
{
if (owner == null)
{
throw new ArgumentException("The owner of a repository must not be null.");
}
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("The name of a repository must not be null or empty.");
}
RepositoryKey key = new RepositoryKey(session, owner, name);
lock (Cache)
{
if (Cache.TryGetValue(key, out Repository existing))
{
return existing;
}
else
{
Repository result = new Repository(key);
Cache[key] = result;
return result;
}
}
}
internal sealed class DefaultInitializer : IModelInitializer
{
public object InitializeModel(BindableBase self, JToken data)
{
return Create(self.Session, data);
}
}
private sealed class RepositoryKey
{
public RepositoryKey(KitHubSession session, User owner, string name)
{
Session = session;
Owner = owner;
Name = name;
}
public KitHubSession Session { get; }
public User Owner { get; }
public string Name { get; }
public override bool Equals(object obj)
{
if (obj is RepositoryKey other)
{
return Session == other.Session && Owner == other.Owner && Name == other.Name;
}
return false;
}
public override int GetHashCode()
{
return Session.GetHashCode() ^ Owner.GetHashCode() ^ Name.GetHashCode();
}
}
}
}
| 29.888554 | 123 | 0.504081 | [
"MIT"
] | niklaskarl/KitHub | src/KitHub/Repository.cs | 9,925 | C# |
/* Copyright (c) 2012 Rick (rick 'at' gibbed 'dot' us)
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*/
using System;
namespace Gibbed.IO
{
public static partial class NumberHelpers
{
public static Int16 BigEndian(this Int16 value)
{
if (BitConverter.IsLittleEndian == true)
{
return value.Swap();
}
return value;
}
public static UInt16 BigEndian(this UInt16 value)
{
if (BitConverter.IsLittleEndian == true)
{
return value.Swap();
}
return value;
}
public static Int32 BigEndian(this Int32 value)
{
if (BitConverter.IsLittleEndian == true)
{
return value.Swap();
}
return value;
}
public static UInt32 BigEndian(this UInt32 value)
{
if (BitConverter.IsLittleEndian == true)
{
return value.Swap();
}
return value;
}
public static Int64 BigEndian(this Int64 value)
{
if (BitConverter.IsLittleEndian == true)
{
return value.Swap();
}
return value;
}
public static UInt64 BigEndian(this UInt64 value)
{
if (BitConverter.IsLittleEndian == true)
{
return value.Swap();
}
return value;
}
public static Single BigEndian(this Single value)
{
if (BitConverter.IsLittleEndian == true)
{
var data = BitConverter.GetBytes(value);
var junk = BitConverter.ToUInt32(data, 0).Swap();
return BitConverter.ToSingle(BitConverter.GetBytes(junk), 0);
}
return value;
}
public static Double BigEndian(this Double value)
{
if (BitConverter.IsLittleEndian == true)
{
var data = BitConverter.GetBytes(value);
var junk = BitConverter.ToUInt64(data, 0).Swap();
return BitConverter.ToDouble(BitConverter.GetBytes(junk), 0);
}
return value;
}
}
}
| 27.649123 | 77 | 0.556472 | [
"MIT"
] | MartinJK/Mafia3-SDSExplorer | Gibbed.IO/NumberHelpers/BigEndian.cs | 3,154 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace System.Globalization.Tests
{
public static class CharUnicodeInfoTestData
{
private static readonly Lazy<List<CharUnicodeInfoTestCase>> s_testCases = new Lazy<List<CharUnicodeInfoTestCase>>(() =>
{
List<CharUnicodeInfoTestCase> testCases = new List<CharUnicodeInfoTestCase>();
string fileName = "UnicodeData.txt";
Stream stream = typeof(CharUnicodeInfoTestData).GetTypeInfo().Assembly.GetManifestResourceStream(fileName);
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
Parse(testCases, reader.ReadLine());
}
}
return testCases;
});
public static List<CharUnicodeInfoTestCase> TestCases => s_testCases.Value;
private static int s_rangeMinCodePoint;
private static void Parse(List<CharUnicodeInfoTestCase> testCases, string line)
{
// Data is in the format:
// code-value;
// character-name;
// general-category;
// canonical-combining-classes; (ignored)
// bidirecional-category; (ignored)
// character-decomposition-mapping; (ignored)
// decimal-digit-value; (ignored)
// digit-value; (ignoed)
// number-value;
string[] data = line.Split(';');
string charValueString = data[0];
string charName = data[1];
string charCategoryString = data[2];
string numericValueString = data[8];
int codePoint = int.Parse(charValueString, NumberStyles.HexNumber);
Parse(testCases, codePoint, charCategoryString, numericValueString);
if (charName.EndsWith("First>"))
{
s_rangeMinCodePoint = codePoint;
}
else if (charName.EndsWith("Last>"))
{
// Assumes that we have already found a range start
for (int rangeCodePoint = s_rangeMinCodePoint + 1; rangeCodePoint < codePoint; rangeCodePoint++)
{
// Assumes that all code points in the range have the same numeric value
// and general category
Parse(testCases, rangeCodePoint, charCategoryString, numericValueString);
}
}
}
private static Dictionary<string, UnicodeCategory> s_unicodeCategories = new Dictionary<string, UnicodeCategory>
{
["Pe"] = UnicodeCategory.ClosePunctuation,
["Pc"] = UnicodeCategory.ConnectorPunctuation,
["Cc"] = UnicodeCategory.Control,
["Sc"] = UnicodeCategory.CurrencySymbol,
["Pd"] = UnicodeCategory.DashPunctuation,
["Nd"] = UnicodeCategory.DecimalDigitNumber,
["Me"] = UnicodeCategory.EnclosingMark,
["Pf"] = UnicodeCategory.FinalQuotePunctuation,
["Cf"] = UnicodeCategory.Format,
["Pi"] = UnicodeCategory.InitialQuotePunctuation,
["Nl"] = UnicodeCategory.LetterNumber,
["Zl"] = UnicodeCategory.LineSeparator,
["Ll"] = UnicodeCategory.LowercaseLetter,
["Sm"] = UnicodeCategory.MathSymbol,
["Lm"] = UnicodeCategory.ModifierLetter,
["Sk"] = UnicodeCategory.ModifierSymbol,
["Mn"] = UnicodeCategory.NonSpacingMark,
["Ps"] = UnicodeCategory.OpenPunctuation,
["Lo"] = UnicodeCategory.OtherLetter,
["Cn"] = UnicodeCategory.OtherNotAssigned,
["No"] = UnicodeCategory.OtherNumber,
["Po"] = UnicodeCategory.OtherPunctuation,
["So"] = UnicodeCategory.OtherSymbol,
["Po"] = UnicodeCategory.OtherPunctuation,
["Zp"] = UnicodeCategory.ParagraphSeparator,
["Co"] = UnicodeCategory.PrivateUse,
["Zs"] = UnicodeCategory.SpaceSeparator,
["Mc"] = UnicodeCategory.SpacingCombiningMark,
["Cs"] = UnicodeCategory.Surrogate,
["Lt"] = UnicodeCategory.TitlecaseLetter,
["Lu"] = UnicodeCategory.UppercaseLetter
};
private static void Parse(List<CharUnicodeInfoTestCase> testCases, int codePoint, string charCategoryString, string numericValueString)
{
string codeValueRepresentation = codePoint > char.MaxValue ? char.ConvertFromUtf32(codePoint) : ((char)codePoint).ToString();
double numericValue = ParseNumericValueString(numericValueString);
UnicodeCategory generalCategory = s_unicodeCategories[charCategoryString];
testCases.Add(new CharUnicodeInfoTestCase()
{
Utf32CodeValue = codeValueRepresentation,
GeneralCategory = generalCategory,
NumericValue = numericValue,
CodePoint = codePoint
});
}
private static double ParseNumericValueString(string numericValueString)
{
if (numericValueString.Length == 0)
{
// Parsing empty string (no numeric value)
return -1;
}
int fractionDelimeterIndex = numericValueString.IndexOf("/");
if (fractionDelimeterIndex == -1)
{
// Parsing basic number
return double.Parse(numericValueString);
}
// Unicode datasets display fractions not decimals (e.g. 1/4 instead of 0.25),
// so we should parse them as such
string numeratorString = numericValueString.Substring(0, fractionDelimeterIndex);
double numerator = double.Parse(numeratorString);
string denominatorString = numericValueString.Substring(fractionDelimeterIndex + 1);
double denominator = double.Parse(denominatorString);
return numerator / denominator;
}
}
public class CharUnicodeInfoTestCase
{
public string Utf32CodeValue { get; set; }
public int CodePoint { get; set; }
public UnicodeCategory GeneralCategory { get; set; }
public double NumericValue { get; set; }
}
}
| 42.803922 | 143 | 0.601619 | [
"MIT"
] | 06needhamt/runtime | src/libraries/System.Globalization/tests/System/Globalization/CharUnicodeInfoTestData.cs | 6,551 | C# |
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NUnit.Framework;
using System;
using System.IO;
using System.IO.Abstractions.TestingHelpers;
using System.Threading.Tasks;
using YetiCommon;
namespace SymbolStores.Tests
{
[TestFixture]
abstract class SymbolStoreBaseTests
{
protected const string FILENAME = "test.debug";
protected const string SOURCE_FILEPATH = @"C:\source\" + FILENAME;
protected const string MISSING_FILEPATH = @"C:\missing\" + FILENAME;
protected const string DEST_FILEPATH = @"C:\dest\" + FILENAME;
protected const string INVALID_PATH = @"C:\invalid|";
protected static readonly BuildId BUILD_ID = new BuildId("1234");
protected MockFileSystem fakeFileSystem;
protected FakeBinaryFileUtil fakeBinaryFileUtil;
protected FakeBuildIdWriter fakeBuildIdWriter;
protected FileReference sourceSymbolFile;
protected StringWriter log;
[SetUp]
public virtual void SetUp()
{
fakeFileSystem = new MockFileSystem();
fakeBinaryFileUtil = new FakeBinaryFileUtil(fakeFileSystem);
fakeBuildIdWriter = new FakeBuildIdWriter(fakeFileSystem);
fakeBuildIdWriter.WriteBuildId(SOURCE_FILEPATH, BUILD_ID);
sourceSymbolFile = new FileReference(fakeFileSystem, SOURCE_FILEPATH);
log = new StringWriter();
}
[Test]
public async Task FindFile_ExistsAsync()
{
var store = await GetStoreWithFileAsync();
var fileReference = await store.FindFileAsync(FILENAME, BUILD_ID, true, log);
await fileReference.CopyToAsync(DEST_FILEPATH);
Assert.AreEqual(BUILD_ID, await fakeBinaryFileUtil.ReadBuildIdAsync(DEST_FILEPATH));
StringAssert.Contains(Strings.FileFound(""), log.ToString());
}
[Test]
public async Task FindFile_NoLogAsync()
{
var store = await GetStoreWithFileAsync();
var fileReference = await store.FindFileAsync(FILENAME, BUILD_ID);
await fileReference.CopyToAsync(DEST_FILEPATH);
Assert.AreEqual(BUILD_ID, await fakeBinaryFileUtil.ReadBuildIdAsync(DEST_FILEPATH));
}
[Test]
public void FindFile_NullFilename()
{
var store = GetEmptyStore();
Assert.ThrowsAsync<ArgumentException>(() => store.FindFileAsync(null, BUILD_ID));
}
[Test]
public async Task FindFile_DoesNotExistAsync()
{
var store = GetEmptyStore();
var fileReference = await store.FindFileAsync(FILENAME, BUILD_ID, true, log);
Assert.Null(fileReference);
StringAssert.Contains(Strings.FileNotFound(""), log.ToString());
}
[Test]
public async Task AddFile_WhenSupportedAsync()
{
var store = GetEmptyStore();
if (!store.SupportsAddingFiles)
{
return;
}
var fileReference = await store.AddFileAsync(sourceSymbolFile, FILENAME, BUILD_ID, log);
Assert.AreEqual(BUILD_ID,
await fakeBinaryFileUtil.ReadBuildIdAsync(fileReference.Location));
StringAssert.Contains(Strings.CopiedFile(FILENAME, fileReference.Location),
log.ToString());
}
[Test]
public void AddFile_WhenNotSupported()
{
var store = GetEmptyStore();
if (store.SupportsAddingFiles)
{
return;
}
Assert.ThrowsAsync<NotSupportedException>(
() => store.AddFileAsync(sourceSymbolFile, FILENAME, BUILD_ID));
}
[Test]
public async Task AddFile_NoLogAsync()
{
var store = GetEmptyStore();
if (!store.SupportsAddingFiles)
{
return;
}
var fileReference = await store.AddFileAsync(sourceSymbolFile, FILENAME, BUILD_ID);
await fileReference.CopyToAsync(DEST_FILEPATH);
Assert.AreEqual(BUILD_ID, await fakeBinaryFileUtil.ReadBuildIdAsync(DEST_FILEPATH));
}
[Test]
public async Task AddFile_AlreadyExistsAsync()
{
var store = await GetStoreWithFileAsync();
if (!store.SupportsAddingFiles)
{
return;
}
await store.AddFileAsync(sourceSymbolFile, FILENAME, BUILD_ID);
}
[Test]
public void AddFile_MissingSource()
{
var store = GetEmptyStore();
if (!store.SupportsAddingFiles)
{
return;
}
Assert.ThrowsAsync<SymbolStoreException>(
() => store.AddFileAsync(new FileReference(fakeFileSystem, MISSING_FILEPATH),
FILENAME, BUILD_ID));
}
[Test]
public void AddFile_InvalidPath()
{
var store = GetEmptyStore();
if (!store.SupportsAddingFiles)
{
return;
}
Assert.ThrowsAsync<SymbolStoreException>(
() => store.AddFileAsync(new FileReference(fakeFileSystem, INVALID_PATH), FILENAME,
BUILD_ID));
}
[Test]
public void AddFile_NullSource()
{
var store = GetEmptyStore();
if (!store.SupportsAddingFiles)
{
return;
}
Assert.ThrowsAsync<ArgumentException>(() =>
store.AddFileAsync(null, FILENAME, BUILD_ID));
}
[TestCase(null, "1234")]
[TestCase(FILENAME, "")]
public void AddFile_InvalidArgument(string filename, string buildIdStr)
{
var buildId = new BuildId(buildIdStr);
var store = GetEmptyStore();
if (!store.SupportsAddingFiles)
{
return;
}
Assert.ThrowsAsync<ArgumentException>(
() => store.AddFileAsync(sourceSymbolFile, filename, buildId));
}
// Gets a valid store of the type being tested that contains no files. Does not need to be
// unique.
protected abstract ISymbolStore GetEmptyStore();
// Gets a store of the type being tested that contains a file with the filename `FILENAME`
// and build id `BUILD_ID`
protected abstract Task<ISymbolStore> GetStoreWithFileAsync();
}
}
| 33.52093 | 100 | 0.593173 | [
"Apache-2.0"
] | googlestadia/vsi-lldb | SymbolStores.Tests/SymbolStoreBaseTests.cs | 7,207 | C# |
using Esso.Data;
using Esso.Model.Models;
using Esso.Models;
using Esso.Web.ViewModels;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;
namespace Esso.Web.Controllers
{
[Authorize]
public class String_DCController : BaseController
{
EssoEntities DB = new EssoEntities();
public ActionResult Index(int stationId)
{
return View(stationId);
}
private void SetCultureInfo()
{
System.Globalization.CultureInfo _CultureInfo = new System.Globalization.CultureInfo("tr-TR");
_CultureInfo.NumberFormat.CurrencyDecimalSeparator = ",";
_CultureInfo.NumberFormat.CurrencyGroupSeparator = ".";
_CultureInfo.NumberFormat.NumberDecimalSeparator = ",";
_CultureInfo.NumberFormat.NumberGroupSeparator = ".";
_CultureInfo.NumberFormat.PercentDecimalSeparator = ",";
_CultureInfo.NumberFormat.PercentGroupSeparator = ".";
System.Threading.Thread.CurrentThread.CurrentCulture = _CultureInfo;
}
public class TempDTO
{
public int ID { get; set; }
public string NAME { get; set; }
public int INV_NO { get; set; }
public int INPUT_NO { get; set; }
public float? VALUE { get; set; }
public long TARIH_NUMBER { get; set; }
}
public ActionResult StringDCGridPartial(int stationId, string date, string hour)
{
SetCultureInfo();
List<TempDTO> strTagNames = DB.stationString
.Join(DB.Tags, r => r.STRING_ID, ro => ro.ID, (r, ro) => new { r, ro })
.Where(x => x.r.STATION_ID == stationId && x.r.IS_DELETED == false)
.GroupBy(x => x.ro.NAME)
.Select(g => new TempDTO { NAME = g.Key, ID = g.FirstOrDefault().ro.ID })
.ToList();
for (int i = 0; i < strTagNames.Count; i++)
{
strTagNames[i].INPUT_NO = Convert.ToInt32(strTagNames[i].NAME.Split('_')[3].Replace(".", ""));
strTagNames[i].INV_NO = Convert.ToInt32(strTagNames[i].NAME.Split('_')[0].Replace("INV", ""));
}
strTagNames = strTagNames.OrderBy(x => x.INV_NO).ThenBy(x => x.INPUT_NO).ToList();
DataTable dt = new DataTable();
if (strTagNames == null || strTagNames.Count == 0)
{
return PartialView(dt);
}
List<string> sameTag = new List<string>();
if (strTagNames != null)
{
string sck = string.Empty;
foreach (TempDTO tag in strTagNames)
{
sck = tag.NAME.Split('_')[0];
if (!dt.Columns.Contains(sck + " (A)"))
{
dt.Columns.Add(sck + " (A)");
sameTag = strTagNames.Where(x => x.NAME.Split('_')[0] == sck).Select(x => x.NAME).ToList();
if (sameTag != null)
{
for (int i = 0; i <= sameTag.Count - 1; i++)
{
if (dt.Rows.Count == 0 || dt.Rows.Count < (i + 1))
{
DataRow rw = dt.NewRow();
rw[sck + " (A)"] = sameTag[i];
dt.Rows.Add(rw);
}
else
{
dt.Rows[i][sck + " (A)"] = sameTag[i];
}
}
}
}
}
}
DateTime curDate = DateTime.Now;
Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR");
List<STR_DTO> values = new List<STR_DTO>();
if (hour == "")
{
values = (from so in DB.StringOzetLive
join t in DB.Tags on so.STRING_ID equals t.ID
join tct in DB.stationString on t.ID equals tct.STRING_ID
where so.STATION_ID == stationId
&& tct.STATION_ID == stationId
&& tct.IS_DELETED == false
&& t.IS_DELETED == false
&& tct.IS_DELETED == false
select new STR_DTO
{
NAME = t.NAME,
ID = t.ID,
date = so.INSERT_DATE.Value,
VALUE = so.VALUE
}
).ToList();
ViewBag.Date = values[0].date;
}
else
{
DateTime slcDate = DateTime.Parse(date);
DateTime nowDate = DateTime.Now;
if (nowDate.Year == slcDate.Year && nowDate.Month == slcDate.Month) //Quarter String
{
string _date = date + " " + hour;
ViewBag.Date = _date;
string[] hourSplit = hour.Split(':');
var _convertDate = ConvertNumberFormatDateAndHourQuarter(date, hourSplit[0], hourSplit[1])._begin;
values = (from so in DB.StringOzetQuarterHourAVG
join t in DB.Tags on so.STRING_ID equals t.ID
join tct in DB.stationString on t.ID equals tct.STRING_ID
where so.STATION_ID == stationId && tct.STATION_ID == stationId
&& tct.IS_DELETED == false
&& t.IS_DELETED == false
&& so.TARIH_NUMBER == _convertDate
select new STR_DTO
{
NAME = t.NAME,
ID = t.ID,
VALUE = (float)Math.Round(so.VALUE, 2)
}
).ToList();
}
else //Hourly String
{
string _date = date + " " + hour;
ViewBag.Date = _date;
string[] hourSplit = hour.Split(':');
var _convertDate = ConvertNumberFormatDateAndHour(date, hourSplit[0])._begin;
values = (from so in DB.StringOzetAVG
join t in DB.Tags on so.STRING_ID equals t.ID
join tct in DB.stationString on t.ID equals tct.STRING_ID
where so.STATION_ID == stationId && tct.STATION_ID == stationId
&& tct.IS_DELETED == false
&& t.IS_DELETED == false
&& so.TARIH_NUMBER == _convertDate
select new STR_DTO
{
NAME = t.NAME,
ID = t.ID,
VALUE = (float)Math.Round(so.VALUE, 2)
}
).ToList();
}
}
if (values.Count != 0)
{
//ViewBag.Date = values[0].date;
if (dt.Columns.Count > 0 && dt.Rows.Count > 0 && values != null)
{
string cellTagName = string.Empty;
foreach (DataRow rw in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
{
cellTagName = rw[col].ToString();
if (values.Any(x => x.NAME == cellTagName))
{
rw[col] = values.Where(x => x.NAME == cellTagName).FirstOrDefault().VALUE;
}
else
{
rw[col] = "-";
}
}
}
}
}
else
{
string cellTagName = string.Empty;
foreach (DataRow rw in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
{
cellTagName = rw[col].ToString();
rw[col] = "-";
}
}
}
if (values.Count != 0)
{
decimal _min;
List<StringMin> _ListStringMin = new List<StringMin>();
for (int j = 0; j < dt.Columns.Count; j++)
{
_min = Convert.ToDecimal(dt.Rows[0][j]);
StringMin _StringMin = new StringMin();
_StringMin.ColumnIndex = j;
_StringMin.FieldName = dt.Columns[j].ColumnName;
try
{
for (int i = 0; i < dt.Rows.Count; i++)
{
if (i == 11)
{
var dddd = dt.Rows[i][j];
}
if (dt.Rows[i][j] != DBNull.Value)
{
if (dt.Rows[i][j].ToString() != "-")
{
if (Convert.ToDecimal(dt.Rows[i][j]) < _min)
{
_min = Convert.ToDecimal(dt.Rows[i][j].ToString());
_StringMin.Min = _min;
_StringMin.RowIndex = i;
}
}
}
}
}
catch (Exception ex)
{
throw;
}
_ListStringMin.Add(_StringMin);
}
ViewBag.StringMin = _ListStringMin;
// Max değeri bulma -----------------------------
decimal _max = 0;
List<StringDeneme> _ListStringMax = new List<StringDeneme>();
for (int j = 0; j < dt.Columns.Count; j++)
{
_max = 0;
StringDeneme _cStringDeneme = new StringDeneme();
_cStringDeneme.ColumnIndex = j;
_cStringDeneme.FieldName = dt.Columns[j].ColumnName;
for (int i = 0; i < dt.Rows.Count; i++)
{
if (dt.Rows[i][j] != DBNull.Value)
{
if (dt.Rows[i][j].ToString() != "-")
{
if (Convert.ToDecimal(dt.Rows[i][j]) > _max)
{
_max = Convert.ToDecimal(dt.Rows[i][j]);
_cStringDeneme.Value = _max;
_cStringDeneme.RowIndex = i;
}
}
}
}
// j++;
_ListStringMax.Add(_cStringDeneme);
}
ViewBag.StringMax = _ListStringMax;
// max bitti--------
// Avg değeri bulma ----------------------
List<StringAvg> ListStringAvg = new List<StringAvg>();
for (int i = 0; i < dt.Columns.Count; i++)
{
decimal count = 0, sum = 0;
if (dt.Columns[i].ColumnName.IndexOf("Name") == -1)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
decimal _ActiveValue = 0;
if (dt.Rows[j][i] != DBNull.Value)
{
if (dt.Rows[j][i].ToString() != "-")
{
_ActiveValue = Decimal.Parse(dt.Rows[j][i].ToString());
if (_ActiveValue > 0)
{
sum += _ActiveValue;
count++;
}
}
}
}
StringAvg _StrAvg = new StringAvg();
if (count != 0)
_StrAvg.Avg = decimal.Round(sum / count, 2);
else
_StrAvg.Avg = 0;
_StrAvg.FieldName = dt.Columns[i].ColumnName;
_StrAvg.ColumnIndex = i;
ListStringAvg.Add(_StrAvg);
}
}
ViewBag.StringAvg = ListStringAvg;
//Inverter Toplam
var invGroup = (from u in ListStringAvg
//group u by u.FieldName.Substring(0, 4) into g
select new StringInvNameAvg { invName = "Inverter " + u.FieldName, Avg = Math.Round(u.Avg, 2) })
.ToList();
ViewBag.ListInvAVG = invGroup;
// avg bitti-----------------------------------------
dt.Columns.Add("Tag", typeof(string)).SetOrdinal(0);
TempDTO mt = strTagNames.AsEnumerable()
.GroupBy(r => r.NAME.Split('_')[0])
.Select(g => new TempDTO { NAME = g.Key, ID = g.Count() })//(g => new TempDTO{ NAME = g.OrderByDescending(r => r.NAME.Split('_')[0] } )
.OrderByDescending(x => x.ID).ToList().First();
List<string> tagTemp = strTagNames.Where(x => x.NAME.StartsWith(mt.NAME + "_")).Select(X => X.NAME).ToList();
List<OrderValue> _ListOrderValueTemp = new List<OrderValue>();
for (int i = 0; i < tagTemp.Count; i++)
{
OrderValue _OrderValue = new OrderValue();
_OrderValue.InverterNumber = Convert.ToInt32(tagTemp[i].Split('_')[3].Replace(".", ""));
_OrderValue.InverterName = tagTemp[i];
_ListOrderValueTemp.Add(_OrderValue);
}
List<OrderValue> _ListOrderValue = _ListOrderValueTemp.OrderBy(x => x.InverterNumber).ToList();
List<string> tagCOl = new List<string>();
for (int i = 0; i < _ListOrderValue.Count; i++)
{
tagCOl.Add(_ListOrderValue[i].InverterName);
}
for (int i = 0; i <= tagCOl.Count - 1; i++)
{
if (dt.Rows.Count < i)
{
break;
}
string[] ccc = tagCOl[i].Split('_');
if (tagCOl[i].Contains("temp"))
{
dt.Rows[i]["Tag"] = "Temp.";
}
else
{
dt.Rows[i]["Tag"] = ccc[1] + " " + ccc[2] + " " + ccc[3] + " " + ccc[4];
}
}
//ViewData["columns"] = columns;
#region ColumnsSums
DataTable _dtSums = dt.Clone();
_dtSums.Rows.Clear();
DataRow _drSums = _dtSums.NewRow();
for (int i = 1; i < dt.Columns.Count; i++)
{
decimal _sum = 0;
for (int j = 0; j < dt.Rows.Count; j++)
{
if (dt.Rows[j][i] != DBNull.Value)
{
if (dt.Rows[j][i].ToString() != "-")
{
_sum += Convert.ToDecimal(dt.Rows[j][i]);
}
}
}
_drSums[i] = _sum;
}
_dtSums.Rows.Add(_drSums);
#endregion
#region StandardDeviation
DataTable _dtSD = dt.Clone();
_dtSD.Rows.Clear();
DataRow _drSD = _dtSD.NewRow();
List<StringAvg> _ListStringAvg = ViewBag.StringAvg as List<StringAvg>;
for (int i = 1; i < dt.Columns.Count; i++)
{
double _value = 0;
int n = -1;
double _avg = 0;
StringAvg _cAvg = _ListStringAvg.Where(x => x.FieldName == dt.Columns[i].ColumnName).FirstOrDefault();
if (_cAvg != null)
{
_avg = Convert.ToDouble(_cAvg.Avg);
}
for (int j = 0; j < dt.Rows.Count; j++)
{
if (dt.Rows[j][i] != DBNull.Value)
{
if (dt.Rows[j][i].ToString() != "-")
{
n++;
double _value2 = Convert.ToDouble(dt.Rows[j][i]) - _avg;
_value2 = _value2 * _value2;
_value += _value2;
}
}
}
_value = Math.Sqrt(_value / n);
_value = Math.Round(_value, 2);
_drSD[i] = _value;
}
_dtSD.Rows.Add(_drSD);
ViewBag._dtSD = _dtSD;
#endregion
}
return PartialView(dt);
}
public JsonResult HourlyColorReport2(int stationId, string slctDate)
{
StringPerformanceView _strModel = new StringPerformanceView();
try
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR");
DateTime date = DateTime.Parse(@slctDate);
DateTime curDate = DateTime.Now;
_strModel.strModel = new StringModel();
List<String_Hour_DTO> values = new List<String_Hour_DTO>();
if (curDate.Date.Year == date.Date.Year && curDate.Date.Month == date.Date.Month)
{
NUMBER_FORMAT_DTO convertFormat = ConvertNumberFormatMinute(slctDate);
long _numberDateBegin = convertFormat._begin;
long _numberDateEnd = convertFormat._end;
values = (from u in DB.StringOzetQuarterHourAVG
join v in DB.stationString on u.STRING_ID equals v.STRING_ID
join t in DB.Tags on v.STRING_ID equals t.ID
where v.IS_DELETED == false
&& v.STATION_ID == stationId
&& u.STATION_ID == stationId
&& _numberDateBegin <= u.TARIH_NUMBER && _numberDateEnd >= u.TARIH_NUMBER
orderby u.TARIH_NUMBER ascending
select new String_Hour_DTO
{
NAME = t.NAME,
ID = u.STRING_ID,
TARIH_NUMBER = u.TARIH_NUMBER.Value,
VALUE = u.VALUE
}).ToList();
///////
List<TempDTO> strTagNames = values
.GroupBy(x => x.NAME)
.Select(g => new TempDTO { NAME = g.Key, ID = g.FirstOrDefault().ID,TARIH_NUMBER=g.FirstOrDefault().TARIH_NUMBER,VALUE=g.FirstOrDefault().VALUE })
.ToList();
for (int i = 0; i < strTagNames.Count; i++)
{
strTagNames[i].INPUT_NO = Convert.ToInt32(strTagNames[i].NAME.Split('_')[3].Replace(".", ""));
strTagNames[i].INV_NO = Convert.ToInt32(strTagNames[i].NAME.Split('_')[0].Replace("INV", ""));
}
strTagNames = strTagNames.OrderBy(x => x.INV_NO).ThenBy(x => x.INPUT_NO).ToList();
////
foreach (var item in strTagNames)
{
_strModel.strModel.StringList.Add(item.NAME);
}
var valueList = new List<Values>();
string[] groupTime = values.GroupBy(grp => grp.TARIH_NUMBER).OrderBy(a => a.Key).Select(a => a.Key.ToString().Substring(8, 4)).ToArray();
int endHour = int.Parse(groupTime[groupTime.Length - 1]);
DateTime EndDate = DateTime.Now.Date;
TimeSpan tEndDate = new TimeSpan((int.Parse(groupTime[groupTime.Length - 1].Substring(0, 2))), (int.Parse(groupTime[groupTime.Length - 1].Substring(2, 2))), 0);
EndDate = EndDate.Date + tEndDate;
DateTime LastDate = EndDate;
TimeSpan tLastDate = new TimeSpan(21, 0, 0);
LastDate = LastDate.Date + tLastDate;
for (int i = 0; i < groupTime.Length; i++)
{
_strModel.strModel.Hours.Add(groupTime[i]);
}
while (EndDate < LastDate)
{
EndDate = EndDate.AddMinutes(15);
_strModel.strModel.Hours.Add(HourMinuteFormat(EndDate));
}
//VALUE SIRALAMA
List<TempDTO> strValue = values
.Select(g => new TempDTO { NAME = g.NAME, ID = g.ID, VALUE = g.VALUE, TARIH_NUMBER = g.TARIH_NUMBER })
.ToList();
for (int i = 0; i < strValue.Count; i++)
{
strValue[i].INPUT_NO = Convert.ToInt32(strValue[i].NAME.Split('_')[3].Replace(".", ""));
strValue[i].INV_NO = Convert.ToInt32(strValue[i].NAME.Split('_')[0].Replace("INV", ""));
strValue[i].VALUE = strValue[i].VALUE;
strValue[i].TARIH_NUMBER = strValue[i].TARIH_NUMBER;
}
strValue = strValue.OrderBy(x => x.INV_NO).ThenBy(x => x.INPUT_NO).ToList();
var groupList = strValue.GroupBy(a => a.NAME).ToList();
foreach (var item in groupList)
{
var listvalue = new Values();
foreach (var i in item.GroupBy(grp => grp.TARIH_NUMBER).OrderBy(a => a.Key).ToList())
{
listvalue.values.Add((float)Math.Round(i.Max(a => a.VALUE.Value), 2));
}
valueList.Add(listvalue);
}
_strModel.strModel.series = valueList.ToList();
_strModel.ErrorMessage = "";
}
else
{
NUMBER_FORMAT_DTO convertFormat = ConvertNumberFormatHour(slctDate);
long _numberDateBegin = convertFormat._begin;
long _numberDateEnd = convertFormat._end;
values = (from u in DB.StringOzetAVG
join v in DB.stationString on u.STRING_ID equals v.STRING_ID
join t in DB.Tags on v.STRING_ID equals t.ID
where v.IS_DELETED == false
&& v.STATION_ID == stationId
&& u.STATION_ID == stationId
&& _numberDateBegin < u.TARIH_NUMBER && _numberDateEnd > u.TARIH_NUMBER
orderby u.TARIH_NUMBER ascending
select new String_Hour_DTO
{
NAME = t.NAME,
ID = u.STRING_ID,
TARIH_NUMBER = u.TARIH_NUMBER.Value,
VALUE = u.VALUE
}).ToList();
///////
List<TempDTO> strTagNames = values
.GroupBy(x => x.NAME)
.Select(g => new TempDTO { NAME = g.Key, ID = g.FirstOrDefault().ID,TARIH_NUMBER=g.FirstOrDefault().TARIH_NUMBER,VALUE=g.FirstOrDefault().VALUE })
.ToList();
for (int i = 0; i < strTagNames.Count; i++)
{
strTagNames[i].INPUT_NO = Convert.ToInt32(strTagNames[i].NAME.Split('_')[3].Replace(".", ""));
strTagNames[i].INV_NO = Convert.ToInt32(strTagNames[i].NAME.Split('_')[0].Replace("INV", ""));
}
strTagNames = strTagNames.OrderBy(x => x.INV_NO).ThenBy(x => x.INPUT_NO).ToList();
////
foreach (var item in strTagNames)
{
_strModel.strModel.StringList.Add(item.NAME);
}
var valueList = new List<Values>();
string[] groupTime = values.GroupBy(grp => grp.TARIH_NUMBER).OrderBy(a => a.Key).Select(a => a.Key.ToString().Substring(8, 2)).ToArray();
int endHour = int.Parse(groupTime[groupTime.Length - 1]);
for (int i = 0; i < groupTime.Length; i++)
{
_strModel.strModel.Hours.Add(groupTime[i] + "00");
}
for (int i = endHour + 1; i < 21; i++)
{
if (!groupTime.Contains(i.ToString()))
{
_strModel.strModel.Hours.Add(i.ToString() + "00");
}
}
//VALUE SIRALAMA
List<TempDTO> strValue = values
.Select(g => new TempDTO { NAME = g.NAME, ID = g.ID, VALUE = g.VALUE, TARIH_NUMBER = g.TARIH_NUMBER })
.ToList();
for (int i = 0; i < strValue.Count; i++)
{
strValue[i].INPUT_NO = Convert.ToInt32(strValue[i].NAME.Split('_')[3].Replace(".", ""));
strValue[i].INV_NO = Convert.ToInt32(strValue[i].NAME.Split('_')[0].Replace("INV", ""));
strValue[i].VALUE = strValue[i].VALUE;
strValue[i].TARIH_NUMBER = strValue[i].TARIH_NUMBER;
}
strValue = strValue.OrderBy(x => x.INV_NO).ThenBy(x => x.INPUT_NO).ToList();
var groupList = strValue.GroupBy(a => a.NAME).ToList();
foreach (var item in groupList)
{
var listvalue = new Values();
foreach (var i in item.GroupBy(grp => grp.TARIH_NUMBER).OrderBy(a => a.Key).ToList())
{
listvalue.values.Add((float)Math.Round(i.Max(a => a.VALUE.Value), 2));
}
valueList.Add(listvalue);
}
_strModel.strModel.series = valueList.ToList();
_strModel.ErrorMessage = "";
}
}
catch (Exception ex)
{
_strModel.ErrorMessage = ex.ToString();
}
return Json(_strModel);
}
public class StringMin
{
public int ColumnIndex { get; set; }
public int RowIndex { get; set; }
public decimal Min { get; set; }
public string FieldName { get; set; }
}
public class STR_DTO
{
public int ID { get; set; }
public string NAME { get; set; }
public DateTime date { get; set; }
public long? dateNumber { get; set; }
public float? VALUE { get; set; }
}
public class StringDeneme
{
public int ColumnIndex { get; set; }
public int RowIndex { get; set; }
public string FieldName { get; set; }
public decimal Value { get; set; }
}
public class StringAvg
{
public int ColumnIndex { get; set; }
public int RowIndex { get; set; }
public decimal Avg { get; set; }
public string FieldName { get; set; }
}
public class OrderValue
{
public int InverterNumber { get; set; } = 0;
public string InverterName { get; set; } = "";
}
public class NUMBER_FORMAT_DTO
{
public long _begin { get; set; }
public long _end { get; set; }
}
public NUMBER_FORMAT_DTO ConvertNumberFormatHour(string date)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR");
DateTime selectDate = DateTime.Parse(date);
string _convertDate = "";
string _year = selectDate.Year.ToString();
string _month = selectDate.Month.ToString();
string _day = selectDate.Day.ToString();
if (_month.Length < 2)
{
_month = "0" + selectDate.Month.ToString();
}
if (_day.Length < 2)
{
_day = "0" + selectDate.Day.ToString();
}
_convertDate = _year + _month + _day;
string _strDateBegin = _convertDate + "04";
string _strDateEnd = _convertDate + "21";
NUMBER_FORMAT_DTO ndto = new NUMBER_FORMAT_DTO();
ndto._begin = Convert.ToInt64(_strDateBegin);
ndto._end = Convert.ToInt64(_strDateEnd);
return ndto;
}
public NUMBER_FORMAT_DTO ConvertNumberFormatMinute(string date)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR");
DateTime selectDate = DateTime.Parse(date);
string _convertDate = "";
string _year = selectDate.Year.ToString();
string _month = selectDate.Month.ToString();
string _day = selectDate.Day.ToString();
if (_month.Length < 2)
{
_month = "0" + selectDate.Month.ToString();
}
if (_day.Length < 2)
{
_day = "0" + selectDate.Day.ToString();
}
_convertDate = _year + _month + _day;
string _strDateBegin = _convertDate + "0400";
string _strDateEnd = _convertDate + "2100";
NUMBER_FORMAT_DTO ndto = new NUMBER_FORMAT_DTO();
ndto._begin = Convert.ToInt64(_strDateBegin);
ndto._end = Convert.ToInt64(_strDateEnd);
return ndto;
}
public string HourMinuteFormat(DateTime dt)
{
string _date = "";
string _hour = dt.Hour.ToString();
string _minute = dt.Minute.ToString();
if (_hour.Length < 2)
{
_hour = "0" + dt.Month.ToString();
}
if (_minute.Length < 2)
{
_minute = "0" + dt.Minute.ToString();
}
_date = _hour + _minute;
return _date;
}
public NUMBER_FORMAT_DTO ConvertNumberFormatDateAndHour(string date, string hour)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR");
DateTime selectDate = DateTime.Parse(date);
string _convertDate = "";
string _year = selectDate.Year.ToString();
string _month = selectDate.Month.ToString();
string _day = selectDate.Day.ToString();
if (_month.Length < 2)
{
_month = "0" + selectDate.Month.ToString();
}
if (_day.Length < 2)
{
_day = "0" + selectDate.Day.ToString();
}
_convertDate = _year + _month + _day;
string _strDateBegin = _convertDate + hour;
NUMBER_FORMAT_DTO ndto = new NUMBER_FORMAT_DTO();
ndto._begin = Convert.ToInt64(_strDateBegin);
return ndto;
}
public NUMBER_FORMAT_DTO ConvertNumberFormatDateAndHourQuarter(string date, string hour, string minute)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR");
DateTime selectDate = DateTime.Parse(date);
string _convertDate = "";
string _year = selectDate.Year.ToString();
string _month = selectDate.Month.ToString();
string _day = selectDate.Day.ToString();
if (_month.Length < 2)
{
_month = "0" + selectDate.Month.ToString();
}
if (_day.Length < 2)
{
_day = "0" + selectDate.Day.ToString();
}
_convertDate = _year + _month + _day;
string _strDateBegin = _convertDate + hour + minute;
NUMBER_FORMAT_DTO ndto = new NUMBER_FORMAT_DTO();
ndto._begin = Convert.ToInt64(_strDateBegin);
return ndto;
}
public class StringInvNameAvg
{
public string invName { get; set; }
public decimal Avg { get; set; }
}
}
}
| 39.267271 | 195 | 0.416376 | [
"MIT"
] | ismailllefe/ESOFT | Esso.Web/Controllers/String_DCController.cs | 34,677 | C# |
/*
* Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
* See https://github.com/ArcherTrister/LeXun.Security.OAuth
* for more information concerning the license and the contributors participating to this project.
*/
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Http;
using System.Security.Claims;
using static Microsoft.AspNetCore.Security.Authentication.Baidu.BaiduAuthenticationConstants;
namespace Microsoft.AspNetCore.Security.Authentication.Baidu
{
/// <summary>
/// Defines a set of options used by <see cref="BaiduAuthenticationHandler"/>.
/// </summary>
public class BaiduAuthenticationOptions : OAuthOptions
{
public BaiduAuthenticationOptions()
{
ClaimsIssuer = BaiduAuthenticationDefaults.Issuer;
CallbackPath = new PathString(BaiduAuthenticationDefaults.CallbackPath);
AuthorizationEndpoint = BaiduAuthenticationDefaults.AuthorizationEndpoint;
TokenEndpoint = BaiduAuthenticationDefaults.TokenEndpoint;
UserInformationEndpoint = BaiduAuthenticationDefaults.UserInformationEndpoint;
Scope.Add("basic");
ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "userid");
ClaimActions.MapJsonKey(ClaimTypes.Name, "username");
//"1"表示男,"0"表示女。
ClaimActions.MapJsonKey(ClaimTypes.Gender, "sex", ClaimValueTypes.Integer);
ClaimActions.MapJsonKey(Claims.UserId, "userid");
ClaimActions.MapJsonKey(Claims.UserName, "username");
ClaimActions.MapJsonKey(Claims.RealName, "realname");
ClaimActions.MapJsonKey(Claims.Portrait, "portrait");
ClaimActions.MapJsonKey(Claims.UserDetail, "userdetail");
ClaimActions.MapJsonKey(Claims.Birthday, "birthday");
ClaimActions.MapJsonKey(Claims.Marriage, "marriage");
ClaimActions.MapJsonKey(Claims.Blood, "blood");
ClaimActions.MapJsonKey(Claims.Figure, "figure");
ClaimActions.MapJsonKey(Claims.Constellation, "constellation");
ClaimActions.MapJsonKey(Claims.Education, "education");
ClaimActions.MapJsonKey(Claims.Trade, "trade");
ClaimActions.MapJsonKey(Claims.Job, "job");
}
}
} | 46.411765 | 98 | 0.705957 | [
"Apache-2.0"
] | ArcherTrister/LeXun.Security.OAuth | src/Microsoft.AspNetCore.Security.Authentication.Baidu/BaiduAuthenticationOptions.cs | 2,385 | C# |
// ---------------------------------------------------------------------------
// Copyright (c) 2019, The .NET Foundation.
// This software is released under the Apache License, Version 2.0.
// The license and further copyright text can be found in the file LICENSE.md
// at the root directory of the distribution.
// ---------------------------------------------------------------------------
using System.Windows;
/* Descriptors are simple classes that define the shape of a bond visual.
They simplify the transfer of information into and out of drawing routines.
You can either use the Point properties and draw primitives directly from those,
or use the DefinedGeometry and draw that directly
*/
namespace Chem4Word.ACME.Drawing
{
public class TripleBondLayout : DoubleBondLayout
{
public Point TertiaryStart;
public Point TertiaryEnd;
}
} | 39.695652 | 84 | 0.595838 | [
"Apache-2.0"
] | kazuyaujihara/Version3-1 | src/Chemistry/Chem4Word.ACME/Drawing/TripleBondLayout.cs | 893 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Identity.Test.Common.Core.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Microsoft.Identity.Test.Unit.ExceptionTests
{
[TestClass]
public class ExperimentalFeatureTests
{
#if DESKTOP
[TestMethod]
public async Task ExperimentalFeatureExceptionAsync()
{
var pca = PublicClientApplicationBuilder.Create(Guid.NewGuid().ToString()).Build();
MsalClientException ex = await AssertException.TaskThrowsAsync<MsalClientException>(
() => pca.AcquireTokenInteractive(new[] { "scope" }).WithProofOfPosession(null).ExecuteAsync())
.ConfigureAwait(false);
Assert.AreEqual(MsalError.ExperimentalFeature, ex.ErrorCode);
}
#endif
}
}
| 31.588235 | 111 | 0.723464 | [
"MIT"
] | DaehyunLee/microsoft-authentication-library-for-dotnet | tests/Microsoft.Identity.Test.Unit.net45/ExceptionTests/ExperimentalFeatureTests.cs | 1,076 | C# |
using AnyConfig.Json;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;
namespace AnyConfig
{
/// <summary>
/// Configuration retrieval management
/// </summary>
public partial class ConfigProvider
{
public static ConfigValueNotSet Empty => ConfigValueNotSet.Instance;
public string LastResolvedConfigurationFilename { get; internal set; }
private static CachedDataProvider<object> _cachedObjects = new CachedDataProvider<object>();
private static CachedFileProvider _cachedFiles = new CachedFileProvider();
/// <summary>
/// Get a connection string by name
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public string GetConnectionString(string name)
{
return InternalGetConnectionString(name);
}
/// <summary>
/// Get a configuration object from a json serialized configuration file
/// </summary>
/// <returns></returns>
public IConfigurationRoot GetConfiguration()
{
return GetConfiguration(DotNetCoreSettingsFilename, null);
}
/// <summary>
/// Get a configuration object from a json serialized configuration file
/// </summary>
/// <param name="appSettingsJson">Name of json settings file</param>
/// <returns></returns>
public IConfigurationRoot GetConfiguration(string appSettingsJson)
{
return GetConfiguration(appSettingsJson, null);
}
/// <summary>
/// Get a configuration object from a json serialized configuration file
/// </summary>
/// <param name="appSettingsJson">Name of json settings file</param>
/// <param name="path">Optional path to json settings file</param>
/// <returns></returns>
public IConfigurationRoot GetConfiguration(string appSettingsJson, string path)
{
var filename = appSettingsJson ?? DotNetCoreSettingsFilename;
if (string.IsNullOrEmpty(path))
{
var resolver = new ConfigurationResolver();
path = Path.GetDirectoryName(resolver.ResolveFilenamePath(filename));
}
var filePath = Path.Combine(path, filename);
var configuration = _cachedObjects.AddOrGet(filePath, () => {
var jsonParser = new JsonParser();
var fileContents = _cachedFiles.AddOrGetFile(filePath);
var rootNode = jsonParser.Parse(fileContents);
var configurationRoot = new ConfigurationRoot(filePath);
var provider = new JsonConfigurationProvider(filePath);
configurationRoot.AddProvider(provider);
foreach (JsonNode node in rootNode.ChildNodes)
{
if (node.ValueType == PrimitiveTypes.Object)
{
configurationRoot.AddSection(node);
}
else
{
// not supported yet
}
}
provider.SetData(MapAllNodes(rootNode, new List<KeyValuePair<string, string>>()));
return configurationRoot;
});
return configuration as IConfigurationRoot;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <returns></returns>
public string Get(string optionName, string defaultValue)
{
InternalTryGet<string>(out var value, optionName, ConfigSource.WebConfig, defaultValue, false);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <returns></returns>
public string Get(string optionName, string defaultValue, ConfigSource configSource)
{
InternalTryGet<string>(out var value, optionName, configSource, defaultValue, false);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <param name="throwsException">True to throw exception if key is not found</param>
/// <param name="configParameters">An optional list of key/value parameters to pass to the lookup method. Example: Get(..., SomeKey=>SomeValue, SomeKey2=>SomeValue)</param>
/// <returns></returns>
public string Get(string optionName, string defaultValue, ConfigSource configSource, bool throwsException, params Expression<Func<object, object>>[] configParameters)
{
InternalTryGet<string>(out var value, optionName, configSource, defaultValue, throwsException);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <param name="optionName"></param>
/// <returns></returns>
public object Get(Type valueType, string optionName, object defaultValue)
{
InternalTryGet(out var value, valueType, optionName, ConfigSource.WebConfig, defaultValue, false);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <param name="throwsException">True to throw exception if key is not found</param>
/// <param name="configParameters">An optional list of key/value parameters to pass to the lookup method. Example: Get(..., SomeKey=>SomeValue, SomeKey2=>SomeValue)</param>
/// <returns></returns>
public object Get(Type valueType, string optionName, object defaultValue, ConfigSource configSource)
{
InternalTryGet(out var value, valueType, optionName, configSource, defaultValue, false);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <param name="throwsException">True to throw exception if key is not found</param>
/// <param name="configParameters">An optional list of key/value parameters to pass to the lookup method. Example: Get(..., SomeKey=>SomeValue, SomeKey2=>SomeValue)</param>
/// <returns></returns>
public object Get(Type valueType, string optionName, object defaultValue, ConfigSource configSource, bool throwsException, params Expression<Func<object, object>>[] configParameters)
{
InternalTryGet(out var value, valueType, optionName, configSource, defaultValue, throwsException, false, configParameters);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <returns></returns>
public T Get<T>(string optionName, T defaultValue)
{
InternalTryGet<T>(out var value, optionName, ConfigSource.WebConfig, defaultValue, false);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <returns></returns>
public T Get<T>(string optionName, T defaultValue, ConfigSource configSource)
{
InternalTryGet<T>(out var value, optionName, configSource, defaultValue, false);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="optionName"></param>
/// <param name="defaultValue">Default value to return if setting is not found</param>
/// <param name="configSource"></param>
/// <param name="throwsException">True to throw exception if key is not found</param>
/// <param name="configParameters">An optional list of key/value parameters to pass to the lookup method. Example: Get(..., SomeKey=>SomeValue, SomeKey2=>SomeValue)</param>
/// <returns></returns>
public T Get<T>(string optionName, T defaultValue, ConfigSource configSource, bool throwsException, params Expression<Func<object, object>>[] configParameters)
{
InternalTryGet<T>(out var value, optionName, configSource, defaultValue, throwsException, false, configParameters);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="configSource"></param>
/// <param name="throwsException">True to throw exception if key is not found</param>
/// <param name="configParameters">An optional list of key/value parameters to pass to the lookup method. Example: Get(..., SomeKey=>SomeValue, SomeKey2=>SomeValue)</param>
/// <returns></returns>
public T Get<T>(ConfigSource configSource, bool throwsException, params Expression<Func<object, object>>[] configParameters)
{
InternalTryGet<T>(out var value, string.Empty, configSource, default, throwsException, false, configParameters);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="defaultValue">Default value to return if setting is not found</param>
/// <param name="configSource"></param>
/// <param name="throwsException">True to throw exception if key is not found</param>
/// <param name="configParameters">An optional list of key/value parameters to pass to the lookup method. Example: Get(..., SomeKey=>SomeValue, SomeKey2=>SomeValue)</param>
/// <returns></returns>
public T Get<T>(T defaultValue, ConfigSource configSource, bool throwsException, params Expression<Func<object, object>>[] configParameters)
{
InternalTryGet<T>(out var value, string.Empty, configSource, defaultValue, throwsException, false, configParameters);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <returns></returns>
public string Get(string optionName)
{
InternalTryGet<string>(out var value, optionName, ConfigSource.WebConfig, default, false);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <returns></returns>
public string Get(string optionName, ConfigSource configSource)
{
InternalTryGet<string>(out var value, optionName, configSource, default, false);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <param name="throwsException">True to throw exception if key is not found</param>
/// <param name="configParameters">An optional list of key/value parameters to pass to the lookup method. Example: Get(..., SomeKey=>SomeValue, SomeKey2=>SomeValue)</param>
/// <returns></returns>
public string Get(string optionName, ConfigSource configSource, bool throwsException, params Expression<Func<object, object>>[] configParameters)
{
InternalTryGet<string>(out var value, optionName, configSource, default, throwsException);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <returns></returns>
public T Get<T>(string optionName)
{
InternalTryGet<T>(out var value, optionName, ConfigSource.WebConfig, default, false);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <returns></returns>
public T Get<T>(string optionName, ConfigSource configSource)
{
InternalTryGet<T>(out var value, optionName, configSource, default, false);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <param name="throwsException">True to throw exception if key is not found</param>
/// <param name="configParameters">An optional list of key/value parameters to pass to the lookup method. Example: Get(..., SomeKey=>SomeValue, SomeKey2=>SomeValue)</param>
/// <returns></returns>
public T Get<T>(string optionName, ConfigSource configSource, bool throwsException, params Expression<Func<object, object>>[] configParameters)
{
InternalTryGet<T>(out var value, optionName, configSource, default, throwsException, false, configParameters);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="optionName"></param>
/// <param name="configSource"></param>
/// <param name="throwsException">True to throw exception if key is not found</param>
/// <param name="expandEnvironmentVariables">True to expand environment variables</param>
/// <param name="configParameters">An optional list of key/value parameters to pass to the lookup method. Example: Get(..., SomeKey=>SomeValue, SomeKey2=>SomeValue)</param>
/// <returns></returns>
public T Get<T>(string optionName, ConfigSource configSource, bool throwsException, bool expandEnvironmentVariables, params Expression<Func<object, object>>[] configParameters)
{
InternalTryGet<T>(out var value, optionName, configSource, default, throwsException, expandEnvironmentVariables, configParameters);
return value;
}
/// <summary>
/// Get a configuration setting from a specific web/app config section name
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="optionName"></param>
/// <returns></returns>
public T GetFromSection<T>(string optionName)
{
GetWebConfigSetting<T>(out var value, optionName, "appSettings", default, false);
return value;
}
/// <summary>
/// Get a configuration setting from a specific web/app config section name
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="optionName"></param>
/// <param name="sectionName">The config section name to read from</param>
/// <returns></returns>
public T GetFromSection<T>(string optionName, string sectionName)
{
GetWebConfigSetting<T>(out var value, optionName, sectionName, default, false);
return value;
}
/// <summary>
/// Get a configuration setting from a specific web/app config section name
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="optionName"></param>
/// <param name="sectionName">The config section name to read from</param>
/// <param name="throwsException">True to throw exception if key is not found</param>
/// <returns></returns>
public T GetFromSection<T>(string optionName, string sectionName, bool throwsException)
{
GetWebConfigSetting<T>(out var value, optionName, sectionName, default, throwsException);
return value;
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <param name="value">The value to output</param>
/// <param name="valueType">The type of the configuration value</param>
/// <param name="optionName">The configuration name of the option</param>
/// <param name="defaultValue">The default value if the configuration is not found</param>
/// <param name="configSource">Which source the configuration should be loaded from</param>
/// <param name="throwsException">True to throw exception if key is not found</param>
/// <param name="configParameters">An optional list of key/value parameters to pass to the lookup method. Example: Get(..., SomeKey=>SomeValue, SomeKey2=>SomeValue)</param>
/// <returns></returns>
public bool TryGet(out object value, Type valueType, string optionName, object defaultValue, ConfigSource configSource, bool throwsException, params Expression<Func<object, object>>[] configParameters)
{
return InternalTryGet(out value, valueType, optionName, configSource, defaultValue, throwsException, false, configParameters);
}
/// <summary>
/// Get a configuration setting
/// </summary>
/// <param name="value">The value to output</param>
/// <param name="optionName">The configuration name of the option</param>
/// <param name="defaultValue">The default value if the configuration is not found</param>
/// <param name="configSource">Which source the configuration should be loaded from</param>
/// <param name="throwsException">True to throw exception if key is not found</param>
/// <param name="configParameters">An optional list of key/value parameters to pass to the lookup method. Example: Get(..., SomeKey=>SomeValue, SomeKey2=>SomeValue)</param>
/// <returns></returns>
public bool TryGet<T>(out T value, string optionName, T defaultValue, ConfigSource configSource, bool throwsException, params Expression<Func<object, object>>[] configParameters)
{
return InternalTryGet<T>(out value, optionName, configSource, defaultValue, throwsException, false, configParameters);
}
}
}
| 47.05665 | 209 | 0.612719 | [
"MIT"
] | replaysMike/AnyConf | AnyConfig/AnyConfig/ConfigProvider.cs | 19,107 | C# |
using System;
using System.Reflection;
using System.Runtime.Serialization;
namespace BitSharper.Threading.Utility
{
/// <summary>
/// Collection of static methods that aid in serialization.
/// </summary>
internal static class SerializationUtilities //NET_ONLY
{
/// <summary>
/// Writes the serializable fields to the SerializationInfo object, which stores all the data needed to serialize the specified object object.
/// </summary>
/// <param name="info">SerializationInfo parameter from the GetObjectData method.</param>
/// <param name="context">StreamingContext parameter from the GetObjectData method.</param>
/// <param name="instance">Object to serialize.</param>
public static void DefaultWriteObject(SerializationInfo info, StreamingContext context, Object instance)
{
var thisType = instance.GetType();
var mi = FormatterServices.GetSerializableMembers(thisType, context);
for (var i = 0; i < mi.Length; i++)
{
info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(instance));
}
}
/// <summary>
/// Reads the serialized fields written by the DefaultWriteObject method.
/// </summary>
/// <param name="info">SerializationInfo parameter from the special deserialization constructor.</param>
/// <param name="context">StreamingContext parameter from the special deserialization constructor</param>
/// <param name="instance">Object to deserialize.</param>
public static void DefaultReadObject(SerializationInfo info, StreamingContext context, Object instance)
{
var thisType = instance.GetType();
var mi = FormatterServices.GetSerializableMembers(thisType, context);
for (var i = 0; i < mi.Length; i++)
{
var fi = (FieldInfo) mi[i];
fi.SetValue(instance, info.GetValue(fi.Name, fi.FieldType));
}
}
}
} | 45.533333 | 150 | 0.636896 | [
"BSD-3-Clause"
] | TangibleCryptography/BitSharper | src/Core/Threading/Utility/SerializationUtilities.cs | 2,049 | C# |
using Discord;
using NadekoBot.Extensions;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
namespace NadekoBot.Classes.JSONModels
{
public class Configuration
{
[JsonIgnore]
public static readonly Dictionary<string, List<string>> DefaultCustomReactions = new Dictionary<string, List<string>>
{
{@"\o\", new List<string>()
{ "/o/" } },
{"/o/", new List<string>()
{ @"\o\" } },
{"moveto", new List<string>() {
@"(👉 ͡° ͜ʖ ͡°)👉 %target%" } },
{"comeatmebro", new List<string>() {
"%target% (ง’̀-‘́)ง" } },
{"e", new List<string>() {
"%user% did it 😒 🔫",
"%target% did it 😒 🔫" } },
{"%mention% insult", new List<string>() {
"%target% You are a poop.",
"%target% You're a jerk.",
"%target% I will eat you when I get my powers back."
} },
{"%mention% praise", new List<string>()
{
"%target% You are cool.",
"%target% You are nice!",
"%target% You did a good job.",
"%target% You did something nice.",
"%target% is awesome!",
"%target% Wow."
} },
{"%mention% pat", new List<string>() {
"http://i.imgur.com/IiQwK12.gif",
"http://i.imgur.com/JCXj8yD.gif",
"http://i.imgur.com/qqBl2bm.gif",
"http://i.imgur.com/eOJlnwP.gif",
"https://45.media.tumblr.com/229ec0458891c4dcd847545c81e760a5/tumblr_mpfy232F4j1rxrpjzo1_r2_500.gif",
"https://media.giphy.com/media/KZQlfylo73AMU/giphy.gif",
"https://media.giphy.com/media/12hvLuZ7uzvCvK/giphy.gif",
"http://gallery1.anivide.com/_full/65030_1382582341.gif",
"https://49.media.tumblr.com/8e8a099c4eba22abd3ec0f70fd087cce/tumblr_nxovj9oY861ur1mffo1_500.gif ",
} },
{"%mention% cry", new List<string>()
{
"http://i.imgur.com/Xg3i1Qy.gif",
"http://i.imgur.com/3K8DRrU.gif",
"http://i.imgur.com/k58BcAv.gif",
"http://i.imgur.com/I2fLXwo.gif"
} },
{"%mention% are you real?", new List<string>()
{
"%user%, I will be soon."
} },
{"%mention% are you there?", new List<string>()
{
"Yes. :)"
} },
{"%mention% draw", new List<string>() {
"Sorry, I don't gamble, type $draw for that function."
} },
{"%mention% bb", new List<string>()
{
"Bye %target%"
} },
{"%mention% call", new List<string>() {
"Calling %target%"
} },
{"%mention% disguise", new List<string>() {
"https://cdn.discordapp.com/attachments/140007341880901632/156721710458994690/Cc5mixjUYAADgBs.jpg",
"https://cdn.discordapp.com/attachments/140007341880901632/156721715831898113/hqdefault.jpg",
"https://cdn.discordapp.com/attachments/140007341880901632/156721724430352385/okawari_01_haruka_weird_mask.jpg",
"https://cdn.discordapp.com/attachments/140007341880901632/156721728763068417/mustache-best-girl.png"
} },
{"%mention% inv", new List<string>() {
"To invite your bot, click on this link -> <https://discordapp.com/oauth2/authorize?client_id=%target%&scope=bot&permissions=66186303>"
} },
{ "%mention% threaten", new List<string>() {
"You wanna die, %target%?"
} },
{ "%mention% archer", new List<string>() {
"http://i.imgur.com/Bha9NhL.jpg"
} },
{ "%mention% formuoli", new List<string>() {
"http://i.imgur.com/sCHYQhl.jpg"
} },
{ "%mention% mei", new List<string>() {
"http://i.imgur.com/Xkrf5y7.png"
} },
{ "%mention% omega yato", new List<string>() {
"https://cdn.discordapp.com/attachments/168617088892534784/221047921410310144/Yato_Animated.gif"
} },
{ "%mention% smack", new List<string>() {
"%target% https://66.media.tumblr.com/dd5d751f86002fd4a544dcef7a9763d6/tumblr_mjpheaAVj51s725bno1_500.gif",
"%target% https://media.giphy.com/media/jLeyZWgtwgr2U/giphy.gif",
"%target% http://orig11.deviantart.net/2d34/f/2013/339/1/2/golden_time_flower_slap_gif_by_paranoxias-d6wv007.gif",
"%target% http://media.giphy.com/media/LB1kIoSRFTC2Q/giphy.gif",
} }
};
public bool DontJoinServers { get; set; } = false;
public bool ForwardMessages { get; set; } = true;
public bool ForwardToAllOwners { get; set; } = false;
public bool IsRotatingStatus { get; set; } = false;
public int BufferSize { get; set; } = 4.MiB();
public string[] RaceAnimals { get; internal set; } = {
"🐼",
"🐻",
"🐧",
"🐨",
"🐬",
"🐞",
"🦀",
"🦄" };
[JsonIgnore]
public List<Quote> Quotes { get; set; } = new List<Quote>();
[JsonIgnore]
public List<PokemonType> PokemonTypes { get; set; } = new List<PokemonType>();
public string RemindMessageFormat { get; set; } = "❗⏰**I've been told to remind you to '%message%' now by %user%.**⏰❗";
[JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
public Dictionary<string, List<string>> CustomReactions { get; set; }
public List<string> RotatingStatuses { get; set; } = new List<string>();
public CommandPrefixesModel CommandPrefixes { get; set; } = new CommandPrefixesModel();
public HashSet<ulong> ServerBlacklist { get; set; } = new HashSet<ulong>();
public HashSet<ulong> ChannelBlacklist { get; set; } = new HashSet<ulong>();
public HashSet<ulong> UserBlacklist { get; set; } = new HashSet<ulong>() {
105309315895693312,
119174277298782216,
143515953525817344
};
[OnDeserialized]
internal void OnDeserialized(StreamingContext context)
{
if (CustomReactions == null)
{
CustomReactions = DefaultCustomReactions;
}
}
[OnSerializing]
internal void OnSerializing(StreamingContext context)
{
if (CustomReactions == null)
{
CustomReactions = DefaultCustomReactions;
}
}
public string[] _8BallResponses { get; set; } =
{
"Most definitely yes",
"For sure",
"As I see it, yes",
"My sources say yes",
"Yes",
"Most likely",
"Perhaps",
"Maybe",
"Not sure",
"It is uncertain",
"Ask me again later",
"Don't count on it",
"Probably not",
"Very doubtful",
"Most likely no",
"Nope",
"No",
"My sources say no",
"Dont even think about it",
"Definitely no",
"NO - It may cause disease contraction"
};
public string CurrencySign { get; set; } = "🌸";
public string CurrencyName { get; set; } = "NadekoFlower";
public string DMHelpString { get; set; } = "Type `-h` for help.";
public string HelpString { get; set; } = @"You can use `{0}modules` command to see a list of all modules.
You can use `{0}commands ModuleName`
(for example `{0}commands Administration`) to see a list of all of the commands in that module.
For a specific command help, use `{0}h ""Command name""` (for example `-h ""!m q""`)
**LIST OF COMMANDS CAN BE FOUND ON THIS LINK**
<http://nadekobot.readthedocs.io/en/latest/Commands%20List/>
Nadeko Support Server: <https://discord.gg/0ehQwTK2RBjAxzEY>";
}
public class CommandPrefixesModel
{
public string Administration { get; set; } = ".";
public string Searches { get; set; } = "~";
public string NSFW { get; set; } = "~";
public string Conversations { get; set; } = "<@{0}>";
public string ClashOfClans { get; set; } = ",";
public string Help { get; set; } = "-";
public string Music { get; set; } = "!!";
public string Trello { get; set; } = "trello ";
public string Games { get; set; } = ">";
public string Gambling { get; set; } = "$";
public string Permissions { get; set; } = ";";
public string Programming { get; set; } = "%";
public string Pokemon { get; set; } = ">";
public string Utility { get; set; } = ".";
}
public static class ConfigHandler
{
private static readonly SemaphoreSlim configLock = new SemaphoreSlim(1, 1);
public static async Task SaveConfig()
{
await configLock.WaitAsync();
try
{
File.WriteAllText("data/config.json", JsonConvert.SerializeObject(NadekoBot.Config, Formatting.Indented));
}
finally
{
configLock.Release();
}
}
public static bool IsBlackListed(MessageEventArgs evArgs) => IsUserBlacklisted(evArgs.User.Id) ||
(!evArgs.Channel.IsPrivate &&
(IsChannelBlacklisted(evArgs.Channel.Id) || IsServerBlacklisted(evArgs.Server.Id)));
public static bool IsServerBlacklisted(ulong id) => NadekoBot.Config.ServerBlacklist.Contains(id);
public static bool IsChannelBlacklisted(ulong id) => NadekoBot.Config.ChannelBlacklist.Contains(id);
public static bool IsUserBlacklisted(ulong id) => NadekoBot.Config.UserBlacklist.Contains(id);
}
public class Quote
{
public string Author { get; set; }
public string Text { get; set; }
public override string ToString() =>
$"{Text}\n\t*-{Author}*";
}
}
| 40.770992 | 155 | 0.522187 | [
"MIT"
] | RufusNash/DeviantBot | NadekoBot/_Models/JSONModels/Configuration.cs | 10,753 | C# |
using System;
using AdminWebsite.Mappers;
using AdminWebsite.Services.Models;
using FluentAssertions;
using NUnit.Framework;
namespace AdminWebsite.UnitTests.Mappers
{
public class PublicHolidaysResponseMapperTest
{
[Test]
public void should_map_public_holiday_to_response()
{
var date = DateTime.Today.AddDays(3);
var title = "Summer Bank Holiday";
var pb = new PublicHoliday
{
Date = date,
Title = title
};
var result = PublicHolidayResponseMapper.MapFrom(pb);
result.Date.Should().Be(date);
result.Name.Should().Be(title);
}
}
} | 25.642857 | 65 | 0.583565 | [
"MIT"
] | hmcts/vh-admin-web | AdminWebsite/AdminWebsite.UnitTests/Mappers/PublicHolidaysResponseMapperTest.cs | 718 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ecs-2014-11-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.ECS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ECS.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for Deployment Object
/// </summary>
public class DeploymentUnmarshaller : IUnmarshaller<Deployment, XmlUnmarshallerContext>, IUnmarshaller<Deployment, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
Deployment IUnmarshaller<Deployment, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Deployment Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
Deployment unmarshalledObject = new Deployment();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("capacityProviderStrategy", targetDepth))
{
var unmarshaller = new ListUnmarshaller<CapacityProviderStrategyItem, CapacityProviderStrategyItemUnmarshaller>(CapacityProviderStrategyItemUnmarshaller.Instance);
unmarshalledObject.CapacityProviderStrategy = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("createdAt", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
unmarshalledObject.CreatedAt = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("desiredCount", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.DesiredCount = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("failedTasks", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.FailedTasks = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("id", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Id = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("launchType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.LaunchType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("networkConfiguration", targetDepth))
{
var unmarshaller = NetworkConfigurationUnmarshaller.Instance;
unmarshalledObject.NetworkConfiguration = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("pendingCount", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.PendingCount = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("platformVersion", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.PlatformVersion = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("rolloutState", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.RolloutState = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("rolloutStateReason", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.RolloutStateReason = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("runningCount", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.RunningCount = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("status", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Status = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("taskDefinition", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.TaskDefinition = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("updatedAt", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
unmarshalledObject.UpdatedAt = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static DeploymentUnmarshaller _instance = new DeploymentUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeploymentUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.369318 | 183 | 0.575882 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/ECS/Generated/Model/Internal/MarshallTransformations/DeploymentUnmarshaller.cs | 7,281 | C# |
using System;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace PuppeteerSharp.Tests.ElementHandleTests
{
[Collection(TestConstants.TestFixtureCollectionName)]
public class QuerySelectorTests : PuppeteerPageBaseTest
{
public QuerySelectorTests(ITestOutputHelper output) : base(output)
{
}
[Fact]
public async Task ShouldQueryExistingElement()
{
await Page.GoToAsync(TestConstants.ServerUrl + "/playground.html");
await Page.SetContentAsync("<html><body><div class=\"second\"><div class=\"inner\">A</div></div></body></html>");
var html = await Page.QuerySelectorAsync("html");
var second = await html.QuerySelectorAsync(".second");
var inner = await second.QuerySelectorAsync(".inner");
var content = await Page.EvaluateFunctionAsync<string>("e => e.textContent", inner);
Assert.Equal("A", content);
}
[Fact]
public async Task ShouldReturnNullForNonExistingElement()
{
await Page.SetContentAsync("<html><body><div class=\"second\"><div class=\"inner\">B</div></div></body></html>");
var html = await Page.QuerySelectorAsync("html");
var second = await html.QuerySelectorAsync(".third");
Assert.Null(second);
}
}
} | 38.361111 | 125 | 0.631427 | [
"MIT"
] | Dgaduin/puppeteer-sharp | lib/PuppeteerSharp.Tests/ElementHandleTests/QuerySelectorTests.cs | 1,381 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Api.Services;
using Api.Interfaces;
namespace Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddTransient<ISumNumberService, SumNumberService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
| 26.701754 | 106 | 0.65703 | [
"MIT"
] | deanagan/CodingPracticeASPNetBackend | SumNumber/Api/Startup.cs | 1,522 | C# |
using System;
using Orleans.Providers;
using UnitTests.GrainInterfaces;
namespace UnitTests.Grains
{
[Serializable]
public class Player1GrainState : Player1Properties, PlayerState
{
public string Email { get; set; }
}
/// <summary>
/// A simple grain that represent a player in a game
/// </summary>
[StorageProvider(ProviderName = "GrainStore")]
public class Player1Grain : PlayerGrain<Player1GrainState, Player1Properties>, IPlayer1Grain
{
}
}
| 23.857143 | 96 | 0.692615 | [
"MIT"
] | OrleansContrib/Orleans.Indexing-1.5 | test/TestGrains/Player1Grain.cs | 503 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading.Tasks;
using Azure.Core.TestFramework;
using Azure.Storage.Sas;
using Azure.Storage.Test;
using NUnit.Framework;
using TestConstants = Azure.Storage.Test.TestConstants;
namespace Azure.Storage.Files.Shares.Tests
{
public class FileSasBuilderTests : FileTestBase
{
private const string Permissions = "rcwd";
public FileSasBuilderTests(bool async, ShareClientOptions.ServiceVersion serviceVersion)
: base(async, serviceVersion, null /* RecordedTestMode.Record /* to re-record */)
{
}
[RecordedTest]
public void FileSasBuilder_ToSasQueryParameters_FilePathTest()
{
// Arrange
var constants = TestConstants.Create(this);
var shareName = GetNewShareName();
var filePath = GetNewDirectoryName();
ShareSasBuilder fileSasBuilder = BuildFileSasBuilder(includeFilePath: true, constants, shareName, filePath);
var signature = BuildSignature(includeFilePath: true, constants, shareName, filePath);
// Act
var sasQueryParameters = fileSasBuilder.ToSasQueryParameters(constants.Sas.SharedKeyCredential);
// Assert
Assert.AreEqual(SasQueryParametersInternals.DefaultSasVersionInternal, sasQueryParameters.Version);
Assert.IsNull(sasQueryParameters.Services);
Assert.IsNull(sasQueryParameters.ResourceTypes);
Assert.AreEqual(constants.Sas.Protocol, sasQueryParameters.Protocol);
Assert.AreEqual(constants.Sas.StartTime, sasQueryParameters.StartsOn);
Assert.AreEqual(constants.Sas.ExpiryTime, sasQueryParameters.ExpiresOn);
Assert.AreEqual(constants.Sas.IPRange, sasQueryParameters.IPRange);
Assert.AreEqual(constants.Sas.Identifier, sasQueryParameters.Identifier);
Assert.AreEqual(Constants.Sas.Resource.File, sasQueryParameters.Resource);
Assert.AreEqual(Permissions, sasQueryParameters.Permissions);
Assert.AreEqual(signature, sasQueryParameters.Signature);
AssertResponseHeaders(constants, sasQueryParameters);
}
[RecordedTest]
public void FileSasBuilder_NullSharedKeyCredentialTest()
{
// Arrange
var constants = TestConstants.Create(this);
var shareName = GetNewShareName();
var filePath = GetNewDirectoryName();
ShareSasBuilder fileSasBuilder = BuildFileSasBuilder(includeFilePath: true, constants, shareName, filePath);
// Act
Assert.Throws<ArgumentNullException>(() => fileSasBuilder.ToSasQueryParameters(null), "sharedKeyCredential");
}
[RecordedTest]
public void FileSasBuilder_IdentifierTest()
{
// Arrange
TestConstants constants = TestConstants.Create(this);
string shareName = GetNewShareName();
string resource = "s";
ShareSasBuilder sasBuilder = new ShareSasBuilder
{
Identifier = constants.Sas.Identifier,
ShareName = shareName,
Resource = resource,
Protocol = SasProtocol.Https,
};
// Act
SasQueryParameters sasQueryParameters = sasBuilder.ToSasQueryParameters(constants.Sas.SharedKeyCredential);
// Assert
Assert.AreEqual(constants.Sas.Identifier, sasQueryParameters.Identifier);
Assert.AreEqual(resource, sasQueryParameters.Resource);
Assert.AreEqual(SasProtocol.Https, sasQueryParameters.Protocol);
Assert.AreEqual(SasQueryParametersInternals.DefaultSasVersionInternal, sasQueryParameters.Version);
}
[RecordedTest]
[TestCase("FTPUCALXDWR")]
[TestCase("rwdxlacuptf")]
public async Task AccountPermissionsRawPermissions(string permissionsString)
{
// Arrange
await using DisposingShare test = await GetTestShareAsync();
AccountSasBuilder accountSasBuilder = new AccountSasBuilder
{
StartsOn = Recording.UtcNow.AddHours(-1),
ExpiresOn = Recording.UtcNow.AddHours(1),
Services = AccountSasServices.Files,
ResourceTypes = AccountSasResourceTypes.All
};
accountSasBuilder.SetPermissions(permissionsString);
StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(TestConfigDefault.AccountName, TestConfigDefault.AccountKey);
Uri uri = new Uri($"{test.Share.Uri}?{accountSasBuilder.ToSasQueryParameters(sharedKeyCredential)}");
ShareClient sasShareClient = new ShareClient(uri, GetOptions());
// Act
await sasShareClient.GetPropertiesAsync();
}
[RecordedTest]
public async Task AccountPermissionsRawPermissions_InvalidPermission()
{
// Arrange
await using DisposingShare test = await GetTestShareAsync();
AccountSasBuilder accountSasBuilder = new AccountSasBuilder
{
StartsOn = Recording.UtcNow.AddHours(-1),
ExpiresOn = Recording.UtcNow.AddHours(1),
Services = AccountSasServices.Blobs,
ResourceTypes = AccountSasResourceTypes.All
};
// Act
TestHelper.AssertExpectedException(
() => accountSasBuilder.SetPermissions("werteyfg"),
new ArgumentException("e is not a valid SAS permission"));
}
[RecordedTest]
[TestCase("LDWCR")]
[TestCase("rcwdl")]
public async Task SharePermissionsRawPermissions(string permissionsString)
{
// Arrange
await using DisposingShare test = await GetTestShareAsync();
ShareSasBuilder blobSasBuilder = new ShareSasBuilder
{
StartsOn = Recording.UtcNow.AddHours(-1),
ExpiresOn = Recording.UtcNow.AddHours(1),
ShareName = test.Share.Name
};
blobSasBuilder.SetPermissions(
rawPermissions: permissionsString,
normalize: true);
StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(TestConfigDefault.AccountName, TestConfigDefault.AccountKey);
ShareUriBuilder blobUriBuilder = new ShareUriBuilder(test.Share.Uri)
{
Sas = blobSasBuilder.ToSasQueryParameters(sharedKeyCredential)
};
ShareClient sasShareClient = new ShareClient(blobUriBuilder.ToUri(), GetOptions());
// Act
await sasShareClient.GetRootDirectoryClient().GetPropertiesAsync();
}
[RecordedTest]
public async Task SharePermissionsRawPermissions_Invalid()
{
// Arrange
await using DisposingShare test = await GetTestShareAsync();
ShareSasBuilder blobSasBuilder = new ShareSasBuilder
{
StartsOn = Recording.UtcNow.AddHours(-1),
ExpiresOn = Recording.UtcNow.AddHours(1),
ShareName = test.Share.Name
};
// Act
TestHelper.AssertExpectedException(
() => blobSasBuilder.SetPermissions(
rawPermissions: "ptsdfsd",
normalize: true),
new ArgumentException("s is not a valid SAS permission"));
}
[RecordedTest]
public void ShareUriBuilder_LocalDockerUrl_PortTest()
{
// Arrange
// BlobEndpoint from https://docs.microsoft.com/en-us/azure/storage/common/storage-use-emulator#connect-to-the-emulator-account-using-the-well-known-account-name-and-key
var uriString = "http://docker_container:10000/devstoreaccount1/sharename";
var originalUri = new UriBuilder(uriString);
// Act
var fileUriBuilder = new ShareUriBuilder(originalUri.Uri);
Uri newUri = fileUriBuilder.ToUri();
// Assert
Assert.AreEqual("http", fileUriBuilder.Scheme);
Assert.AreEqual("docker_container", fileUriBuilder.Host);
Assert.AreEqual("devstoreaccount1", fileUriBuilder.AccountName);
Assert.AreEqual("sharename", fileUriBuilder.ShareName);
Assert.AreEqual("", fileUriBuilder.DirectoryOrFilePath);
Assert.AreEqual("", fileUriBuilder.Snapshot);
Assert.IsNull(fileUriBuilder.Sas);
Assert.AreEqual("", fileUriBuilder.Query);
Assert.AreEqual(10000, fileUriBuilder.Port);
Assert.AreEqual(originalUri, newUri);
}
[RecordedTest]
public void ShareUriBuilder_CustomUri_AccountShareFileTest()
{
// Arrange
var uriString = "https://www.mycustomname.com/sharename/filename";
var originalUri = new UriBuilder(uriString);
// Act
var fileUriBuilder = new ShareUriBuilder(originalUri.Uri);
Uri newUri = fileUriBuilder.ToUri();
// Assert
Assert.AreEqual("https", fileUriBuilder.Scheme);
Assert.AreEqual("www.mycustomname.com", fileUriBuilder.Host);
Assert.AreEqual(String.Empty, fileUriBuilder.AccountName);
Assert.AreEqual("sharename", fileUriBuilder.ShareName);
Assert.AreEqual("filename", fileUriBuilder.DirectoryOrFilePath);
Assert.AreEqual("", fileUriBuilder.Snapshot);
Assert.IsNull(fileUriBuilder.Sas);
Assert.AreEqual("", fileUriBuilder.Query);
Assert.AreEqual(443, fileUriBuilder.Port);
Assert.AreEqual(originalUri, newUri);
}
private ShareSasBuilder BuildFileSasBuilder(bool includeFilePath, TestConstants constants, string shareName, string filePath)
{
var fileSasBuilder = new ShareSasBuilder
{
Version = null,
Protocol = constants.Sas.Protocol,
StartsOn = constants.Sas.StartTime,
ExpiresOn = constants.Sas.ExpiryTime,
IPRange = constants.Sas.IPRange,
Identifier = constants.Sas.Identifier,
ShareName = shareName,
FilePath = "",
CacheControl = constants.Sas.CacheControl,
ContentDisposition = constants.Sas.ContentDisposition,
ContentEncoding = constants.Sas.ContentEncoding,
ContentLanguage = constants.Sas.ContentLanguage,
ContentType = constants.Sas.ContentType
};
fileSasBuilder.SetPermissions(ShareFileSasPermissions.All);
if (includeFilePath)
{
fileSasBuilder.FilePath = filePath;
}
return fileSasBuilder;
}
private string BuildSignature(bool includeFilePath, TestConstants constants, string shareName, string filePath)
{
var canonicalName = "/file/" + constants.Sas.Account + "/" + shareName;
if (includeFilePath)
{
canonicalName += "/" + filePath;
}
var stringToSign = string.Join("\n",
Permissions,
SasExtensions.FormatTimesForSasSigning(constants.Sas.StartTime),
SasExtensions.FormatTimesForSasSigning(constants.Sas.ExpiryTime),
canonicalName,
constants.Sas.Identifier,
constants.Sas.IPRange.ToString(),
SasExtensions.ToProtocolString(constants.Sas.Protocol),
SasQueryParametersInternals.DefaultSasVersionInternal,
constants.Sas.CacheControl,
constants.Sas.ContentDisposition,
constants.Sas.ContentEncoding,
constants.Sas.ContentLanguage,
constants.Sas.ContentType);
return StorageSharedKeyCredentialInternals.ComputeSasSignature(constants.Sas.SharedKeyCredential, stringToSign);
}
}
}
| 41.755932 | 181 | 0.628349 | [
"MIT"
] | AME-Redmond/azure-sdk-for-net | sdk/storage/Azure.Storage.Files.Shares/tests/FileSasBuilderTests.cs | 12,320 | C# |
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TwitterBook2.Services
{
public class ResponseCacheService : IResponseCacheService
{
private readonly IDistributedCache _distributedCache;
public ResponseCacheService(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
public async Task CacheResponseAsync(string cacheKey, object response, TimeSpan timeToLive)
{
if (response == null)
return;
var serializedResponse = JsonConvert.SerializeObject(response);
await _distributedCache.SetStringAsync(cacheKey, serializedResponse, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = timeToLive });
}
public async Task<string> GetCachedResponseAsync(string cacheKey)
{
var cachedResponse = await _distributedCache.GetStringAsync(cacheKey);
return string.IsNullOrEmpty(cachedResponse) ? null : cachedResponse;
}
}
}
| 32.416667 | 164 | 0.707798 | [
"MIT"
] | gitcseme/rest-api | RandD/TwitterBook2/Services/ResponseCacheService.cs | 1,169 | C# |
using System.Collections.Generic;
using System.Linq;
using InfoNovitas.LoginSample.Repositories.DatabaseModel;
namespace InfoNovitas.LoginSample.Repositories.Users
{
public class UserRepository:IUserRepository
{
public List<UserInfo> FindAll()
{
using (var context = new IdentityExDbEntities())
{
return context.UserInfoes.ToList();
}
}
public UserInfo FindBy(int key)
{
using (var context = new IdentityExDbEntities())
{
return context.UserInfoes.FirstOrDefault(user => user.Id == key);
}
}
#region Not implemented
public int Add(UserInfo item)
{
throw new System.NotImplementedException();
}
public bool Delete(UserInfo item)
{
throw new System.NotImplementedException();
}
public UserInfo Save(UserInfo item)
{
throw new System.NotImplementedException();
}
#endregion
}
}
| 23.8 | 81 | 0.571429 | [
"MIT"
] | dadii/InfoNovitasKnjiznica | InfoNovitas.LoginSample.Repositories/Users/UserRepository.cs | 1,073 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace Newtonsoft.JsonV4.Serialization
{
/// <summary>
/// Represents a trace writer that writes to memory. When the trace message limit is
/// reached then old trace messages will be removed as new messages are added.
/// </summary>
public class MemoryTraceWriter : ITraceWriter
{
private readonly Queue<string> _traceMessages;
/// <summary>
/// Gets the <see cref="TraceLevel"/> that will be used to filter the trace messages passed to the writer.
/// For example a filter level of <code>Info</code> will exclude <code>Verbose</code> messages and include <code>Info</code>,
/// <code>Warning</code> and <code>Error</code> messages.
/// </summary>
/// <value>
/// The <see cref="TraceLevel"/> that will be used to filter the trace messages passed to the writer.
/// </value>
public TraceLevel LevelFilter { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MemoryTraceWriter"/> class.
/// </summary>
public MemoryTraceWriter()
{
LevelFilter = TraceLevel.Verbose;
_traceMessages = new Queue<string>();
}
/// <summary>
/// Writes the specified trace level, message and optional exception.
/// </summary>
/// <param name="level">The <see cref="TraceLevel"/> at which to write this trace.</param>
/// <param name="message">The trace message.</param>
/// <param name="ex">The trace exception. This parameter is optional.</param>
public void Trace(TraceLevel level, string message, Exception ex)
{
string traceMessage = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff", CultureInfo.InvariantCulture) + " " + level.ToString("g") + " " + message;
if (_traceMessages.Count >= 1000)
_traceMessages.Dequeue();
_traceMessages.Enqueue(traceMessage);
}
/// <summary>
/// Returns an enumeration of the most recent trace messages.
/// </summary>
/// <returns>An enumeration of the most recent trace messages.</returns>
public IEnumerable<string> GetTraceMessages()
{
return _traceMessages;
}
/// <summary>
/// Returns a <see cref="String"/> of the most recent trace messages.
/// </summary>
/// <returns>
/// A <see cref="String"/> of the most recent trace messages.
/// </returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (string traceMessage in _traceMessages)
{
if (sb.Length > 0)
sb.AppendLine();
sb.Append(traceMessage);
}
return sb.ToString();
}
}
} | 37.160494 | 169 | 0.586379 | [
"MIT"
] | woodp/Newtonsoft.Json | Src/Newtonsoft.Json/Serialization/MemoryTraceWriter.cs | 3,012 | C# |
using System;
namespace UnityEngine.Rendering.Universal.Internal
{
/// <summary>
/// Calculate min and max depth per screen tile for tiled-based deferred shading.
/// </summary>
internal class TileDepthRangePass : ScriptableRenderPass
{
DeferredLights m_DeferredLights;
int m_PassIndex = 0;
public TileDepthRangePass(RenderPassEvent evt, DeferredLights deferredLights, int passIndex)
{
base.profilingSampler = new ProfilingSampler(nameof(TileDepthRangePass));
base.renderPassEvent = evt;
m_DeferredLights = deferredLights;
m_PassIndex = passIndex;
}
public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
{
RenderTargetHandle outputTex;
RenderTextureDescriptor desc;
if (m_PassIndex == 0 && m_DeferredLights.HasTileDepthRangeExtraPass())
{
int alignment = 1 << DeferredConfig.kTileDepthInfoIntermediateLevel;
int depthInfoWidth = (m_DeferredLights.RenderWidth + alignment - 1) >> DeferredConfig.kTileDepthInfoIntermediateLevel;
int depthInfoHeight = (m_DeferredLights.RenderHeight + alignment - 1) >> DeferredConfig.kTileDepthInfoIntermediateLevel;
outputTex = m_DeferredLights.DepthInfoTexture;
desc = new RenderTextureDescriptor(depthInfoWidth, depthInfoHeight, UnityEngine.Experimental.Rendering.GraphicsFormat.R32_UInt, 0);
}
else
{
int tileDepthRangeWidth = m_DeferredLights.GetTiler(0).TileXCount;
int tileDepthRangeHeight = m_DeferredLights.GetTiler(0).TileYCount;
outputTex = m_DeferredLights.TileDepthInfoTexture;
desc = new RenderTextureDescriptor(tileDepthRangeWidth, tileDepthRangeHeight, UnityEngine.Experimental.Rendering.GraphicsFormat.R32_UInt, 0);
}
cmd.GetTemporaryRT(outputTex.id, desc, FilterMode.Point);
base.ConfigureTarget(outputTex.Identifier());
}
/// <inheritdoc/>
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
if (m_PassIndex == 0)
m_DeferredLights.ExecuteTileDepthInfoPass(context, ref renderingData);
else
m_DeferredLights.ExecuteDownsampleBitmaskPass(context, ref renderingData);
}
/// <inheritdoc/>
public override void OnCameraCleanup(CommandBuffer cmd)
{
if (cmd == null)
throw new ArgumentNullException("cmd");
cmd.ReleaseTemporaryRT(m_DeferredLights.TileDepthInfoTexture.id);
m_DeferredLights.TileDepthInfoTexture = RenderTargetHandle.CameraTarget;
}
}
}
| 42.776119 | 157 | 0.662945 | [
"Apache-2.0"
] | AJTheEnder/E428 | Projet/E428/Library/PackageCache/com.unity.render-pipelines.universal@10.4.0/Runtime/Passes/TileDepthRangePass.cs | 2,866 | C# |
using SharpenedMinecraft.Types.Enums;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharpenedMinecraft.Packets
{
public class ServerDifficultyPacket : MinecraftPacket
{
public override State State => State.Play;
public override bool Clientbound => true;
public override int Id => 0x0D;
public Difficulty Difficulty;
public ServerDifficultyPacket(MinecraftClient client)
: base(client)
{
}
public override void Initialize(int length, Stream stream)
{
base.Initialize(length, stream);
Difficulty = World.Difficulty;
}
public override void WritePacket()
{
Write((Byte)Difficulty);
}
}
}
| 23.694444 | 67 | 0.638921 | [
"MIT"
] | SharpenedMinecraft/SM1 | Main/Packets/ServerDifficultyPacket.cs | 855 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using TygaSoft.IDAL;
using TygaSoft.Model;
using TygaSoft.DBUtility;
namespace TygaSoft.SqlServerDAL
{
public partial class OrderReceiptRecord : IOrderReceiptRecord
{
#region IOrderReceiptRecord Member
public int Insert(OrderReceiptRecordInfo model)
{
StringBuilder sb = new StringBuilder(300);
sb.Append(@"insert into OrderReceiptRecord (OrderId,UserId,ProductId,PackageId,StockLocationId,Unit,Qty,LPN,LastUpdatedDate)
values
(@OrderId,@UserId,@ProductId,@PackageId,@StockLocationId,@Unit,@Qty,@LPN,@LastUpdatedDate)
");
SqlParameter[] parms = {
new SqlParameter("@OrderId",SqlDbType.UniqueIdentifier),
new SqlParameter("@UserId",SqlDbType.UniqueIdentifier),
new SqlParameter("@ProductId",SqlDbType.UniqueIdentifier),
new SqlParameter("@PackageId",SqlDbType.UniqueIdentifier),
new SqlParameter("@StockLocationId",SqlDbType.UniqueIdentifier),
new SqlParameter("@Unit",SqlDbType.NVarChar,10),
new SqlParameter("@Qty",SqlDbType.Float),
new SqlParameter("@LPN",SqlDbType.VarChar,36),
new SqlParameter("@LastUpdatedDate",SqlDbType.DateTime)
};
parms[0].Value = model.OrderId;
parms[1].Value = model.UserId;
parms[2].Value = model.ProductId;
parms[3].Value = model.PackageId;
parms[4].Value = model.StockLocationId;
parms[5].Value = model.Unit;
parms[6].Value = model.Qty;
parms[7].Value = model.LPN;
parms[8].Value = model.LastUpdatedDate;
return SqlHelper.ExecuteNonQuery(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), parms);
}
public int InsertByOutput(OrderReceiptRecordInfo model)
{
StringBuilder sb = new StringBuilder(300);
sb.Append(@"insert into OrderReceiptRecord (Id,OrderId,UserId,ProductId,PackageId,StockLocationId,Unit,Qty,LPN,LastUpdatedDate)
values
(@Id,@OrderId,@UserId,@ProductId,@PackageId,@StockLocationId,@Unit,@Qty,@LPN,@LastUpdatedDate)
");
SqlParameter[] parms = {
new SqlParameter("@Id",SqlDbType.UniqueIdentifier),
new SqlParameter("@OrderId",SqlDbType.UniqueIdentifier),
new SqlParameter("@UserId",SqlDbType.UniqueIdentifier),
new SqlParameter("@ProductId",SqlDbType.UniqueIdentifier),
new SqlParameter("@PackageId",SqlDbType.UniqueIdentifier),
new SqlParameter("@StockLocationId",SqlDbType.UniqueIdentifier),
new SqlParameter("@Unit",SqlDbType.NVarChar,10),
new SqlParameter("@Qty",SqlDbType.Float),
new SqlParameter("@LPN",SqlDbType.VarChar,36),
new SqlParameter("@LastUpdatedDate",SqlDbType.DateTime)
};
parms[0].Value = model.Id;
parms[1].Value = model.OrderId;
parms[2].Value = model.UserId;
parms[3].Value = model.ProductId;
parms[4].Value = model.PackageId;
parms[5].Value = model.StockLocationId;
parms[6].Value = model.Unit;
parms[7].Value = model.Qty;
parms[8].Value = model.LPN;
parms[9].Value = model.LastUpdatedDate;
return SqlHelper.ExecuteNonQuery(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), parms);
}
public int Update(OrderReceiptRecordInfo model)
{
StringBuilder sb = new StringBuilder(500);
sb.Append(@"update OrderReceiptRecord set OrderId = @OrderId,UserId = @UserId,ProductId = @ProductId,PackageId = @PackageId,StockLocationId = @StockLocationId,Unit = @Unit,Qty = @Qty,LPN = @LPN,LastUpdatedDate = @LastUpdatedDate
where Id = @Id
");
SqlParameter[] parms = {
new SqlParameter("@Id",SqlDbType.UniqueIdentifier),
new SqlParameter("@OrderId",SqlDbType.UniqueIdentifier),
new SqlParameter("@UserId",SqlDbType.UniqueIdentifier),
new SqlParameter("@ProductId",SqlDbType.UniqueIdentifier),
new SqlParameter("@PackageId",SqlDbType.UniqueIdentifier),
new SqlParameter("@StockLocationId",SqlDbType.UniqueIdentifier),
new SqlParameter("@Unit",SqlDbType.NVarChar,10),
new SqlParameter("@Qty",SqlDbType.Float),
new SqlParameter("@LPN",SqlDbType.VarChar,36),
new SqlParameter("@LastUpdatedDate",SqlDbType.DateTime)
};
parms[0].Value = model.Id;
parms[1].Value = model.OrderId;
parms[2].Value = model.UserId;
parms[3].Value = model.ProductId;
parms[4].Value = model.PackageId;
parms[5].Value = model.StockLocationId;
parms[6].Value = model.Unit;
parms[7].Value = model.Qty;
parms[8].Value = model.LPN;
parms[9].Value = model.LastUpdatedDate;
return SqlHelper.ExecuteNonQuery(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), parms);
}
public int Delete(Guid id)
{
StringBuilder sb = new StringBuilder(250);
sb.Append("delete from OrderReceiptRecord where Id = @Id ");
SqlParameter[] parms = {
new SqlParameter("@Id",SqlDbType.UniqueIdentifier)
};
parms[0].Value = id;
return SqlHelper.ExecuteNonQuery(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), parms);
}
public bool DeleteBatch(IList<object> list)
{
StringBuilder sb = new StringBuilder(500);
ParamsHelper parms = new ParamsHelper();
int n = 0;
foreach (string item in list)
{
n++;
sb.Append(@"delete from OrderReceiptRecord where Id = @Id" + n + " ;");
SqlParameter parm = new SqlParameter("@Id" + n + "", SqlDbType.UniqueIdentifier);
parm.Value = Guid.Parse(item);
parms.Add(parm);
}
return SqlHelper.ExecuteNonQuery(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), parms != null ? parms.ToArray() : null) > 0;
}
public OrderReceiptRecordInfo GetModel(Guid id)
{
OrderReceiptRecordInfo model = null;
StringBuilder sb = new StringBuilder(300);
sb.Append(@"select top 1 Id,OrderId,UserId,ProductId,PackageId,StockLocationId,Unit,Qty,LPN,LastUpdatedDate
from OrderReceiptRecord
where Id = @Id ");
SqlParameter[] parms = {
new SqlParameter("@Id",SqlDbType.UniqueIdentifier)
};
parms[0].Value = id;
using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), parms))
{
if (reader != null)
{
if (reader.Read())
{
model = new OrderReceiptRecordInfo();
model.Id = reader.GetGuid(0);
model.OrderId = reader.GetGuid(1);
model.UserId = reader.GetGuid(2);
model.ProductId = reader.GetGuid(3);
model.PackageId = reader.GetGuid(4);
model.StockLocationId = reader.GetGuid(5);
model.Unit = reader.GetString(6);
model.Qty = reader.GetDouble(7);
model.LPN = reader.GetString(8);
model.LastUpdatedDate = reader.GetDateTime(9);
}
}
}
return model;
}
public IList<OrderReceiptRecordInfo> GetList(int pageIndex, int pageSize, out int totalRecords, string sqlWhere, params SqlParameter[] cmdParms)
{
StringBuilder sb = new StringBuilder(500);
sb.Append(@"select count(*) from OrderReceiptRecord ");
if (!string.IsNullOrEmpty(sqlWhere)) sb.AppendFormat(" where 1=1 {0} ", sqlWhere);
totalRecords = (int)SqlHelper.ExecuteScalar(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), cmdParms);
if (totalRecords == 0) return new List<OrderReceiptRecordInfo>();
sb.Clear();
int startIndex = (pageIndex - 1) * pageSize + 1;
int endIndex = pageIndex * pageSize;
sb.Append(@"select * from(select row_number() over(order by LastUpdatedDate desc) as RowNumber,
Id,OrderId,UserId,ProductId,PackageId,StockLocationId,Unit,Qty,LPN,LastUpdatedDate
from OrderReceiptRecord ");
if (!string.IsNullOrEmpty(sqlWhere)) sb.AppendFormat(" where 1=1 {0} ", sqlWhere);
sb.AppendFormat(@")as objTable where RowNumber between {0} and {1} ", startIndex, endIndex);
IList<OrderReceiptRecordInfo> list = new List<OrderReceiptRecordInfo>();
using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), cmdParms))
{
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
OrderReceiptRecordInfo model = new OrderReceiptRecordInfo();
model.Id = reader.GetGuid(1);
model.OrderId = reader.GetGuid(2);
model.UserId = reader.GetGuid(3);
model.ProductId = reader.GetGuid(4);
model.PackageId = reader.GetGuid(5);
model.StockLocationId = reader.GetGuid(6);
model.Unit = reader.GetString(7);
model.Qty = reader.GetDouble(8);
model.LPN = reader.GetString(9);
model.LastUpdatedDate = reader.GetDateTime(10);
list.Add(model);
}
}
}
return list;
}
public IList<OrderReceiptRecordInfo> GetList(int pageIndex, int pageSize, string sqlWhere, params SqlParameter[] cmdParms)
{
StringBuilder sb = new StringBuilder(500);
int startIndex = (pageIndex - 1) * pageSize + 1;
int endIndex = pageIndex * pageSize;
sb.Append(@"select * from(select row_number() over(order by LastUpdatedDate desc) as RowNumber,
Id,OrderId,UserId,ProductId,PackageId,StockLocationId,Unit,Qty,LPN,LastUpdatedDate
from OrderReceiptRecord ");
if (!string.IsNullOrEmpty(sqlWhere)) sb.AppendFormat(" where 1=1 {0} ", sqlWhere);
sb.AppendFormat(@")as objTable where RowNumber between {0} and {1} ", startIndex, endIndex);
IList<OrderReceiptRecordInfo> list = new List<OrderReceiptRecordInfo>();
using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), cmdParms))
{
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
OrderReceiptRecordInfo model = new OrderReceiptRecordInfo();
model.Id = reader.GetGuid(1);
model.OrderId = reader.GetGuid(2);
model.UserId = reader.GetGuid(3);
model.ProductId = reader.GetGuid(4);
model.PackageId = reader.GetGuid(5);
model.StockLocationId = reader.GetGuid(6);
model.Unit = reader.GetString(7);
model.Qty = reader.GetDouble(8);
model.LPN = reader.GetString(9);
model.LastUpdatedDate = reader.GetDateTime(10);
list.Add(model);
}
}
}
return list;
}
public IList<OrderReceiptRecordInfo> GetList(string sqlWhere, params SqlParameter[] cmdParms)
{
StringBuilder sb = new StringBuilder(500);
sb.Append(@"select Id,OrderId,UserId,ProductId,PackageId,StockLocationId,Unit,Qty,LPN,LastUpdatedDate
from OrderReceiptRecord ");
if (!string.IsNullOrEmpty(sqlWhere)) sb.AppendFormat(" where 1=1 {0} ", sqlWhere);
sb.Append("order by LastUpdatedDate desc ");
IList<OrderReceiptRecordInfo> list = new List<OrderReceiptRecordInfo>();
using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString(), cmdParms))
{
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
OrderReceiptRecordInfo model = new OrderReceiptRecordInfo();
model.Id = reader.GetGuid(0);
model.OrderId = reader.GetGuid(1);
model.UserId = reader.GetGuid(2);
model.ProductId = reader.GetGuid(3);
model.PackageId = reader.GetGuid(4);
model.StockLocationId = reader.GetGuid(5);
model.Unit = reader.GetString(6);
model.Qty = reader.GetDouble(7);
model.LPN = reader.GetString(8);
model.LastUpdatedDate = reader.GetDateTime(9);
list.Add(model);
}
}
}
return list;
}
public IList<OrderReceiptRecordInfo> GetList()
{
StringBuilder sb = new StringBuilder(300);
sb.Append(@"select Id,OrderId,UserId,ProductId,PackageId,StockLocationId,Unit,Qty,LPN,LastUpdatedDate
from OrderReceiptRecord
order by LastUpdatedDate desc ");
IList<OrderReceiptRecordInfo> list = new List<OrderReceiptRecordInfo>();
using (SqlDataReader reader = SqlHelper.ExecuteReader(SqlHelper.WmsDbConnString, CommandType.Text, sb.ToString()))
{
if (reader != null && reader.HasRows)
{
while (reader.Read())
{
OrderReceiptRecordInfo model = new OrderReceiptRecordInfo();
model.Id = reader.GetGuid(0);
model.OrderId = reader.GetGuid(1);
model.UserId = reader.GetGuid(2);
model.ProductId = reader.GetGuid(3);
model.PackageId = reader.GetGuid(4);
model.StockLocationId = reader.GetGuid(5);
model.Unit = reader.GetString(6);
model.Qty = reader.GetDouble(7);
model.LPN = reader.GetString(8);
model.LastUpdatedDate = reader.GetDateTime(9);
list.Add(model);
}
}
}
return list;
}
#endregion
}
}
| 49.043732 | 242 | 0.516883 | [
"MIT"
] | ranran1997/Wms | Src/TygaSoft/SqlServerDAL/AutoCode/OrderReceiptRecord.cs | 16,824 | C# |
using System;
using System.Linq;
using SIL.Machine.DataStructures;
using SIL.Machine.FeatureModel;
using SIL.ObjectModel;
namespace SIL.Machine.Annotations
{
public class Annotation<TOffset> : BidirListNode<Annotation<TOffset>>, IBidirTreeNode<Annotation<TOffset>>, ICloneable<Annotation<TOffset>>, IComparable<Annotation<TOffset>>, IComparable, IFreezable, IValueEquatable<Annotation<TOffset>>
{
private AnnotationList<TOffset> _children;
private int _hashCode;
private FeatureStruct _fs;
private bool _optional;
private object _data;
public Annotation(Range<TOffset> range, FeatureStruct fs)
{
Range = range;
FeatureStruct = fs;
ListID = -1;
Root = this;
}
internal Annotation(Range<TOffset> range)
{
Range = range;
ListID = -1;
Root = this;
}
protected Annotation(Annotation<TOffset> ann)
: this(ann.Range, ann.FeatureStruct.Clone())
{
Optional = ann.Optional;
_data = ann._data;
if (ann._children != null && ann._children.Count > 0)
Children.AddRange(ann.Children.Select(node => node.Clone()));
}
public object Data
{
get { return _data; }
set
{
CheckFrozen();
_data = value;
}
}
public Annotation<TOffset> Parent { get; private set; }
public int Depth { get; private set; }
public bool IsLeaf
{
get { return _children == null || _children.Count == 0; }
}
public Annotation<TOffset> Root { get; private set; }
public AnnotationList<TOffset> Children
{
get
{
if (_children == null)
_children = new AnnotationList<TOffset>(this);
return _children;
}
}
IBidirList<Annotation<TOffset>> IBidirTreeNode<Annotation<TOffset>>.Children
{
get { return Children; }
}
protected internal override void Clear()
{
base.Clear();
Parent = null;
Depth = 0;
Root = this;
}
protected internal override void Init(BidirList<Annotation<TOffset>> list, int levels)
{
base.Init(list, levels);
Parent = ((AnnotationList<TOffset>) list).Parent;
if (Parent != null)
{
Depth = Parent.Depth + 1;
Root = Parent.Root;
}
}
public Range<TOffset> Range { get; internal set; }
public FeatureStruct FeatureStruct
{
get { return _fs; }
set
{
CheckFrozen();
_fs = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this annotation is optional.
/// </summary>
/// <value>
/// <c>true</c> if this annotation is optional, otherwise <c>false</c>.
/// </value>
public bool Optional
{
get { return _optional; }
set
{
CheckFrozen();
_optional = value;
}
}
internal int ListID { get; set; }
public bool Remove(bool preserveChildren)
{
if (List == null)
return false;
return ((AnnotationList<TOffset>) List).Remove(this, preserveChildren);
}
public Annotation<TOffset> Clone()
{
return new Annotation<TOffset>(this);
}
public int CompareTo(Annotation<TOffset> other)
{
if (this == other)
return 0;
if (List != null)
{
if (List.Begin == this)
return -1;
if (List.Begin == other)
return 1;
if (List.End == this)
return 1;
if (List.End == other)
return -1;
}
int res = Range.CompareTo(other.Range);
if (res != 0)
return res;
if (ListID == -1 || other.ListID == -1)
return 0;
return ListID.CompareTo(other.ListID);
}
int IComparable.CompareTo(object obj)
{
return CompareTo(obj as Annotation<TOffset>);
}
public bool IsFrozen { get; private set; }
public void Freeze()
{
if (IsFrozen)
return;
IsFrozen = true;
_fs.Freeze();
if (_children != null)
_children.Freeze();
_hashCode = 23;
_hashCode = _hashCode * 31 + _fs.GetFrozenHashCode();
_hashCode = _hashCode * 31 + (_children == null ? 0 : _children.GetFrozenHashCode());
_hashCode = _hashCode * 31 + _optional.GetHashCode();
_hashCode = _hashCode * 31 + Range.GetHashCode();
}
public bool ValueEquals(Annotation<TOffset> other)
{
if (other == null)
return false;
if (IsLeaf != other.IsLeaf)
return false;
if (!IsLeaf && !_children.ValueEquals(other._children))
return false;
return _fs.ValueEquals(other._fs) && _optional == other._optional && Range == other.Range;
}
public int GetFrozenHashCode()
{
if (!IsFrozen)
{
throw new InvalidOperationException(
"The annotation does not have a valid hash code, because it is mutable.");
}
return _hashCode;
}
private void CheckFrozen()
{
if (IsFrozen)
throw new InvalidOperationException("The annotation is immutable.");
}
public override string ToString()
{
return string.Format("({0} {1})", Range, FeatureStruct);
}
}
}
| 21.0625 | 237 | 0.646248 | [
"MIT"
] | russellmorley/machine | src/SIL.Machine/Annotations/Annotation.cs | 4,718 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Myproject.Web")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Myproject.Web")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("855f1908-32cc-4fed-9245-03862bec127a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.324324 | 84 | 0.751763 | [
"MIT"
] | ahmetkursatesim/ASPNETProject | src/Myproject.Web/Properties/AssemblyInfo.cs | 1,421 | C# |
//---------------------------------------------------------------------
// <copyright file="ColumnInfo.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are covered by the
// Common Public License 1.0 (http://opensource.org/licenses/cpl1.0.php)
// which can be found in the file CPL.TXT at the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by
// the terms of this license.
//
// You must not remove this notice, or any other, from this software.
// </copyright>
// <summary>
// Part of the Deployment Tools Foundation project.
// </summary>
//---------------------------------------------------------------------
namespace CoApp.Packaging.Service.dtf.WindowsInstaller
{
using System;
using System.IO;
using System.Text;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
/// <summary>
/// Defines a single column of a table in an installer database.
/// </summary>
/// <remarks>Once created, a ColumnInfo object is immutable.</remarks>
internal class ColumnInfo
{
private string name;
private Type type;
private int size;
private bool isRequired;
private bool isTemporary;
private bool isLocalizable;
/// <summary>
/// Creates a new ColumnInfo object from a column definition.
/// </summary>
/// <param name="name">name of the column</param>
/// <param name="columnDefinition">column definition string</param>
/// <seealso cref="ColumnDefinitionString"/>
internal ColumnInfo(string name, string columnDefinition)
: this(name, typeof(String), 0, false, false, false)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (columnDefinition == null)
{
throw new ArgumentNullException("columnDefinition");
}
switch (Char.ToLower(columnDefinition[0], CultureInfo.InvariantCulture))
{
case 'i': this.type = typeof(Int32);
break;
case 'j': this.type = typeof(Int32); this.isTemporary = true;
break;
case 'g': this.type = typeof(String); this.isTemporary = true;
break;
case 'l': this.type = typeof(String); this.isLocalizable = true;
break;
case 's': this.type = typeof(String);
break;
case 'v': this.type = typeof(Stream);
break;
default: throw new InstallerException();
}
this.isRequired = Char.IsLower(columnDefinition[0]);
this.size = Int32.Parse(
columnDefinition.Substring(1),
CultureInfo.InvariantCulture.NumberFormat);
if (this.type == typeof(Int32) && this.size <= 2)
{
this.type = typeof(Int16);
}
}
/// <summary>
/// Creates a new ColumnInfo object from a list of parameters.
/// </summary>
/// <param name="name">name of the column</param>
/// <param name="type">type of the column; must be one of the following:
/// Int16, Int32, String, or Stream</param>
/// <param name="size">the maximum number of characters for String columns;
/// ignored for other column types</param>
/// <param name="isRequired">true if the column is required to have a non-null value</param>
internal ColumnInfo(string name, Type type, int size, bool isRequired)
: this(name, type, size, isRequired, false, false)
{
}
/// <summary>
/// Creates a new ColumnInfo object from a list of parameters.
/// </summary>
/// <param name="name">name of the column</param>
/// <param name="type">type of the column; must be one of the following:
/// Int16, Int32, String, or Stream</param>
/// <param name="size">the maximum number of characters for String columns;
/// ignored for other column types</param>
/// <param name="isRequired">true if the column is required to have a non-null value</param>
/// <param name="isTemporary">true to if the column is only in-memory and
/// not persisted with the database</param>
/// <param name="isLocalizable">for String columns, indicates the column
/// is localizable; ignored for other column types</param>
internal ColumnInfo(string name, Type type, int size, bool isRequired, bool isTemporary, bool isLocalizable)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
if (type == typeof(Int32))
{
size = 4;
isLocalizable = false;
}
else if (type == typeof(Int16))
{
size = 2;
isLocalizable = false;
}
else if (type == typeof(String))
{
}
else if (type == typeof(Stream))
{
isLocalizable = false;
}
else
{
throw new ArgumentOutOfRangeException("type");
}
this.name = name;
this.type = type;
this.size = size;
this.isRequired = isRequired;
this.isTemporary = isTemporary;
this.isLocalizable = isLocalizable;
}
/// <summary>
/// Gets the name of the column.
/// </summary>
/// <value>name of the column</value>
internal string Name
{
get { return this.name; }
}
/// <summary>
/// Gets the type of the column as a System.Type. This is one of the following: Int16, Int32, String, or Stream
/// </summary>
/// <value>type of the column</value>
[SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
internal Type Type
{
get { return this.type; }
}
/// <summary>
/// Gets the type of the column as an integer that can be cast to a System.Data.DbType. This is one of the following: Int16, Int32, String, or Binary
/// </summary>
/// <value>equivalent DbType of the column as an integer</value>
internal int DBType
{
get
{
if (this.type == typeof(Int16)) return 10;
else if (this.type == typeof(Int32)) return 11;
else if (this.type == typeof(Stream)) return 1;
else return 16;
}
}
/// <summary>
/// Gets the size of the column.
/// </summary>
/// <value>The size of integer columns this is either 2 or 4. For string columns this is the maximum
/// recommended length of the string, or 0 for unlimited length. For stream columns, 0 is returned.</value>
internal int Size
{
get { return this.size; }
}
/// <summary>
/// Gets a value indicating whether the column must be non-null when inserting a record.
/// </summary>
/// <value>required status of the column</value>
internal bool IsRequired
{
get { return this.isRequired; }
}
/// <summary>
/// Gets a value indicating whether the column is temporary. Temporary columns are not persisted
/// when the database is saved to disk.
/// </summary>
/// <value>temporary status of the column</value>
internal bool IsTemporary
{
get { return this.isTemporary; }
}
/// <summary>
/// Gets a value indicating whether the column is a string column that is localizable.
/// </summary>
/// <value>localizable status of the column</value>
internal bool IsLocalizable
{
get { return this.isLocalizable; }
}
/// <summary>
/// Gets an SQL fragment that can be used to create this column within a CREATE TABLE statement.
/// </summary>
/// <value>SQL fragment to be used for creating the column</value>
/// <remarks><p>
/// Examples:
/// <list type="bullet">
/// <item>LONG</item>
/// <item>SHORT TEMPORARY</item>
/// <item>CHAR(0) LOCALIZABLE</item>
/// <item>CHAR(72) NOT NULL LOCALIZABLE</item>
/// <item>OBJECT</item>
/// </list>
/// </p></remarks>
internal string SqlCreateString
{
get
{
StringBuilder s = new StringBuilder();
s.AppendFormat("`{0}` ", this.name);
if (this.type == typeof(Int16)) s.Append("SHORT");
else if (this.type == typeof(Int32)) s.Append("LONG");
else if (this.type == typeof(String)) s.AppendFormat("CHAR({0})", this.size);
else s.Append("OBJECT");
if (this.isRequired) s.Append(" NOT NULL");
if (this.isTemporary) s.Append(" TEMPORARY");
if (this.isLocalizable) s.Append(" LOCALIZABLE");
return s.ToString();
}
}
/// <summary>
/// Gets a short string defining the type and size of the column.
/// </summary>
/// <value>
/// The definition string consists
/// of a single letter representing the data type followed by the width of the column (in characters
/// when applicable, bytes otherwise). A width of zero designates an unbounded width (for example,
/// long text fields and streams). An uppercase letter indicates that null values are allowed in
/// the column.
/// </value>
/// <remarks><p>
/// <list>
/// <item>s? - String, variable length (?=1-255)</item>
/// <item>s0 - String, variable length</item>
/// <item>i2 - Short integer</item>
/// <item>i4 - Long integer</item>
/// <item>v0 - Binary Stream</item>
/// <item>g? - Temporary string (?=0-255)</item>
/// <item>j? - Temporary integer (?=0,1,2,4)</item>
/// <item>l? - Localizable string, variable length (?=1-255)</item>
/// <item>l0 - Localizable string, variable length</item>
/// </list>
/// </p></remarks>
internal string ColumnDefinitionString
{
get
{
char t;
if (this.type == typeof(Int16) || this.type == typeof(Int32))
{
t = (this.isTemporary ? 'j' : 'i');
}
else if (this.type == typeof(String))
{
t = (this.isTemporary ? 'g' : this.isLocalizable ? 'l' : 's');
}
else
{
t = 'v';
}
return String.Format(
CultureInfo.InvariantCulture,
"{0}{1}",
(this.isRequired ? t : Char.ToUpper(t, CultureInfo.InvariantCulture)),
this.size);
}
}
/// <summary>
/// Gets the name of the column.
/// </summary>
/// <returns>Name of the column.</returns>
public override string ToString()
{
return this.Name;
}
}
}
| 38.883871 | 159 | 0.508711 | [
"Apache-2.0"
] | fearthecowboy/coapp | Packaging/Service/dtf/WindowsInstaller/ColumnInfo.cs | 12,054 | C# |
using System;
using System.Net;
using OneOf;
namespace FluentAssertions.Union.Tests
{
public class SwitchableType
{
private readonly OneOf<int, string> _input1;
private readonly OneOf<DateTime, string, long> _input2;
private readonly OneOf<TimeSpan, string> _input3;
private readonly OneOf<HttpStatusCode, byte> _input4;
public SwitchableType(OneOf<int, string> input1, OneOf<DateTime, string, long> input2, OneOf<TimeSpan, string> input3, OneOf<HttpStatusCode, byte> input4)
{
_input1 = input1;
_input2 = input2;
_input3 = input3;
_input4 = input4;
}
public T Match<T>(Func<int, T> matchFunc, Func<string, T> matchFunc2)
=> _input1.Match(matchFunc, matchFunc2);
public void Switch(Action<DateTime> matchFunc, Action<string> matchFunc2, Action<long> matchFunc3, Action defaultFunc)
=> _input2.Switch(matchFunc, matchFunc2, matchFunc3);
public T Match<T>(Func<TimeSpan, T> matchFunc, Func<string, T> matchFunc2, Func<T> defaultFunc)
=> _input3.Match(matchFunc, matchFunc2);
public void Switch(Action<HttpStatusCode> matchFunc, Action<byte> matchFunc2)
=> _input4.Switch(matchFunc, matchFunc2);
}
}
| 35.189189 | 162 | 0.659754 | [
"MIT"
] | Resultful/FluentAssertions.Resultful | tests/FluentAssertions.Union.Tests/SwitchableType.cs | 1,304 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the firehose-2015-08-04.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.KinesisFirehose.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.KinesisFirehose.Model.Internal.MarshallTransformations
{
/// <summary>
/// ElasticsearchBufferingHints Marshaller
/// </summary>
public class ElasticsearchBufferingHintsMarshaller : IRequestMarshaller<ElasticsearchBufferingHints, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(ElasticsearchBufferingHints requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetIntervalInSeconds())
{
context.Writer.WritePropertyName("IntervalInSeconds");
context.Writer.Write(requestObject.IntervalInSeconds);
}
if(requestObject.IsSetSizeInMBs())
{
context.Writer.WritePropertyName("SizeInMBs");
context.Writer.Write(requestObject.SizeInMBs);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static ElasticsearchBufferingHintsMarshaller Instance = new ElasticsearchBufferingHintsMarshaller();
}
} | 34.720588 | 128 | 0.687421 | [
"Apache-2.0"
] | AltairMartinez/aws-sdk-unity-net | src/Services/KinesisFirehose/Generated/Model/Internal/MarshallTransformations/ElasticsearchBufferingHintsMarshaller.cs | 2,361 | C# |
using System;
using System.Threading.Tasks;
using HotChocolate.Data.Neo4J.Execution;
using HotChocolate.Data.Sorting;
using HotChocolate.Language;
using HotChocolate.Resolvers;
using HotChocolate.Types;
namespace HotChocolate.Data.Neo4J.Sorting
{
/// <inheritdoc />
public class Neo4JSortProvider
: SortProvider<Neo4JSortVisitorContext>
{
/// <inheritdoc/>
public Neo4JSortProvider()
{
}
/// <inheritdoc/>
public Neo4JSortProvider(Action<ISortProviderDescriptor<Neo4JSortVisitorContext>> configure)
: base(configure)
{
}
/// <summary>
/// The visitor thar will traverse a incoming query and execute the sorting handlers
/// </summary>
protected virtual SortVisitor<Neo4JSortVisitorContext, Neo4JSortDefinition> Visitor { get; }
= new();
/// <inheritdoc />
public override FieldMiddleware CreateExecutor<TEntityType>(NameString argumentName)
{
return next => context => ExecuteAsync(next, context);
async ValueTask ExecuteAsync(
FieldDelegate next,
IMiddlewareContext context)
{
IInputField argument = context.Field.Arguments[argumentName];
IValueNode filter = context.ArgumentLiteral<IValueNode>(argumentName);
if (filter is not NullValueNode &&
argument.Type is ListType listType &&
listType.ElementType is NonNullType nn &&
nn.NamedType() is SortInputType sortInputType)
{
var visitorContext = new Neo4JSortVisitorContext(sortInputType);
Visitor.Visit(filter, visitorContext);
if (!visitorContext.TryCreateQuery(out Neo4JSortDefinition[]? sorts) ||
visitorContext.Errors.Count > 0)
{
context.Result = Array.Empty<TEntityType>();
foreach (IError error in visitorContext.Errors)
{
context.ReportError(error.WithPath(context.Path));
}
}
else
{
context.LocalContextData =
context.LocalContextData.SetItem("Sorting", sorts);
await next(context).ConfigureAwait(false);
if (context.Result is INeo4JExecutable executable)
{
context.Result = executable.WithSorting(sorts);
}
}
}
else
{
await next(context).ConfigureAwait(false);
}
}
}
}
}
| 34.819277 | 100 | 0.53045 | [
"MIT"
] | AccountTechnologies/hotchocolate | src/HotChocolate/Neo4J/src/Data/Sorting/Neo4JSortProvider.cs | 2,890 | C# |
/*
* Copyright 2018 Samsung Electronics Co., Ltd. All rights reserved.
*
* Licensed under the Flora License, Version 1.1 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://floralicense.org/license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Xamarin.Forms;
namespace VoiceRecorder.Utils
{
/// <summary>
/// SettingsItemTemplateSelector class.
/// Selects Data Template by SettingItemType.
/// </summary>
public class SettingsItemTemplateSelector : DataTemplateSelector
{
#region properties
/// <summary>
/// File format setting template.
/// </summary>
public DataTemplate FileFormatTemplate { get; set; }
/// <summary>
/// Recording quality setting template.
/// </summary>
public DataTemplate RecordingQualityTemplate { get; set; }
/// <summary>
/// Stereo setting template.
/// </summary>
public DataTemplate StereoTemplate { get; set; }
#endregion
#region methods
/// <summary>
/// Method that allows to select DataTemplate by item type.
/// </summary>
/// <param name="item">The item for which to return a template.</param>
/// <param name="container">An optional container object in which DataTemplateSelector
/// objects could be stored.</param>
/// <returns>Returns defined DataTemplate that is used to display item.</returns>
protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
{
if (item.GetType() != typeof(SettingsItem))
{
throw new NotSupportedException("Item type not supported");
}
var settingsItem = (SettingsItem)item;
switch (settingsItem.SettingItemType)
{
case SettingsItemType.Stereo:
return StereoTemplate;
case SettingsItemType.RecordingQuality:
return RecordingQualityTemplate;
case SettingsItemType.FileFormat:
return FileFormatTemplate;
default:
throw new ArgumentOutOfRangeException();
}
}
#endregion
}
}
| 33.175 | 95 | 0.621703 | [
"Apache-2.0"
] | AchoWang/Tizen-CSharp-Samples | Mobile/VoiceRecorder/src/VoiceRecorder/VoiceRecorder/Utils/SettingsItemTemplateSelector.cs | 2,654 | C# |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.NET.TestFramework;
using Microsoft.NET.TestFramework.Assertions;
using Microsoft.NET.TestFramework.Commands;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
using NuGet.Packaging;
using System.Xml.Linq;
using System.Runtime.CompilerServices;
using System;
using NuGet.Frameworks;
namespace Microsoft.NET.Publish.Tests
{
public class GivenThatWeWantToPublishAToolProjectWithPackagedShim : SdkTest
{
private const string _customToolCommandName = "customToolCommandName";
public GivenThatWeWantToPublishAToolProjectWithPackagedShim(ITestOutputHelper log) : base(log)
{
}
private TestAsset SetupTestAsset([CallerMemberName] string callingMethod = "")
{
TestAsset helloWorldAsset = _testAssetsManager
.CopyTestAsset("PortableTool", callingMethod)
.WithSource()
.WithProjectChanges(project =>
{
XNamespace ns = project.Root.Name.Namespace;
XElement propertyGroup = project.Root.Elements(ns + "PropertyGroup").First();
propertyGroup.Add(new XElement(ns + "PackAsToolShimRuntimeIdentifiers", "win-x64;osx.10.12-x64"));
propertyGroup.Add(new XElement(ns + "ToolCommandName", _customToolCommandName));
});
return helloWorldAsset;
}
[Fact]
public void It_contains_dependencies_shims()
{
var testAsset = SetupTestAsset();
var publishCommand = new PublishCommand(Log, testAsset.TestRoot);
publishCommand.Execute();
publishCommand.GetOutputDirectory(targetFramework: "netcoreapp2.1")
.Sub("shims")
.Sub("win-x64")
.EnumerateFiles().Should().Contain(f => f.Name == _customToolCommandName + ".exe");
}
[Fact]
public void It_contains_dependencies_shims_with_no_build()
{
var testAsset = SetupTestAsset();
var buildCommand = new BuildCommand(Log, testAsset.TestRoot);
buildCommand.Execute();
var publishCommand = new PublishCommand(Log, testAsset.TestRoot);
publishCommand.Execute("/p:NoBuild=true");
publishCommand.GetOutputDirectory(targetFramework: "netcoreapp2.1")
.Sub("shims")
.Sub("win-x64")
.EnumerateFiles().Should().Contain(f => f.Name == _customToolCommandName + ".exe");
}
}
}
| 36.246753 | 118 | 0.644214 | [
"MIT"
] | Logerfo/sdk | src/Tests/Microsoft.NET.Publish.Tests/GivenThatWeWantToPublishAToolProjectWithPackagedShim.cs | 2,793 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Kasp.Data.EF.Models;
using Kasp.Data.Models;
using Microsoft.EntityFrameworkCore;
namespace Kasp.Data.EF.Extensions;
public static class PagedListExtensions {
public static bool IsFirstPage(this IPagedList pagedList) => pagedList.PageIndex == 1;
public static bool IsLastPage(this IPagedList pagedList) => pagedList.PageIndex == pagedList.TotalPage;
public static Task<PagedList<IQueryable<T>, T>> ToPagedListAsync<T>(this IQueryable<T> source, int pageSize, int pageIndex = 1, CancellationToken cancellationToken = default) {
return CreatePagedListCoreAsync(source, pageSize, pageIndex, (data, skip, take) => data.Skip(skip).Take(take).ToArrayAsync(cancellationToken), data => data.CountAsync(cancellationToken));
}
public static PagedList<IEnumerable<T>, T> ToPagedList<T>(this IEnumerable<T> source, int pageSize, int pageIndex = 1) {
return CreatePagedListCore(source, pageSize, pageIndex, (data, skip, take) => data.Skip(skip).Take(take).ToArray(), data => data.Count());
}
public static PagedList<IQueryable<T>, T> ToPagedList<T>(this IQueryable<T> source, int pageSize, int pageIndex = 1) {
return CreatePagedListCore(source, pageSize, pageIndex, (data, skip, take) => data.Skip(skip).Take(take).ToArray(), data => data.Count());
}
private static PagedList<TSource, TElement> CreatePagedListCore<TSource, TElement>(this TSource source, int pageSize, int pageIndex, Func<TSource, int, int, IList<TElement>> pageFunc, Func<TSource, int> countFunc) {
if (source == null)
throw new ArgumentNullException(nameof(source));
if (pageSize <= 0)
throw new ArgumentOutOfRangeException(nameof(pageSize), pageSize, "The page size must be positive.");
if (pageIndex <= 0)
throw new ArgumentOutOfRangeException(nameof(pageIndex), pageIndex, "The page index must be positive.");
var skipValue = pageSize * (pageIndex - 1);
var takeValue = pageSize;
var currentPage = pageFunc(source, skipValue, takeValue);
var totalCount = countFunc(source);
var totalPage = (totalCount - 1) / pageSize + 1;
return new PagedList<TSource, TElement>(currentPage, source, pageSize, pageIndex, totalCount, totalPage);
}
private static async Task<PagedList<TSource, TElement>> CreatePagedListCoreAsync<TSource, TElement>(this TSource source, int pageSize, int pageIndex, Func<TSource, int, int, Task<TElement[]>> pageFunc, Func<TSource, Task<int>> countFunc) {
if (source == null)
throw new ArgumentNullException(nameof(source));
if (pageSize <= 0)
throw new ArgumentOutOfRangeException(nameof(pageSize), pageSize, "The page size must be positive.");
if (pageIndex <= 0)
throw new ArgumentOutOfRangeException(nameof(pageIndex), pageIndex, "The page index must be positive.");
var skipValue = pageSize * (pageIndex - 1);
var takeValue = pageSize;
var currentPage = await pageFunc(source, skipValue, takeValue);
var totalCount = await countFunc(source);
var totalPage = (totalCount - 1) / pageSize + 1;
return new PagedList<TSource, TElement>(currentPage, source, pageSize, pageIndex, totalCount, totalPage);
}
} | 46.362319 | 240 | 0.751485 | [
"MIT"
] | mo3in/Kasp | src/Kasp.Data.EF/Extensions/PagedListExtensions.cs | 3,199 | C# |
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LEMP3")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LEMP3")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.0.1")]
[assembly: AssemblyFileVersion("0.0.0.1")]
| 40.553571 | 97 | 0.734919 | [
"MIT"
] | SLP-KBIT/LEMP3 | LEMP3/Properties/AssemblyInfo.cs | 2,274 | C# |
using System;
namespace _14_Magic_Letter
{
class Program
{
static void Main(string[] args)
{
char startLetter = char.Parse(Console.ReadLine());
char endLetter = char.Parse(Console.ReadLine());
string skip = Console.ReadLine();
string result = "";
for (char i = startLetter; i <= endLetter; i++)
{
for (char j = startLetter; j <= endLetter; j++)
{
for (char k = startLetter; k <= endLetter; k++)
{
result = $"{i}{j}{k}";
if (!result.Contains(skip))
{
Console.Write(result + " ");
}
}
}
}
}
}
} | 27.354839 | 67 | 0.379717 | [
"Apache-2.0"
] | kaliopa1983/Programming-Fundamentals | 03.C# Conditional Statements and Loops - Exercises/14. Magic Letter/Program.cs | 850 | C# |
using UnityEngine;
using System.Collections;
public class Marker : MonoBehaviour {
[SerializeField]
private float size = 1;
[SerializeField]
private Color color = Color.white;
private void OnDrawGizmos()
{
Gizmos.color = color;
Gizmos.DrawSphere(transform.position, size);
}
}
| 17.944444 | 52 | 0.668731 | [
"Apache-2.0"
] | DavidMann10k/Marionette | Assets/_scripts/Marker.cs | 325 | C# |
// Copyright (c) 2019 Lykke Corp.
// See the LICENSE file in the project root for more information.
using System.Data;
using Microsoft.Data.SqlClient;
using Dapper;
namespace MarginTrading.AssetService.SqlRepositories
{
public static class Extensions
{
public static void CreateTableIfDoesntExists(this IDbConnection connection, string createQuery,
string tableName)
{
connection.Open();
try
{
// Check if table exists
connection.ExecuteScalar($"select top 1 * from {tableName}");
}
catch (SqlException)
{
// Create table
var query = string.Format(createQuery, tableName);
connection.Query(query);
}
finally
{
connection.Close();
}
}
}
} | 27.393939 | 103 | 0.54646 | [
"MIT-0"
] | gponomarev-lykke/MarginTrading.AssetService | src/MarginTrading.AssetService.SqlRepositories/Extensions.cs | 906 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.ContainerRegistry.V20190401.Inputs
{
/// <summary>
/// Managed identity for the resource.
/// </summary>
public sealed class IdentityPropertiesArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The principal ID of resource identity.
/// </summary>
[Input("principalId")]
public Input<string>? PrincipalId { get; set; }
/// <summary>
/// The tenant ID of resource.
/// </summary>
[Input("tenantId")]
public Input<string>? TenantId { get; set; }
/// <summary>
/// The identity type.
/// </summary>
[Input("type")]
public Input<Pulumi.AzureNative.ContainerRegistry.V20190401.ResourceIdentityType>? Type { get; set; }
[Input("userAssignedIdentities")]
private InputMap<Inputs.UserIdentityPropertiesArgs>? _userAssignedIdentities;
/// <summary>
/// The list of user identities associated with the resource. The user identity
/// dictionary key references will be ARM resource ids in the form:
/// '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/
/// providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
/// </summary>
public InputMap<Inputs.UserIdentityPropertiesArgs> UserAssignedIdentities
{
get => _userAssignedIdentities ?? (_userAssignedIdentities = new InputMap<Inputs.UserIdentityPropertiesArgs>());
set => _userAssignedIdentities = value;
}
public IdentityPropertiesArgs()
{
}
}
}
| 34.75 | 124 | 0.642343 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/ContainerRegistry/V20190401/Inputs/IdentityPropertiesArgs.cs | 1,946 | C# |
namespace Essensoft.AspNetCore.Payment.Alipay.Response
{
/// <summary>
/// AlipayMarketingCardFormtemplateSetResponse.
/// </summary>
public class AlipayMarketingCardFormtemplateSetResponse : AlipayResponse
{}
}
| 25.777778 | 76 | 0.741379 | [
"MIT"
] | AkonCoder/Payment | src/Essensoft.AspNetCore.Payment.Alipay/Response/AlipayMarketingCardFormtemplateSetResponse.cs | 232 | C# |
// Copyright 2020 Energinet DataHub A/S
//
// Licensed under the Apache License, Version 2.0 (the "License2");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Collections.Generic;
using Azure.Messaging.ServiceBus;
namespace GreenEnergyHub.Charges.Infrastructure.ReplySender
{
public class ServiceBusReplySenderProvider : IServiceBusReplySenderProvider
{
private readonly ServiceBusClient _serviceBusClient;
private readonly Dictionary<string, ServiceBusReplySender?> _senders;
public ServiceBusReplySenderProvider(ServiceBusClient serviceBusClient)
{
_serviceBusClient = serviceBusClient;
_senders = new Dictionary<string, ServiceBusReplySender?>();
}
public IServiceBusReplySender GetInstance(string replyTo)
{
_senders.TryGetValue(replyTo, out var serviceBusReplySender);
if (serviceBusReplySender != null)
return serviceBusReplySender;
serviceBusReplySender = new ServiceBusReplySender(_serviceBusClient.CreateSender(replyTo));
_senders.Add(replyTo, serviceBusReplySender);
return serviceBusReplySender;
}
}
}
| 35.891304 | 103 | 0.722592 | [
"Apache-2.0"
] | Energinet-DataHub/geh-charges | source/GreenEnergyHub.Charges/source/GreenEnergyHub.Charges.Infrastructure/ReplySender/ServiceBusReplySenderProvider.cs | 1,653 | C# |
using System;
using phonebook.Repositories;
using PhoneBook.Models;
namespace PhoneBook.Screens.ContactScreen
{
public class CreateContactScreen
{
public static void Load()
{
Console.Clear();
Console.WriteLine("Adicionando Novo Contato");
Console.WriteLine("------------------------");
Console.WriteLine();
Console.WriteLine("Nome:");
var name = Console.ReadLine();
Console.WriteLine("Telefone:");
var phone = Console.ReadLine();
Create(new Contact
{
Name = name,
Phone = phone
});
Console.ReadKey();
}
public static void Create(Contact contact)
{ try
{
var repository = new Repository<Contact>(Database.Connection);
repository.Create(contact);
Console.WriteLine("Contato adicionado com sucesso.");
}catch
{
Console.WriteLine("Contato adicionado com sucesso.");
}
}
}
} | 26.902439 | 74 | 0.514959 | [
"MIT"
] | BrunoMartins237/-Acesso---dados-com-.NET--C---Dapper-e-SQL-Server | Projetos Exemplos/PhoneBook/Screens/ContactScreen/CreateContactScreen.cs | 1,103 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public static bool _gameIsPaused = false;
public GameObject _pauseMenuUI;
public int maxHealth = 100;
public int currentHealth;
public HealthBar healthBar;
public float speed = 6f;
public float gravity = -9.81f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
public float jumpHeight = 3f;
public float sprint = 60f;
Vector3 velocity;
bool isGrounded;
[SerializeField]
AudioSource hitSound;
public GameObject _loseScreenUI;
void Start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
}
void Update()
{
//checks if we've hit the ground
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y< 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = transform.right * x + transform.forward * z; //Moves based on x and z movement and where the player is facing
//don't want to use new Vector3() because those are GLOBAL Coordinates
controller.Move(move * speed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
if (Input.GetKey(KeyCode.LeftShift))
{
controller.Move(move * sprint * Time.deltaTime);
}
if (currentHealth <= 0)
{
Lose();
}
//we use Velocity to handle Gravity
velocity.y += gravity * Time.deltaTime;
//physics of a free fall
controller.Move(velocity * Time.deltaTime);
}
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Hazard"))
{
other.gameObject.SetActive(false);
TakeDamage(25);
}
if (other.gameObject.CompareTag("Heal"))
{
other.gameObject.SetActive(false);
GiveHealth(20);
}
if (other.gameObject.CompareTag("Projectile"))
{
hitSound.Play();
TakeDamage(15);
}
}
void TakeDamage(int damage)
{
currentHealth -= damage;
healthBar.SetHealth(currentHealth);
}
void GiveHealth(int heal)
{
currentHealth += heal;
healthBar.SetHealth(currentHealth);
}
public void Pause()
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
_pauseMenuUI.SetActive(true);
Time.timeScale = 0f;
_gameIsPaused = true;
}
public void Lose()
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
_loseScreenUI.SetActive(true);
Time.timeScale = 0f;
_gameIsPaused = true;
}
public void Kill()
{
this.gameObject.SetActive(false);
}
}
| 24.092199 | 133 | 0.573742 | [
"MIT"
] | tlm160130/MitchellTyeric_02 | Assets/Scripts/PlayerMovement.cs | 3,399 | C# |
// SharpPusher
// Copyright (c) 2017 Coding Enthusiast
// Distributed under the MIT software license, see the accompanying
// file LICENCE or http://www.opensource.org/licenses/mit-license.php.
using Autarkysoft.Bitcoin.Encoders;
using SharpPusher.MVVM;
using SharpPusher.Services;
using SharpPusher.Services.PushServices;
using System;
using System.Collections.ObjectModel;
using System.Reflection;
namespace SharpPusher.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
public MainWindowViewModel()
{
NetworkList = new ObservableCollection<Networks>((Networks[])Enum.GetValues(typeof(Networks)));
_selNet = NetworkList[0];
SetApiList();
_selApi = ApiList[0];
BroadcastTxCommand = new BindableCommand(BroadcastTx, CanBroadcast);
Version ver = Assembly.GetExecutingAssembly().GetName().Version ?? new Version(0, 0, 0);
VersionString = ver.ToString(3);
_rawTx = string.Empty;
}
public string VersionString { get; }
private string _rawTx;
public string RawTx
{
get => _rawTx;
set
{
if (SetField(ref _rawTx, value))
{
BroadcastTxCommand.RaiseCanExecuteChanged();
}
}
}
public enum Networks
{
Bitcoin,
BitcoinTestnet,
BitcoinCash,
BitcoinSV,
Dogecoin,
Litecoin,
Monero,
Zcash,
Ethereum,
EthereumTestnet,
Dash,
Ripple,
Groestlcoin,
Stellar,
Cardano,
Mixin,
Tezos,
EOS,
BitcoinABC
}
public ObservableCollection<Networks> NetworkList { get; set; }
private Networks _selNet;
public Networks SelectedNetwork
{
get { return _selNet; }
set
{
if (SetField(ref _selNet, value))
{
SetApiList();
}
}
}
private void SetApiList()
{
switch (SelectedNetwork)
{
case Networks.Bitcoin:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.BTC),
new Smartbit(),
new BlockCypher(),
};
break;
case Networks.BitcoinCash:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.BCH),
};
break;
case Networks.Dogecoin:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.DOGE),
};
break;
case Networks.Litecoin:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.LTC),
};
break;
case Networks.Monero:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.XMR),
};
break;
case Networks.BitcoinTestnet:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.TBTC),
};
break;
case Networks.BitcoinSV:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.BSV),
};
break;
case Networks.Zcash:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.ZEC),
};
break;
case Networks.Ripple:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.XRP),
};
break;
case Networks.Stellar:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.XLM),
};
break;
case Networks.Cardano:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.ADA),
};
break;
case Networks.Mixin:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.XIN),
};
break;
case Networks.Tezos:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.XTZ),
};
break;
case Networks.EOS:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.EOS),
};
break;
case Networks.Ethereum:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.ETH),
};
break;
case Networks.EthereumTestnet:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.tETH),
};
break;
case Networks.Groestlcoin:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.GRS),
};
break;
case Networks.Dash:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.DASH),
};
break;
case Networks.BitcoinABC:
ApiList = new ObservableCollection<Api>()
{
new Blockchair(Blockchair.Chain.ABC),
};
break;
}
}
private ObservableCollection<Api> _apiList = new();
public ObservableCollection<Api> ApiList
{
get => _apiList;
set => SetField(ref _apiList, value);
}
private Api _selApi;
public Api SelectedApi
{
get => _selApi;
set
{
if (SetField(ref _selApi, value))
{
BroadcastTxCommand.RaiseCanExecuteChanged();
}
}
}
private bool _isSending;
public bool IsSending
{
get => _isSending;
set
{
if (SetField(ref _isSending, value))
{
BroadcastTxCommand.RaiseCanExecuteChanged();
}
}
}
public BindableCommand BroadcastTxCommand { get; private set; }
private async void BroadcastTx()
{
if (!Base16.IsValid(RawTx))
{
Status = "Invalid hex.";
return;
}
IsSending = true;
Errors = string.Empty;
Status = "Broadcasting Transaction...";
Response<string> resp = await SelectedApi.PushTx(RawTx);
if (resp.Errors.Any())
{
Errors = resp.Errors.GetErrors();
Status = "Finished with error.";
}
else
{
Status = resp.Result;
}
IsSending = false;
}
private bool CanBroadcast()
{
if (!string.IsNullOrWhiteSpace(RawTx) && !IsSending && SelectedApi != null)
{
return true;
}
else
{
return false;
}
}
}
}
| 30.555944 | 107 | 0.424763 | [
"MIT"
] | AngeloMetal/SharpPusher | SharpPusher/ViewModels/MainWindowViewModel.cs | 8,741 | C# |
using System.IO;
using System.Text;
namespace LoadFileAdapter.Importers
{
/// <summary>
/// Imports load file data into a <see cref="DocumentCollection"/>.
/// </summary>
public interface IImporter
{
/// <summary>
/// Imports data into a <see cref="DocumentCollection"/> from a file.
/// </summary>
/// <param name="file"></param>
/// <param name="encoding"></param>
/// <returns></returns>
DocumentCollection Import(FileInfo file, Encoding encoding);
}
}
| 27.85 | 78 | 0.570916 | [
"MIT"
] | JeffGillispie/LoadFileAdapter | LoadFileAdapter/Importers/IImporter.cs | 559 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.Security.Authentication.Web.Provider
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial class WebAccountProviderDeleteAccountOperation : global::Windows.Security.Authentication.Web.Provider.IWebAccountProviderOperation,global::Windows.Security.Authentication.Web.Provider.IWebAccountProviderBaseReportOperation
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public global::Windows.Security.Credentials.WebAccount WebAccount
{
get
{
throw new global::System.NotImplementedException("The member WebAccount WebAccountProviderDeleteAccountOperation.WebAccount is not implemented in Uno.");
}
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public global::Windows.Security.Authentication.Web.Provider.WebAccountProviderOperationKind Kind
{
get
{
throw new global::System.NotImplementedException("The member WebAccountProviderOperationKind WebAccountProviderDeleteAccountOperation.Kind is not implemented in Uno.");
}
}
#endif
// Forced skipping of method Windows.Security.Authentication.Web.Provider.WebAccountProviderDeleteAccountOperation.WebAccount.get
// Forced skipping of method Windows.Security.Authentication.Web.Provider.WebAccountProviderDeleteAccountOperation.Kind.get
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public void ReportCompleted()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Security.Authentication.Web.Provider.WebAccountProviderDeleteAccountOperation", "void WebAccountProviderDeleteAccountOperation.ReportCompleted()");
}
#endif
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__")]
public void ReportError( global::Windows.Security.Authentication.Web.Core.WebProviderError value)
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Security.Authentication.Web.Provider.WebAccountProviderDeleteAccountOperation", "void WebAccountProviderDeleteAccountOperation.ReportError(WebProviderError value)");
}
#endif
// Processing: Windows.Security.Authentication.Web.Provider.IWebAccountProviderOperation
// Processing: Windows.Security.Authentication.Web.Provider.IWebAccountProviderBaseReportOperation
}
}
| 62.52 | 251 | 0.791427 | [
"Apache-2.0"
] | AbdalaMask/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Security.Authentication.Web.Provider/WebAccountProviderDeleteAccountOperation.cs | 3,126 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Prefetch.Other;
namespace Prefetch
{
public enum Version
{
[Description("Windows XP or Windows Server 2003")]
WinXpOrWin2K3 = 17,
[Description("Windows Vista or Windows 7")]
VistaOrWin7 = 23,
[Description("Windows 8.0, Windows 8.1, or Windows Server 2012(R2)")]
Win8xOrWin2012x = 26,
[Description("Windows 10")]
Win10 = 30
}
public interface IPrefetch
{
byte[] RawBytes { get; }
string SourceFilename { get; }
DateTimeOffset SourceCreatedOn { get; }
DateTimeOffset SourceModifiedOn { get; }
DateTimeOffset SourceAccessedOn { get; }
Header Header { get; }
int FileMetricsOffset { get; }
int FileMetricsCount { get; }
int TraceChainsOffset { get; }
int TraceChainsCount { get; }
int FilenameStringsOffset { get; }
int FilenameStringsSize { get; }
int VolumesInfoOffset { get; }
int VolumeCount { get; }
int VolumesInfoSize { get; }
int TotalDirectoryCount { get; }
List<DateTimeOffset> LastRunTimes { get; }
List<VolumeInfo> VolumeInformation { get; }
int RunCount { get; }
bool ParsingError { get; }
List<string> Filenames { get; }
List<FileMetric> FileMetrics { get; }
List<TraceChain> TraceChains { get; }
}
} | 22.984615 | 77 | 0.597055 | [
"MIT"
] | EricZimmerman/Prefetch | Prefetch/IPrefetch.cs | 1,496 | C# |
using Toggl.Multivac.Models;
namespace Toggl.Ultrawave.Models
{
internal sealed partial class Country : ICountry
{
public long Id { get; set; }
public string Name { get; set; }
public string CountryCode { get; set; }
}
}
| 18.642857 | 52 | 0.624521 | [
"BSD-3-Clause"
] | AzureMentor/mobileapp | Toggl.Ultrawave/Models/Country.cs | 263 | C# |
namespace MiddleMan.Tests.Fakes.Command
{
using MiddleMan.Command;
public class MultipleHandlerCommand : ICommand
{
}
} | 15.333333 | 50 | 0.702899 | [
"MIT"
] | DSaunders/MiddleMan | MiddleMan.Tests/Fakes/Command/MultipleHandlerCommand.cs | 140 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
namespace Nest
{
/// <inheritdoc cref="IDocValuesProperty" />
public abstract class DocValuesPropertyDescriptorBase<TDescriptor, TInterface, T>
: CorePropertyDescriptorBase<TDescriptor, TInterface, T>, IDocValuesProperty
where TDescriptor : DocValuesPropertyDescriptorBase<TDescriptor, TInterface, T>, TInterface
where TInterface : class, IDocValuesProperty
where T : class
{
protected DocValuesPropertyDescriptorBase(FieldType type) : base(type) { }
bool? IDocValuesProperty.DocValues { get; set; }
/// <inheritdoc cref="IDocValuesProperty.DocValues" />
public TDescriptor DocValues(bool? docValues = true) => Assign(docValues, (a, v) => a.DocValues = v);
}
}
| 40.409091 | 103 | 0.764904 | [
"Apache-2.0"
] | Atharvpatel21/elasticsearch-net | src/Nest/Mapping/Types/DocValuesPropertyDescriptorBase.cs | 889 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Xoqal.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Xoqal.Tests")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dfce5240-1bb0-476e-ba99-800679ec99fd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.5.4.0")]
[assembly: AssemblyFileVersion("1.5.4.0")]
| 38.189189 | 84 | 0.746638 | [
"Apache-2.0"
] | AmirKarimi/Xoqal | Source/Xoqal.Tests/Properties/AssemblyInfo.cs | 1,416 | C# |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace Npoi.Core.HSSF.Record
{
using Npoi.Core.Util;
using System;
using System.Text;
/**
* Title: Uncalced Record
*
* If this record occurs in the Worksheet Substream, it indicates that the formulas have not
* been recalculated before the document was saved.
*
* @author Olivier Leprince
*/
public class UncalcedRecord : StandardRecord
{
public const short sid = 0x5E;
private short _reserved;
/**
* Default constructor
*/
public UncalcedRecord()
{
_reserved = 0;
}
/**
* Read constructor
*/
public UncalcedRecord(RecordInputStream in1)
{
_reserved = in1.ReadShort();
}
public override short Sid
{
get { return sid; }
}
public override string ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[UNCALCED]\n");
buffer.Append("[/UNCALCED]\n");
return buffer.ToString();
}
public override void Serialize(ILittleEndianOutput out1)
{
out1.WriteShort(_reserved);
}
protected override int DataSize
{
get { return 2; }
}
public static int StaticRecordSize
{
get { return 6; }
}
}
} | 28.46988 | 96 | 0.571308 | [
"Apache-2.0"
] | Arch/Npoi.Core | src/Npoi.Core/HSSF/Record/UncalcedRecord.cs | 2,363 | C# |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
namespace UnityStandardAssets.Characters.FirstPerson
{
[Serializable]
public class MouseLook
{
public float XSensitivity = 2f;
public float YSensitivity = 2f;
public bool clampVerticalRotation = true;
public float MinimumX = -90F;
public float MaximumX = 90F;
public bool smooth;
public float smoothTime = 5f;
public bool lockCursor = true;
private Quaternion m_CharacterTargetRot;
private Quaternion m_CameraTargetRot;
private bool m_cursorIsLocked = true;
public void Init(Transform character, Transform camera)
{
m_CharacterTargetRot = character.localRotation;
m_CameraTargetRot = camera.localRotation;
}
public void LookRotation(Transform character, Transform camera)
{
float yRot = CrossPlatformInputManager.GetAxis("Mouse X") * XSensitivity;
float xRot = CrossPlatformInputManager.GetAxis("Mouse Y") * YSensitivity;
m_CharacterTargetRot *= Quaternion.Euler (0f, yRot, 0f);
m_CameraTargetRot *= Quaternion.Euler (-xRot, 0f, 0f);
if(clampVerticalRotation)
m_CameraTargetRot = ClampRotationAroundXAxis (m_CameraTargetRot);
if(smooth)
{
character.localRotation = Quaternion.Slerp (character.localRotation, m_CharacterTargetRot,
smoothTime * Time.deltaTime);
camera.localRotation = Quaternion.Slerp (camera.localRotation, m_CameraTargetRot,
smoothTime * Time.deltaTime);
}
else
{
character.localRotation = m_CharacterTargetRot;
camera.localRotation = m_CameraTargetRot;
}
UpdateCursorLock();
}
public void SetCursorLock(bool value)
{
lockCursor = value;
if(!lockCursor)
{//we force unlock the cursor if the user disable the cursor locking helper
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
public void UpdateCursorLock()
{
//if the user set "lockCursor" we check & properly lock the cursos
if (lockCursor)
InternalLockUpdate();
}
private void InternalLockUpdate()
{
if(Input.GetKeyUp(KeyCode.Escape))
{
m_cursorIsLocked = false;
}
else if(Input.GetMouseButtonUp(0))
{
m_cursorIsLocked = true;
}
if (m_cursorIsLocked)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
else if (!m_cursorIsLocked)
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
Quaternion ClampRotationAroundXAxis(Quaternion q)
{
q.x /= q.w;
q.y /= q.w;
q.z /= q.w;
q.w = 1.0f;
float angleX = 2.0f * Mathf.Rad2Deg * Mathf.Atan (q.x);
angleX = Mathf.Clamp (angleX, MinimumX, MaximumX);
q.x = Mathf.Tan (0.5f * Mathf.Deg2Rad * angleX);
return q;
}
}
}
| 30.913793 | 107 | 0.537089 | [
"MIT"
] | 0V/TwitterTimeLineShooter | Assets/Standard Assets/Characters/FirstPersonCharacter/Scripts/MouseLook.cs | 3,586 | C# |
using CSharpFunctionalExtensions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
namespace KeepAChangelogParser.Tests.Comparer
{
public class ResultComparer<T> :
IComparer,
IComparer<Result<T>>
{
private readonly IComparer<T> comparer;
public ResultComparer(
IComparer<T> comparer
)
{
this.comparer = comparer;
}
public int Compare(
object? x,
object? y
)
{
if (x is not Result<T>)
{
string message =
string.Format(
CultureInfo.CurrentCulture,
"Required input {0} is not a recognized {1}.",
nameof(y), typeof(Result<T>));
throw new ArgumentException(message, nameof(x));
}
if (y is not Result<T>)
{
string message =
string.Format(
CultureInfo.CurrentCulture,
"Required input {0} is not a recognized {1}.",
nameof(y), typeof(Result<T>));
throw new ArgumentException(message, nameof(y));
}
int result =
this.Compare(
(Result<T>)x,
(Result<T>)y);
return result;
}
public int Compare(
Result<T> x,
Result<T> y
)
{
int result;
if ((result = compare(x.IsSuccess, y.IsSuccess)) != 0) { return result; }
if (x.IsSuccess)
{
if ((result = this.comparer.Compare(x.Value, y.Value)) != 0) { return result; }
}
if (x.IsFailure)
{
if ((result = compare(x.Error, y.Error)) != 0) { return result; }
}
return result;
}
private static int compare(
string x,
string y
)
{
return string.Compare(x, y, StringComparison.Ordinal);
}
private static int compare(
bool x,
bool y
)
{
if (x != y) { return 1; }
return 0;
}
}
} | 19.18 | 87 | 0.541189 | [
"MIT"
] | shuelsmeier/keepachangelogparser | KeepAChangelogParser.Tests/Comparer/ResultComparer.cs | 1,920 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Gcp.BigQuery.Outputs
{
[OutputType]
public sealed class JobExtractSourceModel
{
/// <summary>
/// The ID of the dataset containing this model.
/// </summary>
public readonly string DatasetId;
/// <summary>
/// The ID of the model.
/// </summary>
public readonly string ModelId;
/// <summary>
/// The ID of the project containing this model.
/// </summary>
public readonly string ProjectId;
[OutputConstructor]
private JobExtractSourceModel(
string datasetId,
string modelId,
string projectId)
{
DatasetId = datasetId;
ModelId = modelId;
ProjectId = projectId;
}
}
}
| 26 | 88 | 0.599284 | [
"ECL-2.0",
"Apache-2.0"
] | dimpu47/pulumi-gcp | sdk/dotnet/BigQuery/Outputs/JobExtractSourceModel.cs | 1,118 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// AlipayMarketingVoucherTemplatedetailQueryModel Data Structure.
/// </summary>
[Serializable]
public class AlipayMarketingVoucherTemplatedetailQueryModel : AopObject
{
/// <summary>
/// 券模板ID。可通过对应产品创建优惠券模板接口获取。如:无资金优惠券可通过<a href="https://opendocs.alipay.com/apis/api_5/alipay.marketing.cashlessvoucher.template.create">alipay.marketing.cashlessvoucher.template.create</a>(无资金券模板创建接口)创建券模板;现金抵价券可通过<a href="https://opendocs.alipay.com/apis/api_5/alipay.marketing.cashvoucher.template.create">alipay.marketing.cashvoucher.template.create</a>(创建资金券模板)接口创建券模板。
/// </summary>
[XmlElement("template_id")]
public string TemplateId { get; set; }
}
}
| 43.210526 | 384 | 0.712546 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Domain/AlipayMarketingVoucherTemplatedetailQueryModel.cs | 967 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/UIAnimation.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace TerraFX.Interop.Windows;
public static partial class IID
{
public static ref readonly Guid IID_IUIAnimationManager
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x6C, 0x89, 0x69, 0x91,
0x8D, 0xAC,
0x7D, 0x4E,
0x94,
0xE5,
0x67,
0xFA,
0x4D,
0xC2,
0xF2,
0xE8
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationVariable
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x55, 0xB1, 0xEE, 0x8C,
0x49, 0x28,
0xE5, 0x4C,
0x94,
0x48,
0x91,
0xFF,
0x70,
0xE1,
0xE4,
0xD9
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationStoryboard
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x8F, 0x12, 0xFF, 0xA8,
0xF9, 0x9B,
0xF1, 0x4A,
0x9E,
0x67,
0xE5,
0xE4,
0x10,
0xDE,
0xFB,
0x84
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationTransition
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x52, 0xE2, 0x6C, 0xDC,
0x31, 0xF7,
0xCF, 0x41,
0xB6,
0x10,
0x61,
0x4B,
0x6C,
0xA0,
0x49,
0xAD
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationManagerEventHandler
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xED, 0x21, 0x33, 0x78,
0xA3, 0x78,
0x66, 0x43,
0xB5,
0x74,
0x6A,
0xF6,
0x07,
0xA6,
0x47,
0x88
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationVariableChangeHandler
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xBA, 0xB7, 0x58, 0x63,
0xD2, 0x87,
0xD5, 0x42,
0xBF,
0x71,
0x82,
0xE9,
0x19,
0xDD,
0x58,
0x62
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationVariableIntegerChangeHandler
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x50, 0x15, 0x3E, 0xBB,
0x6E, 0x35,
0xB0, 0x44,
0x99,
0xDA,
0x85,
0xAC,
0x60,
0x17,
0x86,
0x5E
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationStoryboardEventHandler
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x08, 0x90, 0x5C, 0x3D,
0x7C, 0xEC,
0x64, 0x43,
0x9F,
0x8A,
0x9A,
0xF3,
0xC5,
0x8C,
0xBA,
0xE6
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationPriorityComparison
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x74, 0x9B, 0xFA, 0x83,
0x86, 0x5F,
0x18, 0x46,
0xBC,
0x6A,
0xA2,
0xFA,
0xC1,
0x9B,
0x3F,
0x44
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationTransitionLibrary
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xB1, 0x14, 0x5A, 0xCA,
0x4F, 0xD2,
0xB8, 0x48,
0x8F,
0xE4,
0xC7,
0x81,
0x69,
0xBA,
0x95,
0x4E
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationInterpolator
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xBA, 0xCB, 0x15, 0x78,
0xF7, 0xDD,
0x8C, 0x47,
0xA4,
0x6C,
0x7B,
0x6C,
0x73,
0x8B,
0x79,
0x78
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationTransitionFactory
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x03, 0x1E, 0xD9, 0xFC,
0x3B, 0x3E,
0xAD, 0x45,
0xBB,
0xB1,
0x6D,
0xFC,
0x81,
0x53,
0x74,
0x3D
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationTimer
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xD1, 0xFA, 0x0E, 0x6B,
0x53, 0xA0,
0xD6, 0x41,
0x90,
0x85,
0x33,
0xA6,
0x89,
0x14,
0x46,
0x65
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationTimerUpdateHandler
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xB7, 0x09, 0x55, 0x19,
0x5E, 0x5D,
0x3E, 0x4E,
0xB2,
0x78,
0xEE,
0x37,
0x59,
0xB3,
0x67,
0xAD
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationTimerClientEventHandler
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xB6, 0x4D, 0xDB, 0xBE,
0xFA, 0x94,
0xFB, 0x4B,
0xA4,
0x7F,
0xEF,
0x2D,
0x9E,
0x40,
0x8C,
0x25
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationTimerEventHandler
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xEA, 0x7D, 0x4A, 0x27,
0x71, 0xD7,
0x95, 0x40,
0xAB,
0xBD,
0x8D,
0xF7,
0xAB,
0xD2,
0x3C,
0xE3
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationManager2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xD4, 0xF7, 0xB6, 0xD8,
0x09, 0x41,
0x3F, 0x4D,
0xAC,
0xEE,
0x87,
0x99,
0x26,
0x96,
0x8C,
0xB1
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationVariable2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x04, 0xB3, 0x14, 0x49,
0xAB, 0x96,
0xD9, 0x44,
0x9E,
0x77,
0xD5,
0x10,
0x9B,
0x7E,
0x74,
0x66
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationTransition2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x23, 0x91, 0xFF, 0x62,
0x5A, 0xA8,
0x9B, 0x4E,
0xA2,
0x18,
0x43,
0x5A,
0x93,
0xE2,
0x68,
0xFD
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationManagerEventHandler2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xBA, 0x22, 0xE0, 0xF6,
0xF3, 0xBF,
0xEC, 0x42,
0x90,
0x33,
0xE0,
0x73,
0xF3,
0x3E,
0x83,
0xC3
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationVariableChangeHandler2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xD2, 0xC8, 0xAC, 0x63,
0xAE, 0x6E,
0xB0, 0x4B,
0xB8,
0x79,
0x58,
0x6D,
0xD8,
0xCF,
0xBE,
0x42
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationVariableIntegerChangeHandler2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xF1, 0x6C, 0x9B, 0x82,
0x3A, 0x4F,
0x12, 0x44,
0xAE,
0x09,
0xB2,
0x43,
0xEB,
0x4C,
0x6B,
0x58
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationVariableCurveChangeHandler2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x91, 0x5E, 0x89, 0x72,
0x45, 0x01,
0x21, 0x4C,
0x91,
0x92,
0x5A,
0xAB,
0x40,
0xED,
0xDF,
0x80
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationStoryboardEventHandler2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x5A, 0xF5, 0xC5, 0xBA,
0x7C, 0xBA,
0x4C, 0x41,
0xB5,
0x99,
0xFB,
0xF8,
0x50,
0xF5,
0x53,
0xC6
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationLoopIterationChangeHandler2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xA4, 0x15, 0x3B, 0x2D,
0x62, 0x47,
0xAB, 0x47,
0xA0,
0x30,
0xB2,
0x32,
0x21,
0xDF,
0x3A,
0xE0
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationPriorityComparison2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x37, 0x7A, 0x6D, 0x5B,
0x21, 0x46,
0x7C, 0x46,
0x8B,
0x05,
0x70,
0x13,
0x1D,
0xE6,
0x2D,
0xDB
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationTransitionLibrary2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x53, 0xAE, 0xCF, 0x03,
0x80, 0x95,
0xE3, 0x4E,
0xB3,
0x63,
0x2E,
0xCE,
0x51,
0xB4,
0xAF,
0x6A
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationPrimitiveInterpolation
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x63, 0x0D, 0xB2, 0xBA,
0x61, 0x43,
0xDA, 0x45,
0xA2,
0x4F,
0xAB,
0x85,
0x08,
0x84,
0x6B,
0x5B
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationInterpolator2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xF8, 0xAF, 0x76, 0xEA,
0x22, 0xEA,
0x23, 0x4A,
0xA0,
0xEF,
0xA6,
0xA9,
0x66,
0x70,
0x35,
0x18
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationTransitionFactory2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0x16, 0x49, 0x7D, 0x93,
0xA6, 0xC1,
0xD5, 0x42,
0x88,
0xD8,
0x30,
0x34,
0x4D,
0x6E,
0xFE,
0x31
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
public static ref readonly Guid IID_IUIAnimationStoryboard2
{
get
{
ReadOnlySpan<byte> data = new byte[] {
0xD2, 0x9C, 0x28, 0xAE,
0xD4, 0x12,
0x45, 0x49,
0x94,
0x19,
0x9E,
0x41,
0xBE,
0x03,
0x4D,
0xF2
};
Debug.Assert(data.Length == Unsafe.SizeOf<Guid>());
return ref Unsafe.As<byte, Guid>(ref MemoryMarshal.GetReference(data));
}
}
}
| 26.252747 | 145 | 0.4223 | [
"MIT"
] | IngmarBitter/terrafx.interop.windows | sources/Interop/Windows/Windows/um/UIAnimation/IID.cs | 19,114 | C# |
// Copyright 2017-2020 Elringus (Artyom Sovetnikov). All Rights Reserved.
using System.Threading;
using UniRx.Async;
using UnityEngine;
namespace Naninovel.Commands
{
/// <summary>
/// Destroys an object spawned with [@spawn] command.
/// </summary>
/// <remarks>
/// If prefab has a <see cref="MonoBehaviour"/> component attached the root object, and the component implements
/// a <see cref="IParameterized"/> interface, will pass the specified `params` values before destroying the object;
/// if the component implements <see cref="IAwaitable"/> interface, command execution will wait for
/// the async completion task returned by the implementation before destroying the object.
/// </remarks>
/// <example>
/// ; Given a "@spawn Rainbow" command was executed before
/// @despawn Rainbow
/// </example>
[CommandAlias("despawn")]
public class DestroySpawned : Command
{
public interface IParameterized { void SetDestroyParameters (string[] parameters); }
public interface IAwaitable { UniTask AwaitDestroyAsync (CancellationToken cancellationToken = default); }
/// <summary>
/// Name (path) of the prefab resource to destroy.
/// A [@spawn] command with the same parameter is expected to be executed before.
/// </summary>
[ParameterAlias(NamelessParameterAlias), RequiredParameter]
public StringParameter Path;
/// <summary>
/// Parameters to set before destoying the prefab.
/// Requires the prefab to have a <see cref="IParameterized"/> component attached the root object.
/// </summary>
public StringListParameter Params;
protected virtual ISpawnManager SpawnManager => Engine.GetService<ISpawnManager>();
public override async UniTask ExecuteAsync (CancellationToken cancellationToken = default)
{
if (!SpawnManager.IsObjectSpawned(Path))
{
Debug.LogWarning($"Failed to destroy spawned object '{Path}': the object is not found.");
return;
}
await SpawnManager.DestroySpawnedAsync(Path, cancellationToken, Params);
}
}
}
| 42.111111 | 120 | 0.647757 | [
"MIT"
] | 286studio/Sim286 | AVG/Assets/Naninovel/Runtime/Command/Spawn/DestroySpawned.cs | 2,276 | C# |
using System;
using System.Windows;
using CustomControls;
namespace CustomControlsWPFApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
var customControl1 = new CustomControl1();
XamlHost.Child = customControl1;
}
}
}
| 18.041667 | 68 | 0.720554 | [
"MIT"
] | nesherhh/XamlIslandsNET5 | Samples/CustomControlsWPFApp/MainWindow.xaml.cs | 435 | C# |
using Ak.Framework.Core.Extensions;
using Icona.ChannelsDownloading.App.ChannelsService;
using VkNet;
using VkNet.Enums.Filters;
using VkNet.Model;
using VkNet.Model.RequestParams;
namespace Icona.ChannelsDownloading.App.Logic.ChannelsProcessors
{
class VkProcessor : BaseChannelProcessor
{
private string Token { get; }
public VkProcessor(ChannelContract channel) : base(channel)
{
Token = Attributes["Token"];
}
public override void Process()
{
VkApi api = new VkApi();
api.Authorize(new ApiAuthParams
{
ApplicationId = 123456,
AccessToken = Token,
Settings = Settings.All
});
WallGetObject wall = api.Wall.Get(new WallGetParams
{
Domain = Channel.Url
});
if (wall != null && wall.WallPosts.Count > 0)
foreach (Post post in wall.WallPosts)
{
if (!Channel.LastSynchronizationDate.HasValue ||
(post.Date.HasValue && post.Date >= Channel.LastSynchronizationDate.Value))
{
NewsItems.Add(new NewsItemContract
{
ChannelId = Channel.Id,
Date = post.Date.Value,
Title = post.Text.TruncateSpecialSymbols(),
Description = post.Text.TruncateSpecialSymbols(),
Text = post.Text,
Url = $"https://vk.com/{Channel.Url}?w=wall{post.OwnerId}_{post.Id}"
});
}
}
FilterNewsItemsByTags();
SaveNewsItems();
}
}
}
| 33.125 | 99 | 0.491644 | [
"MIT"
] | ak-git1/Island1021-Hackathon-iCona | Icona/Icona.ChannelsDownloading.App/Logic/ChannelsProcessors/VkProcessor.cs | 1,857 | C# |
//-----------------------------------------------------------------------
// <copyright file="RemoteRestartedQuarantinedSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Text;
using Akka.Actor;
using Akka.Configuration;
using Akka.Remote.TestKit;
using FluentAssertions;
namespace Akka.Remote.Tests.MultiNode
{
public class RemoteRestartedQuarantinedMultiNetSpec : MultiNodeConfig
{
public RemoteRestartedQuarantinedMultiNetSpec()
{
First = Role("first");
Second = Role("second");
CommonConfig = DebugConfig(false).WithFallback(ConfigurationFactory.ParseString(@"
akka.loglevel = WARNING
akka.remote.log-remote-lifecycle-events = WARNING
# Keep it long, we don't want reconnects
akka.remote.retry-gate-closed-for = 1 s
# Important, otherwise it is very racy to get a non-writing endpoint: the only way to do it if the two nodes
# associate to each other at the same time. Setting this will ensure that the right scenario happens.
akka.remote.use-passive-connections = off
# TODO should not be needed, but see TODO at the end of the test
akka.remote.transport-failure-detector.heartbeat-interval = 1 s
akka.remote.transport-failure-detector.acceptable-heartbeat-pause = 10 s
"));
TestTransport = true;
}
public RoleName First { get; }
public RoleName Second { get; }
public sealed class Subject : ReceiveActor
{
public Subject()
{
Receive<string>(_ => Context.System.Terminate(), s => "shutdown".Equals(s));
Receive<string>(
_ => Sender.Tell((AddressUidExtension.Uid(Context.System), Self)),
s => "identify".Equals(s));
}
}
}
public class RemoteRestartedQuarantinedSpec : MultiNodeSpec
{
private readonly RemoteRestartedQuarantinedMultiNetSpec _config;
private readonly Func<RoleName, string, (int, IActorRef)> _identifyWithUid;
public RemoteRestartedQuarantinedSpec()
: this(new RemoteRestartedQuarantinedMultiNetSpec())
{
}
protected RemoteRestartedQuarantinedSpec(RemoteRestartedQuarantinedMultiNetSpec config)
: base(config, typeof(RemoteRestartedQuarantinedSpec))
{
_config = config;
_identifyWithUid = (role, actorName) =>
{
Sys.ActorSelection(Node(role) / "user" / actorName).Tell("identify");
return ExpectMsg<(int, IActorRef)>();
};
}
protected override int InitialParticipantsValueFactory { get; } = 2;
[MultiNodeFact]
public void A_restarted_quarantined_system_should_not_crash_the_other_system()
{
Sys.ActorOf<RemoteRestartedQuarantinedMultiNetSpec.Subject>("subject");
EnterBarrier("subject-started");
RunOn(() =>
{
var secondAddress = Node(_config.Second).Address;
var uid = _identifyWithUid(_config.Second, "subject").Item1;
RARP.For(Sys).Provider.Transport.Quarantine(Node(_config.Second).Address, uid);
EnterBarrier("quarantined");
EnterBarrier("still-quarantined");
TestConductor.Shutdown(_config.Second).Wait();
Within(TimeSpan.FromSeconds(30), () =>
{
AwaitAssert(() =>
{
Sys.ActorSelection(new RootActorPath(secondAddress)/"user"/"subject")
.Tell(new Identify("subject"));
ExpectMsg<ActorIdentity>(i => i.Subject != null, TimeSpan.FromSeconds(10));
});
});
Sys.ActorSelection(new RootActorPath(secondAddress) / "user" / "subject").Tell("shutdown");
}, _config.First);
RunOn(() =>
{
var addr = ((ExtendedActorSystem) Sys).Provider.DefaultAddress;
var firstAddress = Node(_config.First).Address;
Sys.EventStream.Subscribe(TestActor, typeof (ThisActorSystemQuarantinedEvent));
var actorRef = _identifyWithUid(_config.First, "subject").Item2;
EnterBarrier("quarantined");
// Check that quarantine is intact
Within(TimeSpan.FromSeconds(30), () =>
{
AwaitAssert(() =>
{
EventFilter.Warning(null, null, "The remote system has quarantined this system")
.ExpectOne(TimeSpan.FromSeconds(10), () => actorRef.Tell("boo!"));
});
});
ExpectMsg<ThisActorSystemQuarantinedEvent>(TimeSpan.FromSeconds(10));
EnterBarrier("still-quarantined");
Sys.WhenTerminated.Wait(TimeSpan.FromSeconds(10));
var sb = new StringBuilder()
.AppendLine("akka.remote.retry-gate-closed-for = 0.5 s")
.AppendLine("akka.remote.dot-netty.tcp {")
.AppendLine("hostname = " + addr.Host)
.AppendLine("port = " + addr.Port)
.AppendLine("}");
var freshSystem = ActorSystem.Create(Sys.Name,
ConfigurationFactory.ParseString(sb.ToString()).WithFallback(Sys.Settings.Config));
var probe = CreateTestProbe(freshSystem);
freshSystem.ActorSelection(new RootActorPath(firstAddress)/"user"/"subject")
.Tell(new Identify("subject"), probe.Ref);
// TODO sometimes it takes long time until the new connection is established,
// It seems like there must first be a transport failure detector timeout, that triggers
// "No response from remote. Handshake timed out or transport failure detector triggered"
probe.ExpectMsg<ActorIdentity>(i => i.Subject != null, TimeSpan.FromSeconds(30));
freshSystem.ActorOf<RemoteRestartedQuarantinedMultiNetSpec.Subject>("subject");
freshSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10));
}, _config.Second);
}
}
}
| 40.757576 | 122 | 0.567584 | [
"Apache-2.0"
] | Aaronontheweb/akka.net | src/core/Akka.Remote.Tests.MultiNode/RemoteRestartedQuarantinedSpec.cs | 6,727 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace ESMAJ.StringSearch
{
public class ReverseColussi
{
public static double preProcessTime;
public static double searchTime;
public static int Search(string pattern, string source, int startIndex)
{
char[] ptrn = pattern.ToCharArray(), y = source.ToCharArray(startIndex, source.Length - startIndex);
char[] x = new char[ptrn.Length + 1];
Array.Copy(ptrn, 0, x, 0, ptrn.Length);
int i, j, s, m = ptrn.Length, n = y.Length;
int[,] rcBc = new int[65536, x.Length];
int[] rcGs = new int[x.Length];
int[] h = new int[x.Length];
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
/* Preprocessing */
PreRc(x, ref h, ref rcBc, ref rcGs);
stopwatch.Stop();
preProcessTime = stopwatch.Elapsed.TotalMilliseconds;
stopwatch.Restart();
/* Searching */
j = 0;
s = m;
while (j <= n - m)
{
while (j <= n - m && x[m - 1] != y[j + m - 1])
{
s = rcBc[y[j + m - 1], s];
j += s;
}
for (i = 1; i < m && j + h[i] < n && x[h[i]] == y[j + h[i]]; ++i)
;
if (j <= n - m && i >= m)
{
stopwatch.Stop();
searchTime = stopwatch.Elapsed.TotalMilliseconds;
return j + startIndex;
}
s = rcGs[i];
j += s;
}
stopwatch.Stop();
searchTime = stopwatch.Elapsed.TotalMilliseconds;
return -1;
}
public static List<int> Search(string pattern, string source)
{
char[] ptrn = pattern.ToCharArray(), y = source.ToCharArray();
char[] x = new char[ptrn.Length + 1];
Array.Copy(ptrn, 0, x, 0, ptrn.Length);
int i, j, s, m = ptrn.Length, n = y.Length;
List<int> result = new List<int>();
int[,] rcBc = new int[65536, x.Length];
int[] rcGs = new int[x.Length];
int[] h = new int[x.Length];
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
/* Preprocessing */
PreRc(x, ref h, ref rcBc, ref rcGs);
stopwatch.Stop();
preProcessTime = stopwatch.Elapsed.TotalMilliseconds;
stopwatch.Restart();
/* Searching */
j = 0;
s = m;
while (j <= n - m)
{
while (j <= n - m && x[m - 1] != y[j + m - 1])
{
s = rcBc[y[j + m - 1], s];
j += s;
}
for (i = 1; i < m && j + h[i] < n && x[h[i]] == y[j + h[i]]; ++i)
;
if (j <= n - m && i >= m)
result.Add(j);
s = rcGs[i];
j += s;
}
stopwatch.Stop();
searchTime = stopwatch.Elapsed.TotalMilliseconds;
return result;
}
private static void PreRc(char[] x, ref int[] h, ref int[,] rcBc, ref int[] rcGs)
{
int a, i, j, k, q, r = 0, s, m = (x.Length - 1);
int[] hmin = new int[x.Length];
int[] kmin = new int[x.Length];
int[] link = new int[x.Length];
int[] locc = new int[rcBc.GetLength(0)];
int[] rmin = new int[x.Length];
/* Computation of link and locc */
for (a = 0; a < locc.Length; ++a)
locc[a] = -1;
link[0] = -1;
for (i = 0; i < m - 1; ++i)
{
link[i + 1] = locc[x[i]];
locc[x[i]] = i;
}
/* Computation of rcBc */
for (a = 0; a < locc.Length; ++a)
for (s = 1; s <= m; ++s)
{
i = locc[a];
j = link[m - s];
while (i - j != s && j >= 0)
if (i - j > s)
i = link[i + 1];
else
j = link[j + 1];
while (i - j > s)
i = link[i + 1];
rcBc[a, s] = m - i - 1;
}
/* Computation of hmin */
k = 1;
i = m - 1;
while (k <= m)
{
while (i - k >= 0 && x[i - k] == x[i])
--i;
hmin[k] = i;
q = k + 1;
while (hmin[q - k] - (q - k) > i)
{
hmin[q] = hmin[q - k];
++q;
}
i += (q - k);
k = q;
if (i == m)
i = m - 1;
}
/* Computation of kmin */
for (i = 0; i < m; i++)
kmin[i] = 0;
for (k = m; k > 0; --k)
kmin[hmin[k]] = k;
/* Computation of rmin */
for (i = m - 1; i >= 0; --i)
{
if (hmin[i + 1] == i)
r = i + 1;
rmin[i] = r;
}
/* Computation of rcGs */
i = 1;
for (k = 1; k <= m; ++k)
if (hmin[k] != m - 1 && kmin[hmin[k]] == k)
{
h[i] = hmin[k];
rcGs[i++] = k;
}
i = m - 1;
for (j = m - 2; j >= 0; --j)
if (kmin[j] == 0)
{
h[i] = j;
rcGs[i--] = rmin[j];
}
rcGs[m] = rmin[0];
}
}
}
| 32.967914 | 113 | 0.332198 | [
"Unlicense"
] | erdincuzun/UzunExt | UzunExt/ESMAJ/StringSearch/ReverseColussi.cs | 6,167 | C# |
// This file was automatically generated and may be regenerated at any
// time. To ensure any changes are retained, modify the tool with any segment/component/group/field name
// or type changes.
namespace Machete.HL7Schema.V26.Maps
{
using V26;
/// <summary>
/// EHC_E01_PRODUCT_SERVICE_SECTION (GroupMap) -
/// </summary>
public class EHC_E01_PRODUCT_SERVICE_SECTIONMap :
HL7V26LayoutMap<EHC_E01_PRODUCT_SERVICE_SECTION>
{
public EHC_E01_PRODUCT_SERVICE_SECTIONMap()
{
Segment(x => x.PSS, 0, x => x.Required = true);
Layout(x => x.ProductServiceGroup, 1, x => x.Required = true);
}
}
} | 33.75 | 105 | 0.660741 | [
"Apache-2.0"
] | AreebaAroosh/Machete | src/Machete.HL7Schema/Generated/V26/Groups/Maps/EHC_E01_PRODUCT_SERVICE_SECTIONMap.cs | 675 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Carts.Carts.Events;
using Carts.Carts.ValueObjects;
using Core.Extensions;
using Marten.Events.Aggregation;
namespace Carts.Carts.Projections
{
public class CartDetails
{
public Guid Id { get; set; }
public Guid ClientId { get; set; }
public CartStatus Status { get; set; }
public IList<PricedProductItem> ProductItems { get; set; } = default!;
public decimal TotalPrice => ProductItems.Sum(pi => pi.TotalPrice);
public int Version { get; set; }
public void Apply(CartInitialized @event)
{
Version++;
Id = @event.CartId;
ClientId = @event.ClientId;
ProductItems = new List<PricedProductItem>();
Status = @event.CartStatus;
}
public void Apply(ProductAdded @event)
{
Version++;
var newProductItem = @event.ProductItem;
var existingProductItem = FindProductItemMatchingWith(newProductItem);
if (existingProductItem is null)
{
ProductItems.Add(newProductItem);
return;
}
ProductItems.Replace(
existingProductItem,
existingProductItem.MergeWith(newProductItem)
);
}
public void Apply(ProductRemoved @event)
{
Version++;
var productItemToBeRemoved = @event.ProductItem;
var existingProductItem = FindProductItemMatchingWith(@event.ProductItem);
if(existingProductItem == null)
return;
if (existingProductItem.HasTheSameQuantity(productItemToBeRemoved))
{
ProductItems.Remove(existingProductItem);
return;
}
ProductItems.Replace(
existingProductItem,
existingProductItem.Substract(productItemToBeRemoved)
);
}
public void Apply(CartConfirmed @event)
{
Version++;
Status = CartStatus.Confirmed;
}
private PricedProductItem? FindProductItemMatchingWith(PricedProductItem productItem)
{
return ProductItems
.SingleOrDefault(pi => pi.MatchesProductAndPrice(productItem));
}
}
public class CartDetailsProjection : AggregateProjection<CartDetails>
{
public CartDetailsProjection()
{
ProjectEvent<CartInitialized>((item, @event) => item.Apply(@event));
ProjectEvent<ProductAdded>((item, @event) => item.Apply(@event));
ProjectEvent<ProductRemoved>((item, @event) => item.Apply(@event));
ProjectEvent<CartConfirmed>((item, @event) => item.Apply(@event));
}
}
}
| 27.32381 | 93 | 0.584176 | [
"MIT"
] | XREvo/EventSourcing.NetCore | Sample/ECommerce/Carts/Carts/Carts/Projections/CartDetails.cs | 2,869 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210
{
using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions;
/// <summary>Input definition for test failover cleanup.</summary>
public partial class TestFailoverCleanupInput :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestFailoverCleanupInput,
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestFailoverCleanupInputInternal
{
/// <summary>Test failover cleanup comments.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Inlined)]
public string Comment { get => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestFailoverCleanupInputPropertiesInternal)Property).Comment; set => ((Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestFailoverCleanupInputPropertiesInternal)Property).Comment = value ?? null; }
/// <summary>Internal Acessors for Property</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestFailoverCleanupInputProperties Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestFailoverCleanupInputInternal.Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.TestFailoverCleanupInputProperties()); set { {_property = value;} } }
/// <summary>Backing field for <see cref="Property" /> property.</summary>
private Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestFailoverCleanupInputProperties _property;
/// <summary>Test failover cleanup input properties.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Origin(Microsoft.Azure.PowerShell.Cmdlets.Migrate.PropertyOrigin.Owned)]
internal Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestFailoverCleanupInputProperties Property { get => (this._property = this._property ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.TestFailoverCleanupInputProperties()); set => this._property = value; }
/// <summary>Creates an new <see cref="TestFailoverCleanupInput" /> instance.</summary>
public TestFailoverCleanupInput()
{
}
}
/// Input definition for test failover cleanup.
public partial interface ITestFailoverCleanupInput :
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.IJsonSerializable
{
/// <summary>Test failover cleanup comments.</summary>
[Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Info(
Required = false,
ReadOnly = false,
Description = @"Test failover cleanup comments.",
SerializedName = @"comments",
PossibleTypes = new [] { typeof(string) })]
string Comment { get; set; }
}
/// Input definition for test failover cleanup.
internal partial interface ITestFailoverCleanupInputInternal
{
/// <summary>Test failover cleanup comments.</summary>
string Comment { get; set; }
/// <summary>Test failover cleanup input properties.</summary>
Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.ITestFailoverCleanupInputProperties Property { get; set; }
}
} | 61.436364 | 392 | 0.735425 | [
"MIT"
] | AverageDesigner/azure-powershell | src/Migrate/generated/api/Models/Api20210210/TestFailoverCleanupInput.cs | 3,325 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using NexStar.Net.NexstarSupport.Internal;
namespace NexStar.Net.NexstarSupport.Commands
{
public class CheckGotoRunningCommand : NexStarCommand<bool>
{
public override bool TypedResult => Convert.ToBoolean(RawResultBytes[0]);
public override byte[] RenderCommandBytes()
{
return new byte[] { Convert.ToByte('L') };
}
}
}
| 24.888889 | 81 | 0.6875 | [
"MIT"
] | paranoidTwitch/StargazerConsole | NexStar.Net/NexstarSupport/Commands/CheckGotoRunningCommand.cs | 450 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Dlp.V2.Snippets
{
using Google.Cloud.Dlp.V2;
public sealed partial class GeneratedDlpServiceClientStandaloneSnippets
{
/// <summary>Snippet for CreateInspectTemplate</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void CreateInspectTemplateResourceNames3()
{
// Create client
DlpServiceClient dlpServiceClient = DlpServiceClient.Create();
// Initialize request argument(s)
OrganizationLocationName parent = OrganizationLocationName.FromOrganizationLocation("[ORGANIZATION]", "[LOCATION]");
InspectTemplate inspectTemplate = new InspectTemplate();
// Make the request
InspectTemplate response = dlpServiceClient.CreateInspectTemplate(parent, inspectTemplate);
}
}
}
| 40.425 | 128 | 0.701299 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/privacy/dlp/v2/google-cloud-privacy-dlp-v2-csharp/Google.Cloud.Dlp.V2.StandaloneSnippets/DlpServiceClient.CreateInspectTemplateResourceNames3Snippet.g.cs | 1,617 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace JJBookStore.Utility
{
public class MD5Util
{
static string key { get; set; } = "!esVsg0F0r@p*rt1E5";
public static string Encrypt(string text)
{
using (var md5 = new MD5CryptoServiceProvider())
{
using (var tdes = new TripleDESCryptoServiceProvider())
{
tdes.Key = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
using (var transform = tdes.CreateEncryptor())
{
byte[] textBytes = UTF8Encoding.UTF8.GetBytes(text);
byte[] bytes = transform.TransformFinalBlock(textBytes, 0, textBytes.Length);
return Convert.ToBase64String(bytes, 0, bytes.Length);
}
}
}
}
public static string Decrypt(string cipher)
{
using (var md5 = new MD5CryptoServiceProvider())
{
using (var tdes = new TripleDESCryptoServiceProvider())
{
tdes.Key = md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
using (var transform = tdes.CreateDecryptor())
{
byte[] cipherBytes = Convert.FromBase64String(cipher);
byte[] bytes = transform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
return UTF8Encoding.UTF8.GetString(bytes);
}
}
}
}
}
} | 36.09434 | 105 | 0.518035 | [
"MIT"
] | jonathanzz/JJBookStore | JJBookStore/Utility/MD5Util.cs | 1,915 | C# |
/*
* Copyright 2019 faddenSoft
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using Asm65;
using CommonUtil;
using TextScanMode = SourceGen.ProjectProperties.AnalysisParameters.TextScanMode;
namespace SourceGen {
/// <summary>
/// Auto-detection of structured data.
///
/// This class doesn't really hold any state. It's just a convenient place to collect
/// the items needed by the analyzer methods.
/// </summary>
public class DataAnalysis {
// Minimum number of consecutive identical bytes for something to be called a "run".
private const int MIN_RUN_LENGTH = 5;
// Minimum length for treating data as a run if the byte is a printable character.
// (Alternatively, the maximum length of a character string composed of a single value.)
// Anything shorter than this is handled with a string directive, anything this long or
// longer becomes FILL. This should be larger than the MinCharsForString parameter.
private const int MAX_STRING_RUN_LENGTH = 62;
// Absolute minimum string length for auto-detection. This is used when generating the
// data tables.
public const int MIN_STRING_LENGTH = 3;
// Minimum length for an ASCII string. Anything shorter is just output as bytes.
// This is the default value; the actual value is configured as a project preference.
public const int DEFAULT_MIN_STRING_LENGTH = 4;
// Set min chars to this to disable string detection.
public const int MIN_CHARS_FOR_STRING_DISABLED = int.MaxValue;
/// <summary>
/// Project with which we are associated.
/// </summary>
private DisasmProject mProject;
/// <summary>
/// Reference to 65xx data.
/// </summary>
private byte[] mFileData;
/// <summary>
/// Attributes, one per byte in input file.
/// </summary>
private Anattrib[] mAnattribs;
/// <summary>
/// Configurable parameters.
/// </summary>
private ProjectProperties.AnalysisParameters mAnalysisParams;
/// <summary>
/// Debug trace log.
/// </summary>
private DebugLog mDebugLog = new DebugLog(DebugLog.Priority.Silent);
public DebugLog DebugLog {
set {
mDebugLog = value;
}
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="proj">Project to analyze.</param>
/// <param name="anattribs">Anattrib array.</param>
public DataAnalysis(DisasmProject proj, Anattrib[] anattribs) {
mProject = proj;
mAnattribs = anattribs;
mFileData = proj.FileData;
mAnalysisParams = proj.ProjectProps.AnalysisParams;
}
// Internal log functions. If we're concerned about performance overhead due to
// call-site string concatenation, we can #ifdef these to nothing in release builds,
// which should allow the compiler to elide the concat.
#if false
private void LogV(int offset, string msg) {
if (mDebugLog.IsLoggable(DebugLog.Priority.Verbose)) {
mDebugLog.LogV("+" + offset.ToString("x6") + " " + msg);
}
}
#else
private void LogV(int offset, string msg) { }
#endif
private void LogD(int offset, string msg) {
if (mDebugLog.IsLoggable(DebugLog.Priority.Debug)) {
mDebugLog.LogD("+" + offset.ToString("x6") + " " + msg);
}
}
private void LogI(int offset, string msg) {
if (mDebugLog.IsLoggable(DebugLog.Priority.Info)) {
mDebugLog.LogI("+" + offset.ToString("x6") + " " + msg);
}
}
private void LogW(int offset, string msg) {
if (mDebugLog.IsLoggable(DebugLog.Priority.Warning)) {
mDebugLog.LogW("+" + offset.ToString("x6") + " " + msg);
}
}
private void LogE(int offset, string msg) {
if (mDebugLog.IsLoggable(DebugLog.Priority.Error)) {
mDebugLog.LogE("+" + offset.ToString("x6") + " " + msg);
}
}
/// <summary>
/// Analyzes instruction operands and Address data descriptors to identify references
/// to offsets within the file.
///
/// Instructions with format descriptors are left alone. Instructions with
/// operand offsets but no descriptor will have a descriptor generated
/// using the label at the target offset; if the target offset is unlabeled,
/// a unique label will be generated. Data descriptors with type=Address are
/// handled the same way.
///
/// In some cases, such as a reference to the middle of an instruction, we will
/// label a nearby location instead.
///
/// This should be called after code analysis has run, user labels and format
/// descriptors have been applied, and platform/project symbols have been merged
/// into the symbol table.
/// </summary>
/// <returns>True on success.</returns>
public void AnalyzeDataTargets() {
mDebugLog.LogI("Analyzing data targets...");
for (int offset = 0; offset < mAnattribs.Length; offset++) {
Anattrib attr = mAnattribs[offset];
if (attr.IsInstructionStart) {
if (attr.DataDescriptor != null) {
// It's being shown as numeric, or as a reference to some other symbol.
// Either way there's nothing further for us to do. (Technically we
// would want to treat it like the no-descriptor case if the type was
// numeric/Address, but we don't allow that for instructions.)
//
// Project and platform symbols are applied later.
Debug.Assert(attr.DataDescriptor.FormatSubType !=
FormatDescriptor.SubType.Address);
continue;
}
// Check for a relocation. It'll be at offset+1 because it's on the operand,
// not the opcode byte. (Make sure to check the length, or an RTS followed
// by relocated data will freak out.)
//
// We don't check for embedded instructions here. If that did somehow happen,
// it's probably intentional, so we should do the replacement.
//
// TODO(someday): this won't get the second byte of an MVN/MVP, which is fine
// since we don't currently support two formats on one instruction.
if (mAnalysisParams.UseRelocData) {
if (attr.Length > 1 && mProject.RelocList.TryGetValue(offset + 1,
out DisasmProject.RelocData reloc) &&
attr.Length > reloc.Width) {
// The relocation address differs from what the analyzer came up
// with. This may be because of incorrect assumptions about the
// bank (assuming B==K) or because the partial address refers to
// a location outside the file bounds. Whatever the case, if the
// address is different, attr.OperandOffset will also be different.
int relOperandOffset = mProject.AddrMap.AddressToOffset(offset,
reloc.Value);
if (relOperandOffset >= 0) {
// Determined a different offset. Use that instead.
//Debug.WriteLine("REL +" + offset.ToString("x6") + " " +
// reloc.Value.ToString("x6") + " vs. " +
// attr.OperandAddress.ToString("x6"));
WeakSymbolRef.Part part = ShiftToPart(reloc.Shift);
SetDataTarget(offset, attr.Length, relOperandOffset, part);
continue;
}
}
// No reloc for this instruction. If it's a relative branch we need
// to do the usual stuff, but if it's a PEA we want to treat it like
// an immediate value. It should also be safe and useful to halt
// processing for "LDA abs" and the like.
OpDef op = mProject.CpuDef.GetOpDef(mProject.FileData[offset]);
bool stopHere = false;
switch (op.AddrMode) {
case OpDef.AddressMode.StackAbs: // PEA
case OpDef.AddressMode.Abs: // technically just non-PBR
case OpDef.AddressMode.AbsIndexX:
case OpDef.AddressMode.AbsIndexY:
stopHere = true;
break;
// AbsIndexXInd, AbsInd, AbsIndLong look like absolute addresses
// but use the program bank or bank 0. They're unambiguous even
// without reloc data, so no need to block them. That also goes
// for long addressing: ideally they'd have reloc data, but even if
// they don't, we might as well hook up a symbol because they can't
// mean anything else. (I think.)
}
if (stopHere) {
continue;
}
}
int operandOffset = attr.OperandOffset;
if (operandOffset >= 0) {
// This is an offset reference: a branch or data access instruction
// whose target is inside the file. Create a FormatDescriptor for it,
// and generate a label at the target if one is not already present.
SetDataTarget(offset, attr.Length, operandOffset, WeakSymbolRef.Part.Low);
}
// We advance by a single byte, rather than .Length, in case there's
// an instruction embedded inside another one.
} else if (attr.DataDescriptor != null) {
// We can't check IsDataStart / IsInlineDataStart because the bytes might
// still be uncategorized. If there's a user-specified format, check it
// to see if it's an address.
FormatDescriptor dfd = attr.DataDescriptor;
// Is this numeric/Address?
if ((dfd.FormatType == FormatDescriptor.Type.NumericLE ||
dfd.FormatType == FormatDescriptor.Type.NumericBE) &&
dfd.FormatSubType == FormatDescriptor.SubType.Address) {
// Treat like an absolute address. Convert the operand
// to an address, then resolve the file offset.
int address = RawData.GetWord(mFileData, offset, dfd.Length,
(dfd.FormatType == FormatDescriptor.Type.NumericBE));
if (dfd.Length < 3) {
// Bank not specified by data, add current program bank. Not always
// correct, but should be often enough. In most cases we'd just
// assume a correct data bank register, but here we need to find
// a file offset, so we have to assume data bank == program bank
// (unless we find a good way to track the data bank register).
address |= attr.Address & 0x7fff0000;
}
int operandOffset = mProject.AddrMap.AddressToOffset(offset, address);
if (operandOffset >= 0) {
SetDataTarget(offset, dfd.Length, operandOffset,
WeakSymbolRef.Part.Low);
}
}
// For other formats, we don't need to do anything. Numeric/Address is
// the only one that represents an offset reference. Numeric/Symbol
// is a name reference. The others are just data.
// There shouldn't be any data items inside other data items, so we
// can just skip forward.
offset += mAnattribs[offset].DataDescriptor.Length - 1;
} else if (mAnalysisParams.UseRelocData && attr.IsUntyped &&
mProject.RelocList.TryGetValue(offset,
out DisasmProject.RelocData reloc)) {
// Byte is unformatted, but there's relocation data here. If the full
// range of bytes is unformatted and unlabeled, create a symbolic reference.
// TODO: we can do better here when a multi-byte reloc has an auto-generated
// label mid-way through: create multiple, smaller formats for the same sym.
// Or don't generate auto labels until all reloc-based formats are placed.
bool allClear = true;
for (int i = 1; i < reloc.Width; i++) {
if (!mAnattribs[offset + i].IsUntyped ||
mAnattribs[offset + i].DataDescriptor != null ||
mAnattribs[offset + i].Symbol != null) {
allClear = false;
break;
}
}
if (allClear) {
int operandOffset = mProject.AddrMap.AddressToOffset(offset, reloc.Value);
if (operandOffset >= 0) {
//Debug.WriteLine("DREL +" + offset.ToString("x6") + " val=" +
// reloc.Value.ToString("x6") +
// " opOff=" + operandOffset.ToString("x6"));
SetDataTarget(offset, reloc.Width, operandOffset,
ShiftToPart(reloc.Shift));
}
}
}
}
}
private static WeakSymbolRef.Part ShiftToPart(int shift) {
if (shift == -16) {
return WeakSymbolRef.Part.Bank;
} else if (shift == -8) {
return WeakSymbolRef.Part.High;
} else {
return WeakSymbolRef.Part.Low;
}
}
/// <summary>
/// Extracts the operand offset from a data item. Only useful for numeric/Address
/// and numeric/Symbol.
/// </summary>
/// <param name="proj">Project reference.</param>
/// <param name="offset">Offset of data item.</param>
/// <returns>Operand offset, or -1 if not applicable.</returns>
public static int GetDataOperandOffset(DisasmProject proj, int offset) {
Anattrib attr = proj.GetAnattrib(offset);
if (!attr.IsDataStart && !attr.IsInlineDataStart) {
return -1;
}
FormatDescriptor dfd = attr.DataDescriptor;
// Is this numeric/Address or numeric/Symbol?
if ((dfd.FormatType != FormatDescriptor.Type.NumericLE &&
dfd.FormatType != FormatDescriptor.Type.NumericBE) ||
(dfd.FormatSubType != FormatDescriptor.SubType.Address &&
dfd.FormatSubType != FormatDescriptor.SubType.Symbol)) {
return -1;
}
// Treat like an absolute address. Convert the operand
// to an address, then resolve the file offset.
int address = RawData.GetWord(proj.FileData, offset, dfd.Length,
(dfd.FormatType == FormatDescriptor.Type.NumericBE));
if (dfd.Length < 3) {
// Add the program bank where the data bank should go. Not perfect but
// we don't have anything better at the moment.
address |= attr.Address & 0x7fff0000;
}
int operandOffset = proj.AddrMap.AddressToOffset(offset, address);
return operandOffset;
}
/// <summary>
/// Returns the "base" operand offset. If the byte at the specified offset is not the
/// start of a code/data/inline-data item, walk backward until the start is found.
/// </summary>
/// <param name="proj">Project reference.</param>
/// <param name="offset">Start offset.</param>
/// <returns>Base offset.</returns>
public static int GetBaseOperandOffset(DisasmProject proj, int offset) {
Debug.Assert(offset >= 0 && offset < proj.FileDataLength);
while (!proj.GetAnattrib(offset).IsStart) {
offset--;
// Should not be possible to walk off the top of the list, since we're in
// the middle of something.
Debug.Assert(offset >= 0);
}
return offset;
}
/// <summary>
/// Creates a FormatDescriptor in the Anattrib array at srcOffset that links to
/// targetOffset, or a nearby label. If targetOffset doesn't have a useful label,
/// one will be generated.
///
/// This is used for both instruction and data operands.
/// </summary>
/// <param name="srcOffset">Offset of instruction or address data.</param>
/// <param name="srcLen">Length of instruction or data item.</param>
/// <param name="targetOffset">Offset of target.</param>
private void SetDataTarget(int srcOffset, int srcLen, int targetOffset,
WeakSymbolRef.Part part) {
// NOTE: don't try to cache mAnattribs[targetOffset] -- we may be changing
// targetOffset and/or altering the Anattrib entry, so grabbing a copy of the
// struct may lead to problems.
// If the target offset has a symbol assigned, use it. Otherwise, try to
// find something nearby that might be more appropriate.
int origTargetOffset = targetOffset;
if (mAnattribs[targetOffset].Symbol is null) {
if (mAnalysisParams.SeekNearbyTargets) {
targetOffset = FindAlternateTarget(srcOffset, targetOffset);
}
// If we're not interested in seeking nearby targets, or we are but we failed
// to find something useful, we need to make sure that we're not pointing
// into the middle of the instruction. The assembler will only see labels on
// the opcode bytes, so if we're pointing at the middle we need to back up.
if (mAnattribs[targetOffset].IsInstruction &&
!mAnattribs[targetOffset].IsInstructionStart) {
while (!mAnattribs[--targetOffset].IsInstructionStart) {
// Should not be possible to move past the start of the file,
// since we know we're in the middle of an instruction.
Debug.Assert(targetOffset > 0);
}
} else if (!mAnattribs[targetOffset].IsInstruction &&
!mAnattribs[targetOffset].IsStart) {
// This is not part of an instruction, and is not the start of a formatted
// data area. However, it might be part of a formatted data area, in which
// case we need to avoid creating an auto label in the middle. So we seek
// backward, looking for the first offset with a descriptor. If that
// descriptor includes this offset, we set the target offset to that.
// (Note the uncategorized data pass hasn't run yet, so only instructions
// and offsets identified by users or scripts have been categorized.)
//
// ?? Can we use GetBaseOperandOffset(), which searches for IsStart?
//
// TODO(performance): we spend a significant amount of time in this loop.
int scanOffset = targetOffset;
while (--scanOffset >= 0) {
FormatDescriptor dfd = mAnattribs[scanOffset].DataDescriptor;
if (!(dfd is null)) {
if (scanOffset + dfd.Length > targetOffset) {
// Found a descriptor that encompasses target offset. Adjust
// target to point at the start of the region.
targetOffset = scanOffset;
}
// Descriptors aren't allowed to overlap, so either way we're done.
break;
}
}
}
}
if (mAnattribs[targetOffset].Symbol == null) {
// No label at target offset, generate one.
//
// Generally speaking, the label we generate will be unique, because it
// incorporates the address. It's possible through various means to end
// up with a user or platform label that matches an auto label, so we
// need to do some renaming in that case. Shouldn't happen often.
Symbol sym = AutoLabel.GenerateUniqueForAddress(mAnattribs[targetOffset].Address,
mProject.SymbolTable, "L");
mAnattribs[targetOffset].Symbol = sym;
// This will throw if the symbol already exists. That is the desired
// behavior, as that would be a bug.
mProject.SymbolTable.Add(sym);
}
// Create a Numeric/Symbol descriptor that references the target label. If the
// source offset already had a descriptor (e.g. Numeric/Address data item),
// this will replace it in the Anattrib array. (The user-specified format
// is unaffected.)
//
// Doing this by target symbol, rather than offset in a Numeric/Address item,
// allows us to avoid carrying the adjustment stuff everywhere. OTOH we have
// to manually refactor label renames in the display list if we don't want to
// redo the data analysis.
bool isBigEndian = false;
if (mAnattribs[srcOffset].DataDescriptor != null) {
LogD(srcOffset, "Replacing " + mAnattribs[srcOffset].DataDescriptor +
" with reference to " + mAnattribs[targetOffset].Symbol.Label +
", adj=" + (origTargetOffset - targetOffset));
if (mAnattribs[srcOffset].DataDescriptor.FormatType ==
FormatDescriptor.Type.NumericBE) {
isBigEndian = true;
}
} else {
LogV(srcOffset, "Creating weak reference to label " +
mAnattribs[targetOffset].Symbol.Label +
", adj=" + (origTargetOffset - targetOffset));
}
mAnattribs[srcOffset].DataDescriptor = FormatDescriptor.Create(srcLen,
new WeakSymbolRef(mAnattribs[targetOffset].Symbol.Label, part), isBigEndian);
}
/// <summary>
/// Given a reference from srcOffset to targetOffset, check to see if there's a
/// nearby location that we'd prefer to refer to. For example, if targetOffset points
/// into the middle of an instruction, we'd rather have it refer to the first byte.
/// </summary>
/// <param name="srcOffset">Reference source.</param>
/// <param name="targetOffset">Reference target.</param>
/// <returns>New value for targetOffset, or original value if nothing better was
/// found.</returns>
private int FindAlternateTarget(int srcOffset, int targetOffset) {
int origTargetOffset = targetOffset;
// Is the target outside the instruction stream? If it's just referencing data,
// do a simple check and move on.
if (!mAnattribs[targetOffset].IsInstruction) {
// We want to use user-defined labels whenever possible. If they're accessing
// memory within a few bytes, use that. We don't want to do this for
// code references, though, or our branches will get all weird.
//
// We look a few back and one forward. Stuff backward (which turns into
// LABEL+N) has priority over forward (which becomes LABEL-N).
//
// TODO(someday): make parameters user-configurable?
const int MAX_FWD = 1;
const int MAX_BACK = 3;
int probeOffset = targetOffset;
bool back = true;
while (true) {
if (back) {
// moving backward
probeOffset--;
if (probeOffset < 0 || probeOffset < targetOffset - MAX_BACK) {
// too far back, reverse direction
probeOffset = targetOffset;
back = false;
}
}
if (!back) {
// moving forward
probeOffset++;
if (probeOffset >= mAnattribs.Length ||
probeOffset > targetOffset + MAX_FWD) {
break; // done
}
}
Symbol sym = mAnattribs[probeOffset].Symbol;
if (sym != null && sym.SymbolSource == Symbol.Source.User) {
// Found a nearby user label. Make sure it's actually nearby.
int addrDiff = mAnattribs[targetOffset].Address -
mAnattribs[probeOffset].Address;
if (addrDiff == targetOffset - probeOffset) {
targetOffset = probeOffset;
break;
} else {
Debug.WriteLine("NOT probing past address boundary change (src=+" +
srcOffset.ToString("x6") +
" targ=+" + targetOffset.ToString("x6") +
" probe=+" + probeOffset.ToString("x6") + ")");
// No point in continuing to search this direction, but we might
// need to look the other way.
if (back) {
probeOffset = targetOffset;
back = false;
} else {
break;
}
}
}
}
return targetOffset;
}
// Target is an instruction. Is the source an instruction or data element
// (e.g. ".dd2 <addr>").
if (!mAnattribs[srcOffset].IsInstructionStart) {
// Might be address-1 to set up an RTS. If the target address isn't
// an instruction start, check to see if the following byte is.
if (!mAnattribs[targetOffset].IsInstructionStart &&
targetOffset + 1 < mAnattribs.Length &&
mAnattribs[targetOffset + 1].IsInstructionStart) {
LogD(srcOffset, "Offsetting address reference");
targetOffset++;
}
return targetOffset;
}
// Source is an instruction, so we have an instruction referencing an instruction.
// Could be a branch, an address push, or self-modifying code.
OpDef op = mProject.CpuDef.GetOpDef(mProject.FileData[srcOffset]);
if (op.IsBranchOrSubCall) {
// Don't mess with jumps and branches -- always go directly to the
// target address.
} else if (op == OpDef.OpPEA_StackAbs || op == OpDef.OpPER_StackPCRelLong) {
// They might be pushing address-1 to set up an RTS. If the target address isn't
// an instruction start, check to see if the following byte is.
if (!mAnattribs[targetOffset].IsInstructionStart &&
targetOffset + 1 < mAnattribs.Length &&
mAnattribs[targetOffset + 1].IsInstructionStart) {
LogD(srcOffset, "Offsetting PEA/PER");
targetOffset++;
}
} else {
// Data operation (LDA, STA, etc). This could be self-modifying code, or
// an indexed access with an offset base address (LDA addr-1,Y) to an
// adjacent data area. Check to see if there's data right after this.
bool nearbyData = false;
for (int i = targetOffset + 1; i <= targetOffset + 2; i++) {
if (i < mAnattribs.Length && !mAnattribs[i].IsInstruction) {
targetOffset = i;
nearbyData = true;
break;
}
}
if (!nearbyData && !mAnattribs[targetOffset].IsInstructionStart) {
// There's no data nearby, and the target is not the start of the
// instruction, so this is probably self-modifying code. We want
// the label to be on the opcode, so back up to the instruction start.
while (!mAnattribs[--targetOffset].IsInstructionStart) {
// Should not be possible to move past the start of the file,
// since we know we're in the middle of an instruction.
Debug.Assert(targetOffset > 0);
}
}
}
if (targetOffset != origTargetOffset) {
LogV(srcOffset, "Creating instruction ref adj=" +
(origTargetOffset - targetOffset));
}
return targetOffset;
}
/// <summary>
/// Analyzes uncategorized regions of the file to see if they fit common patterns.
///
/// This is re-run after most changes to the project, so we don't want to do anything
/// crazily expensive.
/// </summary>
/// <returns>True on success.</returns>
public void AnalyzeUncategorized() {
FormatDescriptor oneByteDefault = FormatDescriptor.Create(1,
FormatDescriptor.Type.Default, FormatDescriptor.SubType.None);
FormatDescriptor.DebugPrefabBump(-1);
// If it hasn't been identified as code or data, set the "data" flag to
// give it a positive identification as data. (This should be the only
// place outside of CodeAnalysis that sets this flag.) This isn't strictly
// necessary, but it helps us assert things when pieces start moving around.
for (int offset = 0; offset < mAnattribs.Length; offset++) {
Anattrib attr = mAnattribs[offset];
if (attr.IsInlineData) {
// While we're here, add a default format descriptor for inline data
// that doesn't have one. We don't try to analyze it otherwise.
if (attr.DataDescriptor == null) {
mAnattribs[offset].DataDescriptor = oneByteDefault;
FormatDescriptor.DebugPrefabBump();
}
} else if (!attr.IsInstruction) {
mAnattribs[offset].IsData = true;
}
}
mDebugLog.LogI("Analyzing uncategorized data...");
int startOffset = -1;
for (int offset = 0; offset < mAnattribs.Length; ) {
// We want to find a contiguous series of offsets which are not known
// to hold code or data. We stop if we encounter a user-defined label,
// format descriptor, or address override.
Anattrib attr = mAnattribs[offset];
if (attr.IsInstruction || attr.IsInlineData || attr.IsDataStart) {
// Instruction, inline data, or formatted data known to be here. Analyze
// previous chunk, then advance past this.
if (startOffset >= 0) {
AnalyzeRange(startOffset, offset - 1);
startOffset = -1;
}
if (attr.IsInstruction) {
// Because of embedded instructions, we can't simply leap forward.
// [or can we?]
offset++;
} else {
Debug.Assert(attr.Length > 0);
offset += attr.Length;
}
} else if (attr.Symbol != null || mProject.HasCommentNoteOrVis(offset)) {
// In an uncategorized area, but we want to break at this byte
// so the user or auto label doesn't get buried in the middle of
// a large chunk.
//
// This is similar to, but independent of, GroupedOffsetSetFromSelected()
// in ProjectView. This is for auto-detection, the other is for user
// selection. It's best if the two behave similarly though.
if (startOffset >= 0) {
AnalyzeRange(startOffset, offset - 1);
}
startOffset = offset;
offset++;
} else {
// This offset is uncategorized, keep gathering.
if (startOffset < 0) {
startOffset = offset;
}
offset++;
// Check to see if we just crossed an address change.
if (offset < mAnattribs.Length &&
!mProject.AddrMap.IsSingleAddrRange(offset - 1, 2)) {
// Must be an ORG here. End region and scan.
AnalyzeRange(startOffset, offset - 1);
startOffset = -1;
}
}
}
// Do the last bit.
if (startOffset >= 0) {
AnalyzeRange(startOffset, mAnattribs.Length - 1);
}
}
/// <summary>
/// Analyzes a range of bytes, looking for opportunities to promote uncategorized
/// data to a more structured form.
/// </summary>
/// <param name="start">Offset of first byte in range.</param>
/// <param name="end">Offset of last byte in range.</param>
private void AnalyzeRange(int start, int end) {
// We want to identify runs of identical bytes, and runs of more than N human-
// readable characters (ASCII, high ASCII, PETSCII, whatever). There are a few
// ways to do this.
//
// The simple approach is to walk through the data from start to end, checking at
// each offset for runs of bytes matching the criteria. Because the data doesn't
// change, we can pre-analyze the data at project load time to speed things up.
//
// One approach is to put runs into TypedRangeSet (setting the type to the byte
// value so a run of 0x00 doesn't merge into an adjacent run of 0x01), and the
// various character encodings into individual RangeSets. Then, for any given
// byte address, you can query the length of a potential run directly. This could
// be made faster with a mergesort-like algorithm that walked through the various
// range sets, rather than iterating over every byte in the range. However, the
// ranges passed into this method tend to be small, so the initial setup time for
// each region can dominate the performance. (The optimized implementation of this
// approach is also fairly complicated.)
//
// A memory-hungry alternative is to create arrays of integers, one entry per byte
// in the file, and set each entry to the number of bytes in the run that would
// follow at that point. So if a run of 20 zeroes began at off set 5, you would
// set run[5]=20, run[6]=19, and so on. That avoids searching in the sets, at the
// cost of potentially several megabytes for a large 65816 file.
//
// It's even possible that Regex would handle this faster and more easily. This
// can be done fairly quickly with "unsafe" code, e.g.:
// https://stackoverflow.com/questions/3028768/net-regular-expressions-on-bytes-instead-of-chars
// https://stackoverflow.com/questions/1660694/regular-expression-to-match-any-character-being-repeated-more-than-10-times
//
// Ultimately we're just not spending that much time here. Setting
// AnalyzeUncategorizedData=false reveals that most of the time is spent in
// the caller, identifying the regions, so a significant improvement here won't
// have much impact on the user experience.
//
// Vague idea: figure out how to re-use the results from the previous analysis
// pass. At a superficial level we can cache the result of calling here with a
// particular (start, end) pair. At a higher level we may be able to avoid
// the search for uncategorized data, certainly at the bank level, possibly within
// a bank.
mDebugLog.LogI("Analyzing [+" + start.ToString("x6") + ",+" + end.ToString("x6") +"]");
FormatDescriptor oneByteDefault = FormatDescriptor.Create(1,
FormatDescriptor.Type.Default, FormatDescriptor.SubType.None);
FormatDescriptor.DebugPrefabBump(-1);
if (!mAnalysisParams.AnalyzeUncategorizedData) {
// Analysis is disabled, so just mark everything as single-byte data.
while (start <= end) {
mAnattribs[start].DataDescriptor = oneByteDefault;
FormatDescriptor.DebugPrefabBump();
start++;
}
return;
}
int minStringChars = mAnalysisParams.MinCharsForString;
#if DATA_PRESCAN // this is actually slower (and uses more memory)
while (start <= end) {
// This is used to let us skip forward. It starts past the end of the block,
// and moves backward as we identify potential points of interest.
int minNextStart = end + 1;
bool found = mProject.RepeatedBytes.GetContainingOrSubsequentRange(start,
out TypedRangeSet.TypedRange tyRange);
if (found) {
if (tyRange.Low <= start) {
// found a matching range
Debug.Assert(tyRange.Low <= start && tyRange.High >= start);
int clampEnd = Math.Min(tyRange.High, end);
int repLen = clampEnd - start + 1;
if (repLen >= MIN_RUN_LENGTH) {
bool isAscii =
TextUtil.IsPrintableAscii((char)(mFileData[start] & 0x7f));
// IF the run isn't ASCII, OR it's so long that we don't want to
// encode it as a string, OR it's so short that we don't want to
// treat it as a string, THEN output it as a run. Otherwise, just
// let the ASCII-catcher handle it later.
if (!isAscii ||
repLen > MIN_RUN_LENGTH_ASCII || repLen < minStringChars) {
LogV(start, "Run of 0x" + mFileData[start].ToString("x2") + ": " +
repLen + " bytes");
mAnattribs[start].DataDescriptor = FormatDescriptor.Create(
repLen, FormatDescriptor.Type.Fill,
FormatDescriptor.SubType.None);
start += repLen;
continue;
}
}
// We didn't like this range. We probably won't like it for any other
// point within the range, so start again past it. Ideally we'd use
// Range.Low of the range that followed the one that was returned, but
// we don't have that handy.
minNextStart = Math.Min(minNextStart, tyRange.High + 1);
} else {
// no match; try to advance to the start of the next range.
Debug.Assert(tyRange.Low > start);
minNextStart = Math.Min(minNextStart, tyRange.Low);
}
}
found = mProject.StdAsciiBytes.GetContainingOrSubsequentRange(start,
out RangeSet.Range range);
if (found) {
if (range.Low <= start) {
// found a matching range
Debug.Assert(range.Low <= start && range.High >= start);
int clampEnd = Math.Min(range.High, end);
int repLen = clampEnd - start + 1;
if (repLen >= minStringChars) {
LogV(start, "Std ASCII string, len=" + repLen + " bytes");
mAnattribs[start].DataDescriptor = FormatDescriptor.Create(repLen,
FormatDescriptor.Type.String, FormatDescriptor.SubType.None);
start += repLen;
continue;
}
minNextStart = Math.Min(minNextStart, range.High + 1);
} else {
Debug.Assert(range.Low > start);
minNextStart = Math.Min(minNextStart, range.Low);
}
}
found = mProject.HighAsciiBytes.GetContainingOrSubsequentRange(start,
out range);
if (found) {
if (range.Low <= start) {
// found a matching range
Debug.Assert(range.Low <= start && range.High >= start);
int clampEnd = Math.Min(range.High, end);
int repLen = clampEnd - start + 1;
if (repLen >= minStringChars) {
LogV(start, "High ASCII string, len=" + repLen + " bytes");
mAnattribs[start].DataDescriptor = FormatDescriptor.Create(repLen,
FormatDescriptor.Type.String, FormatDescriptor.SubType.None);
start += repLen;
continue;
}
minNextStart = Math.Min(minNextStart, range.High + 1);
} else {
Debug.Assert(range.Low > start);
minNextStart = Math.Min(minNextStart, range.Low);
}
}
// Advance to the next possible run location.
int nextStart = minNextStart > 0 ? minNextStart : start + 1;
Debug.Assert(nextStart > start);
// No runs found, output as single bytes. This is the easiest form for users
// to edit.
while (start < nextStart) {
mAnattribs[start].DataDescriptor = oneByteDefault;
FormatDescriptor.DebugPrefabBump();
start++;
}
}
#else
// Select "is printable" test. We use the extended version to include some
// control characters.
// TODO(maybe): require some *actually* printable characters in each string
CharEncoding.InclusionTest testPrintable;
FormatDescriptor.SubType baseSubType;
switch (mAnalysisParams.DefaultTextScanMode) {
case TextScanMode.LowAscii:
testPrintable = CharEncoding.IsExtendedAscii;
baseSubType = FormatDescriptor.SubType.Ascii;
break;
case TextScanMode.LowHighAscii:
testPrintable = CharEncoding.IsExtendedLowOrHighAscii;
baseSubType = FormatDescriptor.SubType.ASCII_GENERIC;
break;
case TextScanMode.C64Petscii:
testPrintable = CharEncoding.IsExtendedC64Petscii;
baseSubType = FormatDescriptor.SubType.C64Petscii;
break;
case TextScanMode.C64ScreenCode:
testPrintable = CharEncoding.IsExtendedC64ScreenCode;
baseSubType = FormatDescriptor.SubType.C64Screen;
break;
default:
Debug.Assert(false);
testPrintable = CharEncoding.IsExtendedLowOrHighAscii;
baseSubType = FormatDescriptor.SubType.ASCII_GENERIC;
break;
}
while (start <= end) {
// Check for block of repeated values.
int runLen = RecognizeRun(mFileData, start, end);
int printLen = 0;
FormatDescriptor.SubType subType = baseSubType;
if (testPrintable(mFileData[start])) {
// The run byte is printable, and the run is shorter than a line. It's
// possible the run is followed by additional printable characters, e.g.
// "*****hello". Text is easier for humans to understand, so we prefer
// that unless the run is longer than one line.
if (runLen <= MAX_STRING_RUN_LENGTH) {
// See if the run is followed by additional printable characters.
printLen = runLen;
// For LowHighAscii we allow a string to be either low or high, but it
// must be entirely one thing. Refine our test.
CharEncoding.InclusionTest refinedTest = testPrintable;
if (mAnalysisParams.DefaultTextScanMode == TextScanMode.LowHighAscii) {
if (CharEncoding.IsExtendedAscii(mFileData[start])) {
refinedTest = CharEncoding.IsExtendedAscii;
subType = FormatDescriptor.SubType.Ascii;
} else {
refinedTest = CharEncoding.IsExtendedHighAscii;
subType = FormatDescriptor.SubType.HighAscii;
}
}
for (int i = start + runLen; i <= end; i++) {
if (!refinedTest(mFileData[i])) {
break;
}
printLen++;
}
}
}
if (printLen >= minStringChars) {
// This either a short run followed by printable characters, or just a
// (possibly very large) bunch of printable characters.
Debug.Assert(subType != FormatDescriptor.SubType.ASCII_GENERIC);
LogD(start, "Character string (" + subType + "), len=" + printLen + " bytes");
mAnattribs[start].DataDescriptor = FormatDescriptor.Create(printLen,
FormatDescriptor.Type.StringGeneric, subType);
start += printLen;
} else if (runLen >= MIN_RUN_LENGTH) {
// Didn't qualify as a string, but it's long enough to be a run.
//
// TODO(someday): allow .fill pseudo-ops to have character encoding
// sub-types, so we can ".fill 64,'*'". Easy to do here, but
// proper treatment requires tweaking data operand editor to allow
// char encoding to be specified.
LogV(start, "Run of 0x" + mFileData[start].ToString("x2") + ": " +
runLen + " bytes");
mAnattribs[start].DataDescriptor = FormatDescriptor.Create(
runLen, FormatDescriptor.Type.Fill,
FormatDescriptor.SubType.None);
start += runLen;
} else {
// Nothing useful found, output 1+ values as single bytes. This is the
// easiest form for users to edit. If we found a run, but it was too short,
// we can go ahead and mark all bytes in the run because we know the later
// matches will also be too short.
Debug.Assert(runLen > 0);
while (runLen-- != 0) {
mAnattribs[start++].DataDescriptor = oneByteDefault;
FormatDescriptor.DebugPrefabBump();
}
}
}
#endif
}
#region Static analyzer methods
/// <summary>
/// Checks for a repeated run of the same byte.
/// </summary>
/// <param name="fileData">Raw data.</param>
/// <param name="start">Offset of first byte in range.</param>
/// <param name="end">Offset of last byte in range.</param>
/// <returns>Length of run.</returns>
public static int RecognizeRun(byte[] fileData, int start, int end) {
byte first = fileData[start];
int index = start;
while (++index <= end) {
if (fileData[index] != first) {
break;
}
}
return index - start;
}
/// <summary>
/// Counts the number of low-ASCII, high-ASCII, and non-ASCII values in the
/// specified region.
/// </summary>
/// <param name="fileData">Raw data.</param>
/// <param name="start">Offset of first byte in range.</param>
/// <param name="end">Offset of last byte in range</param>
/// <param name="charTest">Character test delegate. Must match on both high and
/// low characters.</param>
/// <param name="lowVal">Set to the number of low-range characters found.</param>
/// <param name="highVal">Set to the number of high-range characters found.</param>
/// <param name="nonChar">Set to the number of non-character bytes found.</param>
public static void CountHighLowBytes(byte[] fileData, int start, int end,
CharEncoding.InclusionTest charTest,
out int lowVal, out int highVal, out int nonChar) {
lowVal = highVal = nonChar = 0;
for (int i = start; i <= end; i++) {
byte val = fileData[i];
if (!charTest(val)) {
nonChar++;
} else if ((val & 0x80) == 0) {
lowVal++;
} else {
highVal++;
}
}
}
/// <summary>
/// Counts the number of bytes that match the character test.
/// </summary>
/// <param name="fileData">Raw data.</param>
/// <param name="start">Offset of first byte in range.</param>
/// <param name="end">Offset of last byte in range.</param>
/// <param name="charTest">Character test delegate.</param>
/// <returns>Number of matching characters.</returns>
public static int CountCharacterBytes(byte[] fileData, int start, int end,
CharEncoding.InclusionTest charTest) {
int count = 0;
for (int i = start; i <= end; i++) {
if (charTest(fileData[i])) {
count++;
}
}
return count;
}
/// <summary>
/// Counts the number of null-terminated strings in the buffer.
///
/// Zero-length strings are allowed but not included in the count.
///
/// If any bad data is found, the scan aborts and returns -1.
/// </summary>
/// <param name="fileData">Raw data.</param>
/// <param name="start">Offset of first byte in range.</param>
/// <param name="end">Offset of last byte in range.</param>
/// <param name="charTest">Character test delegate.</param>
/// <param name="limitHiBit">If set, the high bit in all character must be the
/// same. Used to enforce a single encoding when "low or high ASCII" is used.</param>
/// <returns>Number of strings found, or -1 if bad data identified.</returns>
public static int RecognizeNullTerminatedStrings(byte[] fileData, int start, int end,
CharEncoding.InclusionTest charTest, bool limitHiBit) {
// Quick test.
if (fileData[end] != 0x00) {
return -1;
}
int stringCount = 0;
int expectedHiBit = -1;
int stringLen = 0;
for (int i = start; i <= end; i++) {
byte val = fileData[i];
if (val == 0x00) {
// End of string. Only update count if string wasn't empty.
if (stringLen != 0) {
stringCount++;
}
stringLen = 0;
expectedHiBit = -1;
} else {
if (limitHiBit) {
if (expectedHiBit == -1) {
// First byte in string, set hi/lo expectation.
expectedHiBit = val & 0x80;
} else if ((val & 0x80) != expectedHiBit) {
// Mixed ASCII or non-ASCII, fail.
return -1;
}
}
if (!charTest(val)) {
// Not a matching character, fail.
return -1;
}
stringLen++;
}
}
return stringCount;
}
/// <summary>
/// Counts strings prefixed with an 8-bit length.
///
/// Zero-length strings are allowed but not counted.
/// </summary>
/// <param name="fileData">Raw data.</param>
/// <param name="start">Offset of first byte in range.</param>
/// <param name="end">Offset of last byte in range.</param>
/// <param name="charTest">Character test delegate.</param>
/// <param name="limitHiBit">If set, the high bit in all character must be the
/// same. Used to enforce a single encoding when "low or high ASCII" is used.</param>
/// <returns>Number of strings found, or -1 if bad data identified.</returns>
public static int RecognizeLen8Strings(byte[] fileData, int start, int end,
CharEncoding.InclusionTest charTest, bool limitHiBit) {
int posn = start;
int remaining = end - start + 1;
int stringCount = 0;
while (remaining > 0) {
int strLen = fileData[posn++];
if (strLen > --remaining) {
// Buffer doesn't hold entire string, fail.
return -1;
}
if (strLen == 0) {
continue;
}
stringCount++;
remaining -= strLen;
int expectedHiBit = fileData[posn] & 0x80;
while (strLen-- != 0) {
byte val = fileData[posn++];
if (limitHiBit && (val & 0x80) != expectedHiBit) {
// Mixed ASCII, fail.
return -1;
}
if (!charTest(val)) {
// Not a matching character, fail.
return -1;
}
}
}
return stringCount;
}
/// <summary>
/// Counts strings prefixed with a 16-bit length.
///
/// Zero-length strings are allowed but not counted.
/// </summary>
/// <param name="fileData">Raw data.</param>
/// <param name="start">Offset of first byte in range.</param>
/// <param name="end">Offset of last byte in range.</param>
/// <param name="charTest">Character test delegate.</param>
/// <param name="limitHiBit">If set, the high bit in all character must be the
/// same. Used to enforce a single encoding when "low or high ASCII" is used.</param>
/// <returns>Number of strings found, or -1 if bad data identified.</returns>
public static int RecognizeLen16Strings(byte[] fileData, int start, int end,
CharEncoding.InclusionTest charTest, bool limitHiBit) {
int posn = start;
int remaining = end - start + 1;
int stringCount = 0;
while (remaining > 0) {
if (remaining < 2) {
// Not enough bytes for length, fail.
return -1;
}
int strLen = fileData[posn++];
strLen |= fileData[posn++] << 8;
remaining -= 2;
if (strLen > remaining) {
// Buffer doesn't hold entire string, fail.
return -1;
}
if (strLen == 0) {
continue;
}
stringCount++;
remaining -= strLen;
int expectedHiBit = fileData[posn] & 0x80;
while (strLen-- != 0) {
byte val = fileData[posn++];
if (limitHiBit && (val & 0x80) != expectedHiBit) {
// Mixed ASCII, fail.
return -1;
}
if (!charTest(val)) {
// Not a matching character, fail.
return -1;
}
}
}
return stringCount;
}
/// <summary>
/// Counts strings in Dextral Character Inverted format, meaning the high bit on the
/// last byte is the opposite of the preceding.
///
/// Each string must be at least two bytes. To reduce false-positives, we require
/// that all strings have the same hi/lo pattern.
/// </summary>
/// <remarks>
/// For C64Petscii, this will identify strings that are entirely in lower case except
/// for the last letteR, or vice-versa.
/// </remarks>
/// <param name="fileData">Raw data.</param>
/// <param name="start">Offset of first byte in range.</param>
/// <param name="end">Offset of last byte in range.</param>
/// <param name="charTest">Character test delegate.</param>
/// <returns>Number of strings found, or -1 if bad data identified.</returns>
public static int RecognizeDciStrings(byte[] fileData, int start, int end,
CharEncoding.InclusionTest charTest) {
int expectedHiBit = fileData[start] & 0x80;
int stringCount = 0;
int stringLen = 0;
// Quick test on last byte.
if ((fileData[end] & 0x80) == expectedHiBit) {
return -1;
}
for (int i = start; i <= end; i++) {
byte val = fileData[i];
if ((val & 0x80) != expectedHiBit) {
// end of string
if (stringLen == 0) {
// Got two consecutive bytes with end-marker polarity... fail.
return -1;
}
stringCount++;
stringLen = 0;
} else {
stringLen++;
}
if (!charTest((byte)(val & 0x7f))) {
// Not a matching character, fail.
return -1;
}
}
return stringCount;
}
/// <summary>
/// Counts strings in reverse Dextral Character Inverted format, meaning the string is
/// stored in reverse order in memory, and the high bit on the first (last) byte is
/// the opposite of the rest.
///
/// Each string must be at least two bytes. To reduce false-positives, we require
/// that all strings have the same hi/lo pattern.
/// </summary>
/// <param name="fileData">Raw data.</param>
/// <param name="start">Offset of first byte in range.</param>
/// <param name="end">Offset of last byte in range.</param>
/// <returns>Number of strings found, or -1 if bad data identified.</returns>
public static int RecognizeReverseDciStrings(byte[] fileData, int start, int end) {
int expectedHiBit = fileData[end] & 0x80;
int stringCount = 0;
int stringLen = 0;
// Quick test on last (first) byte.
if ((fileData[start] & 0x80) == expectedHiBit) {
return -1;
}
for (int i = end; i >= start; i--) {
byte val = fileData[i];
if ((val & 0x80) != expectedHiBit) {
// end of string
if (stringLen == 0) {
// Got two consecutive bytes with end-marker polarity... fail.
return -1;
}
stringCount++;
stringLen = 0;
} else {
stringLen++;
}
val &= 0x7f;
if (val < 0x20 || val == 0x7f) {
// Non-ASCII, fail.
return -1;
}
}
return stringCount;
}
/// <summary>
/// Verifies that the string data is what is expected. Does not attempt to check
/// the character encoding, just the structure.
/// </summary>
/// <param name="fileData">Raw data.</param>
/// <param name="offset">Start offset of string.</param>
/// <param name="length">Length of string, including leading length and terminating
/// null bytes.</param>
/// <param name="type">Expected string type.</param>
/// <param name="failMsg">Detailed failure message.</param>
/// <returns>True if all is well.</returns>
public static bool VerifyStringData(byte[] fileData, int offset, int length,
FormatDescriptor.Type type, out string failMsg) {
failMsg = string.Empty;
switch (type) {
case FormatDescriptor.Type.StringGeneric:
case FormatDescriptor.Type.StringReverse:
return true;
case FormatDescriptor.Type.StringNullTerm:
// must end in null byte, and have no null bytes before the end
int chk = offset;
while (length-- != 0) {
byte val = fileData[chk++];
if (val == 0x00) {
if (length != 0) {
failMsg = Res.Strings.STR_VFY_NULL_INSIDE_NULL_TERM;
return false;
} else {
return true;
}
}
}
failMsg = Res.Strings.STR_VFY_MISSING_NULL_TERM;
return false;
case FormatDescriptor.Type.StringL8:
if (fileData[offset] != length - 1) {
failMsg = Res.Strings.STR_VFY_L1_LENGTH_MISMATCH;
return false;
}
return true;
case FormatDescriptor.Type.StringL16:
int len = RawData.GetWord(fileData, offset, 2, false);
if (len != length - 2) {
failMsg = Res.Strings.STR_VFY_L2_LENGTH_MISMATCH;
return false;
}
return true;
case FormatDescriptor.Type.StringDci:
if (length < 2) {
failMsg = Res.Strings.STR_VFY_DCI_SHORT;
return false;
}
byte first = (byte)(fileData[offset] & 0x80);
for (int i = offset + 1; i < offset + length - 1; i++) {
if ((fileData[i] & 0x80) != first) {
failMsg = Res.Strings.STR_VFY_DCI_MIXED_DATA;
return false;
}
}
if ((fileData[offset + length - 1] & 0x80) == first) {
failMsg = Res.Strings.STR_VFY_DCI_NOT_TERMINATED;
return false;
}
return true;
default:
Debug.Assert(false);
return false;
}
}
#endregion // Static analyzers
}
}
#if DATA_PRESCAN
/// <summary>
/// Iterator that generates a list of offsets which are not known to hold code or data.
///
/// Generates a set of integers in ascending order.
/// </summary>
private class UndeterminedValueIterator : IEnumerator {
/// <summary>
/// Index of current item, or -1 if we're not started yet.
/// </summary>
private int mCurIndex;
/// <summary>
/// Reference to Anattrib array we're iterating over.
/// </summary>
private Anattrib[] mAnattribs;
/// <summary>
/// Constructor.
/// </summary>
public UndeterminedValueIterator(Anattrib[] anattribs) {
mAnattribs = anattribs;
Reset();
}
// IEnumerator: current element
public object Current {
get {
if (mCurIndex < 0) {
// not started
return null;
}
return mCurIndex;
}
}
// IEnumerator: move to the next element, returning false if there isn't one
public bool MoveNext() {
while (++mCurIndex < mAnattribs.Length) {
Anattrib attr = mAnattribs[mCurIndex];
if (attr.IsInstructionStart) {
// skip past instruction
mCurIndex += attr.Length - 1;
} else if (attr.IsUncategorized) {
// got one
return true;
}
}
return false;
}
// IEnumerator: reset state
public void Reset() {
mCurIndex = -1;
}
}
#endif
| 49.187324 | 136 | 0.504123 | [
"Apache-2.0"
] | absindx/6502bench | SourceGen/DataAnalysis.cs | 69,848 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using Common.Log;
using JetBrains.Annotations;
using Lykke.Common.Log;
using Lykke.RabbitMqBroker;
using Lykke.RabbitMqBroker.Subscriber;
using Lykke.Service.IndexHedgingEngine.Domain;
using Lykke.Service.IndexHedgingEngine.Domain.Services;
using Lykke.Service.IndexHedgingEngine.Rabbit.Contracts.LykkeOrderBooks;
using Lykke.Service.IndexHedgingEngine.Settings.ServiceSettings.Rabbit.Subscribers;
namespace Lykke.Service.IndexHedgingEngine.Rabbit.Subscribers
{
[UsedImplicitly]
public class LykkeOrderBookSubscriber : IDisposable
{
private readonly SubscriberSettings _settings;
private readonly IOrderBookService _orderBookService;
private readonly ILogFactory _logFactory;
private readonly ILog _log;
private RabbitMqSubscriber<LykkeOrderBook> _subscriber;
public LykkeOrderBookSubscriber(
SubscriberSettings settings,
IOrderBookService orderBookService,
ILogFactory logFactory)
{
_settings = settings;
_orderBookService = orderBookService;
_logFactory = logFactory;
_log = logFactory.CreateLog(this);
}
public void Start()
{
var settings = RabbitMqSubscriptionSettings
.ForSubscriber(_settings.ConnectionString, _settings.Exchange, _settings.Queue);
settings.DeadLetterExchangeName = null;
_subscriber = new RabbitMqSubscriber<LykkeOrderBook>(_logFactory, settings,
new ResilientErrorHandlingStrategy(_logFactory, settings, TimeSpan.FromSeconds(10)))
.SetMessageDeserializer(new JsonMessageDeserializer<LykkeOrderBook>())
.Subscribe(ProcessMessageAsync)
.CreateDefaultBinding()
.Start();
}
public void Stop()
{
_subscriber?.Stop();
}
public void Dispose()
{
_subscriber?.Dispose();
}
private async Task ProcessMessageAsync(LykkeOrderBook message)
{
try
{
var limitOrders = message.LimitOrders
.Select(o => new LimitOrder
{
Id = o.Id,
WalletId = o.ClientId,
Volume = Math.Abs(o.Volume),
Price = o.Price,
Type = message.IsBuy ? LimitOrderType.Buy : LimitOrderType.Sell
})
.ToArray();
if (message.IsBuy)
{
await _orderBookService.UpdateBuyLimitOrdersAsync(message.AssetPairId, message.Timestamp,
limitOrders);
}
else
{
await _orderBookService.UpdateSellLimitOrdersAsync(message.AssetPairId, message.Timestamp,
limitOrders);
}
}
catch (Exception exception)
{
_log.Error(exception, "An error occurred during processing lykke order book", message);
}
}
}
}
| 34.063158 | 110 | 0.591471 | [
"MIT"
] | LykkeCity/Lykke.Service.IndexHedgingEngine | src/Lykke.Service.IndexHedgingEngine/Rabbit/Subscribers/LykkeOrderBookSubscriber.cs | 3,236 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using SysKit.ODG.Base.Interfaces.Generation;
namespace SysKit.ODG.Base.DTO.Generation.Results
{
public class UserGenerationTaskResult: IGenerationTaskResult
{
public bool HadErrors { get; }
public IEnumerable<UserEntry> CreatedUsers { get; }
public UserGenerationTaskResult(IEnumerable<UserEntry> createdUsers, bool hadErrors)
{
HadErrors = hadErrors;
CreatedUsers = createdUsers;
}
}
}
| 26.65 | 92 | 0.69606 | [
"MIT"
] | SysKitTeam/ODG | SysKit.ODG.App/SysKit.ODG.Base/DTO/Generation/Results/UserGenerationTaskResult.cs | 535 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class DrawFurObjectInstanced : MonoBehaviour
{
private Mesh mesh;
[Header("Offset Prop")]
public float baseScale = 0.07f;
public float stepScale = 0.03f;
public int drawCount = 11;
MeshFilter mf;
Material[] mats;
List<Matrix4x4> transformList = new List<Matrix4x4>();
static MaterialPropertyBlock block;
// Start is called before the first frame update
void OnEnable()
{
if (block == null)
block = new MaterialPropertyBlock();
mf = GetComponent<MeshFilter>();
mesh = mf.sharedMesh;
var r = GetComponent<Renderer>();
mats = r.sharedMaterials;
r.enabled = false;
var offsetList = new List<float>();
for (int i = 0; i < drawCount; i++)
{
transformList.Add(mf.transform.localToWorldMatrix);
offsetList.Add(baseScale + i * stepScale);
}
block.SetFloatArray("_FurOffset", offsetList);
}
// Update is called once per frame
void Update()
{
if (!mesh)
{
enabled = false;
return;
}
for (int i = 0; i < mesh.subMeshCount; i++)
{
if (i > mats.Length)
break;
Graphics.DrawMeshInstanced(mesh, i, mats[i], transformList, block);
}
}
}
| 23.33871 | 79 | 0.573601 | [
"Apache-2.0"
] | redcool/PowerFur | PowerFur/Scripts/DrawFurObjectInstanced.cs | 1,447 | C# |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace GridStackNET
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
| 18.111111 | 42 | 0.705521 | [
"MIT"
] | DonSagiv/GridStackNET | GridStackNET/App.xaml.cs | 328 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using COMCMS.Common;
using COMCMS.Web.Common;
using COMCMS.Web.Controllers.api;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace COMCMS.Web.Filter
{
public class CheckFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var error = string.Empty;
foreach (var key in context.ModelState.Keys)
{
var state = context.ModelState[key];
if (state.Errors.Any())
{
error = string.Join("\r\n", state.Errors.ToList().ConvertAll(item => item.ErrorMessage));
if (error.Equals(string.Empty))
error = string.Join("\r\n", state.Errors.ToList().ConvertAll(item => item.Exception.Message));
break;
}
}
throw new Exception(error);
}
var notVali = ValiSignature(context.HttpContext);
if (notVali != null)
{
// 过滤器不要抛出错误,也不要向响应流写东西,应该直接赋值Result进行短路
context.Result = new ContentResult()
{
Content = notVali.ToJson(),
ContentType = "application/json"
};
}
}
private ReJson ValiSignature(HttpContext context)
{
var Request = context.Request;
var queryStrings = Request.Query;
List<string> keys = new List<string>();
//string[] keys = HttpContext.Current.Request.QueryString.AllKeys;
if (queryStrings == null)
{
throw new Exception("queryStrings Is Null");
}
foreach (var item in queryStrings.Keys)
{
keys.Add(item);
}
SortedDictionary<string, string> pars = new SortedDictionary<string, string>();
string signature = "";
foreach (var k in keys)
{
if (k != "signature")
{
string v = Request.Query[k];
pars.Add(k, v);
}
else
{
signature = Request.Query[k];
}
}
//没有签名返回错误
if (string.IsNullOrEmpty(signature))
return new ReJson(40004, "signature 为空!");
if (!MySign.CheckSign(pars, signature))
{
return new ReJson(40004, "signature 错误!");
}
//判断是否超时
string timeStamp = pars["timeStamp"];
//判断时间有效性
DateTime postTime = Utils.StampToDateTime(timeStamp);
if (postTime < DateTime.Now.AddSeconds(-120))//30秒有效期
{
return new ReJson(40004, "signature 错误!", 1);
}
return null;
}
}
}
| 31.067961 | 122 | 0.492813 | [
"MIT"
] | huangbosheng/- | COMCMS.Web/Filter/CheckFilter.cs | 3,332 | C# |
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
namespace PtaSheet3.ViewModels
{
public class MainWindowViewModel : BindableBase
{
private string _title = "PtaSheet";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public DelegateCommand NewCommand { get; private set; }
public DelegateCommand EditAbilitiesCommand { get; private set; }
public MainWindowViewModel(IEventAggregator eventAggregator, IRegionManager regionManager)
{
_ = eventAggregator.GetEvent<Core.Mvvm.Messaging.WindowTitleUpdateEvent>().Subscribe(title => Title = title, ThreadOption.UIThread);
NewCommand = new DelegateCommand(() =>
{
regionManager.RequestNavigate(Core.RegionNames.ContentRegion, "Sheet");
});
EditAbilitiesCommand = new DelegateCommand(() =>
{
regionManager.RequestNavigate(Core.RegionNames.ContentRegion, "AbilityEditor");
});
}
}
}
| 30.378378 | 144 | 0.628114 | [
"Unlicense"
] | formlesstree4/PokeSheet | PrismSheet/PtaSheet3/PtaSheet3/ViewModels/MainWindowViewModel.cs | 1,126 | C# |
using System;
using System.Globalization;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Fluid;
using Fluid.Accessors;
using Fluid.Values;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Localization;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using OrchardCore.DisplayManagement.Layout;
using OrchardCore.DisplayManagement.Liquid.Filters;
using OrchardCore.DisplayManagement.Liquid.Internal;
using OrchardCore.DisplayManagement.Liquid.Tags;
using OrchardCore.DisplayManagement.Shapes;
using OrchardCore.DisplayManagement.Zones;
using OrchardCore.DynamicCache.Liquid;
using OrchardCore.Environment.Shell.Scope;
using OrchardCore.Liquid;
namespace OrchardCore.DisplayManagement.Liquid
{
public class LiquidViewTemplate : BaseFluidTemplate<LiquidViewTemplate>
{
public static readonly string ViewsFolder = "Views";
public static readonly string ViewExtension = ".liquid";
public static readonly MemoryCache Cache = new MemoryCache(new MemoryCacheOptions());
static LiquidViewTemplate()
{
FluidValue.SetTypeMapping<Shape>(o => new ObjectValue(o));
FluidValue.SetTypeMapping<ZoneHolding>(o => new ObjectValue(o));
TemplateContext.GlobalMemberAccessStrategy.Register<Shape>("*", new ShapeAccessor());
TemplateContext.GlobalMemberAccessStrategy.Register<ZoneHolding>("*", new ShapeAccessor());
Factory.RegisterTag<RenderBodyTag>("render_body");
Factory.RegisterTag<RenderSectionTag>("render_section");
Factory.RegisterTag<RenderTitleSegmentsTag>("page_title");
Factory.RegisterTag<AntiForgeryTokenTag>("antiforgerytoken");
Factory.RegisterTag<LayoutTag>("layout");
Factory.RegisterTag<ClearAlternatesTag>("shape_clear_alternates");
Factory.RegisterTag<AddAlternatesTag>("shape_add_alternates");
Factory.RegisterTag<ClearWrappers>("shape_clear_wrappers");
Factory.RegisterTag<AddWrappersTag>("shape_add_wrappers");
Factory.RegisterTag<ClearClassesTag>("shape_clear_classes");
Factory.RegisterTag<AddClassesTag>("shape_add_classes");
Factory.RegisterTag<ClearAttributesTag>("shape_clear_attributes");
Factory.RegisterTag<AddAttributesTag>("shape_add_attributes");
Factory.RegisterTag<ShapeTypeTag>("shape_type");
Factory.RegisterTag<ShapeDisplayTypeTag>("shape_display_type");
Factory.RegisterTag<ShapePositionTag>("shape_position");
Factory.RegisterTag<ShapeCacheTag>("shape_cache");
Factory.RegisterTag<ShapeTabTag>("shape_tab");
Factory.RegisterTag<ShapeRemoveItemTag>("shape_remove_item");
Factory.RegisterTag<ShapeAddPropertyTag>("shape_add_properties");
Factory.RegisterTag<ShapeRemovePropertyTag>("shape_remove_property");
Factory.RegisterTag<ShapePagerTag>("shape_pager");
Factory.RegisterTag<HelperTag>("helper");
Factory.RegisterTag<NamedHelperTag>("shape");
Factory.RegisterTag<NamedHelperTag>("contentitem");
Factory.RegisterTag<NamedHelperTag>("link");
Factory.RegisterTag<NamedHelperTag>("meta");
Factory.RegisterTag<NamedHelperTag>("resources");
Factory.RegisterTag<NamedHelperTag>("script");
Factory.RegisterTag<NamedHelperTag>("style");
Factory.RegisterBlock<HelperBlock>("block");
Factory.RegisterBlock<NamedHelperBlock>("a");
Factory.RegisterBlock<NamedHelperBlock>("zone");
Factory.RegisterBlock<NamedHelperBlock>("scriptblock");
// Dynamic caching
Factory.RegisterBlock<CacheBlock>("cache");
Factory.RegisterTag<CacheDependencyTag>("cache_dependency");
Factory.RegisterTag<CacheExpiresOnTag>("cache_expires_on");
Factory.RegisterTag<CacheExpiresAfterTag>("cache_expires_after");
Factory.RegisterTag<CacheExpiresSlidingTag>("cache_expires_sliding");
NamedHelperTag.RegisterDefaultArgument("shape", "type");
NamedHelperBlock.RegisterDefaultArgument("zone", "name");
TemplateContext.GlobalFilters.WithLiquidViewFilters();
}
/// <summary>
/// Retrieve the current <see cref="LiquidTemplateContext"/> from the current shell scope.
/// </summary>
public static LiquidTemplateContext Context => ShellScope.GetOrCreateFeature(() => new LiquidTemplateContext(ShellScope.Services));
internal static async Task RenderAsync(RazorPage<dynamic> page)
{
var services = page.Context.RequestServices;
var path = Path.ChangeExtension(page.ViewContext.ExecutingFilePath, ViewExtension);
var fileProviderAccessor = services.GetRequiredService<ILiquidViewFileProviderAccessor>();
var isDevelopment = services.GetRequiredService<IHostEnvironment>().IsDevelopment();
var template = await ParseAsync(path, fileProviderAccessor.FileProvider, Cache, isDevelopment);
var context = Context;
var htmlEncoder = services.GetRequiredService<HtmlEncoder>();
try
{
await context.EnterScopeAsync(page.ViewContext, (object)page.Model);
await template.RenderAsync(page.Output, htmlEncoder, context);
}
finally
{
context.ReleaseScope();
}
}
public static Task<LiquidViewTemplate> ParseAsync(string path, IFileProvider fileProvider, IMemoryCache cache, bool isDevelopment)
{
return cache.GetOrCreateAsync(path, async entry =>
{
entry.SetSlidingExpiration(TimeSpan.FromHours(1));
var fileInfo = fileProvider.GetFileInfo(path);
if (isDevelopment)
{
entry.ExpirationTokens.Add(fileProvider.Watch(path));
}
using (var stream = fileInfo.CreateReadStream())
{
using (var sr = new StreamReader(stream))
{
if (TryParse(await sr.ReadToEndAsync(), out var template, out var errors))
{
return template;
}
else
{
throw new Exception($"Failed to parse liquid file {path}: {String.Join(System.Environment.NewLine, errors)}");
}
}
}
});
}
}
internal class ShapeAccessor : DelegateAccessor
{
public ShapeAccessor() : base(_getter) { }
private static Func<object, string, object> _getter => (o, n) =>
{
if (o is Shape shape)
{
if (shape.Properties.TryGetValue(n, out var result))
{
return result;
}
if (n == "Items")
{
return shape.Items;
}
// Model.Content.MyNamedPart
// Model.Content.MyType__MyField
// Model.Content.MyType-MyField
return shape.Named(n.Replace("__", "-"));
}
return null;
};
}
public static class LiquidViewTemplateExtensions
{
public static async Task<string> RenderAsync(this LiquidViewTemplate template, TextEncoder encoder, LiquidTemplateContext context, object model)
{
var viewContext = context.Services.GetRequiredService<ViewContextAccessor>().ViewContext;
if (viewContext == null)
{
viewContext = await GetViewContextAsync(context);
}
try
{
await context.EnterScopeAsync(viewContext, model);
return await template.RenderAsync(context, encoder);
}
finally
{
context.ReleaseScope();
}
}
public static async Task RenderAsync(this LiquidViewTemplate template, TextWriter writer, TextEncoder encoder, LiquidTemplateContext context, object model)
{
var viewContext = context.Services.GetRequiredService<ViewContextAccessor>().ViewContext;
if (viewContext == null)
{
viewContext = await GetViewContextAsync(context);
}
try
{
await context.EnterScopeAsync(viewContext, model);
await template.RenderAsync(writer, encoder, context);
}
finally
{
context.ReleaseScope();
}
}
public static async Task<ViewContext> GetViewContextAsync(LiquidTemplateContext context)
{
var actionContext = context.Services.GetService<IActionContextAccessor>()?.ActionContext;
if (actionContext == null)
{
var httpContext = context.Services.GetRequiredService<IHttpContextAccessor>().HttpContext;
actionContext = await GetActionContextAsync(httpContext);
}
return GetViewContext(actionContext);
}
internal static async Task<ActionContext> GetActionContextAsync(HttpContext httpContext)
{
var routeData = new RouteData();
routeData.Routers.Add(new RouteCollection());
var actionContext = new ActionContext(httpContext, routeData, new ActionDescriptor());
var filters = httpContext.RequestServices.GetServices<IAsyncViewActionFilter>();
foreach (var filter in filters)
{
await filter.OnActionExecutionAsync(actionContext);
}
return actionContext;
}
internal static ViewContext GetViewContext(ActionContext actionContext)
{
var services = actionContext.HttpContext.RequestServices;
var options = services.GetService<IOptions<MvcViewOptions>>();
var viewEngine = options.Value.ViewEngines[0];
var viewResult = viewEngine.GetView(executingFilePath: null,
LiquidViewsFeatureProvider.DefaultRazorViewPath, isMainPage: true);
var tempDataProvider = services.GetService<ITempDataProvider>();
return new ViewContext(
actionContext,
viewResult.View,
new ViewDataDictionary(
metadataProvider: new EmptyModelMetadataProvider(),
modelState: new ModelStateDictionary()),
new TempDataDictionary(
actionContext.HttpContext,
tempDataProvider),
TextWriter.Null,
new HtmlHelperOptions());
}
}
public static class LiquidTemplateContextExtensions
{
internal static async Task EnterScopeAsync(this LiquidTemplateContext context, ViewContext viewContext, object model)
{
if (!context.IsInitialized)
{
context.AmbientValues.EnsureCapacity(9);
context.AmbientValues.Add("Services", context.Services);
var displayHelper = context.Services.GetRequiredService<IDisplayHelper>();
context.AmbientValues.Add("DisplayHelper", displayHelper);
var urlHelperFactory = context.Services.GetRequiredService<IUrlHelperFactory>();
var urlHelper = urlHelperFactory.GetUrlHelper(viewContext);
context.AmbientValues.Add("UrlHelper", urlHelper);
var shapeFactory = context.Services.GetRequiredService<IShapeFactory>();
context.AmbientValues.Add("ShapeFactory", shapeFactory);
var layoutAccessor = context.Services.GetRequiredService<ILayoutAccessor>();
var layout = await layoutAccessor.GetLayoutAsync();
context.AmbientValues.Add("ThemeLayout", layout);
var options = context.Services.GetRequiredService<IOptions<LiquidOptions>>().Value;
context.AddAsyncFilters(options);
foreach (var handler in context.Services.GetServices<ILiquidTemplateEventHandler>())
{
await handler.RenderingAsync(context);
}
context.CultureInfo = CultureInfo.CurrentUICulture;
context.IsInitialized = true;
}
context.EnterChildScope();
var viewLocalizer = context.Services.GetRequiredService<IViewLocalizer>();
if (viewLocalizer is IViewContextAware contextable)
{
contextable.Contextualize(viewContext);
}
context.SetValue("ViewLocalizer", viewLocalizer);
if (model != null)
{
context.MemberAccessStrategy.Register(model.GetType());
}
context.SetValue("Model", model);
}
internal static void AddAsyncFilters(this LiquidTemplateContext context, LiquidOptions options)
{
context.Filters.EnsureCapacity(options.FilterRegistrations.Count);
foreach (var registration in options.FilterRegistrations)
{
context.Filters.AddAsyncFilter(registration.Key, (input, arguments, ctx) =>
{
var filter = (ILiquidFilter)context.Services.GetRequiredService(registration.Value);
return filter.ProcessAsync(input, arguments, ctx);
});
}
}
}
}
| 39.936111 | 163 | 0.626835 | [
"BSD-3-Clause"
] | alirizaadiyahsi/OrchardCore | src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidViewTemplate.cs | 14,377 | C# |
using System.Windows;
using System.Windows.Input;
using CentralAptitudeTest.Models;
using CentralAptitudeTest.Views;
namespace CentralAptitudeTest
{
/// <summary>
/// MainWindow.xaml에 대한 상호 작용 논리
/// </summary>
public partial class MainWindow : Window
{
private Config Config;
private int PageNum = 0;
public MainWindow()
{
InitializeComponent();
MainControl.Content = new InsertView();
this.Insert.IsSelected = true;
}
private void panelHeader_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
DragMove();
}
}
private void Insert_Selected(object sender, RoutedEventArgs e)
{
//asd.Content = new InsertView();
}
private void Process_Selected(object sender, RoutedEventArgs e)
{
//asd.Content = new ProgressView(String.Empty);
}
private void ListViewItem_Selected(object sender, RoutedEventArgs e)
{
}
private void NextPageButton_Click(object sender, RoutedEventArgs e)
{
switch (PageNum)
{
case 0:
this.Insert.IsSelected = false;
this.Complete.IsSelected = false;
this.Process.IsSelected = true;
NextPageButton.Visibility = Visibility.Visible;
PreviewPageButton.Visibility = Visibility.Visible;
HomeButton.Visibility = Visibility.Hidden;
MainControl.Content = new ProgressView();
PageNum += 1;
break;
case 1:
this.Insert.IsSelected = false;
this.Process.IsSelected = false;
this.Complete.IsSelected = true;
NextPageButton.Visibility = Visibility.Hidden;
PreviewPageButton.Visibility = Visibility.Visible;
HomeButton.Visibility = Visibility.Visible;
MainControl.Content = new ResultView();
PageNum += 1;
break;
case 2:
NextPageButton.Visibility = Visibility.Hidden;
PreviewPageButton.Visibility = Visibility.Visible;
HomeButton.Visibility = Visibility.Visible;
break;
}
}
private void PreviewPageButton_Click(object sender, RoutedEventArgs e)
{
switch (PageNum)
{
case 0:
NextPageButton.Visibility = Visibility.Visible;
PreviewPageButton.Visibility = Visibility.Hidden;
HomeButton.Visibility = Visibility.Hidden;
break;
case 1:
this.Process.IsSelected = false;
this.Complete.IsSelected = false;
this.Insert.IsSelected = true;
NextPageButton.Visibility = Visibility.Visible;
PreviewPageButton.Visibility = Visibility.Hidden;
HomeButton.Visibility = Visibility.Hidden;
MainControl.Content = new InsertView();
PageNum -= 1;
break;
case 2:
this.Insert.IsSelected = false;
this.Complete.IsSelected = false;
this.Process.IsSelected = true;
NextPageButton.Visibility = Visibility.Visible;
PreviewPageButton.Visibility = Visibility.Visible;
HomeButton.Visibility = Visibility.Hidden;
MainControl.Content = new ProgressView();
PageNum -= 1;
break;
}
}
private void HomeButton_Click(object sender, RoutedEventArgs e)
{
this.Process.IsSelected = false;
this.Complete.IsSelected = false;
this.Insert.IsSelected = true;
NextPageButton.Visibility = Visibility.Visible;
PreviewPageButton.Visibility = Visibility.Hidden;
HomeButton.Visibility = Visibility.Hidden;
MainControl.Content = new InsertView();
PageNum = 0;
}
private void root_Loaded(object sender, RoutedEventArgs e)
{
Config = Config.GetConfig();
}
}
}
| 36.110236 | 81 | 0.528565 | [
"MIT"
] | Marhead/CentralAptitudeTest | MainWindow.xaml.cs | 4,606 | C# |
using Hyperledger.Indy.LedgerApi;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
namespace Hyperledger.Indy.Test.LedgerTests
{
[TestClass]
public class PoolRestartRequestTest : IndyIntegrationTestWithPoolAndSingleWallet
{
/// <summary>
/// Marked as ignore, see commented out code. Havent found a suitable replacement so this test might be obsolete
/// </summary>
/// <returns>The build pool restart request works.</returns>
[TestMethod]
[Ignore]
public async Task TestBuildPoolRestartRequestWorks()
{
var expectedResult = string.Format("\"identifier\":\"%s\"," +
"\"operation\":{\"type\":\"118\"," +
"\"action\":\"start\"," +
"\"schedule\":{}", DID1);
var action = "start";
var schedule = "{}";
var poolRestartRequest = ""; //TODO await Ledger.BuildPoolRestartRequestAsync(DID1, action, schedule);
Assert.IsTrue(poolRestartRequest.Replace("\\", "").Contains(expectedResult));
}
}
}
| 35.96875 | 121 | 0.609904 | [
"Apache-2.0"
] | scipsycho/indy-sdk | wrappers/dotnet/indy-sdk-dotnet-test/LedgerTests/PoolRestartRequestTest.cs | 1,153 | C# |
using College.Services.BAL;
using College.Services.Common;
using College.Services.Persistence;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace College.Services
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// Adding EF Core
var connectionString = Configuration[Constants.ConnectionString];
services.AddDbContext<CollegeDbContext>(o => o.UseSqlServer(connectionString));
// Application Services
services.AddScoped<ProfessorsBal>();
services.AddScoped<ProfessorsDal>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
| 31.854167 | 106 | 0.672989 | [
"MIT"
] | vishipayyallore/speaker_series_csharp_dotnetcode | SQLServer2017DockerWebApi/College.Services/College.Services/Startup.cs | 1,531 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NLog;
namespace DeadManSwitch.UI.Web.AspNetMvc
{
internal class HttpExceptionLogger
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public void Log(HttpException ex)
{
string ip = HttpContext.Current.Request.UserHostAddress;
int httpStatusCode = ex.GetHttpCode();
if (httpStatusCode >= 400 && httpStatusCode < 500)
{
this.Log400Range(ip, httpStatusCode, ex);
}
else if (httpStatusCode >= 500)
{
logger.Fatal("IP Address: {0}; HttpStatusCode: {1} Exception: {2}", ip, httpStatusCode, ex);
}
else
{
logger.Error("IP Address: {0}; HttpStatusCode: {1} Exception: {2}", ip, httpStatusCode, ex);
}
}
private void Log400Range(string ip, int httpStatusCode, HttpException ex)
{
switch (httpStatusCode)
{
case 404:
logger.Warn("IP Address: {0}; HttpStatusCode: {1} Exception: {2}", ip, httpStatusCode, ex);
break;
default:
logger.Error("IP Address: {0}; HttpStatusCode: {1} Exception: {2}", ip, httpStatusCode, ex);
break;
}
}
}
} | 30.744681 | 112 | 0.534948 | [
"MIT"
] | tategriffin/DeadManSwitch | Source/DeadManSwitch.UI.Web.AspNetMvc/HttpExceptionLogger.cs | 1,447 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Core.Query.InternalTrees
{
using System.Data.Entity.Core.Metadata.Edm;
using System.Diagnostics;
/// <summary>
/// Represents an EXISTS subquery?
/// </summary>
internal sealed class ExistsOp : ScalarOp
{
#region constructors
internal ExistsOp(TypeUsage type)
: base(OpType.Exists, type)
{
}
private ExistsOp()
: base(OpType.Exists)
{
}
#endregion
#region public methods
/// <summary>
/// Pattern for transformation rules
/// </summary>
internal static readonly ExistsOp Pattern = new ExistsOp();
/// <summary>
/// 1 child - collection input
/// </summary>
internal override int Arity
{
get { return 1; }
}
/// <summary>
/// Visitor pattern method
/// </summary>
/// <param name="v"> The BasicOpVisitor that is visiting this Op </param>
/// <param name="n"> The Node that references this Op </param>
[DebuggerNonUserCode]
internal override void Accept(BasicOpVisitor v, Node n)
{
v.Visit(this, n);
}
/// <summary>
/// Visitor pattern method for visitors with a return value
/// </summary>
/// <param name="v"> The visitor </param>
/// <param name="n"> The node in question </param>
/// <returns> An instance of TResultType </returns>
[DebuggerNonUserCode]
internal override TResultType Accept<TResultType>(BasicOpVisitorOfT<TResultType> v, Node n)
{
return v.Visit(this, n);
}
#endregion
}
}
| 28.764706 | 133 | 0.538344 | [
"Apache-2.0"
] | TerraVenil/entityframework | src/EntityFramework/Core/Query/InternalTrees/ExistsOp.cs | 1,956 | C# |
// Copyright 2004-2012 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.Windsor.Diagnostics.Helpers
{
using System.Collections.Generic;
using System.Text;
using Castle.Core.Internal;
using Castle.MicroKernel;
using Castle.MicroKernel.Handlers;
using Castle.Windsor.Diagnostics.DebuggerViews;
public class DefaultComponentViewBuilder : IComponentDebuggerExtension
{
private readonly IHandler handler;
public DefaultComponentViewBuilder(IHandler handler)
{
this.handler = handler;
}
public IEnumerable<object> Attach()
{
yield return new DebuggerViewItem("Implementation", GetImplementation());
foreach (var service in handler.ComponentModel.Services)
{
yield return new DebuggerViewItem("Service", service);
}
yield return GetStatus();
yield return new DebuggerViewItem("Lifestyle", handler.ComponentModel.GetLifestyleDescriptionLong());
if (HasInterceptors())
{
var interceptors = handler.ComponentModel.Interceptors;
var value = interceptors.ToArray();
yield return new DebuggerViewItem("Interceptors", "Count = " + value.Length, value);
}
yield return new DebuggerViewItem("Name", handler.ComponentModel.Name);
yield return new DebuggerViewItem("Raw handler/component", handler);
}
private object GetImplementation()
{
var implementation = handler.ComponentModel.Implementation;
if (implementation != typeof(LateBoundComponent))
{
return implementation;
}
return LateBoundComponent.Instance;
}
private object GetStatus()
{
if (handler.CurrentState == HandlerState.Valid)
{
return new DebuggerViewItem("Status", "All required dependencies can be resolved.");
}
return new DebuggerViewItemWithDetails("Status", "This component may not resolve properly.", GetStatusDetails(handler as IExposeDependencyInfo));
}
private string GetStatusDetails(IExposeDependencyInfo info)
{
var message = new StringBuilder("Some dependencies of this component could not be statically resolved.");
if (info == null)
{
return message.ToString();
}
var inspector = new DependencyInspector(message);
info.ObtainDependencyDetails(inspector);
return inspector.Message;
}
private bool HasInterceptors()
{
return handler.ComponentModel.HasInterceptors;
}
}
} | 31.659341 | 148 | 0.746269 | [
"Apache-2.0"
] | 111cctv19/Windsor | src/Castle.Windsor/Windsor/Diagnostics/Helpers/DefaultComponentViewBuilder.cs | 2,883 | C# |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Avalonia.Data;
using Avalonia.Logging;
using Avalonia.Utilities;
namespace Avalonia
{
/// <summary>
/// Maintains a list of prioritized bindings together with a current value.
/// </summary>
/// <remarks>
/// Bindings, in the form of <see cref="IObservable{Object}"/>s are added to the object using
/// the <see cref="Add"/> method. With the observable is passed a priority, where lower values
/// represent higher priorities. The current <see cref="Value"/> is selected from the highest
/// priority binding that doesn't return <see cref="AvaloniaProperty.UnsetValue"/>. Where there
/// are multiple bindings registered with the same priority, the most recently added binding
/// has a higher priority. Each time the value changes, the
/// <see cref="IPriorityValueOwner.Changed"/> method on the
/// owner object is fired with the old and new values.
/// </remarks>
internal class PriorityValue
{
private readonly Type _valueType;
private readonly SingleOrDictionary<int, PriorityLevel> _levels = new SingleOrDictionary<int, PriorityLevel>();
private readonly Func<object, object> _validate;
private readonly SetAndNotifyCallback<(object, int)> _setAndNotifyCallback;
private (object value, int priority) _value;
private DeferredSetter<object> _setter;
/// <summary>
/// Initializes a new instance of the <see cref="PriorityValue"/> class.
/// </summary>
/// <param name="owner">The owner of the object.</param>
/// <param name="property">The property that the value represents.</param>
/// <param name="valueType">The value type.</param>
/// <param name="validate">An optional validation function.</param>
public PriorityValue(
IPriorityValueOwner owner,
AvaloniaProperty property,
Type valueType,
Func<object, object> validate = null)
{
Owner = owner;
Property = property;
_valueType = valueType;
_value = (AvaloniaProperty.UnsetValue, int.MaxValue);
_validate = validate;
_setAndNotifyCallback = SetAndNotify;
}
/// <summary>
/// Gets a value indicating whether the property is animating.
/// </summary>
public bool IsAnimating
{
get
{
return ValuePriority <= (int)BindingPriority.Animation &&
GetLevel(ValuePriority).ActiveBindingIndex != -1;
}
}
/// <summary>
/// Gets the owner of the value.
/// </summary>
public IPriorityValueOwner Owner { get; }
/// <summary>
/// Gets the property that the value represents.
/// </summary>
public AvaloniaProperty Property { get; }
/// <summary>
/// Gets the current value.
/// </summary>
public object Value => _value.value;
/// <summary>
/// Gets the priority of the binding that is currently active.
/// </summary>
public int ValuePriority => _value.priority;
/// <summary>
/// Adds a new binding.
/// </summary>
/// <param name="binding">The binding.</param>
/// <param name="priority">The binding priority.</param>
/// <returns>
/// A disposable that will remove the binding.
/// </returns>
public IDisposable Add(IObservable<object> binding, int priority)
{
return GetLevel(priority).Add(binding);
}
/// <summary>
/// Sets the value for a specified priority.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="priority">The priority</param>
public void SetValue(object value, int priority)
{
GetLevel(priority).DirectValue = value;
}
/// <summary>
/// Gets the currently active bindings on this object.
/// </summary>
/// <returns>An enumerable collection of bindings.</returns>
public IEnumerable<PriorityBindingEntry> GetBindings()
{
foreach (var level in _levels)
{
foreach (var binding in level.Value.Bindings)
{
yield return binding;
}
}
}
/// <summary>
/// Returns diagnostic string that can help the user debug the bindings in effect on
/// this object.
/// </summary>
/// <returns>A diagnostic string.</returns>
public string GetDiagnostic()
{
var b = new StringBuilder();
var first = true;
foreach (var level in _levels)
{
if (!first)
{
b.AppendLine();
}
b.Append(ValuePriority == level.Key ? "*" : string.Empty);
b.Append("Priority ");
b.Append(level.Key);
b.Append(": ");
b.AppendLine(level.Value.Value?.ToString() ?? "(null)");
b.AppendLine("--------");
b.Append("Direct: ");
b.AppendLine(level.Value.DirectValue?.ToString() ?? "(null)");
foreach (var binding in level.Value.Bindings)
{
b.Append(level.Value.ActiveBindingIndex == binding.Index ? "*" : string.Empty);
b.Append(binding.Description ?? binding.Observable.GetType().Name);
b.Append(": ");
b.AppendLine(binding.Value?.ToString() ?? "(null)");
}
first = false;
}
return b.ToString();
}
/// <summary>
/// Called when the value for a priority level changes.
/// </summary>
/// <param name="level">The priority level of the changed entry.</param>
public void LevelValueChanged(PriorityLevel level)
{
if (level.Priority <= ValuePriority)
{
if (level.Value != AvaloniaProperty.UnsetValue)
{
UpdateValue(level.Value, level.Priority);
}
else
{
foreach (var i in _levels.Values.OrderBy(x => x.Priority))
{
if (i.Value != AvaloniaProperty.UnsetValue)
{
UpdateValue(i.Value, i.Priority);
return;
}
}
UpdateValue(AvaloniaProperty.UnsetValue, int.MaxValue);
}
}
}
/// <summary>
/// Called when a priority level encounters an error.
/// </summary>
/// <param name="level">The priority level of the changed entry.</param>
/// <param name="error">The binding error.</param>
public void LevelError(PriorityLevel level, BindingNotification error)
{
Owner.LogError(Property, error.Error);
}
/// <summary>
/// Causes a revalidation of the value.
/// </summary>
public void Revalidate()
{
if (_validate != null)
{
PriorityLevel level;
if (_levels.TryGetValue(ValuePriority, out level))
{
UpdateValue(level.Value, level.Priority);
}
}
}
/// <summary>
/// Gets the <see cref="PriorityLevel"/> with the specified priority, creating it if it
/// doesn't already exist.
/// </summary>
/// <param name="priority">The priority.</param>
/// <returns>The priority level.</returns>
private PriorityLevel GetLevel(int priority)
{
PriorityLevel result;
if (!_levels.TryGetValue(priority, out result))
{
result = new PriorityLevel(this, priority);
_levels.Add(priority, result);
}
return result;
}
/// <summary>
/// Updates the current <see cref="Value"/> and notifies all subscribers.
/// </summary>
/// <param name="value">The value to set.</param>
/// <param name="priority">The priority level that the value came from.</param>
private void UpdateValue(object value, int priority)
{
var newValue = (value, priority);
if (newValue == _value)
{
return;
}
if (_setter == null)
{
_setter = Owner.GetNonDirectDeferredSetter(Property);
}
_setter.SetAndNotifyCallback(Property, _setAndNotifyCallback, ref _value, newValue);
}
private void SetAndNotify(AvaloniaProperty property, ref (object value, int priority) backing, (object value, int priority) update)
{
var val = update.value;
var notification = val as BindingNotification;
object castValue;
if (notification != null)
{
val = (notification.HasValue) ? notification.Value : null;
}
if (TypeUtilities.TryConvertImplicit(_valueType, val, out castValue))
{
var old = backing.value;
if (_validate != null && castValue != AvaloniaProperty.UnsetValue)
{
castValue = _validate(castValue);
}
backing = (castValue, update.priority);
if (notification?.HasValue == true)
{
notification.SetValue(castValue);
}
if (notification == null || notification.HasValue)
{
Owner?.Changed(Property, ValuePriority, old, Value);
}
if (notification != null)
{
Owner?.BindingNotificationReceived(Property, notification);
}
}
else
{
Logger.Error(
LogArea.Binding,
Owner,
"Binding produced invalid value for {$Property} ({$PropertyType}): {$Value} ({$ValueType})",
Property.Name,
_valueType,
val,
val?.GetType());
}
}
}
}
| 34.678344 | 139 | 0.522638 | [
"MIT"
] | Karnah/Avalonia | src/Avalonia.Base/PriorityValue.cs | 10,889 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MusicListRank : MonoBehaviour
{
internal int[] InGameScoreSave;
static internal int InGameScore;
private void Start()
{
}
}
| 11.818182 | 42 | 0.669231 | [
"MIT"
] | see241/KataNote_VR | Assets/Katanote/Resource/Scripts/MusiicList/MusicListRank.cs | 262 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace SkiaSharp.Tests
{
public delegate IntPtr WNDPROC(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential)]
public struct WNDCLASS
{
public uint style;
[MarshalAs(UnmanagedType.FunctionPtr)]
public WNDPROC lpfnWndProc;
public int cbClsExtra;
public int cbWndExtra;
public IntPtr hInstance;
public IntPtr hIcon;
public IntPtr hCursor;
public IntPtr hbrBackground;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszMenuName;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszClassName;
}
}
| 24.259259 | 85 | 0.783206 | [
"MIT"
] | AlexanderSemenyak/SkiaSharp | tests/Tests/PlatformUtils/Win32/WNDCLASS.cs | 657 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Gov.Jag.PillPressRegistry.Interfaces
{
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for Applicationtypes.
/// </summary>
public static partial class ApplicationtypesExtensions
{
/// <summary>
/// Get entities from bcgov_applicationtypes
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='top'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
public static MicrosoftDynamicsCRMbcgovApplicationtypeCollection Get(this IApplicationtypes operations, int? top = default(int?), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>))
{
return operations.GetAsync(top, filter, count, orderby, select, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Get entities from bcgov_applicationtypes
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='top'>
/// </param>
/// <param name='filter'>
/// </param>
/// <param name='count'>
/// </param>
/// <param name='orderby'>
/// Order items by property values
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<MicrosoftDynamicsCRMbcgovApplicationtypeCollection> GetAsync(this IApplicationtypes operations, int? top = default(int?), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(top, filter, count, orderby, select, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Add new entity to bcgov_applicationtypes
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// New entity
/// </param>
/// <param name='prefer'>
/// Required in order for the service to return a JSON representation of the
/// object.
/// </param>
public static MicrosoftDynamicsCRMbcgovApplicationtype Create(this IApplicationtypes operations, MicrosoftDynamicsCRMbcgovApplicationtype body, string prefer = "return=representation")
{
return operations.CreateAsync(body, prefer).GetAwaiter().GetResult();
}
/// <summary>
/// Add new entity to bcgov_applicationtypes
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='body'>
/// New entity
/// </param>
/// <param name='prefer'>
/// Required in order for the service to return a JSON representation of the
/// object.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<MicrosoftDynamicsCRMbcgovApplicationtype> CreateAsync(this IApplicationtypes operations, MicrosoftDynamicsCRMbcgovApplicationtype body, string prefer = "return=representation", CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(body, prefer, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get entity from bcgov_applicationtypes by key
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bcgovApplicationtypeid'>
/// key: bcgov_applicationtypeid of bcgov_applicationtype
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
public static MicrosoftDynamicsCRMbcgovApplicationtype GetByKey(this IApplicationtypes operations, string bcgovApplicationtypeid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>))
{
return operations.GetByKeyAsync(bcgovApplicationtypeid, select, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Get entity from bcgov_applicationtypes by key
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bcgovApplicationtypeid'>
/// key: bcgov_applicationtypeid of bcgov_applicationtype
/// </param>
/// <param name='select'>
/// Select properties to be returned
/// </param>
/// <param name='expand'>
/// Expand related entities
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<MicrosoftDynamicsCRMbcgovApplicationtype> GetByKeyAsync(this IApplicationtypes operations, string bcgovApplicationtypeid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetByKeyWithHttpMessagesAsync(bcgovApplicationtypeid, select, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Update entity in bcgov_applicationtypes
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bcgovApplicationtypeid'>
/// key: bcgov_applicationtypeid of bcgov_applicationtype
/// </param>
/// <param name='body'>
/// New property values
/// </param>
public static void Update(this IApplicationtypes operations, string bcgovApplicationtypeid, MicrosoftDynamicsCRMbcgovApplicationtype body)
{
operations.UpdateAsync(bcgovApplicationtypeid, body).GetAwaiter().GetResult();
}
/// <summary>
/// Update entity in bcgov_applicationtypes
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bcgovApplicationtypeid'>
/// key: bcgov_applicationtypeid of bcgov_applicationtype
/// </param>
/// <param name='body'>
/// New property values
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task UpdateAsync(this IApplicationtypes operations, string bcgovApplicationtypeid, MicrosoftDynamicsCRMbcgovApplicationtype body, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.UpdateWithHttpMessagesAsync(bcgovApplicationtypeid, body, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Delete entity from bcgov_applicationtypes
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bcgovApplicationtypeid'>
/// key: bcgov_applicationtypeid of bcgov_applicationtype
/// </param>
/// <param name='ifMatch'>
/// ETag
/// </param>
public static void Delete(this IApplicationtypes operations, string bcgovApplicationtypeid, string ifMatch = default(string))
{
operations.DeleteAsync(bcgovApplicationtypeid, ifMatch).GetAwaiter().GetResult();
}
/// <summary>
/// Delete entity from bcgov_applicationtypes
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='bcgovApplicationtypeid'>
/// key: bcgov_applicationtypeid of bcgov_applicationtype
/// </param>
/// <param name='ifMatch'>
/// ETag
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this IApplicationtypes operations, string bcgovApplicationtypeid, string ifMatch = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(bcgovApplicationtypeid, ifMatch, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
}
}
| 46.016529 | 429 | 0.5625 | [
"Apache-2.0"
] | GeorgeWalker/jag-pill-press-registry | pill-press-interfaces/Dynamics-Autorest/ApplicationtypesExtensions.cs | 11,136 | C# |
using Newtonsoft.Json;
namespace Alipay.AopSdk.Core.Response
{
/// <summary>
/// AlipayMobilePublicMenuUserQueryResponse.
/// </summary>
public class AlipayMobilePublicMenuUserQueryResponse : AopResponse
{
/// <summary>
/// 结果码
/// </summary>
[JsonProperty("code")]
public string Code { get; set; }
/// <summary>
/// 菜单唯一标识
/// </summary>
[JsonProperty("menu_key")]
public string MenuKey { get; set; }
/// <summary>
/// 结果码描述
/// </summary>
[JsonProperty("msg")]
public string Msg { get; set; }
}
} | 19.75 | 67 | 0.616637 | [
"MIT"
] | ArcherTrister/LeXun.Alipay.AopSdk | src/Alipay.AopSdk.Core/Response/AlipayMobilePublicMenuUserQueryResponse.cs | 581 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.