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 |
|---|---|---|---|---|---|---|---|---|
// *** 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.Web.V20200901
{
public static class ListWebAppFunctionKeysSlot
{
/// <summary>
/// String dictionary resource.
/// </summary>
public static Task<ListWebAppFunctionKeysSlotResult> InvokeAsync(ListWebAppFunctionKeysSlotArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<ListWebAppFunctionKeysSlotResult>("azure-native:web/v20200901:listWebAppFunctionKeysSlot", args ?? new ListWebAppFunctionKeysSlotArgs(), options.WithVersion());
}
public sealed class ListWebAppFunctionKeysSlotArgs : Pulumi.InvokeArgs
{
/// <summary>
/// Function name.
/// </summary>
[Input("functionName", required: true)]
public string FunctionName { get; set; } = null!;
/// <summary>
/// Site name.
/// </summary>
[Input("name", required: true)]
public string Name { get; set; } = null!;
/// <summary>
/// Name of the resource group to which the resource belongs.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// Name of the deployment slot.
/// </summary>
[Input("slot", required: true)]
public string Slot { get; set; } = null!;
public ListWebAppFunctionKeysSlotArgs()
{
}
}
[OutputType]
public sealed class ListWebAppFunctionKeysSlotResult
{
/// <summary>
/// Resource Id.
/// </summary>
public readonly string Id;
/// <summary>
/// Kind of resource.
/// </summary>
public readonly string? Kind;
/// <summary>
/// Resource Name.
/// </summary>
public readonly string Name;
/// <summary>
/// Settings.
/// </summary>
public readonly ImmutableDictionary<string, string> Properties;
/// <summary>
/// The system metadata relating to this resource.
/// </summary>
public readonly Outputs.SystemDataResponse SystemData;
/// <summary>
/// Resource type.
/// </summary>
public readonly string Type;
[OutputConstructor]
private ListWebAppFunctionKeysSlotResult(
string id,
string? kind,
string name,
ImmutableDictionary<string, string> properties,
Outputs.SystemDataResponse systemData,
string type)
{
Id = id;
Kind = kind;
Name = name;
Properties = properties;
SystemData = systemData;
Type = type;
}
}
}
| 29.219048 | 214 | 0.580508 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/Web/V20200901/ListWebAppFunctionKeysSlot.cs | 3,068 | C# |
namespace AudioBand.Models
{
/// <summary>
/// Specifies the type of content for a button.
/// </summary>
public enum ButtonContentType
{
/// <summary>
/// Specifies that the button content is an image.
/// </summary>
Image,
/// <summary>
/// Specifies that the button content is text.
/// </summary>
Text,
}
}
| 22.052632 | 59 | 0.501193 | [
"MIT",
"BSD-3-Clause"
] | AudioBand/AudioBand | src/AudioBand/Models/ButtonContentType.cs | 421 | C# |
#if !JSB_UNITYLESS
using System;
using System.Reflection;
namespace jsb.Editor
{
using QuickJS.Unity;
using QuickJS.Binding;
using UnityEngine;
/// <summary>
/// the most essential types for scripting.
/// you could define your own BindingProcess anywhere in your project's 'Assets' editor directory,
/// add more types to export and transform even the types already added here.
/// </summary>
public class UnityBinding : AbstractBindingProcess
{
public bool IsAvailable(MethodInfo methodInfo)
{
return methodInfo != null && methodInfo.IsPublic;
}
public override void OnPreCollectAssemblies(BindingManager bindingManager)
{
HackGetComponents(bindingManager.TransformType(typeof(GameObject)));
HackGetComponents(bindingManager.TransformType(typeof(Component)));
bindingManager.TransformType(typeof(MonoBehaviour))
.WriteCrossBindingConstructor();
bindingManager.TransformType(typeof(ScriptableObject))
.WriteCrossBindingConstructor()
.SetMethodBlocked("CreateInstance", typeof(string))
// .SetMethodBlocked("CreateInstance", typeof(Type))
.AddTSMethodDeclaration("static CreateInstance<T extends ScriptableObject>(type: { new(): T }): T", "CreateInstance", typeof(Type))
.WriteCSMethodOverrideBinding("CreateInstance", ScriptableObjectFix.BindStatic_CreateInstance)
;
// var buildTarget = EditorUserBuildSettings.activeBuildTarget;
// if (buildTarget != BuildTarget.iOS)
// {
// bindingManager.AddTypePrefixBlacklist("UnityEngine.Apple");
// }
// if (buildTarget != BuildTarget.Android)
// {
// bindingManager.AddTypePrefixBlacklist("UnityEngine.Android");
// }
// bindingManager.AddTypePrefixBlacklist("SyntaxTree.");
// fix d.ts, some C# classes use explicit implemented interface method
bindingManager.SetTypeBlocked(typeof(UnityEngine.ILogHandler));
bindingManager.SetTypeBlocked(typeof(UnityEngine.ISerializationCallbackReceiver));
bindingManager.SetTypeBlocked(typeof(UnityEngine.Playables.ScriptPlayable<>));
bindingManager.SetTypeBlocked(typeof(AOT.MonoPInvokeCallbackAttribute));
// SetTypeBlocked(typeof(RendererExtensions));
bindingManager.TransformType(typeof(UnityEngine.Events.UnityEvent<>))
.Rename("UnityEvent1");
bindingManager.TransformType(typeof(UnityEngine.Events.UnityEvent<,>))
.Rename("UnityEvent2");
bindingManager.TransformType(typeof(UnityEngine.Events.UnityEvent<,,>))
.Rename("UnityEvent3");
bindingManager.TransformType(typeof(UnityEngine.Events.UnityEvent<,,,>))
.Rename("UnityEvent4");
bindingManager.TransformType(typeof(UnityEngine.Texture))
.SetMemberBlocked("imageContentsHash");
bindingManager.TransformType(typeof(UnityEngine.Texture2D))
.AddRequiredDefinesForMember("alphaIsTransparency", "UNITY_EDITOR");
bindingManager.TransformType(typeof(UnityEngine.Input))
.SetMemberBlocked("IsJoystickPreconfigured"); // specific platform available only
bindingManager.TransformType(typeof(UnityEngine.MonoBehaviour))
.SetMemberBlocked("runInEditMode"); // editor only
bindingManager.TransformType(typeof(UnityEngine.QualitySettings))
.SetMemberBlocked("streamingMipmapsRenderersPerFrame");
}
public override void OnPreExporting(BindingManager bindingManager)
{
bindingManager.AddExportedType(typeof(LayerMask));
bindingManager.AddExportedType(typeof(Color));
bindingManager.AddExportedType(typeof(Color32));
bindingManager.AddExportedType(typeof(Vector2));
bindingManager.AddExportedType(typeof(Vector2Int));
bindingManager.AddExportedType(typeof(Vector3));
bindingManager.AddExportedType(typeof(Vector3Int));
bindingManager.AddExportedType(typeof(Vector4));
bindingManager.AddExportedType(typeof(Rect));
bindingManager.AddExportedType(typeof(Quaternion));
bindingManager.AddExportedType(typeof(Matrix4x4));
bindingManager.AddExportedType(typeof(PrimitiveType));
bindingManager.AddExportedType(typeof(UnityEngine.Object))
.EnableOperatorOverloading(false)
;
bindingManager.AddExportedType(typeof(KeyCode));
bindingManager.AddExportedType(typeof(Texture));
bindingManager.AddExportedType(typeof(Texture2D));
bindingManager.AddExportedType(typeof(Material));
bindingManager.AddExportedType(typeof(Time));
bindingManager.AddExportedType(typeof(Random));
bindingManager.AddExportedType(typeof(GameObject), true);
bindingManager.AddExportedType(typeof(Camera), true);
bindingManager.AddExportedType(typeof(Transform), true);
bindingManager.AddExportedType(typeof(RectTransform), true);
bindingManager.AddExportedType(typeof(MonoBehaviour), true);
bindingManager.AddExportedType(typeof(ScriptableObject), true);
bindingManager.AddExportedType(typeof(Sprite), true);
bindingManager.AddExportedType(typeof(SpriteRenderer), true);
bindingManager.AddExportedType(typeof(Animation), true);
bindingManager.AddExportedType(typeof(AnimationClip), true);
bindingManager.AddExportedType(typeof(Animator), true);
bindingManager.AddExportedType(typeof(AnimationState), true);
bindingManager.AddExportedType(typeof(WrapMode), true);
bindingManager.AddExportedType(typeof(Debug));
bindingManager.AddExportedType(typeof(WaitForSeconds), true);
bindingManager.AddExportedType(typeof(WaitForEndOfFrame), true);
bindingManager.AddExportedType(typeof(Input));
bindingManager.AddExportedType(typeof(Application));
bindingManager.AddExportedType(typeof(Ray));
bindingManager.AddExportedType(typeof(RaycastHit));
bindingManager.AddExportedType(typeof(Physics));
bindingManager.AddExportedType(typeof(Collider));
bindingManager.AddExportedType(typeof(BoxCollider));
bindingManager.AddExportedType(typeof(SphereCollider));
bindingManager.AddExportedType(typeof(Rigidbody));
bindingManager.AddExportedType(typeof(Resources))
.SetAllConstructorsBlocked()
// .SetMethodBlocked("FindObjectsOfTypeAll", typeof(Type))
.AddTSMethodDeclaration("static FindObjectsOfTypeAll<T extends Object>(type: { new(): T }): T[]", "FindObjectsOfTypeAll", typeof(Type))
.WriteCSMethodOverrideBinding("FindObjectsOfTypeAll", ResourcesFix.BindStatic_FindObjectsOfTypeAll)
;
bindingManager.AddExportedType(typeof(QuickJS.Unity.JSSerializationContext)).SetAllConstructorsBlocked();
}
private static TypeTransform HackGetComponents(TypeTransform typeTransform)
{
if (typeTransform.type == typeof(GameObject))
{
typeTransform.AddTSMethodDeclaration($"AddComponent<T extends Component>(type: {{ new(): T }}): T",
"AddComponent", typeof(Type));
typeTransform.WriteCSMethodOverrideBinding("AddComponent", GameObjectFix.Bind_AddComponent);
typeTransform.WriteCSMethodOverrideBinding("GetComponent", GameObjectFix.Bind_GetComponent);
typeTransform.WriteCSMethodOverrideBinding("GetComponentInChildren", GameObjectFix.Bind_GetComponentInChildren);
typeTransform.WriteCSMethodOverrideBinding("GetComponentInParent", GameObjectFix.Bind_GetComponentInParent);
typeTransform.WriteCSMethodOverrideBinding("GetComponentsInChildren", GameObjectFix.Bind_GetComponentsInChildren);
typeTransform.WriteCSMethodOverrideBinding("GetComponentsInParent", GameObjectFix.Bind_GetComponentsInParent);
typeTransform.WriteCSMethodOverrideBinding("GetComponents", GameObjectFix.Bind_GetComponents);
}
else
{
typeTransform.WriteCSMethodOverrideBinding("GetComponent", ComponentFix.Bind_GetComponent);
typeTransform.WriteCSMethodOverrideBinding("GetComponentInChildren", ComponentFix.Bind_GetComponentInChildren);
typeTransform.WriteCSMethodOverrideBinding("GetComponentInParent", ComponentFix.Bind_GetComponentInParent);
typeTransform.WriteCSMethodOverrideBinding("GetComponentsInChildren", ComponentFix.Bind_GetComponentsInChildren);
typeTransform.WriteCSMethodOverrideBinding("GetComponentsInParent", ComponentFix.Bind_GetComponentsInParent);
typeTransform.WriteCSMethodOverrideBinding("GetComponents", ComponentFix.Bind_GetComponents);
}
typeTransform.AddTSMethodDeclaration($"GetComponent<T extends Component>(type: {{ new(): T }}): T",
"GetComponent", typeof(Type))
.AddTSMethodDeclaration($"GetComponentInChildren<T extends Component>(type: {{ new(): T }}, includeInactive: boolean): T",
"GetComponentInChildren", typeof(Type), typeof(bool))
.AddTSMethodDeclaration($"GetComponentInChildren<T extends Component>(type: {{ new(): T }}): T",
"GetComponentInChildren", typeof(Type))
.AddTSMethodDeclaration($"GetComponentInParent<T extends Component>(type: {{ new(): T }}): T",
"GetComponentInParent", typeof(Type))
.AddTSMethodDeclaration($"GetComponents<T extends Component>(type: {{ new(): T }}): T[]",
"GetComponents", typeof(Type))
.AddTSMethodDeclaration($"GetComponentsInChildren<T extends Component>(type: {{ new(): T }}, includeInactive: boolean): T[]",
"GetComponentsInChildren", typeof(Type), typeof(bool))
.AddTSMethodDeclaration($"GetComponentsInChildren<T extends Component>(type: {{ new(): T }}): T[]",
"GetComponentsInChildren", typeof(Type))
.AddTSMethodDeclaration($"GetComponentsInParent<T extends Component>(type: {{ new(): T }}, includeInactive: boolean): T[]",
"GetComponentsInParent", typeof(Type), typeof(bool))
.AddTSMethodDeclaration($"GetComponentsInParent<T extends Component>(type: {{ new(): T }}): T[]",
"GetComponentsInParent", typeof(Type))
;
return typeTransform;
}
}
}
#endif | 59.436842 | 152 | 0.656779 | [
"MIT"
] | shunfy/unity-jsb | Packages/cc.starlessnight.unity-jsb/Source/Unity/Editor/CustomBindings/UnityBinding.cs | 11,293 | C# |
using SeniorBlockchain.Base;
using SeniorBlockchain.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace SeniorBlockchain.Builder
{
/// <summary>
/// A class providing extension methods for <see cref="IFullNodeBuilder"/>.
/// </summary>
public static class FullNodeBuilderNodeSettingsExtension
{
/// <summary>
/// Makes the full node builder use specific node settings.
/// </summary>
/// <param name="builder">Full node builder to change node settings for.</param>
/// <param name="nodeSettings">Node settings to be used.</param>
/// <returns>Interface to allow fluent code.</returns>
public static IFullNodeBuilder UseNodeSettings(this IFullNodeBuilder builder, NodeSettings nodeSettings)
{
var nodeBuilder = builder as FullNodeBuilder;
nodeBuilder.NodeSettings = nodeSettings;
nodeBuilder.Network = nodeSettings.Network;
builder.ConfigureServices(service =>
{
service.AddSingleton(nodeBuilder.NodeSettings);
service.AddSingleton(nodeBuilder.Network);
});
return builder.UseBaseFeature();
}
/// <summary>
/// Makes the full node builder use the default node settings.
/// </summary>
/// <param name="builder">Full node builder to change node settings for.</param>
/// <returns>Interface to allow fluent code.</returns>
public static IFullNodeBuilder UseDefaultNodeSettings(this IFullNodeBuilder builder)
{
return builder.UseNodeSettings(NodeSettings.Default(builder.Network));
}
}
}
| 38.590909 | 112 | 0.649588 | [
"MIT"
] | seniorblockchain/blockchain | src/SeniorBlockchain/Builder/FullNodeBuilderNodeSettingsExtension.cs | 1,700 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using SistemaControle.Models;
namespace SistemaControle.Controllers
{
[Authorize]
public class ManageController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public ManageController()
{
}
public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Manage/Index
public async Task<ActionResult> Index(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? "An error has occurred."
: message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed."
: "";
var userId = User.Identity.GetUserId();
var model = new IndexViewModel
{
HasPassword = HasPassword(),
PhoneNumber = await UserManager.GetPhoneNumberAsync(userId),
TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId),
Logins = await UserManager.GetLoginsAsync(userId),
BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId)
};
return View(model);
}
//
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey)
{
ManageMessageId? message;
var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey));
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
message = ManageMessageId.RemoveLoginSuccess;
}
else
{
message = ManageMessageId.Error;
}
return RedirectToAction("ManageLogins", new { Message = message });
}
//
// GET: /Manage/AddPhoneNumber
public ActionResult AddPhoneNumber()
{
return View();
}
//
// POST: /Manage/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number);
if (UserManager.SmsService != null)
{
var message = new IdentityMessage
{
Destination = model.Number,
Body = "Your security code is: " + code
};
await UserManager.SmsService.SendAsync(message);
}
return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number });
}
//
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> EnableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", "Manage");
}
//
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DisableTwoFactorAuthentication()
{
await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false);
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", "Manage");
}
//
// GET: /Manage/VerifyPhoneNumber
public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber)
{
var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber);
// Send an SMS through the SMS provider to verify the phone number
return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
//
// POST: /Manage/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess });
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "Failed to verify phone");
return View(model);
}
//
// POST: /Manage/RemovePhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RemovePhoneNumber()
{
var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null);
if (!result.Succeeded)
{
return RedirectToAction("Index", new { Message = ManageMessageId.Error });
}
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess });
}
//
// GET: /Manage/ChangePassword
public ActionResult ChangePassword()
{
return View();
}
//
// POST: /Manage/ChangePassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}
//
// GET: /Manage/SetPassword
public ActionResult SetPassword()
{
return View();
}
//
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SetPassword(SetPasswordViewModel model)
{
if (ModelState.IsValid)
{
var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Manage/ManageLogins
public async Task<ActionResult> ManageLogins(ManageMessageId? message)
{
ViewBag.StatusMessage =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.Error ? "An error has occurred."
: "";
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user == null)
{
return View("Error");
}
var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId());
var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList();
ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
//
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId());
}
//
// GET: /Manage/LinkLoginCallback
public async Task<ActionResult> LinkLoginCallback()
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId());
if (loginInfo == null)
{
return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login);
return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}
protected override void Dispose(bool disposing)
{
if (disposing && _userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private bool HasPassword()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PasswordHash != null;
}
return false;
}
private bool HasPhoneNumber()
{
var user = UserManager.FindById(User.Identity.GetUserId());
if (user != null)
{
return user.PhoneNumber != null;
}
return false;
}
public enum ManageMessageId
{
AddPhoneSuccess,
ChangePasswordSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
#endregion
}
} | 37.321337 | 176 | 0.551936 | [
"MIT"
] | Cesar1986BR/Sistema-Controle | SistemaControle/Controllers/MVC/ManageController.cs | 14,520 | C# |
#region Copyright
//
<<<<<<< HEAD
<<<<<<< HEAD
=======
=======
>>>>>>> update form orginal repo
// DotNetNuke® - https://www.dnnsoftware.com
// Copyright (c) 2002-2018
// by DotNetNuke Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
<<<<<<< HEAD
>>>>>>> Merges latest changes from release/9.4.x into development (#3178)
=======
>>>>>>> update form orginal repo
#region Usings
using System;
using Telerik.Web.UI;
#endregion
namespace DotNetNuke.Web.UI.WebControls
{
public class DnnTreeView : RadTreeView
{
//public DnnTreeView()
//{
// Utilities.ApplySkin(this);
//}
}
} | 34.142857 | 116 | 0.708308 | [
"MIT"
] | DnnSoftwarePersian/Dnn.Platform | DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnTreeView.cs | 1,674 | 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.ContainerService.V20191001.Outputs
{
[OutputType]
public sealed class ManagedClusterServicePrincipalProfileResponse
{
/// <summary>
/// The ID for the service principal.
/// </summary>
public readonly string ClientId;
/// <summary>
/// The secret password associated with the service principal in plain text.
/// </summary>
public readonly string? Secret;
[OutputConstructor]
private ManagedClusterServicePrincipalProfileResponse(
string clientId,
string? secret)
{
ClientId = clientId;
Secret = secret;
}
}
}
| 27.805556 | 84 | 0.647353 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/ContainerService/V20191001/Outputs/ManagedClusterServicePrincipalProfileResponse.cs | 1,001 | C# |
using Ipfs;
using System;
using System.IO;
using System.Threading.Tasks;
namespace IDVN.Web.Logic
{
public class IPFSService : IDisposable
{
private readonly IpfsClient ipfs;
public IPFSService()
{
this.ipfs = new IpfsClient();
}
public async Task<string> AddFile(string fileName, Stream fileStream)
{
if (string.IsNullOrEmpty(fileName))
{
return null;
}
if (fileStream == null)
{
return null;
}
using (var inputStream = new IpfsStream(fileName, fileStream))
{
var node = await ipfs.Add(inputStream);
return node.ToString();
}
}
public async Task<Stream> ReadFile(string hash)
{
if (string.IsNullOrEmpty(hash))
{
return null;
}
return await ipfs.Cat(hash);
}
public void Dispose()
{
using (var ipfs = new IpfsClient())
{
var peers = ipfs.Swarm.Peers().GetAwaiter().GetResult();
ipfs.Swarm.Disconnect(peers).Wait();
}
}
}
}
| 22.553571 | 77 | 0.480602 | [
"MIT"
] | dzhenko/IDvNEXT | IDVN.Web/Logic/IPFSService.cs | 1,263 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace razor1.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
| 20.115385 | 54 | 0.632887 | [
"MIT"
] | junioridi/portfolio | h-care/razor1/Pages/Index.cshtml.cs | 525 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OutputLogListener.cs" company="CatenaLogic">
// Copyright (c) 2014 - 2016 CatenaLogic. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace PdbGit.Logging
{
using System;
using Catel.Logging;
internal class OutputLogListener : ConsoleLogListener
{
internal OutputLogListener()
{
IgnoreCatelLogging = true;
IsDebugEnabled = true;
}
protected override string FormatLogEvent(ILog log, string message, LogEvent logEvent, object extraData, LogData logData, DateTime time)
{
return message;
}
}
} | 34.16 | 143 | 0.462529 | [
"MIT"
] | AArnott/GitLink | src/PdbGit/Logging/OutputLogListener.cs | 856 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über die folgenden
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die mit einer Assembly verknüpft sind.
[assembly: AssemblyTitle("KaupischIT.CardReader")]
[assembly: AssemblyDescription("Stellt Funktionen bereit, um Daten von Krankenversichertenkarten & elektronischen Gesundheitskarten auszulesen")]
[assembly: AssemblyCompany("Kaupisch IT-Systeme GmbH")]
[assembly: AssemblyProduct("KaupischIT.CardReader")]
[assembly: AssemblyCopyright("Copyright © Kaupisch IT-Systeme GmbH")]
// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar
// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von
// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("225f8fd0-c99f-4173-9811-7b98bf29fa04")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
| 46.90625 | 146 | 0.758161 | [
"MIT"
] | Kaupisch-IT/eGK-KVK | KaupischIT.CardReader/Properties/AssemblyInfo.cs | 1,519 | C# |
using System;
using Server;
using System.IO;
using Server.Commands;
using Server.Items;
using Server.Mobiles;
using Server.Network;
namespace Server
{
public static class DecorateML
{
public static void Initialize()
{
CommandSystem.Register( "DecorateML", AccessLevel.Administrator, new CommandEventHandler( DecorateML_OnCommand ) );
}
[Usage( "DecorateML" )]
[Description( "Generates Mondain's Legacy world decoration." )]
private static void DecorateML_OnCommand( CommandEventArgs e )
{
e.Mobile.SendMessage( "Generating Mondain's Legacy world decoration, please wait." );
Decorate.Generate( "Data/Decoration/Mondain's Legacy/Trammel", Map.Trammel );
Decorate.Generate( "Data/Decoration/Mondain's Legacy/Felucca", Map.Felucca );
Decorate.Generate( "Data/Decoration/Mondain's Legacy/Ilshenar", Map.Ilshenar );
Decorate.Generate( "Data/Decoration/Mondain's Legacy/Malas", Map.Malas );
Decorate.Generate( "Data/Decoration/Mondain's Legacy/Tokuno", Map.Tokuno );
e.Mobile.SendMessage( "Mondain's Legacy world generation complete." );
}
}
} | 33.060606 | 118 | 0.744271 | [
"BSD-2-Clause"
] | greeduomacro/vivre-uo | Scripts/Customs/Nerun's Distro/ML/Commands/DecorateML.cs | 1,091 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace MssqlRabbitTool
{
public class QueueInventory
{
public string ConsumerGroup { get; set; }
public string ExchangeName { get; set; }
public string QueuePrefix { get; set; }
public int QueueCount { get; set; }
public int LeaseExpirySeconds { get; set; }
}
}
| 24.125 | 51 | 0.65285 | [
"MIT"
] | Rebalanser/rebalanser-net-mssql | src/MssqlRabbitTool/QueueInventory.cs | 388 | C# |
//
// HttpMethod.cs
//
// Author:
// Martin Baulig <martin.baulig@xamarin.com>
//
// Copyright (c) 2015 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
namespace Xamarin.WebTests.HttpClient
{
public enum HttpMethod
{
Get,
Post,
Put,
Head,
Delete
}
}
| 33.175 | 80 | 0.743783 | [
"MIT"
] | stefb965/web-tests | Xamarin.WebTests.Framework/Xamarin.WebTests.HttpClient/HttpMethod.cs | 1,329 | C# |
namespace Stumps.Server.Data
{
using System;
using System.IO;
using NUnit.Framework;
[TestFixture]
public class ConfigurationDataAccessTests
{
[Test]
public void Configuration_WithNullFileName_ThrowsException()
{
Assert.That(
() => new ConfigurationDataAccess(null),
Throws.Exception.TypeOf<ArgumentNullException>().With.Property("ParamName").EqualTo("configurationFile"));
}
[Test]
public void Configuration_WithValidFileName_DoesNotThrowError()
{
Assert.DoesNotThrow(() => new ConfigurationDataAccess("someValue"));
}
[Test]
public void LoadConfiguration_LoadsExpectedEntity()
{
var tempFile = Path.GetTempFileName();
File.WriteAllText(tempFile, TestData.SampleConfiguration);
try
{
var dal = new ConfigurationDataAccess(tempFile);
var entity = dal.LoadConfiguration();
Assert.IsNotNull(entity);
Assert.AreEqual(100, entity.DataCompatibilityVersion);
StringAssert.AreEqualIgnoringCase("C:\\SomeValue\\", entity.StoragePath);
Assert.AreEqual(8000, entity.WebApiPort);
}
finally
{
File.Delete(tempFile);
}
}
[Test]
public void SaveConfiguration_WithNullValue_ThrowsException()
{
var tempFile = Path.GetTempFileName();
try
{
var dal = new ConfigurationDataAccess(tempFile);
Assert.That(
() => dal.SaveConfiguration(null),
Throws.Exception.TypeOf<ArgumentNullException>().With.Property("ParamName").EqualTo("value"));
}
finally
{
File.Delete(tempFile);
}
}
[Test]
public void SaveConfiguration_WithValidEntity_CreateExpectedFile()
{
var tempFile = Path.GetTempFileName();
try
{
var dal = new ConfigurationDataAccess(tempFile);
var entity = new ConfigurationEntity
{
DataCompatibilityVersion = 100,
StoragePath = "C:\\SomeValue\\",
WebApiPort = 8000
};
dal.SaveConfiguration(entity);
var savedText = File.ReadAllText(tempFile);
StringAssert.AreEqualIgnoringCase(TestData.SampleConfiguration, savedText);
}
finally
{
File.Delete(tempFile);
}
}
}
}
| 29.308511 | 122 | 0.53176 | [
"Apache-2.0"
] | Pankaj-chhatani/stumps | src/test/unit/Stumps.Server.Tests/Data/ConfigurationDataAccessTests.cs | 2,757 | C# |
using System;
using System.Web.Routing;
using JetBrains.Annotations;
using Orchard.ContentManagement;
using Orchard.Settings;
using Orchard.Themes.Models;
namespace Orchard.Themes.Services {
[UsedImplicitly]
public class SiteThemeSelector : IThemeSelector {
protected virtual ISite CurrentSite { get; [UsedImplicitly] private set; }
public ThemeSelectorResult GetTheme(RequestContext context) {
string currentThemeName = CurrentSite.As<ThemeSiteSettings>().Record.CurrentThemeName;
if (String.IsNullOrEmpty(currentThemeName)) {
return null;
}
return new ThemeSelectorResult { Priority = -5, ThemeName = currentThemeName };
}
}
} | 31.541667 | 99 | 0.676354 | [
"BSD-3-Clause"
] | mofashi2011/orchardcms | src/Orchard.Web/Modules/Orchard.Themes/Services/SiteThemeSelector.cs | 759 | C# |
using System.Collections;
using UnityEngine;
using Assets.Gamelogic.Core;
using Assets.Gamelogic.Utils;
using Improbable.Abilities;
using Improbable.Fire;
using Improbable.Gdk.GameObjectRepresentation;
namespace Assets.Gamelogic.Player
{
[WorkerType(WorkerPlatform.UnityClient)]
public class PlayerAnimController : MonoBehaviour
{
[Require] private Spells.Requirable.Reader spells;
[Require] private Flammable.Requirable.Reader flammable;
private Vector3 lastPosition;
[SerializeField] private Animator anim;
[SerializeField] private ParticleSystem CastAnim;
[SerializeField] private GameObject playerModel;
private void Awake()
{
anim = gameObject.GetComponentIfUnassigned(anim);
anim.enabled = true;
}
private void OnEnable()
{
flammable.ComponentUpdated += FlammableUpdated;
lastPosition = transform.position;
}
private void OnDisable()
{
}
private void FlammableUpdated(Flammable.Update update)
{
if (update.IsOnFire.HasValue)
{
anim.SetBool("OnFire", update.IsOnFire.Value);
}
}
private void Update()
{
float movementTargetDistance = (lastPosition - transform.position).magnitude;
float animSpeed = Mathf.Min(1, movementTargetDistance / SimulationSettings.PlayerMovementTargetSlowingThreshold);
anim.SetFloat("ForwardSpeed", animSpeed);
lastPosition = transform.position;
}
public void AnimateSpellCast()
{
CastAnim.Play();
anim.SetTrigger("CastLightning");
StartCoroutine(TimerUtils.WaitAndPerform(SimulationSettings.PlayerCastAnimationTime, CancelCastAnim));
}
private void CancelCastAnim()
{
CastAnim.Stop();
}
public void SetModelVisibility(bool isVisible)
{
playerModel.SetActive(isVisible);
}
}
}
| 28.534247 | 125 | 0.630341 | [
"MIT"
] | tsukitsutsuki/sdk-for-unity-wizards-tutorial | workers/unity/Assets/Gamelogic/Player/PlayerAnimController.cs | 2,083 | C# |
namespace More.Windows.Controls
{
using global::Windows.UI.Xaml.Controls;
using global::Windows.UI.Xaml.Navigation;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
/// <summary>
/// Represents a <see cref="INavigationService">navigation service</see> adapter for a <see cref="WebView">web view</see>.
/// </summary>
[CLSCompliant( false )]
public class WebViewNavigationAdapter : INavigationService
{
readonly WebView webView;
/// <summary>
/// Initializes a new instance of the <see cref="WebViewNavigationAdapter"/> class.
/// </summary>
/// <param name="webView">The <see cref="WebView">web view</see> to adapt to.</param>
public WebViewNavigationAdapter( WebView webView )
{
Arg.NotNull( webView, nameof( webView ) );
this.webView = webView;
this.webView.NavigationCompleted += OnWebViewNavigationCompleted;
this.webView.NavigationStarting += OnSourceNavigationStarting;
}
/// <summary>
/// Gets the underlying web view.
/// </summary>
/// <value>The underlying <see cref="WebView">web view</see> being adapted to.</value>
protected WebView WebView
{
get
{
Contract.Ensures( webView != null );
return webView;
}
}
void OnWebViewNavigationCompleted( WebView sender, WebViewNavigationCompletedEventArgs args )
{
Contract.Requires( args != null );
var e = new WebViewNavigationCompletedEventArgsAdapter( args );
if ( args.IsSuccess )
{
OnNavigated( e );
}
else
{
OnNavigationFailed( e );
}
}
/// <summary>
/// Raises the <see cref="Navigated"/> event.
/// </summary>
/// <param name="e">The <see cref="INavigationEventArgs"/> event data.</param>
[SuppressMessage( "Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "e", Justification = "This is the standard raise event signature." )]
protected virtual void OnNavigated( INavigationEventArgs e )
{
Arg.NotNull( e, nameof( e ) );
Navigated?.Invoke( this, e );
}
/// <summary>
/// Raises the <see cref="Navigating"/> event.
/// </summary>
/// <param name="e">The <see cref="NavigatingCancelEventArgs"/> event data.</param>
[SuppressMessage( "Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "e", Justification = "This is the standard raise event signature." )]
protected virtual void OnNavigating( INavigationStartingEventArgs e )
{
Arg.NotNull( e, nameof( e ) );
Navigating?.Invoke( this, e );
}
/// <summary>
/// Raises the <see cref="NavigationFailed"/> event.
/// </summary>
/// <param name="e">The <see cref="INavigationEventArgs"/> event data.</param>
[SuppressMessage( "Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "e", Justification = "This is the standard raise event signature." )]
protected virtual void OnNavigationFailed( INavigationEventArgs e )
{
Arg.NotNull( e, nameof( e ) );
NavigationFailed?.Invoke( this, e );
}
/// <summary>
/// Raises the <see cref="NavigationStopped"/> event.
/// </summary>
/// <param name="e">The <see cref="INavigationEventArgs"/> event data.</param>
[SuppressMessage( "Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "e", Justification = "This is the standard raise event signature." )]
protected virtual void OnNavigationStopped( INavigationEventArgs e )
{
Arg.NotNull( e, nameof( e ) );
NavigationStopped?.Invoke( this, e );
}
/// <summary>
/// Gets a value indicating whether there is at least one entry in back navigation history.
/// </summary>
/// <value>True if there is at least one entry in back navigation history; false if there are no entries in back navigation history or the
/// web view does not own its own navigation history.</value>
public virtual bool CanGoBack => WebView.CanGoBack;
/// <summary>
/// Gets a value indicating whether there is at least one entry in forward navigation history.
/// </summary>
/// <value>True if there is at least one entry in forward navigation history; false if there are no entries in forward navigation history or
/// the web view does not own its own navigation history.</value>
public virtual bool CanGoForward => WebView.CanGoForward;
/// <summary>
/// Navigates to the most recent item in back navigation history, if a web view manages its own navigation history.
/// </summary>
public virtual void GoBack() => WebView.GoBack();
/// <summary>
/// Navigates to the most recent item in forward navigation history, if a web view manages its own navigation history.
/// </summary>
public virtual void GoForward() => WebView.GoForward();
bool INavigationService.Navigate( Type sourcePageType, object parameter ) => throw new NotSupportedException();
/// <summary>
/// Causes the service to load content that is specified by URI, also passing a parameter to be interpreted by the target of the navigation.
/// </summary>
/// <param name="sourcePage">The <see cref="Uri">URL</see> of the content to load.</param>
/// <param name="parameter">The object parameter to pass to the target.</param>
/// <returns>True if the service can navigate according to its settings; otherwise, false.</returns>
public virtual bool Navigate( Uri sourcePage, object parameter )
{
if ( sourcePage == null )
{
return false;
}
// cannot evaluate Cancel because the event args cannot be created
WebView.Navigate( sourcePage );
return true;
}
[SuppressMessage( "Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Intentionally hidden because this adapter does not support cache sizes." )]
int INavigationService.SetCacheSize( int cacheSize ) => 0;
/// <summary>
/// Occurs when the content that is being navigated to has been found and is available from the Content property, although it may not have completed loading.
/// </summary>
public event EventHandler<INavigationEventArgs> Navigated;
/// <summary>
/// Occurs when a new navigation is requested.
/// </summary>
public event EventHandler<INavigationStartingEventArgs> Navigating;
/// <summary>
/// Occurs when an error is raised while navigating to the requested content.
/// </summary>
public event EventHandler<INavigationEventArgs> NavigationFailed;
/// <summary>
/// Occurs when a new navigation is requested while a current navigation is in progress.
/// </summary>
public event EventHandler<INavigationEventArgs> NavigationStopped;
void OnSourceNavigationStarting( WebView sender, WebViewNavigationStartingEventArgs args ) => OnNavigating( new WebViewNavigationStartingEventArgsAdapter( args ) );
sealed class WebViewNavigationCompletedEventArgsAdapter : INavigationEventArgs
{
readonly WebViewNavigationCompletedEventArgs source;
internal WebViewNavigationCompletedEventArgsAdapter( WebViewNavigationCompletedEventArgs source ) => this.source = source;
public object SourceEventArgs => source;
public bool IsSuccess => source.IsSuccess;
public Uri Uri => source.Uri;
}
sealed class WebViewNavigationStartingEventArgsAdapter : INavigationStartingEventArgs
{
readonly WebViewNavigationStartingEventArgs source;
internal WebViewNavigationStartingEventArgsAdapter( WebViewNavigationStartingEventArgs source ) => this.source = source;
public object SourceEventArgs => source;
public bool Cancel
{
get => source.Cancel;
set => source.Cancel = value;
}
public Uri Uri => source.Uri;
}
}
} | 42.897059 | 193 | 0.626786 | [
"MIT"
] | JTOne123/More | src/More.UI.Presentation/Platforms/uap10.0/More/Windows.Controls/WebViewNavigationAdapter.cs | 8,753 | C# |
using FluffyMusic.Core;
using FluffyMusic.Modules;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
namespace FluffyMusic.Web
{
public class Program
{
public static async Task Main(string[] args)
{
IHost host = CreateHostBuilder(args).Build();
//FluffyClient client = host.Services.GetRequiredService<FluffyClient>();
//CommandHandler handler = host.Services.GetRequiredService<CommandHandler>();
//await client.RunAsync();
//await handler.LoadModulesAsync(typeof(BasicModule).Assembly);
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
| 32.666667 | 90 | 0.640816 | [
"MIT"
] | Masya1/FluffyMusic | FluffyMusic.Web/Program.cs | 980 | C# |
using System;
namespace Cuyahoga.Core.Domain
{
/// <summary>
/// Association class between Node and Role.
/// </summary>
public class NodePermission : Permission
{
private Node _node;
/// <summary>
/// Property Node (Node)
/// </summary>
public Node Node
{
get { return this._node; }
set { this._node = value; }
}
/// <summary>
/// Default constructor.
/// </summary>
public NodePermission() : base()
{
}
}
}
| 16.482759 | 46 | 0.569038 | [
"BSD-3-Clause"
] | dineshkummarc/cuyahoga | src/Cuyahoga.Core/Domain/NodePermission.cs | 478 | C# |
using System.Diagnostics;
using xnaMugen.IO;
namespace xnaMugen.StateMachine.Controllers
{
[StateControllerName("TargetLifeAdd")]
internal class TargetLifeAdd : StateController
{
public TargetLifeAdd(StateSystem statesystem, string label, TextSection textsection)
: base(statesystem, label, textsection)
{
m_life = textsection.GetAttribute<Evaluation.Expression>("value", null);
m_targetid = textsection.GetAttribute<Evaluation.Expression>("ID", null);
m_kill = textsection.GetAttribute<Evaluation.Expression>("kill", null);
m_abs = textsection.GetAttribute<Evaluation.Expression>("absolute", null);
}
public override void Run(Combat.Character character)
{
var amount = EvaluationHelper.AsInt32(character, Amount, null);
var targetId = EvaluationHelper.AsInt32(character, TargetId, int.MinValue);
var cankill = EvaluationHelper.AsBoolean(character, CanKill, true);
var absolute = EvaluationHelper.AsBoolean(character, Absolute, false);
if (amount == null) return;
foreach (var target in character.GetTargets(targetId))
{
var newamount = amount.Value;
if (absolute == false && newamount < 0)
{
newamount = (int)(newamount * character.OffensiveInfo.AttackMultiplier);
newamount = (int)(newamount / target.DefensiveInfo.DefenseMultiplier);
}
target.Life += newamount;
if (target.Life == 0 && cankill == false) target.Life = 1;
}
}
public override bool IsValid()
{
if (base.IsValid() == false) return false;
if (Amount == null) return false;
return true;
}
public Evaluation.Expression Amount => m_life;
public Evaluation.Expression TargetId => m_targetid;
public Evaluation.Expression CanKill => m_kill;
public Evaluation.Expression Absolute => m_abs;
#region Fields
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Evaluation.Expression m_life;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Evaluation.Expression m_targetid;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Evaluation.Expression m_kill;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly Evaluation.Expression m_abs;
#endregion
}
} | 30.586667 | 87 | 0.720575 | [
"BSD-3-Clause"
] | BlazesRus/xnamugen | src/StateMachine/Controllers/TargetLifeAdd.cs | 2,294 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Circle:Shape
{
public Circle(double width, double height)
: base(width, height)
{
if (this.width != this.height)
{
throw new ArgumentException("Width must be equal to the height!");
}
}
public override double CalculateSurface()
{
return Math.PI*height*height;
}
}
| 19.416667 | 78 | 0.630901 | [
"MIT"
] | Ico093/TelerikAcademy | C#OOP/Homework/02.ObjectOrientedProgarammingPriciples2/ObjectOrientedProgarammingPriciples2/ObjectOrientedProgarammingPriciples2/Circle.cs | 468 | 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;
using System.Numerics;
using Windows.UI.Composition;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Hosting;
using Windows.UI.Xaml.Media.Animation;
namespace Microsoft.Toolkit.Uwp.UI.Animations.Effects
{
/// <summary>
/// An abstract class that provides the mechanism to create
/// an effect using composition.
/// </summary>
public abstract class AnimationEffect
{
private static string[] _effectProperties;
/// <summary>
/// Gets a value indicating whether this instance is supported.
/// </summary>
/// <value>
/// <c>true</c> if this instance is supported; otherwise, <c>false</c>.
/// </value>
public abstract bool IsSupported { get; }
/// <summary>
/// Gets the name of the effect.
/// </summary>
/// <value>
/// The name of the effect.
/// </value>
public abstract string EffectName { get; }
/// <summary>
/// Gets or sets the compositor.
/// </summary>
/// <value>
/// The compositor.
/// </value>
public Compositor Compositor { get; set; }
/// <summary>
/// Gets or sets the effect brush.
/// </summary>
/// <value>
/// The effect brush.
/// </value>
public CompositionEffectBrush EffectBrush { get; set; }
/// <summary>
/// Applies the effect.
/// </summary>
/// <returns>An array of strings of the effect properties to change.</returns>
public abstract string[] ApplyEffect();
/// <summary>
/// An animation which will apply the derived effect.
/// </summary>
/// <param name="animationSet">The animation set.</param>
/// <param name="value">The value.</param>
/// <param name="duration">The duration in milliseconds.</param>
/// <param name="delay">The delay in milliseconds.</param>
/// <param name="easingType">The easing function to use</param>
/// <param name="easingMode">The easing mode to use</param>
/// <returns>An animation set with the effect added to it.</returns>
public AnimationSet EffectAnimation(
AnimationSet animationSet,
double value = 0d,
double duration = 500d,
double delay = 0d,
EasingType easingType = EasingType.Default,
EasingMode easingMode = EasingMode.EaseOut)
{
if (animationSet == null)
{
return null;
}
if (!IsSupported)
{
return null;
}
var visual = animationSet.Visual;
var associatedObject = animationSet.Element as FrameworkElement;
if (associatedObject == null)
{
return animationSet;
}
Compositor = visual?.Compositor;
if (Compositor == null)
{
return null;
}
// check to see if the visual already has an effect applied.
var spriteVisual = ElementCompositionPreview.GetElementChildVisual(associatedObject) as SpriteVisual;
EffectBrush = spriteVisual?.Brush as CompositionEffectBrush;
if (EffectBrush == null || EffectBrush?.Comment != EffectName)
{
_effectProperties = ApplyEffect();
EffectBrush.Comment = EffectName;
var sprite = Compositor.CreateSpriteVisual();
sprite.Brush = EffectBrush;
ElementCompositionPreview.SetElementChildVisual(associatedObject, sprite);
sprite.Size = new Vector2((float)associatedObject.ActualWidth, (float)associatedObject.ActualHeight);
associatedObject.SizeChanged +=
(s, e) =>
{
sprite.Size = new Vector2(
(float)associatedObject.ActualWidth,
(float)associatedObject.ActualHeight);
};
}
if (duration <= 0)
{
foreach (var effectProperty in _effectProperties)
{
animationSet.AddEffectDirectPropertyChange(EffectBrush, (float)value, effectProperty);
}
}
else
{
#if NETFX_CORE
foreach (var effectProperty in _effectProperties)
{
var animation = Compositor.CreateScalarKeyFrameAnimation();
animation.InsertKeyFrame(1f, (float)value, AnimationExtensions.GetCompositionEasingFunction(easingType, Compositor, easingMode));
animation.Duration = TimeSpan.FromMilliseconds(duration);
animation.DelayTime = TimeSpan.FromMilliseconds(delay);
animationSet.AddCompositionEffectAnimation(EffectBrush, animation, effectProperty);
}
#endif
}
// Saturation starts from 1 to 0, instead of 0 to 1 so this makes sure the
// the brush isn't removed from the UI element incorrectly. Completing on
// Saturation as it's reusing the same sprite visual. Removing the Sprite removes the effect.
if (EffectName != "Saturation" && value == 0)
{
animationSet.Completed += AnimationSet_Completed;
}
return animationSet;
}
/// <summary>
/// Handles the Completed event of the AnimationSet control.
/// When an animation is completed the brush is removed from the sprite.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
private void AnimationSet_Completed(object sender, EventArgs e)
{
var animationSet = sender as AnimationSet;
if (animationSet != null)
{
animationSet.Completed -= AnimationSet_Completed;
var spriteVisual = ElementCompositionPreview.GetElementChildVisual(animationSet.Element) as SpriteVisual;
var brush = spriteVisual?.Brush as CompositionEffectBrush;
if (brush != null && brush.Comment == EffectName)
{
spriteVisual.Brush = null;
}
}
}
}
} | 36.291892 | 149 | 0.565386 | [
"MIT"
] | IamNeha99/Uno.WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI.Animations/Effects/AnimationEffect.cs | 6,714 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LargeFileExchange.Controllers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;
namespace LargeFileExchange
{
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.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "File Management API", Version = "v1" });
c.IncludeXmlComments(GetXmlCommentsPath());
c.OperationFilter<FileOperationFilter>();
});
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
}
private string GetXmlCommentsPath()
{
var app = PlatformServices.Default.Application;
return System.IO.Path.Combine(app.ApplicationBasePath, "chunked-upload-csharp.xml");
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSwagger(options => { });
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "api-docs";
c.SwaggerEndpoint("/swagger/v1/swagger.json", "File Management API v1");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.UseCors("MyPolicy");
app.UseDefaultFiles();
}
}
}
| 33.510204 | 143 | 0.587393 | [
"MIT"
] | MaxMelcher/GeoWebApp | Startup.cs | 3,286 | C# |
using Newtonsoft.Json;
namespace Notion.Client
{
public class VideoBlock : Block
{
public override BlockType Type => BlockType.Video;
[JsonProperty("video")]
public FileObject Video { get; set; }
}
}
| 18.384615 | 58 | 0.631799 | [
"MIT"
] | hognevevle/notion-sdk-net | Src/Notion.Client/Models/Blocks/VideoBlock.cs | 241 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace MSR.LST.MDShow {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Strings {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Strings() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MDShowManager.Strings", typeof(Strings).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to The crossbar output pin is not routed to any of the physical connectors we are aware of..
/// </summary>
internal static string CrossbarOutputPinNotRouted {
get {
return ResourceManager.GetString("CrossbarOutputPinNotRouted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This device does not support the IAMCrossbar interface!.
/// </summary>
internal static string DeviceDoesNotSupportError {
get {
return ResourceManager.GetString("DeviceDoesNotSupportError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to DirectShow ErrorText: {0}.
/// </summary>
internal static string DirectshowErrortext {
get {
return ResourceManager.GetString("DirectshowErrortext", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This device does not support the IAMAnalogVideoDecoder interface!.
/// </summary>
internal static string DoesNotSupportIAMAnalogVideoDecoder {
get {
return ResourceManager.GetString("DoesNotSupportIAMAnalogVideoDecoder", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This device does not support the IAMVfwCaptureDialogs interface!.
/// </summary>
internal static string DoesNotSupportIAMVfwCaptureDialogs {
get {
return ResourceManager.GetString("DoesNotSupportIAMVfwCaptureDialogs", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to File not found.
/// </summary>
internal static string FileNotFound {
get {
return ResourceManager.GetString("FileNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Filter with moniker {0} not found..
/// </summary>
internal static string FilterMonikerNotFound {
get {
return ResourceManager.GetString("FilterMonikerNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Filter with name {0} not found..
/// </summary>
internal static string FilterNameNotFound {
get {
return ResourceManager.GetString("FilterNameNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to InputPin count: {0}, index used: {1}.
/// </summary>
internal static string InputPinCount {
get {
return ResourceManager.GetString("InputPinCount", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to InputPin provided is not from this device!.
/// </summary>
internal static string InputPinError {
get {
return ResourceManager.GetString("InputPinError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid index, must be >= 0 and < {0}, index provided: {1}.
/// </summary>
internal static string InvalidIndex {
get {
return ResourceManager.GetString("InvalidIndex", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find CxpRtpFilters.ax in the local directory..
/// </summary>
internal static string MissingCxpRtpFiltersError {
get {
return ResourceManager.GetString("MissingCxpRtpFiltersError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find ScreenScraperFilter.ax in the local directory..
/// </summary>
internal static string MissingScreenScraperFilterError {
get {
return ResourceManager.GetString("MissingScreenScraperFilterError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Null is not a valid value for parameter 'rtpSender'.
/// </summary>
internal static string NullRtpSenderError {
get {
return ResourceManager.GetString("NullRtpSenderError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Null is not a valid value for parameter 'start'.
/// </summary>
internal static string NullStartError {
get {
return ResourceManager.GetString("NullStartError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to OutputPin count: {0}, index used: {1}.
/// </summary>
internal static string OutputPinCount {
get {
return ResourceManager.GetString("OutputPinCount", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to OutputPin provided is not from this device!.
/// </summary>
internal static string OutputPinError {
get {
return ResourceManager.GetString("OutputPinError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Can't RenderLocal when graph is already rendered.
/// </summary>
internal static string RenderLocalError {
get {
return ResourceManager.GetString("RenderLocalError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to rtpSender.
/// </summary>
internal static string RtpSender {
get {
return ResourceManager.GetString("RtpSender", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to start.
/// </summary>
internal static string Start {
get {
return ResourceManager.GetString("Start", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The 'start' parameter must be either the 'source' or 'compressor' filter.
/// </summary>
internal static string StartParameterError {
get {
return ResourceManager.GetString("StartParameterError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to convert - {0} to Guid.
/// </summary>
internal static string UnableToConvertToGuid {
get {
return ResourceManager.GetString("UnableToConvertToGuid", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find a compressor that supports - {0}.
/// </summary>
internal static string UnableToFindACompressor {
get {
return ResourceManager.GetString("UnableToFindACompressor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find audio compressor - {0}.
/// </summary>
internal static string UnableToFindAudioCompressor {
get {
return ResourceManager.GetString("UnableToFindAudioCompressor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find the default audio renderer - {0}.
/// </summary>
internal static string UnableToFindDefaultAudioRenderer {
get {
return ResourceManager.GetString("UnableToFindDefaultAudioRenderer", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find the default compressor - {0}.
/// </summary>
internal static string UnableToFindDefaultCompressor {
get {
return ResourceManager.GetString("UnableToFindDefaultCompressor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to find video compressor - {0}.
/// </summary>
internal static string UnableToFindVideoCompressor {
get {
return ResourceManager.GetString("UnableToFindVideoCompressor", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unexpected filter category.
/// </summary>
internal static string UnexpectedFilterCategory {
get {
return ResourceManager.GetString("UnexpectedFilterCategory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown filter category - {0}.
/// </summary>
internal static string UnknownFilterCategory {
get {
return ResourceManager.GetString("UnknownFilterCategory", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The device's video standard does not map to any of the video standards we are aware of..
/// </summary>
internal static string VideoStandardDoesNotMap {
get {
return ResourceManager.GetString("VideoStandardDoesNotMap", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Windows Media Audio V2.
/// </summary>
internal static string WindowsMediaAudioV2 {
get {
return ResourceManager.GetString("WindowsMediaAudioV2", resourceCulture);
}
}
}
}
| 40.011662 | 165 | 0.55494 | [
"Apache-2.0"
] | ForestLin001/conferencexp | MSR.LST.MDShow/MDShowManager/Strings.Designer.cs | 13,726 | 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 Microsoft.Build.Framework;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
using System;
using Microsoft.Build.Utilities;
using System.Linq;
namespace Microsoft.NET.Build.Tasks
{
public class GetAssemblyAttributes : TaskBase
{
[Required]
public string PathToTemplateFile { get; set; }
[Output]
public ITaskItem[] AssemblyAttributes { get; private set; }
protected override void ExecuteCore()
{
var fileVersionInfo = FileVersionInfo.GetVersionInfo(Path.GetFullPath(PathToTemplateFile));
Version assemblyVersion = FileUtilities.TryGetAssemblyVersion(Path.GetFullPath(PathToTemplateFile));
AssemblyAttributes = FormatToAttributes(AssemblyAttributesNameByFieldInFileVersionInfo: new Dictionary<string, string>
{
["System.Reflection.AssemblyCompanyAttribute"] = fileVersionInfo.CompanyName,
["System.Reflection.AssemblyCopyrightAttribute"] = fileVersionInfo.LegalCopyright,
["System.Reflection.AssemblyDescriptionAttribute"] = fileVersionInfo.Comments,
["System.Reflection.AssemblyFileVersionAttribute"] = fileVersionInfo.FileVersion,
["System.Reflection.AssemblyInformationalVersionAttribute"] = fileVersionInfo.ProductVersion,
["System.Reflection.AssemblyProductAttribute"] = fileVersionInfo.ProductName,
["System.Reflection.AssemblyTitleAttribute"] = fileVersionInfo.FileDescription,
["System.Reflection.AssemblyVersionAttribute"] = assemblyVersion != null ? assemblyVersion.ToString() : string.Empty
});
}
private ITaskItem[] FormatToAttributes(IDictionary<string, string> AssemblyAttributesNameByFieldInFileVersionInfo)
{
if (AssemblyAttributesNameByFieldInFileVersionInfo == null)
{
AssemblyAttributesNameByFieldInFileVersionInfo = new Dictionary<string, string>();
}
return AssemblyAttributesNameByFieldInFileVersionInfo
.Where(kv => !string.IsNullOrEmpty(kv.Value))
.Select(kv =>
{
var item = new TaskItem(kv.Key);
item.SetMetadata("_Parameter1", kv.Value);
return item;
})
.ToArray();
}
}
}
| 44 | 132 | 0.66718 | [
"MIT"
] | 01xOfFoo/sdk | src/Tasks/Microsoft.NET.Build.Tasks/GetAssemblyAttributes.cs | 2,598 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace fukuv0709_2.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}
| 34.387097 | 151 | 0.581614 | [
"MIT"
] | hayato88100329/fukuv0709_2 | fukuv0709_2/Properties/Settings.Designer.cs | 1,068 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AlibabaCloud.SDK.Dingtalkdrive_1_0.Models
{
public class DeleteSpaceRequest : TeaModel {
/// <summary>
/// 用户id
/// </summary>
[NameInMap("unionId")]
[Validation(Required=false)]
public string UnionId { get; set; }
}
}
| 19.136364 | 54 | 0.631829 | [
"Apache-2.0"
] | aliyun/dingtalk-sdk | dingtalk/csharp/core/drive_1_0/Models/DeleteSpaceRequest.cs | 425 | C# |
using CommandLine;
using MediatR;
namespace Wtfd.Commands.Init
{
[Verb("init", HelpText = "Initialize skeleton documentation json file.")]
public class InitRequest : IRequest<InitResponse>
{
[Option('t', "target", Required = false,
HelpText = "Specify the target directory. Current directory will be used otherwise.")]
public string Target { get; set; }
[Option('o', "overwrite", Required = false, Default = false, HelpText = "Overwrite if target exists.")]
public bool Overwrite { get; set; }
[Option('r', "root", Required = false, Default = true, HelpText = "Create a root configuration file")]
public bool IsRoot { get; set; }
}
} | 34.526316 | 105 | 0.698171 | [
"MIT"
] | garyng/wtfd | src/Wtfd/Commands/Init/InitRequest.cs | 658 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace vegetable_market
{
class Program
{
static void Main(string[] args)
{
var vegetablePrice = double.Parse(Console.ReadLine());
var fruitPrice = double.Parse(Console.ReadLine());
var vegetableKG = int.Parse(Console.ReadLine());
var fruitKG = int.Parse(Console.ReadLine());
Console.WriteLine(((vegetablePrice*vegetableKG) + (fruitPrice*fruitKG)) / 1.94);
}
}
}
| 26.409091 | 92 | 0.635112 | [
"MIT"
] | nikoivo/programming-basics | exam-1st/vegetable-market/Program.cs | 583 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace GlaucomaWay.Models
{
public class Vf14ResultModel
{
[Key]
public int Id { get; set; }
public DateTime Date { get; set; }
public Vf14Answer Q1Score { get; set; }
public Vf14Answer Q2Score { get; set; }
public Vf14Answer Q3Score { get; set; }
public Vf14Answer Q4Score { get; set; }
public Vf14Answer Q5Score { get; set; }
public Vf14Answer Q6Score { get; set; }
public Vf14Answer Q7Score { get; set; }
public Vf14Answer Q8Score { get; set; }
public Vf14Answer Q9Score { get; set; }
public Vf14Answer Q10Score { get; set; }
public Vf14Answer Q11Score { get; set; }
public Vf14Answer Q12Score { get; set; }
public Vf14Answer Q13Score { get; set; }
public Vf14Answer Q14Score { get; set; }
public float Total { get; set; }
public PatientModel Patient { get; set; }
}
public class Vf14CreateOrUpdateModel
{
public DateTime Date { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q1Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q2Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q3Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q4Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q5Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q6Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q7Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q8Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q9Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q10Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q11Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q12Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q13Score { get; set; }
[Required]
[Range(0, 5)]
public Vf14Answer Q14Score { get; set; }
public Vf14ResultModel ToVf14ResultModel(PatientModel patient)
=> new ()
{
Date = Date,
Q1Score = Q1Score,
Q2Score = Q2Score,
Q3Score = Q3Score,
Q4Score = Q4Score,
Q5Score = Q5Score,
Q6Score = Q6Score,
Q7Score = Q7Score,
Q8Score = Q8Score,
Q9Score = Q9Score,
Q10Score = Q10Score,
Q11Score = Q11Score,
Q12Score = Q12Score,
Q13Score = Q13Score,
Q14Score = Q14Score,
Total = CalculateTotal(),
Patient = patient
};
private float CalculateTotal()
{
var scores = new Vf14Answer[] { Q1Score, Q2Score, Q3Score, Q4Score, Q5Score, Q6Score, Q7Score, Q8Score, Q9Score, Q10Score, Q11Score, Q12Score, Q13Score, Q14Score };
var x4 = scores.Where(s => s == Vf14Answer.None).Count();
var x4F = scores.Where(s => s == Vf14Answer.None).Count() * 4;
var x3 = scores.Where(s => s == Vf14Answer.Alittle).Count();
var x3F = scores.Where(s => s == Vf14Answer.Alittle).Count() * 3;
var x2 = scores.Where(s => s == Vf14Answer.Moderate).Count();
var x2F = scores.Where(s => s == Vf14Answer.Moderate).Count() * 2;
var x1 = scores.Where(s => s == Vf14Answer.GreatDeal).Count();
var x1F = scores.Where(s => s == Vf14Answer.GreatDeal).Count();
float total = x4 + x3 + x2 + x1;
float factored = x4F + x3F + x2F + x1F;
return total != 0f ? factored / total : 0f;
}
}
}
| 27.824324 | 176 | 0.524769 | [
"MIT"
] | olena-stoliarova/GlaucomaWay | GlaucomaWay/Models/Vf14ResultModel.cs | 4,120 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.ServiceBus.Fluent.Models
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.ServiceBus.Fluent;
using Newtonsoft.Json;
using System.Linq;
/// <summary>
/// Message Count Details.
/// </summary>
public partial class MessageCountDetails
{
/// <summary>
/// Initializes a new instance of the MessageCountDetails class.
/// </summary>
public MessageCountDetails()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the MessageCountDetails class.
/// </summary>
/// <param name="activeMessageCount">Number of active messages in the
/// queue, topic, or subscription.</param>
/// <param name="deadLetterMessageCount">Number of messages that are
/// dead lettered.</param>
/// <param name="scheduledMessageCount">Number of scheduled
/// messages.</param>
/// <param name="transferDeadLetterMessageCount">Number of messages
/// transferred into dead letters.</param>
/// <param name="transferMessageCount">Number of messages transferred
/// to another queue, topic, or subscription.</param>
public MessageCountDetails(long? activeMessageCount = default(long?), long? deadLetterMessageCount = default(long?), long? scheduledMessageCount = default(long?), long? transferDeadLetterMessageCount = default(long?), long? transferMessageCount = default(long?))
{
ActiveMessageCount = activeMessageCount;
DeadLetterMessageCount = deadLetterMessageCount;
ScheduledMessageCount = scheduledMessageCount;
TransferDeadLetterMessageCount = transferDeadLetterMessageCount;
TransferMessageCount = transferMessageCount;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// Gets number of active messages in the queue, topic, or
/// subscription.
/// </summary>
[JsonProperty(PropertyName = "activeMessageCount")]
public long? ActiveMessageCount { get; private set; }
/// <summary>
/// Gets number of messages that are dead lettered.
/// </summary>
[JsonProperty(PropertyName = "deadLetterMessageCount")]
public long? DeadLetterMessageCount { get; private set; }
/// <summary>
/// Gets number of scheduled messages.
/// </summary>
[JsonProperty(PropertyName = "scheduledMessageCount")]
public long? ScheduledMessageCount { get; private set; }
/// <summary>
/// Gets number of messages transferred into dead letters.
/// </summary>
[JsonProperty(PropertyName = "transferDeadLetterMessageCount")]
public long? TransferDeadLetterMessageCount { get; private set; }
/// <summary>
/// Gets number of messages transferred to another queue, topic, or
/// subscription.
/// </summary>
[JsonProperty(PropertyName = "transferMessageCount")]
public long? TransferMessageCount { get; private set; }
}
}
| 39.717391 | 270 | 0.645868 | [
"MIT"
] | AntoineGa/azure-libraries-for-net | src/ResourceManagement/ServiceBus/Generated/Models/MessageCountDetails.cs | 3,654 | C# |
/*
* Copyright 2008-2013 Mohawk College of Applied Arts and Technology
*
* 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.
*
* User: Justin Fyfe
* Date: 12-11-2011
**/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MohawkCollege.EHR.gpmr.Pipeline.Triggers.CorDelta.Annotations
{
/// <summary>
/// Represents a constraint where the legnth has been constrained
/// </summary>
public class LengthConstraintAnnotation : ConstraintAnnotation
{
}
}
| 31.393939 | 81 | 0.72973 | [
"Apache-2.0"
] | avjabalpur/ccd-generator | MohawkCollege.EHR.gpmr.Pipeline.Triggers.CorDelta/Annotations/LengthConstraintAnnotation.cs | 1,038 | C# |
using System.Collections.Generic;
namespace Accounting.DataLayer.Repositories
{
public interface ICustomerRepository
{
List<Customers> GetAllCustomers();
Customers GetCustomerbyID(int customerId);
bool InsertCustomer(Customers customer);
bool UpdateCustomer(Customers customer);
bool DeleteCustomer(Customers customer);
bool DeleteCustomer(int customerId);
void Save();
}
}
| 26.117647 | 50 | 0.702703 | [
"CC0-1.0"
] | htabrizi/Accounting | Accounting/Accounting. DataLayer/Repositories/ICustomerRepository.cs | 446 | C# |
using MediatR;
using Opdex.Platform.Application.Abstractions.EntryCommands.LiquidityPools.Quotes;
using Opdex.Platform.Application.Abstractions.Models.Transactions;
using Opdex.Platform.Application.Abstractions.Queries.LiquidityPools;
using Opdex.Platform.Application.Abstractions.Queries.Markets;
using Opdex.Platform.Application.Abstractions.Queries.Tokens;
using Opdex.Platform.Application.Assemblers;
using Opdex.Platform.Application.EntryHandlers.Transactions;
using Opdex.Platform.Common.Configurations;
using Opdex.Platform.Common.Constants;
using Opdex.Platform.Common.Constants.SmartContracts;
using Opdex.Platform.Common.Extensions;
using Opdex.Platform.Common.Models;
using Opdex.Platform.Domain.Models.Transactions;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Opdex.Platform.Application.EntryHandlers.LiquidityPools.Quotes;
public class CreateRemoveLiquidityTransactionQuoteCommandHandler : BaseTransactionQuoteCommandHandler<CreateRemoveLiquidityTransactionQuoteCommand>
{
private const string MethodName = RouterConstants.Methods.RemoveLiquidity;
private readonly FixedDecimal CrsToSend = FixedDecimal.Zero;
public CreateRemoveLiquidityTransactionQuoteCommandHandler(IModelAssembler<TransactionQuote, TransactionQuoteDto> quoteAssembler,
IMediator mediator, OpdexConfiguration config)
: base(quoteAssembler, mediator, config)
{
}
public override async Task<TransactionQuoteDto> Handle(CreateRemoveLiquidityTransactionQuoteCommand request, CancellationToken cancellationToken)
{
var pool = await _mediator.Send(new RetrieveLiquidityPoolByAddressQuery(request.LiquidityPool), cancellationToken);
var token = await _mediator.Send(new RetrieveTokenByIdQuery(pool.SrcTokenId), cancellationToken);
var router = await _mediator.Send(new RetrieveActiveMarketRouterByMarketIdQuery(pool.MarketId), cancellationToken);
var amountCrsMin = request.AmountCrsMin.ToSatoshis(TokenConstants.Cirrus.Decimals);
var amountSrcMin = request.AmountSrcMin.ToSatoshis(token.Decimals);
var amountLpt = request.AmountLpt.ToSatoshis(TokenConstants.LiquidityPoolToken.Decimals);
var requestParameters = new List<TransactionQuoteRequestParameter>
{
new TransactionQuoteRequestParameter("Token", token.Address),
new TransactionQuoteRequestParameter("OLPT Amount", amountLpt),
new TransactionQuoteRequestParameter("Minimum CRS Amount", (ulong)amountCrsMin),
new TransactionQuoteRequestParameter("Minimum SRC Amount", amountSrcMin),
new TransactionQuoteRequestParameter("Recipient", request.Recipient),
new TransactionQuoteRequestParameter("Deadline", request.Deadline)
};
var quoteRequest = new TransactionQuoteRequest(request.WalletAddress, router.Address, CrsToSend, MethodName, _callbackEndpoint, requestParameters);
return await ExecuteAsync(quoteRequest, cancellationToken);
}
}
| 54.22807 | 155 | 0.789065 | [
"MIT"
] | Opdex/opdex-v1-api | src/Opdex.Platform.Application/EntryHandlers/LiquidityPools/Quotes/CreateRemoveLiquidityTransactionQuoteCommandHandler.cs | 3,091 | C# |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
namespace Mosa.HardwareSystem
{
/// <summary>
/// Interface to a PCI Controller
/// </summary>
public interface IPCIController
{
/// <summary>
/// Reads from configuration space
/// </summary>
/// <param name="bus">The bus.</param>
/// <param name="slot">The slot.</param>
/// <param name="function">The function.</param>
/// <param name="register">The register.</param>
/// <returns></returns>
uint ReadConfig32(byte bus, byte slot, byte function, byte register);
/// <summary>
/// Reads from configuration space
/// </summary>
/// <param name="bus">The bus.</param>
/// <param name="slot">The slot.</param>
/// <param name="function">The function.</param>
/// <param name="register">The register.</param>
/// <returns></returns>
ushort ReadConfig16(byte bus, byte slot, byte function, byte register);
/// <summary>
/// Reads from configuration space
/// </summary>
/// <param name="bus">The bus.</param>
/// <param name="slot">The slot.</param>
/// <param name="function">The function.</param>
/// <param name="register">The register.</param>
/// <returns></returns>
byte ReadConfig8(byte bus, byte slot, byte function, byte register);
/// <summary>
/// Writes to configuration space
/// </summary>
/// <param name="bus">The bus.</param>
/// <param name="slot">The slot.</param>
/// <param name="function">The function.</param>
/// <param name="register">The register.</param>
/// <param name="value">The value.</param>
void WriteConfig32(byte bus, byte slot, byte function, byte register, uint value);
/// <summary>
/// Writes to configuration space
/// </summary>
/// <param name="bus">The bus.</param>
/// <param name="slot">The slot.</param>
/// <param name="function">The function.</param>
/// <param name="register">The register.</param>
/// <param name="value">The value.</param>
void WriteConfig16(byte bus, byte slot, byte function, byte register, ushort value);
/// <summary>
/// Writes to configuration space
/// </summary>
/// <param name="bus">The bus.</param>
/// <param name="slot">The slot.</param>
/// <param name="function">The function.</param>
/// <param name="register">The register.</param>
/// <param name="value">The value.</param>
void WriteConfig8(byte bus, byte slot, byte function, byte register, byte value);
}
}
| 34.253521 | 86 | 0.640214 | [
"BSD-3-Clause"
] | carverh/ShiftOS | Source/Mosa.HardwareSystem/IPCIController.cs | 2,434 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal partial class SymbolTreeInfo : IObjectWritable
{
private const string PrefixMetadataSymbolTreeInfo = "<SymbolTreeInfo>";
private static readonly Checksum SerializationFormatChecksum = Checksum.Create("19");
/// <summary>
/// Loads the SpellChecker for a given assembly symbol (metadata or project). If the
/// info can't be loaded, it will be created (and persisted if possible).
/// </summary>
private static Task<SpellChecker> LoadOrCreateSpellCheckerAsync(
Solution solution,
Checksum checksum,
string filePath,
string concatenatedNames,
ImmutableArray<Node> sortedNodes)
{
var result = TryLoadOrCreateAsync(
solution,
checksum,
loadOnly: false,
createAsync: () => CreateSpellCheckerAsync(checksum, concatenatedNames, sortedNodes),
keySuffix: "_SpellChecker_" + filePath,
tryReadObject: SpellChecker.TryReadFrom,
cancellationToken: CancellationToken.None);
Contract.ThrowIfNull(result, "Result should never be null as we passed 'loadOnly: false'.");
return result;
}
/// <summary>
/// Generalized function for loading/creating/persisting data. Used as the common core
/// code for serialization of SymbolTreeInfos and SpellCheckers.
/// </summary>
private static async Task<T> TryLoadOrCreateAsync<T>(
Solution solution,
Checksum checksum,
bool loadOnly,
Func<Task<T>> createAsync,
string keySuffix,
Func<ObjectReader, T> tryReadObject,
CancellationToken cancellationToken) where T : class, IObjectWritable, IChecksummedObject
{
using (Logger.LogBlock(FunctionId.SymbolTreeInfo_TryLoadOrCreate, cancellationToken))
{
if (checksum == null)
{
return loadOnly ? null : await CreateWithLoggingAsync().ConfigureAwait(false);
}
// Ok, we can use persistence. First try to load from the persistence service.
var persistentStorageService = (IChecksummedPersistentStorageService)solution.Workspace.Services.GetService<IPersistentStorageService>();
T result;
using (var storage = persistentStorageService.GetStorage(solution, checkBranchId: false))
{
// Get the unique key to identify our data.
var key = PrefixMetadataSymbolTreeInfo + keySuffix;
using (var stream = await storage.ReadStreamAsync(key, checksum, cancellationToken).ConfigureAwait(false))
using (var reader = ObjectReader.TryGetReader(stream))
{
if (reader != null)
{
// We have some previously persisted data. Attempt to read it back.
// If we're able to, and the version of the persisted data matches
// our version, then we can reuse this instance.
result = tryReadObject(reader);
if (result != null)
{
// If we were able to read something in, it's checksum better
// have matched the checksum we expected.
Debug.Assert(result.Checksum == checksum);
return result;
}
}
}
cancellationToken.ThrowIfCancellationRequested();
// Couldn't read from the persistence service. If we've been asked to only load
// data and not create new instances in their absence, then there's nothing left
// to do at this point.
if (loadOnly)
{
return null;
}
// Now, try to create a new instance and write it to the persistence service.
result = await CreateWithLoggingAsync().ConfigureAwait(false);
Contract.ThrowIfNull(result);
using (var stream = SerializableBytes.CreateWritableStream())
using (var writer = new ObjectWriter(stream, cancellationToken: cancellationToken))
{
result.WriteTo(writer);
stream.Position = 0;
await storage.WriteStreamAsync(key, stream, checksum, cancellationToken).ConfigureAwait(false);
}
}
return result;
}
async Task<T> CreateWithLoggingAsync()
{
using (Logger.LogBlock(FunctionId.SymbolTreeInfo_Create, cancellationToken))
{
return await createAsync().ConfigureAwait(false);
}
};
}
bool IObjectWritable.ShouldReuseInSerialization => true;
public void WriteTo(ObjectWriter writer)
{
writer.WriteString(_concatenatedNames);
writer.WriteInt32(_nodes.Length);
foreach (var node in _nodes)
{
writer.WriteInt32(node.NameSpan.Start);
writer.WriteInt32(node.NameSpan.Length);
writer.WriteInt32(node.ParentIndex);
}
writer.WriteInt32(_inheritanceMap.Keys.Count);
foreach (var kvp in _inheritanceMap)
{
writer.WriteInt32(kvp.Key);
writer.WriteInt32(kvp.Value.Count);
foreach (var v in kvp.Value)
{
writer.WriteInt32(v);
}
}
if (_simpleTypeNameToExtensionMethodMap == null)
{
writer.WriteInt32(0);
}
else
{
writer.WriteInt32(_simpleTypeNameToExtensionMethodMap.Count);
foreach (var key in _simpleTypeNameToExtensionMethodMap.Keys)
{
writer.WriteString(key);
var values = _simpleTypeNameToExtensionMethodMap[key];
writer.WriteInt32(values.Count);
foreach (var value in values)
{
writer.WriteString(value.FullyQualifiedContainerName);
writer.WriteString(value.Name);
}
}
}
writer.WriteInt32(_extensionMethodOfComplexType.Length);
foreach (var methodInfo in _extensionMethodOfComplexType)
{
writer.WriteString(methodInfo.FullyQualifiedContainerName);
writer.WriteString(methodInfo.Name);
}
}
internal static SymbolTreeInfo ReadSymbolTreeInfo_ForTestingPurposesOnly(
ObjectReader reader, Checksum checksum)
{
return TryReadSymbolTreeInfo(reader, checksum,
(names, nodes) => Task.FromResult(
new SpellChecker(checksum, nodes.Select(n => new StringSlice(names, n.NameSpan)))));
}
private static SymbolTreeInfo TryReadSymbolTreeInfo(
ObjectReader reader,
Checksum checksum,
Func<string, ImmutableArray<Node>, Task<SpellChecker>> createSpellCheckerTask)
{
try
{
var concatenatedNames = reader.ReadString();
var nodeCount = reader.ReadInt32();
var nodes = ArrayBuilder<Node>.GetInstance(nodeCount);
for (var i = 0; i < nodeCount; i++)
{
var start = reader.ReadInt32();
var length = reader.ReadInt32();
var parentIndex = reader.ReadInt32();
nodes.Add(new Node(new TextSpan(start, length), parentIndex));
}
var inheritanceMap = new OrderPreservingMultiDictionary<int, int>();
var inheritanceMapKeyCount = reader.ReadInt32();
for (var i = 0; i < inheritanceMapKeyCount; i++)
{
var key = reader.ReadInt32();
var valueCount = reader.ReadInt32();
for (var j = 0; j < valueCount; j++)
{
var value = reader.ReadInt32();
inheritanceMap.Add(key, value);
}
}
MultiDictionary<string, ExtensionMethodInfo> simpleTypeNameToExtensionMethodMap;
ImmutableArray<ExtensionMethodInfo> extensionMethodOfComplexType;
var keyCount = reader.ReadInt32();
if (keyCount == 0)
{
simpleTypeNameToExtensionMethodMap = null;
}
else
{
simpleTypeNameToExtensionMethodMap = new MultiDictionary<string, ExtensionMethodInfo>();
for (var i = 0; i < keyCount; i++)
{
var typeName = reader.ReadString();
var valueCount = reader.ReadInt32();
for (var j = 0; j < valueCount; j++)
{
var containerName = reader.ReadString();
var name = reader.ReadString();
simpleTypeNameToExtensionMethodMap.Add(typeName, new ExtensionMethodInfo(containerName, name));
}
}
}
var arrayLength = reader.ReadInt32();
if (arrayLength == 0)
{
extensionMethodOfComplexType = ImmutableArray<ExtensionMethodInfo>.Empty;
}
else
{
var builder = ArrayBuilder<ExtensionMethodInfo>.GetInstance(arrayLength);
for (var i = 0; i < arrayLength; ++i)
{
var containerName = reader.ReadString();
var name = reader.ReadString();
builder.Add(new ExtensionMethodInfo(containerName, name));
}
extensionMethodOfComplexType = builder.ToImmutableAndFree();
}
var nodeArray = nodes.ToImmutableAndFree();
var spellCheckerTask = createSpellCheckerTask(concatenatedNames, nodeArray);
return new SymbolTreeInfo(
checksum, concatenatedNames, nodeArray, spellCheckerTask, inheritanceMap,
extensionMethodOfComplexType, simpleTypeNameToExtensionMethodMap);
}
catch
{
Logger.Log(FunctionId.SymbolTreeInfo_ExceptionInCacheRead);
}
return null;
}
}
}
| 41.319444 | 161 | 0.536471 | [
"Apache-2.0"
] | DanVioletSagmiller/roslyn | src/Workspaces/Core/Portable/FindSymbols/SymbolTree/SymbolTreeInfo_Serialization.cs | 11,902 | C# |
namespace Forum.App.Models
{
using Forum.App.Contracts;
internal class Label : ILabel
{
public Label(string text, Position position, bool isHidden = false)
{
this.Text = text;
this.Position = position;
this.IsHidden = isHidden;
}
public string Text { get; }
public bool IsHidden { get; }
public Position Position { get; }
}
} | 21.5 | 75 | 0.55814 | [
"MIT"
] | MustafaAmish/All-Curses-in-SoftUni | 05. C# OOP Advanced/15. Workshop/Forum.App/Models/Label.cs | 432 | C# |
namespace NatureShot.Data.Seeding
{
using System;
using System.Linq;
using System.Threading.Tasks;
using NatureShot.Scraping;
using NatureShot.Data.Models;
using System.Collections.Generic;
public class LocationSeeder : ISeeder
{
public LocationSeeder()
{
}
public async Task SeedAsync(ApplicationDbContext dbContext, IServiceProvider serviceProvider)
{
if (dbContext.Locations.Any())
{
return;
}
var locationNames = new List<string>();
await dbContext.Locations.AddAsync(new Location { Name = "/Bulgaria", Country = new Country { Name = "Bulgaria" } });
await dbContext.Locations.AddAsync(new Location { Name = "/Germany", Country = new Country { Name = "Germany" } });
await dbContext.Locations.AddAsync(new Location { Name = "/Greece", Country = new Country { Name = "Greece" } });
await dbContext.Locations.AddAsync(new Location { Name = "/Macedonia", Country = new Country { Name = "Macedonia" } });
await dbContext.Locations.AddAsync(new Location { Name = "/Serbia", Country = new Country { Name = "Serbia" } });
await dbContext.Locations.AddAsync(new Location { Name = "/Romania", Country = new Country { Name = "Romania" } });
await dbContext.Locations.AddAsync(new Location { Name = "/Turkey", Country = new Country { Name = "Turkey" } });
await dbContext.Locations.AddAsync(new Location { Name = "/Norway", Country = new Country { Name = "Norway" } });
await dbContext.Locations.AddAsync(new Location { Name = "/Finland", Country = new Country { Name = "Finland" } });
await dbContext.Locations.AddAsync(new Location { Name = "/France", Country = new Country { Name = "France" } });
await dbContext.Locations.AddAsync(new Location { Name = "/Italy", Country = new Country { Name = "Italy" } });
await dbContext.Locations.AddAsync(new Location { Name = "/England", Country = new Country { Name = "England" } });
await Program.GetTowns(locationNames);
var country = new Country { Name = "Bulgaria" };
foreach (var town in locationNames)
{
await dbContext.Locations.AddAsync(new Location { Name = town + "/" + country.Name, Country = country, Town = new Town { Name = town, Country = country } });
}
locationNames.Clear();
Program.GetCaves(locationNames);
Program.GetLakes(locationNames);
await Program.GetMountains(locationNames);
await Program.GetRivers(locationNames);
foreach (var location in locationNames)
{
await dbContext.Locations.AddAsync(new Location { Name = location + " / " + country.Name, Country = country });
}
await dbContext.SaveChangesAsync();
}
}
}
| 49.633333 | 173 | 0.606111 | [
"MIT"
] | DimitarKazakov/NatureShotWebSite | Nature_Shot/Data/NatureShot.Data/Seeding/LocationSeeder.cs | 2,980 | 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("LifeCycle")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("LifeCycle")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[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("f8036964-cdfb-4bbe-aae9-143c7559913f")]
// 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.027778 | 84 | 0.750913 | [
"MIT"
] | noenemy/Book-Windows-Phone-Programming-Bible | Chapter 12/LifeCycle/LifeCycle/Properties/AssemblyInfo.cs | 1,372 | C# |
using FBLARoverAgenda.ViewModels;
using Syncfusion.ListView.XForms;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Xaml;
namespace FBLARoverAgenda.Views
{
/// <summary>
/// Page to show my address page.
/// </summary>
[Preserve(AllMembers = true)]
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class AllClubsPage
{
/// <summary>
/// Initializes a new instance of the <see cref="AllClubsPage" /> class.
/// </summary>
public AllClubsPage()
{
this.InitializeComponent();
this.BindingContext = AllClubsPageViewModel.BindingContext;
}
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
if (width < height)
{
if (this.myAddress.LayoutManager is GridLayout)
{
(this.myAddress.LayoutManager as GridLayout).SpanCount = 1;
}
}
else
{
if (this.myAddress.LayoutManager is GridLayout)
{
(this.myAddress.LayoutManager as GridLayout).SpanCount = 2;
}
}
}
}
} | 28.977273 | 80 | 0.556863 | [
"MIT"
] | eahs/FBLARoverAgenda | FBLARoverAgenda/FBLARoverAgenda/Views/AllClubsPage.xaml.cs | 1,275 | C# |
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
public class Target : MonoBehaviour
{
public ItemType ItemType;
} | 19.222222 | 35 | 0.809249 | [
"MIT"
] | justinryder/Agent-Smith-s-Super-Saving-A-Neo-Shopping-Experience | Agent Smiths Super Savings A Neo Shopping Experience/Assets/Scripts/Target.cs | 175 | C# |
/***************************************************************************************
Toolkit for WPF
Copyright (C) 2007-2019 Xceed Software Inc.
This program is provided to you under the terms of the Microsoft Public
License (Ms-PL) as published at https://github.com/xceedsoftware/wpftoolkit/blob/master/license.md
For more features, controls, and fast professional support,
pick up the Plus Edition at https://xceed.com/xceed-toolkit-plus-for-wpf/
Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids
*************************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Media;
using System.Linq;
using System.Collections.ObjectModel;
namespace Xceed.Wpf.Toolkit.LiveExplorer.Samples.PropertyGrid.Views
{
/// <summary>
/// Interaction logic for PropertyGridPropertiesView.xaml
/// </summary>
public partial class PropertyGridPropertiesView : DemoView
{
public PropertyGridPropertiesView()
{
InitializeComponent();
}
}
}
| 29.615385 | 102 | 0.638095 | [
"MIT"
] | O-Debegnach/Supervisor-de-Comercio | wpftoolkit-master/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.Toolkit.LiveExplorer/Samples/PropertyGrid/Views/PropertyGridPropertiesView.xaml.cs | 1,157 | C# |
/*
* Hydrogen Integration API
*
* The Hydrogen Integration API
*
* OpenAPI spec version: 1.3.1
* Contact: info@hydrogenplatform.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using NUnit.Framework;
using System;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using Integration.Api;
using Integration.ModelEntity;
using Integration.Client;
using System.Reflection;
using Newtonsoft.Json;
namespace Integration.Test
{
/// <summary>
/// Class for testing Identification
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the model.
/// </remarks>
[TestFixture]
public class IdentificationTests
{
// TODO uncomment below to declare an instance variable for Identification
//private Identification instance;
/// <summary>
/// Setup before each test
/// </summary>
[SetUp]
public void Init()
{
// TODO uncomment below to create an instance of Identification
//instance = new Identification();
}
/// <summary>
/// Clean up after each test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of Identification
/// </summary>
[Test]
public void IdentificationInstanceTest()
{
// TODO uncomment below to test "IsInstanceOfType" Identification
//Assert.IsInstanceOfType<Identification> (instance, "variable 'instance' is a Identification");
}
/// <summary>
/// Test the property 'CountryOfIssue'
/// </summary>
[Test]
public void CountryOfIssueTest()
{
// TODO unit test for the property 'CountryOfIssue'
}
/// <summary>
/// Test the property 'DocNumber'
/// </summary>
[Test]
public void DocNumberTest()
{
// TODO unit test for the property 'DocNumber'
}
/// <summary>
/// Test the property 'DocType'
/// </summary>
[Test]
public void DocTypeTest()
{
// TODO unit test for the property 'DocType'
}
/// <summary>
/// Test the property 'ExpiryDate'
/// </summary>
[Test]
public void ExpiryDateTest()
{
// TODO unit test for the property 'ExpiryDate'
}
/// <summary>
/// Test the property 'IssueDate'
/// </summary>
[Test]
public void IssueDateTest()
{
// TODO unit test for the property 'IssueDate'
}
/// <summary>
/// Test the property 'IssuingAuthority'
/// </summary>
[Test]
public void IssuingAuthorityTest()
{
// TODO unit test for the property 'IssuingAuthority'
}
/// <summary>
/// Test the property 'StateOfIssue'
/// </summary>
[Test]
public void StateOfIssueTest()
{
// TODO unit test for the property 'StateOfIssue'
}
}
}
| 25.310078 | 108 | 0.549158 | [
"Apache-2.0"
] | ShekharPaatni/SDK | integration/csharp/src/Integration.Test/Model/IdentificationTests.cs | 3,265 | C# |
#region License
/*
* HttpListenerRequest.cs
*
* This code is derived from HttpListenerRequest.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2021 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace WebSocketSharp.Net
{
/// <summary>
/// Represents an incoming HTTP request to a <see cref="HttpListener"/>
/// instance.
/// </summary>
/// <remarks>
/// This class cannot be inherited.
/// </remarks>
public sealed class HttpListenerRequest
{
#region Private Fields
private static readonly byte[] _100continue;
private string[] _acceptTypes;
private bool _chunked;
private readonly HttpConnection _connection;
private Encoding _contentEncoding;
private long _contentLength;
private readonly HttpListenerContext _context;
private CookieCollection _cookies;
private readonly WebHeaderCollection _headers;
private string _httpMethod;
private Stream _inputStream;
private Version _protocolVersion;
private NameValueCollection _queryString;
private string _rawUrl;
private readonly Guid _requestTraceIdentifier;
private Uri _url;
private Uri _urlReferrer;
private bool _urlSet;
private string _userHostName;
private string[] _userLanguages;
#endregion
#region Static Constructor
static HttpListenerRequest ()
{
_100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
}
#endregion
#region Internal Constructors
internal HttpListenerRequest (HttpListenerContext context)
{
_context = context;
_connection = context.Connection;
_contentLength = -1;
_headers = new WebHeaderCollection ();
_requestTraceIdentifier = Guid.NewGuid ();
}
#endregion
#region Public Properties
/// <summary>
/// Gets the media types that are acceptable for the client.
/// </summary>
/// <value>
/// <para>
/// An array of <see cref="string"/> that contains the names of the media
/// types specified in the value of the Accept header.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string[] AcceptTypes {
get {
var val = _headers["Accept"];
if (val == null)
return null;
if (_acceptTypes == null) {
_acceptTypes = val
.SplitHeaderValue (',')
.TrimEach ()
.ToList ()
.ToArray ();
}
return _acceptTypes;
}
}
/// <summary>
/// Gets an error code that identifies a problem with the certificate
/// provided by the client.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents an error code.
/// </value>
/// <exception cref="NotSupportedException">
/// This property is not supported.
/// </exception>
public int ClientCertificateError {
get {
throw new NotSupportedException ();
}
}
/// <summary>
/// Gets the encoding for the entity body data included in the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Encoding"/> converted from the charset value of the
/// Content-Type header.
/// </para>
/// <para>
/// <see cref="Encoding.UTF8"/> if the charset value is not available.
/// </para>
/// </value>
public Encoding ContentEncoding {
get {
if (_contentEncoding == null)
_contentEncoding = getContentEncoding ();
return _contentEncoding;
}
}
/// <summary>
/// Gets the length in bytes of the entity body data included in the
/// request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="long"/> converted from the value of the Content-Length
/// header.
/// </para>
/// <para>
/// -1 if the header is not present.
/// </para>
/// </value>
public long ContentLength64 {
get {
return _contentLength;
}
}
/// <summary>
/// Gets the media type of the entity body data included in the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the value of the Content-Type
/// header.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string ContentType {
get {
return _headers["Content-Type"];
}
}
/// <summary>
/// Gets the cookies included in the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="CookieCollection"/> that contains the cookies.
/// </para>
/// <para>
/// An empty collection if not included.
/// </para>
/// </value>
public CookieCollection Cookies {
get {
if (_cookies == null)
_cookies = _headers.GetCookies (false);
return _cookies;
}
}
/// <summary>
/// Gets a value indicating whether the request has the entity body data.
/// </summary>
/// <value>
/// <c>true</c> if the request has the entity body data; otherwise,
/// <c>false</c>.
/// </value>
public bool HasEntityBody {
get {
return _contentLength > 0 || _chunked;
}
}
/// <summary>
/// Gets the headers included in the request.
/// </summary>
/// <value>
/// A <see cref="NameValueCollection"/> that contains the headers.
/// </value>
public NameValueCollection Headers {
get {
return _headers;
}
}
/// <summary>
/// Gets the HTTP method specified by the client.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the HTTP method specified in
/// the request line.
/// </value>
public string HttpMethod {
get {
return _httpMethod;
}
}
/// <summary>
/// Gets a stream that contains the entity body data included in
/// the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Stream"/> that contains the entity body data.
/// </para>
/// <para>
/// <see cref="Stream.Null"/> if the entity body data is not available.
/// </para>
/// </value>
public Stream InputStream {
get {
if (_inputStream == null) {
_inputStream = _contentLength > 0 || _chunked
? _connection
.GetRequestStream (_contentLength, _chunked)
: Stream.Null;
}
return _inputStream;
}
}
/// <summary>
/// Gets a value indicating whether the client is authenticated.
/// </summary>
/// <value>
/// <c>true</c> if the client is authenticated; otherwise, <c>false</c>.
/// </value>
public bool IsAuthenticated {
get {
return _context.User != null;
}
}
/// <summary>
/// Gets a value indicating whether the request is sent from the local
/// computer.
/// </summary>
/// <value>
/// <c>true</c> if the request is sent from the same computer as the server;
/// otherwise, <c>false</c>.
/// </value>
public bool IsLocal {
get {
return _connection.IsLocal;
}
}
/// <summary>
/// Gets a value indicating whether a secure connection is used to send
/// the request.
/// </summary>
/// <value>
/// <c>true</c> if the connection is secure; otherwise, <c>false</c>.
/// </value>
public bool IsSecureConnection {
get {
return _connection.IsSecure;
}
}
/// <summary>
/// Gets a value indicating whether the request is a WebSocket handshake
/// request.
/// </summary>
/// <value>
/// <c>true</c> if the request is a WebSocket handshake request; otherwise,
/// <c>false</c>.
/// </value>
public bool IsWebSocketRequest {
get {
return _httpMethod == "GET" && _headers.Upgrades ("websocket");
}
}
/// <summary>
/// Gets a value indicating whether a persistent connection is requested.
/// </summary>
/// <value>
/// <c>true</c> if the request specifies that the connection is kept open;
/// otherwise, <c>false</c>.
/// </value>
public bool KeepAlive {
get {
return _headers.KeepsAlive (_protocolVersion);
}
}
/// <summary>
/// Gets the endpoint to which the request is sent.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the server IP
/// address and port number.
/// </value>
public System.Net.IPEndPoint LocalEndPoint {
get {
return _connection.LocalEndPoint;
}
}
/// <summary>
/// Gets the HTTP version specified by the client.
/// </summary>
/// <value>
/// A <see cref="Version"/> that represents the HTTP version specified in
/// the request line.
/// </value>
public Version ProtocolVersion {
get {
return _protocolVersion;
}
}
/// <summary>
/// Gets the query string included in the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="NameValueCollection"/> that contains the query
/// parameters.
/// </para>
/// <para>
/// An empty collection if not included.
/// </para>
/// </value>
public NameValueCollection QueryString {
get {
if (_queryString == null) {
var url = Url;
_queryString = QueryStringCollection
.Parse (
url != null ? url.Query : null,
Encoding.UTF8
);
}
return _queryString;
}
}
/// <summary>
/// Gets the raw URL specified by the client.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the request target specified in
/// the request line.
/// </value>
public string RawUrl {
get {
return _rawUrl;
}
}
/// <summary>
/// Gets the endpoint from which the request is sent.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the client IP
/// address and port number.
/// </value>
public System.Net.IPEndPoint RemoteEndPoint {
get {
return _connection.RemoteEndPoint;
}
}
/// <summary>
/// Gets the trace identifier of the request.
/// </summary>
/// <value>
/// A <see cref="Guid"/> that represents the trace identifier.
/// </value>
public Guid RequestTraceIdentifier {
get {
return _requestTraceIdentifier;
}
}
/// <summary>
/// Gets the URL requested by the client.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Uri"/> that represents the URL parsed from the request.
/// </para>
/// <para>
/// <see langword="null"/> if the URL cannot be parsed.
/// </para>
/// </value>
public Uri Url {
get {
if (!_urlSet) {
_url = HttpUtility
.CreateRequestUrl (
_rawUrl,
_userHostName ?? UserHostAddress,
IsWebSocketRequest,
IsSecureConnection
);
_urlSet = true;
}
return _url;
}
}
/// <summary>
/// Gets the URI of the resource from which the requested URL was obtained.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Uri"/> converted from the value of the Referer header.
/// </para>
/// <para>
/// <see langword="null"/> if the header value is not available.
/// </para>
/// </value>
public Uri UrlReferrer {
get {
var val = _headers["Referer"];
if (val == null)
return null;
if (_urlReferrer == null)
_urlReferrer = val.ToUri ();
return _urlReferrer;
}
}
/// <summary>
/// Gets the user agent from which the request is originated.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the value of the User-Agent
/// header.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string UserAgent {
get {
return _headers["User-Agent"];
}
}
/// <summary>
/// Gets the IP address and port number to which the request is sent.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the server IP address and port
/// number.
/// </value>
public string UserHostAddress {
get {
return _connection.LocalEndPoint.ToString ();
}
}
/// <summary>
/// Gets the server host name requested by the client.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the value of the Host header.
/// </para>
/// <para>
/// It includes the port number if provided.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string UserHostName {
get {
return _userHostName;
}
}
/// <summary>
/// Gets the natural languages that are acceptable for the client.
/// </summary>
/// <value>
/// <para>
/// An array of <see cref="string"/> that contains the names of the
/// natural languages specified in the value of the Accept-Language
/// header.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string[] UserLanguages {
get {
var val = _headers["Accept-Language"];
if (val == null)
return null;
if (_userLanguages == null)
_userLanguages = val.Split (',').TrimEach ().ToList ().ToArray ();
return _userLanguages;
}
}
#endregion
#region Private Methods
private Encoding getContentEncoding ()
{
var val = _headers["Content-Type"];
if (val == null)
return Encoding.UTF8;
Encoding ret;
return HttpUtility.TryGetEncoding (val, out ret)
? ret
: Encoding.UTF8;
}
#endregion
#region Internal Methods
internal void AddHeader (string headerField)
{
var start = headerField[0];
if (start == ' ' || start == '\t') {
_context.ErrorMessage = "Invalid header field";
return;
}
var colon = headerField.IndexOf (':');
if (colon < 1) {
_context.ErrorMessage = "Invalid header field";
return;
}
var name = headerField.Substring (0, colon).Trim ();
if (name.Length == 0 || !name.IsToken ()) {
_context.ErrorMessage = "Invalid header name";
return;
}
var val = colon < headerField.Length - 1
? headerField.Substring (colon + 1).Trim ()
: String.Empty;
_headers.InternalSet (name, val, false);
var lower = name.ToLower (CultureInfo.InvariantCulture);
if (lower == "host") {
if (_userHostName != null) {
_context.ErrorMessage = "Invalid Host header";
return;
}
if (val.Length == 0) {
_context.ErrorMessage = "Invalid Host header";
return;
}
_userHostName = val;
return;
}
if (lower == "content-length") {
if (_contentLength > -1) {
_context.ErrorMessage = "Invalid Content-Length header";
return;
}
long len;
if (!Int64.TryParse (val, out len)) {
_context.ErrorMessage = "Invalid Content-Length header";
return;
}
if (len < 0) {
_context.ErrorMessage = "Invalid Content-Length header";
return;
}
_contentLength = len;
return;
}
}
internal void FinishInitialization ()
{
if (_userHostName == null) {
_context.ErrorMessage = "Host header required";
return;
}
var transferEnc = _headers["Transfer-Encoding"];
if (transferEnc != null) {
var comparison = StringComparison.OrdinalIgnoreCase;
if (!transferEnc.Equals ("chunked", comparison)) {
_context.ErrorMessage = "Invalid Transfer-Encoding header";
_context.ErrorStatusCode = 501;
return;
}
_chunked = true;
}
if (_httpMethod == "POST" || _httpMethod == "PUT") {
if (_contentLength <= 0 && !_chunked) {
_context.ErrorMessage = String.Empty;
_context.ErrorStatusCode = 411;
return;
}
}
var expect = _headers["Expect"];
if (expect != null) {
var comparison = StringComparison.OrdinalIgnoreCase;
if (!expect.Equals ("100-continue", comparison)) {
_context.ErrorMessage = "Invalid Expect header";
return;
}
var output = _connection.GetResponseStream ();
output.InternalWrite (_100continue, 0, _100continue.Length);
}
}
internal bool FlushInput ()
{
var input = InputStream;
if (input == Stream.Null)
return true;
var len = 2048;
if (_contentLength > 0 && _contentLength < len)
len = (int) _contentLength;
var buff = new byte[len];
while (true) {
try {
var ares = input.BeginRead (buff, 0, len, null, null);
if (!ares.IsCompleted) {
var timeout = 100;
if (!ares.AsyncWaitHandle.WaitOne (timeout))
return false;
}
if (input.EndRead (ares) <= 0)
return true;
}
catch {
return false;
}
}
}
internal bool IsUpgradeRequest (string protocol)
{
return _headers.Upgrades (protocol);
}
internal void SetRequestLine (string requestLine)
{
var parts = requestLine.Split (new[] { ' ' }, 3);
if (parts.Length < 3) {
_context.ErrorMessage = "Invalid request line (parts)";
return;
}
var method = parts[0];
if (method.Length == 0) {
_context.ErrorMessage = "Invalid request line (method)";
return;
}
var target = parts[1];
if (target.Length == 0) {
_context.ErrorMessage = "Invalid request line (target)";
return;
}
var rawVer = parts[2];
if (rawVer.Length != 8) {
_context.ErrorMessage = "Invalid request line (version)";
return;
}
if (!rawVer.StartsWith ("HTTP/", StringComparison.Ordinal)) {
_context.ErrorMessage = "Invalid request line (version)";
return;
}
Version ver;
if (!rawVer.Substring (5).TryCreateVersion (out ver)) {
_context.ErrorMessage = "Invalid request line (version)";
return;
}
if (ver != HttpVersion.Version11) {
_context.ErrorMessage = "Invalid request line (version)";
_context.ErrorStatusCode = 505;
return;
}
if (!method.IsHttpMethod (ver)) {
_context.ErrorMessage = "Invalid request line (method)";
_context.ErrorStatusCode = 501;
return;
}
_httpMethod = method;
_rawUrl = target;
_protocolVersion = ver;
}
#endregion
#region Public Methods
/// <summary>
/// Begins getting the certificate provided by the client asynchronously.
/// </summary>
/// <returns>
/// An <see cref="IAsyncResult"/> instance that indicates the status of the
/// operation.
/// </returns>
/// <param name="requestCallback">
/// An <see cref="AsyncCallback"/> delegate that invokes the method called
/// when the operation is complete.
/// </param>
/// <param name="state">
/// An <see cref="object"/> that represents a user defined object to pass to
/// the callback delegate.
/// </param>
/// <exception cref="NotSupportedException">
/// This method is not supported.
/// </exception>
public IAsyncResult BeginGetClientCertificate (
AsyncCallback requestCallback, object state
)
{
throw new NotSupportedException ();
}
/// <summary>
/// Ends an asynchronous operation to get the certificate provided by the
/// client.
/// </summary>
/// <returns>
/// A <see cref="X509Certificate2"/> that represents an X.509 certificate
/// provided by the client.
/// </returns>
/// <param name="asyncResult">
/// An <see cref="IAsyncResult"/> instance returned when the operation
/// started.
/// </param>
/// <exception cref="NotSupportedException">
/// This method is not supported.
/// </exception>
public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
{
throw new NotSupportedException ();
}
/// <summary>
/// Gets the certificate provided by the client.
/// </summary>
/// <returns>
/// A <see cref="X509Certificate2"/> that represents an X.509 certificate
/// provided by the client.
/// </returns>
/// <exception cref="NotSupportedException">
/// This method is not supported.
/// </exception>
public X509Certificate2 GetClientCertificate ()
{
throw new NotSupportedException ();
}
/// <summary>
/// Returns a string that represents the current instance.
/// </summary>
/// <returns>
/// A <see cref="string"/> that contains the request line and headers
/// included in the request.
/// </returns>
public override string ToString ()
{
var buff = new StringBuilder (64);
buff
.AppendFormat (
"{0} {1} HTTP/{2}\r\n", _httpMethod, _rawUrl, _protocolVersion
)
.Append (_headers.ToString ());
return buff.ToString ();
}
#endregion
}
}
| 25.869752 | 80 | 0.557442 | [
"MIT"
] | Nobatgeldi/websocket-sharp | websocket-sharp/Net/HttpListenerRequest.cs | 24,033 | C# |
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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 MassTransit.PipeConfigurators
{
using System;
using System.Collections.Generic;
using System.Transactions;
using GreenPipes;
using Pipeline.Filters;
public class TransactionPipeSpecification<T> :
ITransactionConfigurator,
IPipeSpecification<T>
where T : class, PipeContext
{
IsolationLevel _isolationLevel;
TimeSpan _timeout;
public TransactionPipeSpecification()
{
_isolationLevel = IsolationLevel.ReadCommitted;
_timeout = TimeSpan.FromSeconds(30);
}
public void Apply(IPipeBuilder<T> builder)
{
builder.AddFilter(new TransactionFilter<T>(_isolationLevel, _timeout));
}
public IEnumerable<ValidationResult> Validate()
{
if (_timeout == TimeSpan.Zero)
yield return this.Failure("Timeout", "Must be > 0");
}
public TimeSpan Timeout
{
set { _timeout = value; }
}
public IsolationLevel IsolationLevel
{
set { _isolationLevel = value; }
}
}
} | 32.122807 | 84 | 0.628072 | [
"Apache-2.0"
] | andymac4182/MassTransit | src/MassTransit/Configuration/PipeConfigurators/TransactionPipeSpecification.cs | 1,831 | C# |
using FluentValidation.TestHelper;
using Opdex.Auth.Api.Validation;
using SSAS.NET;
using Xunit;
namespace Opdex.Auth.Api.Tests.Validation;
public class StratisSignatureAuthCallbackBodyValidatorTests
{
private readonly StratisSignatureAuthCallbackBodyValidator _validator;
public StratisSignatureAuthCallbackBodyValidatorTests()
{
_validator = new StratisSignatureAuthCallbackBodyValidator();
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("ContainsInvalidBase64Characters_ContainsInvalidBase64Characters_ContainsInvalidBase64Cha")]
[InlineData("LessThan88Base64CharactersLessThan88Base64CharactersLessThan88Base64CharactersLessThan8")]
[InlineData("MoreThan88Base64CharactersMoreThan88Base64CharactersMoreThan88Base64CharactersMoreThan88B")]
public void Signature_Invalid(string signature)
{
// Arrange
var request = new StratisSignatureAuthCallbackBody
{
Signature = signature
};
// Act
var result = _validator.TestValidate(request);
// Assert
result.ShouldHaveValidationErrorFor(r => r.Signature);
}
[Fact]
public void Signature_Valid()
{
// Arrange
var request = new StratisSignatureAuthCallbackBody
{
Signature = "IPkq8t9M00nKyI3RP4KriflomZpMYDp8+C0RdvvbgNF6bSCAXgp4yFbx+Uscr1EQ2uKGyg6z9wj07sf1ZwH0XmI="
};
// Act
var result = _validator.TestValidate(request);
// Assert
result.ShouldNotHaveValidationErrorFor(r => r.Signature);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData("PVwyqbwu5CazeACoAMRonaQSyRvTHZvAUl")]
[InlineData("PVwyqbwu5CazeACoAMRonaQSyRvTHZvAUI")]
[InlineData("PVwyqbwu5CazeACoAMRonaQSyRvTHZvAUO")]
[InlineData("PVwyqbwu5CazeACoAMRonaQSyRvTHZvAU0")]
public void PublicKey_Invalid(string publicKey)
{
// Arrange
var request = new StratisSignatureAuthCallbackBody
{
PublicKey = publicKey
};
// Act
var result = _validator.TestValidate(request);
// Assert
result.ShouldHaveValidationErrorFor(r => r.PublicKey);
}
[Fact]
public void PublicKey_Valid()
{
// Arrange
var request = new StratisSignatureAuthCallbackBody
{
PublicKey = "tQ9RukZsB6bBsenHnGSo1q69CJzWGnxohm"
};
// Act
var result = _validator.TestValidate(request);
// Assert
result.ShouldNotHaveValidationErrorFor(r => r.PublicKey);
}
} | 28.43956 | 114 | 0.684699 | [
"MIT"
] | Opdex/opdex-auth-api | test/Opdex.Auth.Api.Tests/Validation/StratisSignatureAuthCallbackBodyValidatorTests.cs | 2,588 | C# |
using System;
using FluentAssertions;
using Hadoop.Client.Hdfs.WebHdfs;
using Hadoop.Client.Jobs;
using Hadoop.Client.Jobs.Hive;
using Hadoop.Client.Jobs.WebHCatalog;
using Xunit;
namespace Hadoop.Client.Tests
{
public class JobSchedulingTests
{
private const string WebHcatBase = @"http://sandbox.hortonworks.com:50111/";
private const string WebHdfsBase = @"http://sandbox.hortonworks.com:50070/";
[Fact]
public void schedule_hive_job()
{
var client = new WebHCatalogJobClient(Connect.WithTestUser(to: WebHcatBase));
var job = new HiveJobCreateParameters
{
StatusFolder = "test.output",
JobName = "test-hive-query",
Query = @"
SELECT s07.description, s07.total_emp, s08.total_emp, s07.salary
FROM
sample_07 s07 JOIN
sample_08 s08
ON ( s07.code = s08.code )
WHERE
( s07.total_emp > s08.total_emp
AND s07.salary > 100000 )
SORT BY s07.salary DESC"
};
var result = client.SubmitHiveJob(job).Result;
result.JobId.Should().NotBeNullOrEmpty();
Console.WriteLine(result.JobId);
}
[Fact]
public void execute_hive_query()
{
const string hiveQuery = @"
SELECT s07.description, s07.total_emp, s08.total_emp, s07.salary
FROM
sample_07 s07 JOIN
sample_08 s08
ON ( s07.code = s08.code )
WHERE
( s07.total_emp > s08.total_emp
AND s07.salary > 100000 )
SORT BY s07.salary DESC";
var result = CreateApacheHiveClient().Query(hiveQuery).Result;
result.Should().NotBeNullOrEmpty();
Console.WriteLine(result);
}
private static HiveClient CreateApacheHiveClient()
{
var hdfsClient = new WebHdfsHttpClient(Connect.WithTestUser(WebHdfsBase));
var hCatalogClient = new WebHCatalogJobClient(Connect.WithTestUser(WebHcatBase));
var client = new HiveClient(hdfsClient, hCatalogClient, new HiveClientConfig
{
ResultsFolderBase = @"/tmp/hiveQueries/",
StrandardOutputFileName = "stdout"
});
return client;
}
}
} | 33.441558 | 93 | 0.541359 | [
"Apache-2.0"
] | sadowskik/Hadoop.Client | Hadoop.Client.Tests/JobSchedulingTests.cs | 2,577 | C# |
using Godot;
public class LabelUI : RichTextLabel
{
public override void _Ready()
{
GetParent().GetParent().GetNode("RocketNoLandingLegs").Connect("SendRocketVelocity", this, nameof(OnSendRocketVelocity));
}
public void OnSendRocketVelocity(Vector2 velocity)
{
Text = "Velocity: " + velocity.ToString();
}
} | 26.769231 | 129 | 0.681034 | [
"MIT"
] | RookieIndieDev/space-sim | scripts/LabelUI.cs | 348 | C# |
using Lucene.Net.Analysis.Cjk;
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.Ja.Dict;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.IO;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Analysis.Ja
{
/*
* 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.
*/
/// <summary>
/// Analyzer for Japanese that uses morphological analysis.
/// </summary>
/// <seealso cref="JapaneseTokenizer"/>
public class JapaneseAnalyzer : StopwordAnalyzerBase
{
private readonly JapaneseTokenizerMode mode;
private readonly ISet<string> stoptags;
private readonly UserDictionary userDict;
public JapaneseAnalyzer(LuceneVersion matchVersion)
: this(matchVersion, null, JapaneseTokenizer.DEFAULT_MODE, DefaultSetHolder.DEFAULT_STOP_SET, DefaultSetHolder.DEFAULT_STOP_TAGS)
{
}
public JapaneseAnalyzer(LuceneVersion matchVersion, UserDictionary userDict, JapaneseTokenizerMode mode, CharArraySet stopwords, ISet<string> stoptags)
: base(matchVersion, stopwords)
{
this.userDict = userDict;
this.mode = mode;
this.stoptags = stoptags;
}
public static CharArraySet GetDefaultStopSet()
{
return DefaultSetHolder.DEFAULT_STOP_SET;
}
public static ISet<string> GetDefaultStopTags()
{
return DefaultSetHolder.DEFAULT_STOP_TAGS;
}
/// <summary>
/// Atomically loads DEFAULT_STOP_SET, DEFAULT_STOP_TAGS in a lazy fashion once the
/// outer class accesses the static final set the first time.
/// </summary>
private static class DefaultSetHolder
{
internal static readonly CharArraySet DEFAULT_STOP_SET = LoadDefaultStopSet();
internal static readonly ISet<string> DEFAULT_STOP_TAGS = LoadDefaultStopTagSet();
private static CharArraySet LoadDefaultStopSet() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006)
{
try
{
return LoadStopwordSet(true, typeof(JapaneseAnalyzer), "stopwords.txt", "#"); // ignore case
}
catch (IOException ex)
{
// default set should always be present as it is part of the distribution (JAR)
throw new Exception("Unable to load default stopword set", ex);
}
}
private static ISet<string> LoadDefaultStopTagSet() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006)
{
try
{
CharArraySet tagset = LoadStopwordSet(false, typeof(JapaneseAnalyzer), "stoptags.txt", "#");
var DEFAULT_STOP_TAGS = new JCG.HashSet<string>();
foreach (string element in tagset)
{
DEFAULT_STOP_TAGS.Add(element);
}
return DEFAULT_STOP_TAGS;
}
catch (IOException ex)
{
// default set should always be present as it is part of the distribution (JAR)
throw new Exception("Unable to load default stoptag set", ex);
}
}
}
protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
Tokenizer tokenizer = new JapaneseTokenizer(reader, userDict, true, mode);
TokenStream stream = new JapaneseBaseFormFilter(tokenizer);
stream = new JapanesePartOfSpeechStopFilter(m_matchVersion, stream, stoptags);
stream = new CJKWidthFilter(stream);
stream = new StopFilter(m_matchVersion, stream, m_stopwords);
stream = new JapaneseKatakanaStemFilter(stream);
stream = new LowerCaseFilter(m_matchVersion, stream);
return new TokenStreamComponents(tokenizer, stream);
}
}
}
| 42.711864 | 177 | 0.632341 | [
"Apache-2.0"
] | Ref12/lucenenet | src/Lucene.Net.Analysis.Kuromoji/JapaneseAnalyzer.cs | 5,042 | C# |
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// Este código fue generado por una herramienta.
// Versión de runtime:4.0.30319.42000
//
// Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si
// se vuelve a generar el código.
// </auto-generated>
//------------------------------------------------------------------------------
namespace API.Endpoints.Events.Models
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="Widul")]
public partial class CommentsDataContext : System.Data.Linq.DataContext
{
private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
#region Definiciones de métodos de extensibilidad
partial void OnCreated();
partial void InsertVW_EventComment(VW_EventComment instance);
partial void UpdateVW_EventComment(VW_EventComment instance);
partial void DeleteVW_EventComment(VW_EventComment instance);
#endregion
public CommentsDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["WidulConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
public CommentsDataContext(string connection) :
base(connection, mappingSource)
{
OnCreated();
}
public CommentsDataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
public CommentsDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public CommentsDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public System.Data.Linq.Table<NewComment> NewComments
{
get
{
return this.GetTable<NewComment>();
}
}
public System.Data.Linq.Table<VW_EventComment> VW_EventComments
{
get
{
return this.GetTable<VW_EventComment>();
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="")]
public partial class NewComment
{
private string _comment;
public NewComment()
{
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_comment", CanBeNull=false)]
public string comment
{
get
{
return this._comment;
}
set
{
if ((this._comment != value))
{
this._comment = value;
}
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.VW_EventComments")]
public partial class VW_EventComment : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private System.Guid _event_token;
private string _user_fullname;
private System.Guid _user_token;
private string _user_photo;
private string _createdAt;
private string _comment;
#region Definiciones de métodos de extensibilidad
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void Onevent_tokenChanging(System.Guid value);
partial void Onevent_tokenChanged();
partial void Onuser_fullnameChanging(string value);
partial void Onuser_fullnameChanged();
partial void Onuser_tokenChanging(System.Guid value);
partial void Onuser_tokenChanged();
partial void Onuser_photoChanging(string value);
partial void Onuser_photoChanged();
partial void OncreatedAtChanging(string value);
partial void OncreatedAtChanged();
partial void OncommentChanging(string value);
partial void OncommentChanged();
#endregion
public VW_EventComment()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="EVN_Token", Storage="_event_token", DbType="UniqueIdentifier NOT NULL", IsPrimaryKey=true)]
public System.Guid event_token
{
get
{
return this._event_token;
}
set
{
if ((this._event_token != value))
{
this.Onevent_tokenChanging(value);
this.SendPropertyChanging();
this._event_token = value;
this.SendPropertyChanged("event_token");
this.Onevent_tokenChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="USR_FullName", Storage="_user_fullname", DbType="VarChar(200) NOT NULL", CanBeNull=false)]
public string user_fullname
{
get
{
return this._user_fullname;
}
set
{
if ((this._user_fullname != value))
{
this.Onuser_fullnameChanging(value);
this.SendPropertyChanging();
this._user_fullname = value;
this.SendPropertyChanged("user_fullname");
this.Onuser_fullnameChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="USR_Token", Storage="_user_token", DbType="UniqueIdentifier NOT NULL")]
public System.Guid user_token
{
get
{
return this._user_token;
}
set
{
if ((this._user_token != value))
{
this.Onuser_tokenChanging(value);
this.SendPropertyChanging();
this._user_token = value;
this.SendPropertyChanged("user_token");
this.Onuser_tokenChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="USR_Photo", Storage="_user_photo", DbType="VarChar(1000) NOT NULL", CanBeNull=false)]
public string user_photo
{
get
{
return this._user_photo;
}
set
{
if ((this._user_photo != value))
{
this.Onuser_photoChanging(value);
this.SendPropertyChanging();
this._user_photo = value;
this.SendPropertyChanged("user_photo");
this.Onuser_photoChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="COM_createdAt", Storage="_createdAt", DbType="VarChar(500) NOT NULL", CanBeNull=false)]
public string createdAt
{
get
{
return this._createdAt;
}
set
{
if ((this._createdAt != value))
{
this.OncreatedAtChanging(value);
this.SendPropertyChanging();
this._createdAt = value;
this.SendPropertyChanged("createdAt");
this.OncreatedAtChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="COM_Comment", Storage="_comment", DbType="VarChar(500) NOT NULL", CanBeNull=false)]
public string comment
{
get
{
return this._comment;
}
set
{
if ((this._comment != value))
{
this.OncommentChanging(value);
this.SendPropertyChanging();
this._comment = value;
this.SendPropertyChanged("comment");
this.OncommentChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
#pragma warning restore 1591
| 26.39322 | 150 | 0.662728 | [
"Apache-2.0"
] | dmunozgaete/Widul-API | v1/Endpoints/Events/Models/Comments.designer.cs | 7,795 | C# |
// Copyright (c) Six Labors and contributors.
// Licensed under the Apache License, Version 2.0.
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using BenchmarkDotNet.Attributes;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
namespace SixLabors.ImageSharp.Benchmarks
{
[Config(typeof(Config.ShortClr))]
#pragma warning disable SA1649 // File name should match first type name
public abstract class ResizeBenchmarkBase<TPixel>
#pragma warning restore SA1649 // File name should match first type name
where TPixel : unmanaged, IPixel<TPixel>
{
protected readonly Configuration Configuration = new Configuration(new JpegConfigurationModule());
private Image<TPixel> sourceImage;
private Bitmap sourceBitmap;
[Params("3032-400")]
public virtual string SourceToDest { get; set; }
protected int SourceSize { get; private set; }
protected int DestSize { get; private set; }
[GlobalSetup]
public virtual void Setup()
{
string[] stuff = this.SourceToDest.Split('-');
this.SourceSize = int.Parse(stuff[0], CultureInfo.InvariantCulture);
this.DestSize = int.Parse(stuff[1], CultureInfo.InvariantCulture);
this.sourceImage = new Image<TPixel>(this.Configuration, this.SourceSize, this.SourceSize);
this.sourceBitmap = new Bitmap(this.SourceSize, this.SourceSize);
}
[GlobalCleanup]
public void Cleanup()
{
this.sourceImage.Dispose();
this.sourceBitmap.Dispose();
}
[Benchmark(Baseline = true)]
public int SystemDrawing()
{
using (var destination = new Bitmap(this.DestSize, this.DestSize))
{
using (var g = Graphics.FromImage(destination))
{
g.CompositingMode = CompositingMode.SourceCopy;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.SmoothingMode = SmoothingMode.HighQuality;
g.DrawImage(this.sourceBitmap, 0, 0, this.DestSize, this.DestSize);
}
return destination.Width;
}
}
[Benchmark(Description = "ImageSharp, MaxDegreeOfParallelism = 1")]
public int ImageSharp_P1() => this.RunImageSharpResize(1);
// Parallel cases have been disabled for fast benchmark execution.
// Uncomment, if you are interested in parallel speedup
/*
[Benchmark(Description = "ImageSharp, MaxDegreeOfParallelism = 4")]
public int ImageSharp_P4() => this.RunImageSharpResize(4);
[Benchmark(Description = "ImageSharp, MaxDegreeOfParallelism = 8")]
public int ImageSharp_P8() => this.RunImageSharpResize(8);
*/
protected int RunImageSharpResize(int maxDegreeOfParallelism)
{
this.Configuration.MaxDegreeOfParallelism = maxDegreeOfParallelism;
using (Image<TPixel> clone = this.sourceImage.Clone(this.ExecuteResizeOperation))
{
return clone.Width;
}
}
protected abstract void ExecuteResizeOperation(IImageProcessingContext ctx);
}
public class Resize_Bicubic_Rgba32 : ResizeBenchmarkBase<Rgba32>
{
protected override void ExecuteResizeOperation(IImageProcessingContext ctx)
{
ctx.Resize(this.DestSize, this.DestSize, KnownResamplers.Bicubic);
}
// RESULTS - 2019 April - ResizeWorker:
//
// BenchmarkDotNet=v0.11.3, OS=Windows 10.0.17134.706 (1803/April2018Update/Redstone4)
// Intel Core i7-7700HQ CPU 2.80GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores
// Frequency=2742189 Hz, Resolution=364.6722 ns, Timer=TSC
// .NET Core SDK=2.2.202
// [Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
// Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3394.0
// Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
//
// IterationCount=3 LaunchCount=1 WarmupCount=3
//
// Method | Job | Runtime | SourceToDest | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
// ----------------------------------------- |----- |-------- |------------- |----------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:|
// SystemDrawing | Clr | Clr | 3032-400 | 120.11 ms | 1.435 ms | 0.0786 ms | 1.00 | 0.00 | - | - | - | 1638 B |
// 'ImageSharp, MaxDegreeOfParallelism = 1' | Clr | Clr | 3032-400 | 75.32 ms | 34.143 ms | 1.8715 ms | 0.63 | 0.02 | - | - | - | 16384 B |
// | | | | | | | | | | | | |
// SystemDrawing | Core | Core | 3032-400 | 120.33 ms | 6.669 ms | 0.3656 ms | 1.00 | 0.00 | - | - | - | 96 B |
// 'ImageSharp, MaxDegreeOfParallelism = 1' | Core | Core | 3032-400 | 88.56 ms | 1.864 ms | 0.1022 ms | 0.74 | 0.00 | - | - | - | 15568 B |
}
/// <summary>
/// Is it worth to set a larger working buffer limit for resize?
/// Conclusion: It doesn't really have an effect.
/// </summary>
public class Resize_Bicubic_Rgba32_CompareWorkBufferSizes : Resize_Bicubic_Rgba32
{
[Params(128, 512, 1024, 8 * 1024)]
public int WorkingBufferSizeHintInKilobytes { get; set; }
[Params("3032-400", "4000-300")]
public override string SourceToDest { get; set; }
public override void Setup()
{
this.Configuration.WorkingBufferSizeHintInBytes = this.WorkingBufferSizeHintInKilobytes * 1024;
base.Setup();
}
}
public class Resize_Bicubic_Bgra32 : ResizeBenchmarkBase<Bgra32>
{
protected override void ExecuteResizeOperation(IImageProcessingContext ctx)
{
ctx.Resize(this.DestSize, this.DestSize, KnownResamplers.Bicubic);
}
// RESULTS (2019 April):
//
// BenchmarkDotNet=v0.11.3, OS=Windows 10.0.17134.648 (1803/April2018Update/Redstone4)
// Intel Core i7-7700HQ CPU 2.80GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores
// Frequency=2742192 Hz, Resolution=364.6718 ns, Timer=TSC
// .NET Core SDK=2.1.602
// [Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
// Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0
// Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
//
// IterationCount=3 LaunchCount=1 WarmupCount=3
//
// Method | Job | Runtime | SourceSize | DestSize | Mean | Error | StdDev | Ratio | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
// ----------------------------------------- |----- |-------- |----------- |--------- |----------:|----------:|----------:|------:|------------:|------------:|------------:|--------------------:|
// SystemDrawing | Clr | Clr | 3032 | 400 | 119.01 ms | 18.513 ms | 1.0147 ms | 1.00 | - | - | - | 1638 B |
// 'ImageSharp, MaxDegreeOfParallelism = 1' | Clr | Clr | 3032 | 400 | 104.71 ms | 16.078 ms | 0.8813 ms | 0.88 | - | - | - | 45056 B |
// | | | | | | | | | | | | |
// SystemDrawing | Core | Core | 3032 | 400 | 121.58 ms | 50.084 ms | 2.7453 ms | 1.00 | - | - | - | 96 B |
// 'ImageSharp, MaxDegreeOfParallelism = 1' | Core | Core | 3032 | 400 | 96.96 ms | 7.899 ms | 0.4329 ms | 0.80 | - | - | - | 44512 B |
}
public class Resize_Bicubic_Rgb24 : ResizeBenchmarkBase<Rgb24>
{
protected override void ExecuteResizeOperation(IImageProcessingContext ctx)
{
ctx.Resize(this.DestSize, this.DestSize, KnownResamplers.Bicubic);
}
// RESULTS (2019 April):
//
// BenchmarkDotNet=v0.11.3, OS=Windows 10.0.17134.648 (1803/April2018Update/Redstone4)
// Intel Core i7-7700HQ CPU 2.80GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores
// Frequency=2742192 Hz, Resolution=364.6718 ns, Timer=TSC
// .NET Core SDK=2.1.602
// [Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
// Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0
// Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
//
// Method | Job | Runtime | SourceSize | DestSize | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
// ----------------------------------------- |----- |-------- |----------- |--------- |----------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:|
// SystemDrawing | Clr | Clr | 3032 | 400 | 121.37 ms | 48.580 ms | 2.6628 ms | 1.00 | 0.00 | - | - | - | 2048 B |
// 'ImageSharp, MaxDegreeOfParallelism = 1' | Clr | Clr | 3032 | 400 | 99.36 ms | 11.356 ms | 0.6224 ms | 0.82 | 0.02 | - | - | - | 45056 B |
// | | | | | | | | | | | | | |
// SystemDrawing | Core | Core | 3032 | 400 | 118.06 ms | 15.667 ms | 0.8587 ms | 1.00 | 0.00 | - | - | - | 96 B |
// 'ImageSharp, MaxDegreeOfParallelism = 1' | Core | Core | 3032 | 400 | 92.47 ms | 5.683 ms | 0.3115 ms | 0.78 | 0.01 | - | - | - | 44512 B |
}
public class Resize_BicubicCompand_Rgba32 : ResizeBenchmarkBase<Rgba32>
{
protected override void ExecuteResizeOperation(IImageProcessingContext ctx)
{
ctx.Resize(this.DestSize, this.DestSize, KnownResamplers.Bicubic, true);
}
// RESULTS (2019 April):
//
// BenchmarkDotNet=v0.11.3, OS=Windows 10.0.17134.648 (1803/April2018Update/Redstone4)
// Intel Core i7-7700HQ CPU 2.80GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores
// Frequency=2742192 Hz, Resolution=364.6718 ns, Timer=TSC
// .NET Core SDK=2.1.602
// [Host] : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
// Clr : .NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3362.0
// Core : .NET Core 2.1.9 (CoreCLR 4.6.27414.06, CoreFX 4.6.27415.01), 64bit RyuJIT
//
// IterationCount=3 LaunchCount=1 WarmupCount=3
//
// Method | Job | Runtime | SourceSize | DestSize | Mean | Error | StdDev | Ratio | RatioSD | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
// ----------------------------------------- |----- |-------- |----------- |--------- |---------:|----------:|----------:|------:|--------:|------------:|------------:|------------:|--------------------:|
// SystemDrawing | Clr | Clr | 3032 | 400 | 120.7 ms | 68.985 ms | 3.7813 ms | 1.00 | 0.00 | - | - | - | 1638 B |
// 'ImageSharp, MaxDegreeOfParallelism = 1' | Clr | Clr | 3032 | 400 | 132.2 ms | 15.976 ms | 0.8757 ms | 1.10 | 0.04 | - | - | - | 16384 B |
// | | | | | | | | | | | | | |
// SystemDrawing | Core | Core | 3032 | 400 | 118.3 ms | 6.899 ms | 0.3781 ms | 1.00 | 0.00 | - | - | - | 96 B |
// 'ImageSharp, MaxDegreeOfParallelism = 1' | Core | Core | 3032 | 400 | 122.4 ms | 15.069 ms | 0.8260 ms | 1.03 | 0.01 | - | - | - | 15712 B |
}
}
| 60.640351 | 213 | 0.469478 | [
"Apache-2.0"
] | asmodat/ImageSharp | tests/ImageSharp.Benchmarks/Samplers/Resize.cs | 13,826 | C# |
using UnityEngine;
using ActiveObjects.Triggers;
namespace ActiveObjects
{
public class AutoTranspanent :
MonoBehaviour
{
[RequiredField]
public FieldTrigger Field;
public Renderer Model;
public float Transparency;
void Start()
{
Field.Active += Field_Active;
Field.Deactive += Field_Deactive;
Field.Enable();
}
private void Field_Active(object sender, System.EventArgs e)
{
var color = Model.material.color;
color.a = Transparency;
Model.material.color = color;
}
private void Field_Deactive(object sender, System.EventArgs e)
{
var color = Model.material.color;
color.a = 1f;
Model.material.color = color;
}
}
} | 24.970588 | 70 | 0.564193 | [
"MIT"
] | Sumrix/DAZVillage | Assets/Scripts/ActiveObjects/Interaction/AutoTranspanent.cs | 851 | C# |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace pf
{
public class CSVReader
{
static string SPLIT_RE = @",(?=(?:[^""]*""[^""]*"")*(?![^""]*""))";
static string LINE_SPLIT_RE = @"\r\n|\n\r|\n|\r";
static char[] TRIM_CHARS = { '\"' };
public static List<Dictionary<string, object>> Read(string file)
{
var list = new List<Dictionary<string, object>>();
TextAsset data = Resources.Load(file) as TextAsset;
var lines = Regex.Split(data.text, LINE_SPLIT_RE);
if (lines.Length <= 1) return list;
var header = Regex.Split(lines[0], SPLIT_RE);
for (var i = 1; i < lines.Length; i++)
{
var values = Regex.Split(lines[i], SPLIT_RE);
if (values.Length == 0 || values[0] == "") continue;
var entry = new Dictionary<string, object>();
for (var j = 0; j < header.Length && j < values.Length; j++)
{
string value = values[j];
value = value.TrimStart(TRIM_CHARS).TrimEnd(TRIM_CHARS).Replace("\\", "");
object finalvalue = value;
int n;
float f;
if (int.TryParse(value, out n))
{
finalvalue = n;
}
else if (float.TryParse(value, out f))
{
finalvalue = f;
}
entry[header[j]] = finalvalue;
}
list.Add(entry);
}
return list;
}
}
} | 25.037037 | 79 | 0.597633 | [
"MIT"
] | jtlehtinen/platformer | Assets/Libs/CSVReader/CSVReader.cs | 1,352 | C# |
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
namespace Restaurante.Data.Migrations
{
public partial class Versao_01 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Restaurante",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
NomeRestaurante = table.Column<string>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Restaurante", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Prato",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
NomePrato = table.Column<string>(nullable: false),
PrecoPrato = table.Column<decimal>(nullable: false),
IdRestaurante = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Prato", x => x.Id);
table.ForeignKey(
name: "FK_Prato_Restaurante_IdRestaurante",
column: x => x.IdRestaurante,
principalTable: "Restaurante",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_Prato_IdRestaurante",
table: "Prato",
column: "IdRestaurante");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Prato");
migrationBuilder.DropTable(
name: "Restaurante");
}
}
}
| 37.666667 | 122 | 0.517257 | [
"MIT"
] | JulioBorges/cedro-restaurant | restaurante.api/Restaurante.Data/Migrations/20180924054952_Versao_01.cs | 2,262 | 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.Logic.Latest.Inputs
{
/// <summary>
/// The network configuration.
/// </summary>
public sealed class NetworkConfigurationArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The access endpoint.
/// </summary>
[Input("accessEndpoint")]
public Input<Inputs.IntegrationServiceEnvironmentAccessEndpointArgs>? AccessEndpoint { get; set; }
[Input("subnets")]
private InputList<Inputs.ResourceReferenceArgs>? _subnets;
/// <summary>
/// The subnets.
/// </summary>
public InputList<Inputs.ResourceReferenceArgs> Subnets
{
get => _subnets ?? (_subnets = new InputList<Inputs.ResourceReferenceArgs>());
set => _subnets = value;
}
/// <summary>
/// Gets the virtual network address space.
/// </summary>
[Input("virtualNetworkAddressSpace")]
public Input<string>? VirtualNetworkAddressSpace { get; set; }
public NetworkConfigurationArgs()
{
}
}
}
| 29.404255 | 106 | 0.625904 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Logic/Latest/Inputs/NetworkConfigurationArgs.cs | 1,382 | C# |
using System;
namespace _01.Thea_The_Photographer
{
class Program
{
static void Main(string[] args)
{
long photosTaken = long.Parse(Console.ReadLine());
int secondsToFilter = int.Parse(Console.ReadLine());
int filterFactor = int.Parse(Console.ReadLine());
int uploadSeconds = int.Parse(Console.ReadLine());
long photosToUpload = (long)Math.Ceiling(photosTaken * (filterFactor / 100.0));
long timeFilter = photosTaken * secondsToFilter;
long totalTime = timeFilter + (photosToUpload * uploadSeconds);
long seconds = totalTime % 60;
long minutes = (totalTime / 60) % 60;
long hours = (totalTime / 60 / 60) % 24;
long days = (totalTime / 60 / 60) / 24;
Console.WriteLine($"{days:d1}:{hours:d2}:{minutes:d2}:{seconds:d2}");
}
}
}
| 34.703704 | 92 | 0.562433 | [
"MIT"
] | KrasimiraGeorgieva/Tech-Module-Programming-Fundamentals | All Exams Tasks Solutions/Thea The Photographer_01/01. Thea The Photographer.cs | 939 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("DigitalPlatform.Drawing")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DigitalPlatform.Drawing")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("7CCF1B70-9B4A-4623-8F8F-D7B8CADB5051")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
| 26.324324 | 56 | 0.717659 | [
"Apache-2.0"
] | DigitalPlatform/dp2 | DigitalPlatform.Drawing/AssemblyInfo.cs | 1,333 | C# |
using System;
namespace UmbracoVault.TypeHandlers.Primitives
{
public class UshortTypeHandler : ITypeHandler
{
private static object Get(string stringValue)
{
ushort result;
ushort.TryParse(stringValue, out result);
return result;
}
public object GetAsType<T>(object input)
{
return Get(input.ToString());
}
public Type TypeSupported => typeof (ushort);
}
}
| 19.708333 | 53 | 0.59408 | [
"Apache-2.0"
] | wkallhof/UmbracoVault.Lite | UmbracoVault/TypeHandlers/Primitives/UShortTypeHandler.cs | 475 | C# |
#if CSHARP_7_OR_LATER
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using UnityEngine.EventSystems;
namespace UniRx.Async.Triggers
{
[DisallowMultipleComponent]
public class AsyncUpdateSelectedTrigger : AsyncTriggerBase
{
AsyncTriggerPromise<BaseEventData> onUpdateSelected;
AsyncTriggerPromiseDictionary<BaseEventData> onUpdateSelecteds;
protected override IEnumerable<ICancelablePromise> GetPromises()
{
return Concat(onUpdateSelected, onUpdateSelecteds);
}
void OnUpdateSelected(BaseEventData eventData)
{
TrySetResult(onUpdateSelected, onUpdateSelecteds, eventData);
}
public UniTask OnUpdateSelectedAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return GetOrAddPromise(ref onUpdateSelected, ref onUpdateSelecteds, cancellationToken);
}
}
}
#endif
| 25.071429 | 110 | 0.730294 | [
"MIT"
] | SkaillZ/ubernet | Assets/Plugins/Ubernet/Scripts/Core/Libs/UniRx/Scripts/Async/Triggers/AsyncUpdateSelectedTrigger.cs | 1,053 | C# |
// TODO Can this be moved up to SIL.Lift.Tests?
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using SIL.DictionaryServices.Model;
using SIL.Lift;
using SIL.TestUtilities;
namespace SIL.DictionaryServices.Tests.Model
{
[TestFixture]
public class LexRelationCloneableTests : CloneableTests<IPalasoDataObjectProperty>
{
public override IPalasoDataObjectProperty CreateNewCloneable()
{
return new LexRelation("Id", "targetId", null);
}
public override string ExceptionList
{
//PropertyChanged: No good way to clone eventhandlers
//_parent: We are doing top down clones. Children shouldn't make clones of their parents, but parents of their children.
get { return "|_parent|PropertyChanged|"; }
}
protected override List<ValuesToSet> DefaultValuesForTypes
{
get
{
return new List<ValuesToSet>
{
new ValuesToSet("to be", "!(to be)"),
new ValuesToSet(
new List<LexTrait> { new LexTrait("one", "eins"), new LexTrait("two", "zwei") },
new List<LexTrait> { new LexTrait("three", "drei"), new LexTrait("four", "vier") }),
new ValuesToSet(
new List<LexField> { new LexField("one"), new LexField("two") },
new List<LexField> { new LexField("three"), new LexField("four") }),
new ValuesToSet(new List<string>{"to", "be"}, new List<string>{"!","to","be"})
};
}
}
}
[TestFixture]
public class LexRelationTests
{
private string _filePath;
[SetUp]
public void Setup()
{
_filePath = Path.GetTempFileName();
}
[TearDown]
public void TearDown()
{
File.Delete(_filePath);
}
[Test]
public void Construct_TargetIdNull_TargetIdIsEmptyString()
{
LexSense sense = new LexSense();
LexRelationType synonymRelationType = new LexRelationType("synonym",
LexRelationType.Multiplicities
.Many,
LexRelationType.TargetTypes.
Sense);
LexRelation relation = new LexRelation(synonymRelationType.ID, null, sense);
Assert.AreEqual(string.Empty, relation.Key);
}
[Test]
public void TargetId_SetNull_GetStringEmpty()
{
LexSense sense = new LexSense();
LexRelationType synonymRelationType = new LexRelationType("synonym",
LexRelationType.Multiplicities
.Many,
LexRelationType.TargetTypes.
Sense);
LexRelation relation = new LexRelation(synonymRelationType.ID, "something", sense);
relation.Key = null;
Assert.AreEqual(string.Empty, relation.Key);
}
}
} | 28.659341 | 123 | 0.659126 | [
"MIT"
] | MaxMood96/libpalaso | SIL.DictionaryServices.Tests/Model/LexRelationTests.cs | 2,608 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using CodeMania.Core.EqualityComparers.Specialized;
using NUnit.Framework;
namespace CodeMania.UnitTests.EqualityComparers
{
[TestFixture]
public class IntArrayMemoryEqualityComparerTestBase : ArrayMemoryEqualityComparerTestBase<int>
{
public IntArrayMemoryEqualityComparerTestBase() : base(UnmanagedTypeArrayEqualityComparer<int>.Default)
{
}
protected override IEnumerable<TestCase> GetTestCases()
{
yield return new TestCase(new int[] { 1 }, new int[] { 1 }, true);
yield return new TestCase(new int[] { 1 }, new int[] { 0 }, false);
yield return new TestCase(new int[] { 0 }, new int[] { 1 }, false);
yield return new TestCase(new int[] { 1, 2, 3 }, new int[] { 1, 2, 0 }, false);
yield return new TestCase(new int[] { }, new int[] { 1 }, false);
yield return new TestCase(new int[] { }, new int[] { }, true);
yield return new TestCase(new int[1024], new int[1024], true);
yield return new TestCase(new int[1024], new int[1025], false);
var random = new Random(Guid.NewGuid().GetHashCode());
var ints = Enumerable.Range(0, 10000).Select(x => random.Next()).ToArray();
var ints2 = ints.ToList().ToArray();
yield return new TestCase(ints, ints2, true);
ints2[ints2.Length - 1] = unchecked(~(ints2[ints2.Length - 1] + 1));
yield return new TestCase(ints, ints2, false);
}
}
} | 39.055556 | 105 | 0.691323 | [
"MIT"
] | aivascu/CodeMania | src/CodeMania.Core.UnitTests/EqualityComparers/IntArrayMemoryEqualityComparerTestBase.cs | 1,408 | C# |
// ReSharper disable InconsistentNaming
using System;
using System.Threading.Tasks;
using EasyNetQ.Consumer;
using EasyNetQ.Logging;
using FluentAssertions;
using NSubstitute;
using RabbitMQ.Client;
using Xunit;
namespace EasyNetQ.Tests.HandlerRunnerTests
{
public class When_a_user_handler_is_executed
{
public When_a_user_handler_is_executed()
{
var consumerErrorStrategy = Substitute.For<IConsumerErrorStrategy>();
var handlerRunner = new HandlerRunner(Substitute.For<ILogger<IHandlerRunner>>(), consumerErrorStrategy);
var consumer = Substitute.For<IBasicConsumer>();
channel = Substitute.For<IModel, IRecoverable>();
consumer.Model.Returns(channel);
var context = new ConsumerExecutionContext(
(body, properties, info, _) =>
{
deliveredBody = body;
deliveredProperties = properties;
deliveredInfo = info;
return Task.FromResult(AckStrategies.Ack);
},
messageInfo,
messageProperties,
messageBody
);
var handlerTask = handlerRunner.InvokeUserMessageHandlerAsync(context, default)
.ContinueWith(async x =>
{
var ackStrategy = await x;
return ackStrategy(channel, 42);
}, TaskContinuationOptions.ExecuteSynchronously)
.Unwrap();
if (!handlerTask.Wait(5000))
{
throw new TimeoutException();
}
}
private ReadOnlyMemory<byte> deliveredBody;
private MessageProperties deliveredProperties;
private MessageReceivedInfo deliveredInfo;
private readonly MessageProperties messageProperties = new()
{
CorrelationId = "correlation_id"
};
private readonly MessageReceivedInfo messageInfo = new("consumer_tag", 42, false, "exchange", "routingKey", "queue");
private readonly byte[] messageBody = new byte[0];
private readonly IModel channel;
[Fact]
public void Should_ACK()
{
channel.Received().BasicAck(42, false);
}
[Fact]
public void Should_deliver_body()
{
deliveredBody.ToArray().Should().BeEquivalentTo(messageBody);
}
[Fact]
public void Should_deliver_info()
{
deliveredInfo.Should().BeSameAs(messageInfo);
}
[Fact]
public void Should_deliver_properties()
{
deliveredProperties.Should().BeSameAs(messageProperties);
}
}
}
// ReSharper restore InconsistentNaming
| 29.755319 | 125 | 0.591348 | [
"MIT"
] | 10088/EasyNetQ | Source/EasyNetQ.Tests/HandlerRunnerTests/When_a_user_handler_is_executed.cs | 2,797 | C# |
using DaJet.Metadata;
using Microsoft.Data.SqlClient;
using Npgsql;
using NpgsqlTypes;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
namespace DaJet.Data.Messaging.V1
{
/// <summary>
/// Табличный интерфейс входящей очереди сообщений
/// (непериодический независимый регистр сведений)
/// </summary>
[Table("РегистрСведений.ВходящаяОчередь")] [Version(1)] public sealed class IncomingMessage : IncomingMessageDataMapper
{
#region "DATA CONTRACT - INSTANCE PROPERTIES"
/// <summary>
/// "НомерСообщения" Порядковый номер сообщения (может генерироваться средствами СУБД) - numeric(19,0)
/// </summary>
[Column("НомерСообщения")] [Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public long MessageNumber { get; set; } = 0L;
/// <summary>
/// "Заголовки" Заголовки сообщения в формате JSON { "ключ": "значение" } - nvarchar(max)
/// </summary>
[Column("Заголовки")] public string Headers { get; set; } = string.Empty;
/// <summary>
/// "Отправитель" Код или UUID отправителя сообщения - nvarchar(36)
/// </summary>
[Column("Отправитель")] public string Sender { get; set; } = string.Empty;
/// <summary>
/// "ТипСообщения" Тип сообщения, например, "Справочник.Номенклатура" - nvarchar(1024)
/// </summary>
[Column("ТипСообщения")] public string MessageType { get; set; } = string.Empty;
/// <summary>
/// "ТелоСообщения" Тело сообщения в формате JSON или XML - nvarchar(max)
/// </summary>
[Column("ТелоСообщения")] public string MessageBody { get; set; } = string.Empty;
/// <summary>
/// "ДатаВремя" Время создания сообщения - datetime2
/// </summary>
[Column("ДатаВремя")] public DateTime DateTimeStamp { get; set; } = DateTime.MinValue;
/// <summary>
/// "ОписаниеОшибки" Описание ошибки, возникшей при обработке сообщения - nvarchar(1024)
/// </summary>
[Column("ОписаниеОшибки")] public string ErrorDescription { get; set; } = string.Empty;
/// <summary>
/// "КоличествоОшибок" Количество неудачных попыток обработки сообщения - numeric(2,0)
/// </summary>
[Column("КоличествоОшибок")] public int ErrorCount { get; set; } = 0;
#endregion
#region "DATA MAPPING - INSERT COMMAND"
private const string MS_INCOMING_QUEUE_INSERT_SCRIPT_TEMPLATE =
"INSERT {TABLE_NAME} " +
"({НомерСообщения}, {Заголовки}, {Отправитель}, {ТипСообщения}, {ТелоСообщения}, {ДатаВремя}, {ОписаниеОшибки}, {КоличествоОшибок}) " +
"SELECT NEXT VALUE FOR {SEQUENCE_NAME}, " +
"@Заголовки, @Отправитель, @ТипСообщения, @ТелоСообщения, @ДатаВремя, @ОписаниеОшибки, @КоличествоОшибок;";
private const string PG_INCOMING_QUEUE_INSERT_SCRIPT_TEMPLATE =
"INSERT INTO {TABLE_NAME} " +
"({НомерСообщения}, {Заголовки}, {Отправитель}, {ТипСообщения}, {ТелоСообщения}, {ДатаВремя}, {ОписаниеОшибки}, {КоличествоОшибок}) " +
"SELECT CAST(nextval('{SEQUENCE_NAME}') AS numeric(19,0)), " +
"CAST(@Заголовки AS mvarchar), CAST(@Отправитель AS mvarchar), CAST(@ТипСообщения AS mvarchar), " +
"CAST(@ТелоСообщения AS mvarchar), @ДатаВремя, CAST(@ОписаниеОшибки AS mvarchar), @КоличествоОшибок;";
public override string GetInsertScript(DatabaseProvider provider)
{
if (provider == DatabaseProvider.SQLServer)
{
return MS_INCOMING_QUEUE_INSERT_SCRIPT_TEMPLATE;
}
else
{
return PG_INCOMING_QUEUE_INSERT_SCRIPT_TEMPLATE;
}
}
public override void ConfigureCommandParameters<T>(in T command)
{
command.Parameters.Clear();
if (command is SqlCommand ms)
{
ms.Parameters.Add("Заголовки", SqlDbType.NVarChar);
ms.Parameters.Add("Отправитель", SqlDbType.NVarChar);
ms.Parameters.Add("ТипСообщения", SqlDbType.NVarChar);
ms.Parameters.Add("ТелоСообщения", SqlDbType.NVarChar);
ms.Parameters.Add("ДатаВремя", SqlDbType.DateTime2);
ms.Parameters.Add("ОписаниеОшибки", SqlDbType.NVarChar);
ms.Parameters.Add("КоличествоОшибок", SqlDbType.Int);
}
else if (command is NpgsqlCommand pg)
{
pg.Parameters.Add("Заголовки", NpgsqlDbType.Varchar);
pg.Parameters.Add("Отправитель", NpgsqlDbType.Varchar);
pg.Parameters.Add("ТипСообщения", NpgsqlDbType.Varchar);
pg.Parameters.Add("ТелоСообщения", NpgsqlDbType.Varchar);
pg.Parameters.Add("ДатаВремя", NpgsqlDbType.Timestamp);
pg.Parameters.Add("ОписаниеОшибки", NpgsqlDbType.Varchar);
pg.Parameters.Add("КоличествоОшибок", NpgsqlDbType.Integer);
}
}
public override void SetMessageData<T>(in IncomingMessageDataMapper source, in T target)
{
if (!(source is IncomingMessage message))
{
throw new ArgumentOutOfRangeException(nameof(source));
}
target.Parameters["Заголовки"].Value = message.Headers;
target.Parameters["Отправитель"].Value = message.Sender;
target.Parameters["ТипСообщения"].Value = message.MessageType;
target.Parameters["ТелоСообщения"].Value = message.MessageBody;
target.Parameters["ДатаВремя"].Value = message.DateTimeStamp;
target.Parameters["ОписаниеОшибки"].Value = message.ErrorDescription;
target.Parameters["КоличествоОшибок"].Value = message.ErrorCount;
}
#endregion
}
} | 47.285714 | 147 | 0.622692 | [
"MIT"
] | zhichkin/dajet-data-messaging | src/dajet-data-messaging/contracts/v1/IncomingMessage.cs | 7,182 | C# |
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace TiqSoft.ScreenAssistant.Core
{
internal static class WinApiHelper
{
private static IntPtr _prevPoint;
private static string _prevProcess = string.Empty;
[DllImport("user32.dll")]
public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
internal static string GetActiveProcessName()
{
var fWindow = GetForegroundWindow();
if (fWindow != _prevPoint)
{
_prevPoint = fWindow;
GetWindowThreadProcessId(fWindow, out var pid);
var p = Process.GetProcessById((int)pid);
_prevProcess = p.ProcessName;
}
return _prevProcess;
}
}
} | 30.933333 | 94 | 0.619612 | [
"MIT"
] | angusbeef93/screen-access | ScreenAssistant/Core/WinApiHelper.cs | 930 | C# |
/*
* Copyright (c) 2014-2020 GraphDefined GmbH
* This file is part of WWCP OCPP <https://github.com/OpenChargingCloud/WWCP_OCPP>
*
* 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.
*/
#region Usings
using System;
using System.Xml.Linq;
using Newtonsoft.Json.Linq;
using org.GraphDefined.Vanaheimr.Illias;
using org.GraphDefined.Vanaheimr.Hermod.JSON;
#endregion
namespace cloud.charging.adapters.OCPPv1_6.CP
{
/// <summary>
/// A get composite schedule response.
/// </summary>
public class GetCompositeScheduleResponse : AResponse<CS.GetCompositeScheduleRequest,
GetCompositeScheduleResponse>
{
#region Properties
/// <summary>
/// The result of the request.
/// </summary>
public GetCompositeScheduleStatus Status { get; }
/// <summary>
/// The charging schedule contained in this notification
/// applies to a specific connector.
/// </summary>
public Connector_Id? ConnectorId { get; }
/// <summary>
/// The periods contained in the charging profile are relative
/// to this timestamp.
/// </summary>
public DateTime? ScheduleStart { get; }
/// <summary>
/// The planned composite charging schedule, the energy consumption
/// over time. Always relative to ScheduleStart.
/// </summary>
public ChargingSchedule ChargingSchedule { get; }
#endregion
#region Constructor(s)
#region GetCompositeScheduleResponse(Request, Status, ConnectorId, ScheduleStart, ChargingSchedule)
/// <summary>
/// Create a new get composite schedule response.
/// </summary>
/// <param name="Request">The start transaction request leading to this response.</param>
/// <param name="Status">The result of the request.</param>
/// <param name="ConnectorId">The charging schedule contained in this notification applies to a specific connector.</param>
/// <param name="ScheduleStart">The periods contained in the charging profile are relative to this timestamp.</param>
/// <param name="ChargingSchedule">The planned composite charging schedule, the energy consumption over time. Always relative to ScheduleStart.</param>
public GetCompositeScheduleResponse(CS.GetCompositeScheduleRequest Request,
GetCompositeScheduleStatus Status,
Connector_Id? ConnectorId,
DateTime? ScheduleStart,
ChargingSchedule ChargingSchedule)
: base(Request,
Result.OK())
{
this.Status = Status;
this.ConnectorId = ConnectorId;
this.ScheduleStart = ScheduleStart;
this.ChargingSchedule = ChargingSchedule;
}
#endregion
#region GetCompositeScheduleResponse(Request, Result)
/// <summary>
/// Create a new get composite schedule response.
/// </summary>
/// <param name="Request">The start transaction request leading to this response.</param>
/// <param name="Result">The result.</param>
public GetCompositeScheduleResponse(CS.GetCompositeScheduleRequest Request,
Result Result)
: base(Request,
Result)
{ }
#endregion
#endregion
#region Documentation
// <soap:Envelope xmlns:soap = "http://www.w3.org/2003/05/soap-envelope"
// xmlns:ns = "urn://Ocpp/Cp/2015/10/">
// <soap:Header/>
// <soap:Body>
// <ns:getCompositeScheduleResponse>
//
// <ns:status>?</ns:status>
//
// <!--Optional:-->
// <ns:connectorId>?</ns:connectorId>
//
// <!--Optional:-->
// <ns:scheduleStart>?</ns:scheduleStart>
//
// <!--Optional:-->
// <ns:chargingSchedule>
//
// <!--Optional:-->
// <ns:duration>?</ns:duration>
//
// <!--Optional:-->
// <ns:startSchedule>?</ns:startSchedule>
//
// <ns:chargingRateUnit>?</ns:chargingRateUnit>
//
// <!--1 or more repetitions:-->
// <ns:chargingSchedulePeriod>
//
// <ns:startPeriod>?</ns:startPeriod>
// <ns:limit>?</ns:limit>
//
// <!--Optional:-->
// <ns:numberPhases>?</ns:numberPhases>
//
// </ns:chargingSchedulePeriod>
//
// <!--Optional:-->
// <ns:minChargingRate>?</ns:minChargingRate>
//
// </ns:chargingSchedule>
//
// </ns:getCompositeScheduleResponse>
// </soap:Body>
// </soap:Envelope>
// {
// "$schema": "http://json-schema.org/draft-04/schema#",
// "id": "urn:OCPP:1.6:2019:12:GetCompositeScheduleResponse",
// "title": "GetCompositeScheduleResponse",
// "type": "object",
// "properties": {
// "status": {
// "type": "string",
// "additionalProperties": false,
// "enum": [
// "Accepted",
// "Rejected"
// ]
// },
// "connectorId": {
// "type": "integer"
// },
// "scheduleStart": {
// "type": "string",
// "format": "date-time"
// },
// "chargingSchedule": {
// "type": "object",
// "properties": {
// "duration": {
// "type": "integer"
// },
// "startSchedule": {
// "type": "string",
// "format": "date-time"
// },
// "chargingRateUnit": {
// "type": "string",
// "additionalProperties": false,
// "enum": [
// "A",
// "W"
// ]
// },
// "chargingSchedulePeriod": {
// "type": "array",
// "items": {
// "type": "object",
// "properties": {
// "startPeriod": {
// "type": "integer"
// },
// "limit": {
// "type": "number",
// "multipleOf" : 0.1
// },
// "numberPhases": {
// "type": "integer"
// }
// },
// "additionalProperties": false,
// "required": [
// "startPeriod",
// "limit"
// ]
// }
// },
// "minChargingRate": {
// "type": "number",
// "multipleOf" : 0.1
// }
// },
// "additionalProperties": false,
// "required": [
// "chargingRateUnit",
// "chargingSchedulePeriod"
// ]
// }
// },
// "additionalProperties": false,
// "required": [
// "status"
// ]
// }
#endregion
#region (static) Parse (Request, GetCompositeScheduleResponseXML, OnException = null)
/// <summary>
/// Parse the given XML representation of a get composite schedule response.
/// </summary>
/// <param name="Request">The start transaction request leading to this response.</param>
/// <param name="GetCompositeScheduleResponseXML">The XML to be parsed.</param>
/// <param name="OnException">An optional delegate called whenever an exception occured.</param>
public static GetCompositeScheduleResponse Parse(CS.GetCompositeScheduleRequest Request,
XElement GetCompositeScheduleResponseXML,
OnExceptionDelegate OnException = null)
{
if (TryParse(Request,
GetCompositeScheduleResponseXML,
out GetCompositeScheduleResponse getCompositeScheduleResponse,
OnException))
{
return getCompositeScheduleResponse;
}
return null;
}
#endregion
#region (static) Parse (Request, GetCompositeScheduleResponseJSON, OnException = null)
/// <summary>
/// Parse the given JSON representation of a get composite schedule response.
/// </summary>
/// <param name="Request">The start transaction request leading to this response.</param>
/// <param name="GetCompositeScheduleResponseJSON">The JSON to be parsed.</param>
/// <param name="OnException">An optional delegate called whenever an exception occured.</param>
public static GetCompositeScheduleResponse Parse(CS.GetCompositeScheduleRequest Request,
JObject GetCompositeScheduleResponseJSON,
OnExceptionDelegate OnException = null)
{
if (TryParse(Request,
GetCompositeScheduleResponseJSON,
out GetCompositeScheduleResponse getCompositeScheduleResponse,
OnException))
{
return getCompositeScheduleResponse;
}
return null;
}
#endregion
#region (static) Parse (Request, GetCompositeScheduleResponseText, OnException = null)
/// <summary>
/// Parse the given text representation of a get composite schedule response.
/// </summary>
/// <param name="Request">The start transaction request leading to this response.</param>
/// <param name="GetCompositeScheduleResponseText">The text to be parsed.</param>
/// <param name="OnException">An optional delegate called whenever an exception occured.</param>
public static GetCompositeScheduleResponse Parse(CS.GetCompositeScheduleRequest Request,
String GetCompositeScheduleResponseText,
OnExceptionDelegate OnException = null)
{
if (TryParse(Request,
GetCompositeScheduleResponseText,
out GetCompositeScheduleResponse getCompositeScheduleResponse,
OnException))
{
return getCompositeScheduleResponse;
}
return null;
}
#endregion
#region (static) TryParse(Request, GetCompositeScheduleResponseXML, out GetCompositeScheduleResponse, OnException = null)
/// <summary>
/// Try to parse the given XML representation of a get composite schedule response.
/// </summary>
/// <param name="Request">The start transaction request leading to this response.</param>
/// <param name="GetCompositeScheduleResponseXML">The XML to be parsed.</param>
/// <param name="GetCompositeScheduleResponse">The parsed get composite schedule response.</param>
/// <param name="OnException">An optional delegate called whenever an exception occured.</param>
public static Boolean TryParse(CS.GetCompositeScheduleRequest Request,
XElement GetCompositeScheduleResponseXML,
out GetCompositeScheduleResponse GetCompositeScheduleResponse,
OnExceptionDelegate OnException = null)
{
try
{
GetCompositeScheduleResponse = new GetCompositeScheduleResponse(
Request,
GetCompositeScheduleResponseXML.MapEnumValuesOrFail(OCPPNS.OCPPv1_6_CP + "status",
GetCompositeScheduleStatusExtentions.Parse),
GetCompositeScheduleResponseXML.MapValueOrNull (OCPPNS.OCPPv1_6_CP + "connectorId",
Connector_Id.Parse),
GetCompositeScheduleResponseXML.MapValueOrNullable (OCPPNS.OCPPv1_6_CP + "scheduleStart",
DateTime.Parse),
GetCompositeScheduleResponseXML.MapElement (OCPPNS.OCPPv1_6_CP + "chargingSchedule",
ChargingSchedule.Parse)
);
return true;
}
catch (Exception e)
{
OnException?.Invoke(DateTime.UtcNow, GetCompositeScheduleResponseXML, e);
GetCompositeScheduleResponse = null;
return false;
}
}
#endregion
#region (static) TryParse(Request, GetCompositeScheduleResponseJSON, out GetCompositeScheduleResponse, OnException = null)
/// <summary>
/// Try to parse the given JSON representation of a get composite schedule response.
/// </summary>
/// <param name="Request">The start transaction request leading to this response.</param>
/// <param name="GetCompositeScheduleResponseJSON">The JSON to be parsed.</param>
/// <param name="GetCompositeScheduleResponse">The parsed get composite schedule response.</param>
/// <param name="OnException">An optional delegate called whenever an exception occured.</param>
public static Boolean TryParse(CS.GetCompositeScheduleRequest Request,
JObject GetCompositeScheduleResponseJSON,
out GetCompositeScheduleResponse GetCompositeScheduleResponse,
OnExceptionDelegate OnException = null)
{
try
{
GetCompositeScheduleResponse = null;
#region GetCompositeScheduleStatus
if (!GetCompositeScheduleResponseJSON.MapMandatory("status",
"get composite schedule status",
GetCompositeScheduleStatusExtentions.Parse,
out GetCompositeScheduleStatus GetCompositeScheduleStatus,
out String ErrorResponse))
{
return false;
}
#endregion
#region ConnectorId
if (GetCompositeScheduleResponseJSON.ParseOptionalStruct("connectorId",
"connector identification",
Connector_Id.TryParse,
out Connector_Id? ConnectorId,
out ErrorResponse))
{
if (ErrorResponse != null)
return false;
}
#endregion
#region ScheduleStart
if (GetCompositeScheduleResponseJSON.ParseOptional("scheduleStart",
"schedule start",
out DateTime? ScheduleStart,
out ErrorResponse))
{
if (ErrorResponse != null)
return false;
}
#endregion
#region ChargingSchedule
if (GetCompositeScheduleResponseJSON.ParseOptionalJSON("chargingSchedule",
"availability status",
OCPPv1_6.ChargingSchedule.TryParse,
out ChargingSchedule ChargingSchedule,
out ErrorResponse,
OnException))
{
if (ErrorResponse != null)
return false;
}
#endregion
GetCompositeScheduleResponse = new GetCompositeScheduleResponse(Request,
GetCompositeScheduleStatus,
ConnectorId,
ScheduleStart,
ChargingSchedule);
return true;
}
catch (Exception e)
{
OnException?.Invoke(DateTime.UtcNow, GetCompositeScheduleResponseJSON, e);
GetCompositeScheduleResponse = null;
return false;
}
}
#endregion
#region (static) TryParse(Request, GetCompositeScheduleResponseText, out GetCompositeScheduleResponse, OnException = null)
/// <summary>
/// Try to parse the given text representation of a get composite schedule response.
/// </summary>
/// <param name="Request">The start transaction request leading to this response.</param>
/// <param name="GetCompositeScheduleResponseText">The text to be parsed.</param>
/// <param name="GetCompositeScheduleResponse">The parsed get composite schedule response.</param>
/// <param name="OnException">An optional delegate called whenever an exception occured.</param>
public static Boolean TryParse(CS.GetCompositeScheduleRequest Request,
String GetCompositeScheduleResponseText,
out GetCompositeScheduleResponse GetCompositeScheduleResponse,
OnExceptionDelegate OnException = null)
{
try
{
GetCompositeScheduleResponseText = GetCompositeScheduleResponseText?.Trim();
if (GetCompositeScheduleResponseText.IsNotNullOrEmpty())
{
if (GetCompositeScheduleResponseText.StartsWith("{") &&
TryParse(Request,
JObject.Parse(GetCompositeScheduleResponseText),
out GetCompositeScheduleResponse,
OnException))
{
return true;
}
if (TryParse(Request,
XDocument.Parse(GetCompositeScheduleResponseText).Root,
out GetCompositeScheduleResponse,
OnException))
{
return true;
}
}
}
catch (Exception e)
{
OnException?.Invoke(DateTime.UtcNow, GetCompositeScheduleResponseText, e);
}
GetCompositeScheduleResponse = null;
return false;
}
#endregion
#region ToXML()
/// <summary>
/// Return a XML representation of this object.
/// </summary>
public XElement ToXML()
=> new XElement(OCPPNS.OCPPv1_6_CP + "getCompositeScheduleResponse",
new XElement(OCPPNS.OCPPv1_6_CP + "status", Status.AsText()),
ConnectorId != null
? new XElement(OCPPNS.OCPPv1_6_CP + "connectorId", ConnectorId.ToString())
: null,
ScheduleStart.HasValue
? new XElement(OCPPNS.OCPPv1_6_CP + "scheduleStart", ScheduleStart.Value.ToIso8601())
: null,
ChargingSchedule?.ToXML()
);
#endregion
#region ToJSON(CustomGetCompositeScheduleResponseSerializer = null)
/// <summary>
/// Return a JSON representation of this object.
/// </summary>
/// <param name="CustomGetCompositeScheduleResponseSerializer">A delegate to serialize custom get composite schedule responses.</param>
public JObject ToJSON(CustomJObjectSerializerDelegate<GetCompositeScheduleResponse> CustomGetCompositeScheduleResponseSerializer = null)
{
var JSON = JSONObject.Create(
new JProperty("status", Status. AsText()),
ConnectorId.HasValue
? new JProperty("connectorId", ConnectorId. Value.ToString())
: null,
ScheduleStart.HasValue
? new JProperty("scheduleStart", ScheduleStart.Value.ToIso8601())
: null,
ChargingSchedule != null
? new JProperty("chargingSchedule", ChargingSchedule. ToJSON())
: null
);
return CustomGetCompositeScheduleResponseSerializer != null
? CustomGetCompositeScheduleResponseSerializer(this, JSON)
: JSON;
}
#endregion
#region Static methods
/// <summary>
/// The get composite schedule request failed.
/// </summary>
/// <param name="Request">The start transaction request leading to this response.</param>
public static GetCompositeScheduleResponse Failed(CS.GetCompositeScheduleRequest Request)
=> new GetCompositeScheduleResponse(Request,
Result.Server());
#endregion
#region Operator overloading
#region Operator == (GetCompositeScheduleResponse1, GetCompositeScheduleResponse2)
/// <summary>
/// Compares two get composite schedule responses for equality.
/// </summary>
/// <param name="GetCompositeScheduleResponse1">A get composite schedule response.</param>
/// <param name="GetCompositeScheduleResponse2">Another get composite schedule response.</param>
/// <returns>True if both match; False otherwise.</returns>
public static Boolean operator == (GetCompositeScheduleResponse GetCompositeScheduleResponse1, GetCompositeScheduleResponse GetCompositeScheduleResponse2)
{
// If both are null, or both are same instance, return true.
if (ReferenceEquals(GetCompositeScheduleResponse1, GetCompositeScheduleResponse2))
return true;
// If one is null, but not both, return false.
if ((GetCompositeScheduleResponse1 is null) || (GetCompositeScheduleResponse2 is null))
return false;
return GetCompositeScheduleResponse1.Equals(GetCompositeScheduleResponse2);
}
#endregion
#region Operator != (GetCompositeScheduleResponse1, GetCompositeScheduleResponse2)
/// <summary>
/// Compares two get composite schedule responses for inequality.
/// </summary>
/// <param name="GetCompositeScheduleResponse1">A get composite schedule response.</param>
/// <param name="GetCompositeScheduleResponse2">Another get composite schedule response.</param>
/// <returns>False if both match; True otherwise.</returns>
public static Boolean operator != (GetCompositeScheduleResponse GetCompositeScheduleResponse1, GetCompositeScheduleResponse GetCompositeScheduleResponse2)
=> !(GetCompositeScheduleResponse1 == GetCompositeScheduleResponse2);
#endregion
#endregion
#region IEquatable<GetCompositeScheduleResponse> Members
#region Equals(Object)
/// <summary>
/// Compares two instances of this object.
/// </summary>
/// <param name="Object">An object to compare with.</param>
/// <returns>true|false</returns>
public override Boolean Equals(Object Object)
{
if (Object is null)
return false;
if (!(Object is GetCompositeScheduleResponse GetCompositeScheduleResponse))
return false;
return Equals(GetCompositeScheduleResponse);
}
#endregion
#region Equals(GetCompositeScheduleResponse)
/// <summary>
/// Compares two get composite schedule responses for equality.
/// </summary>
/// <param name="GetCompositeScheduleResponse">A get composite schedule response to compare with.</param>
/// <returns>True if both match; False otherwise.</returns>
public override Boolean Equals(GetCompositeScheduleResponse GetCompositeScheduleResponse)
{
if (GetCompositeScheduleResponse is null)
return false;
return Status.Equals(GetCompositeScheduleResponse.Status) &&
((ConnectorId == null && GetCompositeScheduleResponse.ConnectorId == null) ||
(ConnectorId != null && GetCompositeScheduleResponse.ConnectorId != null && ConnectorId. Equals(GetCompositeScheduleResponse.ConnectorId))) &&
((!ScheduleStart.HasValue && !GetCompositeScheduleResponse.ScheduleStart.HasValue) ||
(ScheduleStart.HasValue && GetCompositeScheduleResponse.ScheduleStart.HasValue && ScheduleStart.Value.Equals(GetCompositeScheduleResponse.ScheduleStart.Value))) &&
((ChargingSchedule == null && GetCompositeScheduleResponse.ChargingSchedule == null) ||
(ChargingSchedule != null && GetCompositeScheduleResponse.ChargingSchedule != null && ChargingSchedule. Equals(GetCompositeScheduleResponse.ChargingSchedule)));
}
#endregion
#endregion
#region (override) GetHashCode()
/// <summary>
/// Return the HashCode of this object.
/// </summary>
/// <returns>The HashCode of this object.</returns>
public override Int32 GetHashCode()
{
unchecked
{
return Status.GetHashCode() * 11 ^
(ConnectorId != null
? ConnectorId.GetHashCode() * 7
: 0) ^
(ScheduleStart.HasValue
? ScheduleStart.GetHashCode() * 5
: 0) ^
(ChargingSchedule != null
? ChargingSchedule.GetHashCode()
: 0);
}
}
#endregion
#region (override) ToString()
/// <summary>
/// Return a text representation of this object.
/// </summary>
public override String ToString()
=> String.Concat(Status,
ConnectorId != null
? " / " + ConnectorId
: "",
ScheduleStart != null
? " / " + ScheduleStart.Value.ToIso8601()
: "",
ChargingSchedule != null
? " / has schedule"
: "");
#endregion
}
}
| 39.848052 | 187 | 0.485383 | [
"Apache-2.0"
] | phoompat/WWCP_OCPP | WWCP_OCPPv1.6/Messages/ChargePoint/GetCompositeScheduleResponse.cs | 30,685 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Token : MonoBehaviour {
public RPS_State type;
public TokenSpawner spawner;
public int position;
static float inactiveTime = 3f;
float current;
bool active = false;
// Use this for initialization
void Start ()
{
current = inactiveTime;
}
// Update is called once per frame
void Update ()
{
current -= Time.deltaTime;
if (current <= 0)
{
active = true;
}
GetComponent<BoxCollider2D> ().enabled = active;
if (active) {
GetComponent<SpriteRenderer> ().color = Color.white;
} else {
GetComponent<SpriteRenderer> ().color = RPSX.basicColorFaded;
}
}
public void collect ()
{
spawner.occupiedPositions.Remove (position);
spawner.queueToken (type);
Destroy (this.gameObject);
}
}
| 19.186047 | 64 | 0.69697 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | apetersell/RPSX | RPSXUnity/Assets/Scripts/NewStuff/Token.cs | 827 | C# |
using System;
namespace CSF.Screenplay.Selenium.Models
{
/// <summary>
/// Represents a single option item within an HTML <c><select></c> element.
/// </summary>
public class Option : IEquatable<Option>
{
/// <summary>
/// Gets the option text.
/// </summary>
/// <value>The text.</value>
public string Text { get; private set; }
/// <summary>
/// Gets the option value.
/// </summary>
/// <value>The value.</value>
public string Value { get; private set; }
/// <summary>
/// Serves as a hash function for a <see cref="Option"/> object.
/// </summary>
/// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a hash table.</returns>
public override int GetHashCode()
{
var textHash = (Text?? String.Empty).GetHashCode();
var valueHash = (Value?? String.Empty).GetHashCode();
return textHash ^ valueHash;
}
/// <summary>
/// Determines whether the specified <see cref="object"/> is equal to the current <see cref="Option"/>.
/// </summary>
/// <param name="obj">The <see cref="object"/> to compare with the current <see cref="Option"/>.</param>
/// <returns><c>true</c> if the specified <see cref="object"/> is equal to the current
/// <see cref="Option"/>; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
if(ReferenceEquals(this, obj))
return true;
var other = obj as Option;
if(ReferenceEquals(other, null))
return false;
return Equals(this, other);
}
/// <summary>
/// Determines whether the specified <see cref="Option"/> is equal to the current <see cref="Option"/>.
/// </summary>
/// <param name="obj">The <see cref="Option"/> to compare with the current <see cref="Option"/>.</param>
/// <returns><c>true</c> if the specified <see cref="Option"/> is equal to the current
/// <see cref="Option"/>; otherwise, <c>false</c>.</returns>
public bool Equals(Option obj)
{
if(ReferenceEquals(obj, null))
return false;
return this.Text == obj.Text && this.Value == obj.Value;
}
/// <summary>
/// Initializes a new instance of the <see cref="Option"/> class.
/// </summary>
/// <param name="text">The option text.</param>
/// <param name="value">The option value.</param>
public Option(string text, string value)
{
Text = text;
Value = value;
}
}
}
| 32.397436 | 145 | 0.603482 | [
"MIT"
] | csf-dev/CSF.Screenplay.Selenium | CSF.Screenplay.Selenium/Models/Option.cs | 2,529 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using api.Dtos;
using Octokit;
namespace api.Services {
public class IssueService : IIssueService {
public async Task<IEnumerable<IssueDto>> GetIssuesAsync () {
var client = new GitHubClient (new ProductHeaderValue ("OpenArabic"));
var issueFilter = new RepositoryIssueRequest {
Filter = IssueFilter.All,
State = ItemStateFilter.Open,
};
const string organization = "Edenmind";
const string repositoryName = "OpenArabic";
var issuesFromGithub = await client.Issue.GetAllForRepository (organization, repositoryName, issueFilter);
var extractedIssueValues = new List<IssueDto> ();
foreach (var issue in issuesFromGithub) {
var issueToAdd = new IssueDto () {
Title = issue.Title,
Id = issue.Id,
Body = issue.Body,
CreatedAt = issue.CreatedAt,
Url = issue.HtmlUrl,
Number = issue.Number,
UserLogin = issue.User.Login,
UserHtmlUrl = issue.User.HtmlUrl,
MilestoneDueOn = issue.Milestone.DueOn,
MilestoneHtmlUrl = issue.Milestone.HtmlUrl,
MilestoneTitle = issue.Milestone.Title,
};
extractedIssueValues.Add (issueToAdd);
}
return extractedIssueValues;
}
}
}
| 30.269231 | 118 | 0.556544 | [
"MIT"
] | edenmind/OpenArabic | api/Services/IssueService.cs | 1,574 | C# |
using System.Collections.Generic;
using NetTopologySuite.Algorithm;
using NetTopologySuite.Algorithm.Locate;
using NetTopologySuite.Geometries;
using NetTopologySuite.Geometries.Utilities;
namespace NetTopologySuite.Operation.Predicate
{
/// <summary>I
/// Implementation of the <tt>Intersects</tt> spatial predicate
/// optimized for the case where one <see cref="Geometry"/> is a rectangle.
/// </summary>
/// <remarks>
/// This class works for all input geometries, including <see cref="GeometryCollection"/>s.
/// <para/>
/// As a further optimization, this class can be used in batch style
/// to test many geometries against a single rectangle.
/// </remarks>
public class RectangleIntersects
{
/// <summary>
/// Crossover size at which brute-force intersection scanning
/// is slower than indexed intersection detection.
/// Must be determined empirically. Should err on the
/// safe side by making value smaller rather than larger.
/// </summary>
public const int MaximumScanSegmentCount = 200;
/// <summary>
/// Tests whether a rectangle intersects a given geometry.
/// </summary>
/// <param name="rectangle">A rectangular polygon</param>
/// <param name="b">A geometry of any kind</param>
/// <returns><c>true</c> if the geometries intersect.</returns>
public static bool Intersects(Polygon rectangle, Geometry b)
{
var rp = new RectangleIntersects(rectangle);
return rp.Intersects(b);
}
private readonly Polygon _rectangle;
private readonly Envelope _rectEnv;
/// <summary>
/// Create a new intersects computer for a rectangle.
/// </summary>
/// <param name="rectangle">A rectangular polygon.</param>
public RectangleIntersects(Polygon rectangle)
{
_rectangle = rectangle;
_rectEnv = rectangle.EnvelopeInternal;
}
/// <summary>
/// Tests whether the given Geometry intersects the query rectangle.
/// </summary>
/// <param name="geom">The Geometry to test (may be of any type)</param>
/// <returns><c>true</c> if an intersection must occur
/// or <c>false</c> if no conclusion about intersection can be made</returns>
public bool Intersects(Geometry geom)
{
if (!_rectEnv.Intersects(geom.EnvelopeInternal))
return false;
/**
* Test if rectangle envelope intersects any component envelope.
* This handles Point components as well
*/
var visitor = new EnvelopeIntersectsVisitor(_rectEnv);
visitor.ApplyTo(geom);
if (visitor.Intersects)
return true;
/**
* Test if any rectangle vertex is contained in the target geometry
*/
var ecpVisitor = new GeometryContainsPointVisitor(_rectangle);
ecpVisitor.ApplyTo(geom);
if (ecpVisitor.ContainsPoint)
return true;
/**
* Test if any target geometry line segment intersects the rectangle
*/
var riVisitor = new RectangleIntersectsSegmentVisitor(_rectangle);
riVisitor.ApplyTo(geom);
return riVisitor.Intersects;
}
}
/// <summary>
/// Tests whether it can be concluded that a rectangle intersects a geometry,
/// based on the relationship of the envelope(s) of the geometry.
/// </summary>
/// <author>Martin Davis</author>
internal class EnvelopeIntersectsVisitor : ShortCircuitedGeometryVisitor
{
private readonly Envelope _rectEnv;
/// <summary>
/// Creates an instance of this class using the provided <c>Envelope</c>
/// </summary>
/// <param name="rectEnv">The query envelope</param>
public EnvelopeIntersectsVisitor(Envelope rectEnv)
{
_rectEnv = rectEnv;
}
/// <summary>
/// Reports whether it can be concluded that an intersection occurs,
/// or whether further testing is required.
/// </summary>
/// <returns><c>true</c> if an intersection must occur <br/>
/// or <c>false</c> if no conclusion about intersection can be made</returns>
public bool Intersects { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="element"></param>
protected override void Visit(Geometry element)
{
var elementEnv = element.EnvelopeInternal;
// disjoint => no intersection
if (!_rectEnv.Intersects(elementEnv))
return;
// rectangle contains target env => must intersect
if (_rectEnv.Contains(elementEnv))
{
Intersects = true;
return;
}
/*
* Since the envelopes intersect and the test element is connected,
* if its envelope is completely bisected by an edge of the rectangle
* the element and the rectangle must touch. (This is basically an application of
* the Jordan Curve Theorem). The alternative situation is that the test
* envelope is "on a corner" of the rectangle envelope, i.e. is not
* completely bisected. In this case it is not possible to make a conclusion
*/
if (elementEnv.MinX >= _rectEnv.MinX && elementEnv.MaxX <= _rectEnv.MaxX)
{
Intersects = true;
return;
}
if (elementEnv.MinY >= _rectEnv.MinY && elementEnv.MaxY <= _rectEnv.MaxY)
{
Intersects = true;
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected override bool IsDone()
{
return Intersects;
}
}
/// <summary>
/// A visitor which tests whether it can be
/// concluded that a geometry contains a vertex of
/// a query geometry.
/// </summary>
/// <author>Martin Davis</author>
internal class GeometryContainsPointVisitor : ShortCircuitedGeometryVisitor
{
private readonly CoordinateSequence _rectSeq;
private readonly Envelope _rectEnv;
/// <summary>
///
/// </summary>
/// <param name="rectangle"></param>
public GeometryContainsPointVisitor(Polygon rectangle)
{
_rectSeq = rectangle.ExteriorRing.CoordinateSequence;
_rectEnv = rectangle.EnvelopeInternal;
}
/// <summary>
/// Gets a value indicating whether it can be concluded that a corner point of the rectangle is
/// contained in the geometry, or whether further testing is required.
/// </summary>
/// <returns><c>true</c> if a corner point is contained
/// or <c>false</c> if no conclusion about intersection can be made
/// </returns>
public bool ContainsPoint { get; private set; }
/// <summary>
///
/// </summary>
/// <param name="geom"></param>
protected override void Visit(Geometry geom)
{
if (!(geom is Polygon))
return;
var elementEnv = geom.EnvelopeInternal;
if (! _rectEnv.Intersects(elementEnv))
return;
// test each corner of rectangle for inclusion
var rectPt = _rectSeq.CreateCoordinate();
for (int i = 0; i < 4; i++)
{
_rectSeq.GetCoordinate(i, rectPt);
if (!elementEnv.Contains(rectPt))
continue;
// check rect point in poly (rect is known not to touch polygon at this point)
if (SimplePointInAreaLocator.ContainsPointInPolygon(rectPt, (Polygon) geom))
{
ContainsPoint = true;
return;
}
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
protected override bool IsDone()
{
return ContainsPoint;
}
}
/// <summary>
/// A visitor to test for intersection between the query rectangle and the line segments of the geometry.
/// </summary>
/// <author>Martin Davis</author>
internal class RectangleIntersectsSegmentVisitor : ShortCircuitedGeometryVisitor
{
private readonly Envelope _rectEnv;
private readonly RectangleLineIntersector _rectIntersector;
private readonly Coordinate _p0 = new Coordinate();
private readonly Coordinate _p1 = new Coordinate();
/// <summary>
/// Creates a visitor for checking rectangle intersection with segments
/// </summary>
/// <param name="rectangle">the query rectangle </param>
public RectangleIntersectsSegmentVisitor(Polygon rectangle)
{
_rectEnv = rectangle.EnvelopeInternal;
_rectIntersector = new RectangleLineIntersector(_rectEnv);
}
/// <summary>Reports whether any segment intersection exists.</summary>
/// <returns>true if a segment intersection exists or
/// false if no segment intersection exists</returns>
public bool Intersects { get; private set; }
protected override void Visit(Geometry geom)
{
/*
* It may be the case that the rectangle and the
* envelope of the geometry component are disjoint,
* so it is worth checking this simple condition.
*/
var elementEnv = geom.EnvelopeInternal;
if (!_rectEnv.Intersects(elementEnv))
return;
// check segment intersections
// get all lines from geometry component
// (there may be more than one if it's a multi-ring polygon)
var lines = LinearComponentExtracter.GetLines(geom);
CheckIntersectionWithLineStrings(lines);
}
private void CheckIntersectionWithLineStrings(IEnumerable<Geometry> lines)
{
foreach (LineString testLine in lines)
{
CheckIntersectionWithSegments(testLine);
if (Intersects)
return;
}
}
private void CheckIntersectionWithSegments(LineString testLine)
{
var seq1 = testLine.CoordinateSequence;
for (int j = 1; j < seq1.Count; j++)
{
_p0.X = seq1.GetX(j - 1);
_p0.Y = seq1.GetY(j - 1);
_p1.X = seq1.GetX(j);
_p1.Y = seq1.GetY(j);
if (!_rectIntersector.Intersects(_p0, _p1)) continue;
Intersects = true;
return;
}
}
protected override bool IsDone()
{
return Intersects;
}
}
}
| 35.785256 | 109 | 0.572682 | [
"EPL-1.0"
] | Amit909Singh/NetTopologySuite | src/NetTopologySuite/Operation/Predicate/RectangleIntersects.cs | 11,165 | C# |
using System;
using System.Windows.Media.Effects;
using System.Windows;
using System.Windows.Media;
namespace ZumtenSoft.WebsiteCrawler.Resources.Effects
{
public class GrayscaleEffect : ShaderEffect
{
private static PixelShader _pixelShader = new PixelShader() { UriSource = new Uri(@"pack://application:,,,/Resources/Effects/GrayscaleEffect.ps") };
public GrayscaleEffect()
{
PixelShader = _pixelShader;
UpdateShaderValue(InputProperty);
UpdateShaderValue(DesaturationFactorProperty);
}
public static readonly DependencyProperty InputProperty = ShaderEffect.RegisterPixelShaderSamplerProperty("Input", typeof(GrayscaleEffect), 0);
public Brush Input
{
get { return (Brush)GetValue(InputProperty); }
set { SetValue(InputProperty, value); }
}
public static readonly DependencyProperty DesaturationFactorProperty = DependencyProperty.Register("DesaturationFactor", typeof(double), typeof(GrayscaleEffect), new UIPropertyMetadata(0.0, PixelShaderConstantCallback(0), CoerceDesaturationFactor));
public double DesaturationFactor
{
get { return (double)GetValue(DesaturationFactorProperty); }
set { SetValue(DesaturationFactorProperty, value); }
}
private static object CoerceDesaturationFactor(DependencyObject d, object value)
{
GrayscaleEffect effect = (GrayscaleEffect)d;
double newFactor = (double)value;
if (newFactor < 0.0 || newFactor > 1.0)
{
return effect.DesaturationFactor;
}
return newFactor;
}
}
}
| 35.854167 | 257 | 0.664149 | [
"Apache-2.0"
] | zumten/WebsiteCrawler | src/ZumtenSoft.WebsiteCrawler/Resources/Effects/GrayscaleEffect.cs | 1,723 | C# |
using System.Threading.Tasks;
using DbTool.Core;
using Microsoft.Extensions.Configuration;
using Xunit;
namespace DbTool.Test
{
public class MySqlTest : BaseDbTest
{
public override string DbType => "MySql";
[Fact]
public override Task QueryTest()
{
return base.QueryTest();
}
[Fact]
public override void CreateTest()
{
base.CreateTest();
}
public MySqlTest(IConfiguration configuration, IDbHelperFactory dbHelperFactory, DbProviderFactory dbProviderFactory) : base(configuration, dbHelperFactory, dbProviderFactory)
{
}
[Theory]
[InlineData("mediumText", true, "string")]
[InlineData("nchar", true, "string")]
[InlineData("char", true, "string")]
[InlineData("text", true, "string")]
[InlineData("int", true, "int?")]
[InlineData("int", false, "int")]
public override void DbType2ClrTypeTest(string dbType, bool isNullable, string expectedType)
{
base.DbType2ClrTypeTest(dbType, isNullable, expectedType);
}
}
}
| 27.878049 | 183 | 0.611549 | [
"MIT"
] | WeihanLi/DbTool.Packages | test/DbTool.Test/MySqlTest.cs | 1,145 | C# |
namespace Mutators.Tests.FunctionalTests.SecondOuterContract
{
public class LineItem
{
public string LineItemIdentifier { get; set; }
public ItemNumberIdentification ItemNumberIdentification { get; set; }
}
} | 26.333333 | 78 | 0.721519 | [
"MIT"
] | RGleb/GrobExp.Mutators | Mutators.Tests/FunctionalTests/SecondOuterContract/LineItem.cs | 237 | C# |
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp.AutoMapper;
using Volo.Abp.Modularity;
using Volo.Abp.Application;
namespace Volo.Abp.WorkFlowManagement
{
[DependsOn(
typeof(WorkFlowManagementDomainModule),
typeof(WorkFlowManagementApplicationContractsModule),
typeof(AbpDddApplicationModule),
typeof(AbpAutoMapperModule)
)]
public class WorkFlowManagementApplicationModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
context.Services.AddAutoMapperObjectMapper<WorkFlowManagementApplicationModule>();
Configure<AbpAutoMapperOptions>(options =>
{
options.AddMaps<WorkFlowManagementApplicationModule>(validate: true);
});
}
}
}
| 32.115385 | 94 | 0.705389 | [
"Apache-2.0"
] | AbpApp/volo.abp.elsa | modules/workflow-mamagement/Volo.Abp.WorkFlowManagement.Application/Volo/Abp/WorkFlowManagement/WorkFlowManagementApplicationModule.cs | 837 | C# |
/*
* Farseer Physics Engine based on Box2D.XNA port:
* Copyright (c) 2010 Ian Qvist
*
* Box2D.XNA port of Box2D:
* Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler
*
* Original source Box2D:
* Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com
*
* 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;
using FarseerPhysics.Common;
using Microsoft.Xna.Framework;
namespace FarseerPhysics.Collision.Shapes
{
/// <summary>
/// This holds the mass data computed for a shape.
/// </summary>
public struct MassData : IEquatable<MassData>
{
/// <summary>
/// The area of the shape
/// </summary>
public float Area;
/// <summary>
/// The position of the shape's centroid relative to the shape's origin.
/// </summary>
public Vector2 Centroid;
/// <summary>
/// The rotational inertia of the shape about the local origin.
/// </summary>
public float Inertia;
/// <summary>
/// The mass of the shape, usually in kilograms.
/// </summary>
public float Mass;
#region IEquatable<MassData> Members
public bool Equals(MassData other)
{
return this == other;
}
#endregion
public static bool operator ==(MassData left, MassData right)
{
return (left.Area == right.Area && left.Mass == right.Mass && left.Centroid == right.Centroid &&
left.Inertia == right.Inertia);
}
public static bool operator !=(MassData left, MassData right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (obj.GetType() != typeof(MassData)) return false;
return Equals((MassData)obj);
}
public override int GetHashCode()
{
unchecked
{
int result = Area.GetHashCode();
result = (result * 397) ^ Centroid.GetHashCode();
result = (result * 397) ^ Inertia.GetHashCode();
result = (result * 397) ^ Mass.GetHashCode();
return result;
}
}
}
public enum ShapeType
{
Unknown = -1,
Circle = 0,
Edge = 1,
Polygon = 2,
Loop = 3,
TypeCount = 4,
}
/// <summary>
/// A shape is used for collision detection. You can create a shape however you like.
/// Shapes used for simulation in World are created automatically when a Fixture
/// is created. Shapes may encapsulate a one or more child shapes.
/// </summary>
public abstract class Shape
{
private static int _shapeIdCounter;
public MassData MassData;
public int ShapeId;
internal float _density;
internal float _radius;
protected Shape(float density)
{
_density = density;
ShapeType = ShapeType.Unknown;
ShapeId = _shapeIdCounter++;
}
/// <summary>
/// Get the type of this shape.
/// </summary>
/// <value>The type of the shape.</value>
public ShapeType ShapeType { get; internal set; }
/// <summary>
/// Get the number of child primitives.
/// </summary>
/// <value></value>
public abstract int ChildCount { get; }
/// <summary>
/// Gets or sets the density.
/// </summary>
/// <value>The density.</value>
public float Density
{
get { return _density; }
set
{
_density = value;
ComputeProperties();
}
}
/// <summary>
/// Radius of the Shape
/// </summary>
public float Radius
{
get { return _radius; }
set
{
_radius = value;
ComputeProperties();
}
}
/// <summary>
/// Clone the concrete shape
/// </summary>
/// <returns>A clone of the shape</returns>
public abstract Shape Clone();
/// <summary>
/// Test a point for containment in this shape. This only works for convex shapes.
/// </summary>
/// <param name="transform">The shape world transform.</param>
/// <param name="point">a point in world coordinates.</param>
/// <returns>True if the point is inside the shape</returns>
public abstract bool TestPoint(ref Transform transform, ref Vector2 point);
/// <summary>
/// Cast a ray against a child shape.
/// </summary>
/// <param name="output">The ray-cast results.</param>
/// <param name="input">The ray-cast input parameters.</param>
/// <param name="transform">The transform to be applied to the shape.</param>
/// <param name="childIndex">The child shape index.</param>
/// <returns>True if the ray-cast hits the shape</returns>
public abstract bool RayCast(out RayCastOutput output, ref RayCastInput input, ref Transform transform,
int childIndex);
/// <summary>
/// Given a transform, compute the associated axis aligned bounding box for a child shape.
/// </summary>
/// <param name="aabb">The aabb results.</param>
/// <param name="transform">The world transform of the shape.</param>
/// <param name="childIndex">The child shape index.</param>
public abstract void ComputeAABB(out AABB aabb, ref Transform transform, int childIndex);
/// <summary>
/// Compute the mass properties of this shape using its dimensions and density.
/// The inertia tensor is computed about the local origin, not the centroid.
/// </summary>
public abstract void ComputeProperties();
public bool CompareTo(Shape shape)
{
if (shape is PolygonShape && this is PolygonShape)
return ((PolygonShape)this).CompareTo((PolygonShape)shape);
if (shape is CircleShape && this is CircleShape)
return ((CircleShape)this).CompareTo((CircleShape)shape);
if (shape is EdgeShape && this is EdgeShape)
return ((EdgeShape)this).CompareTo((EdgeShape)shape);
return false;
}
public abstract float ComputeSubmergedArea(Vector2 normal, float offset, Transform xf, out Vector2 sc);
}
} | 33.513514 | 111 | 0.581183 | [
"MIT"
] | CollectifBlueprint/GoalRush | Project/06 - External/Farseer Physics/Collision/Shapes/Shape.cs | 7,442 | C# |
#region License
/*
Copyright © 2014-2019 European Support Limited
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.
*/
#endregion
using Amdocs.Ginger.Common;
using Amdocs.Ginger.Repository;
using GingerCore.Actions.WebServices;
using GingerCore.Helpers;
using GingerCore.Properties;
using GingerCoreNET.SolutionRepositoryLib.RepositoryObjectsLib.PlatformsLib;
using System;
using System.Collections.Generic;
using Amdocs.Ginger.Common.InterfacesLib;
using Amdocs.Ginger.Common.Enums;
namespace GingerCore.Actions
{
public class ActSoapUI : Act
{
public override string ActionDescription { get { return "SoapUI Wrapper Action"; } }
public override string ActionUserDescription { get { return "Run SoapUI commands on Dos/Unix system"; } }
public override void ActionUserRecommendedUseCase(ITextBoxFormatter TBH)
{
TBH.AddText("Use this action in case you need to run SoapUI Project XML using the SoapUI test runner." + Environment.NewLine + Environment.NewLine + "This action contains list of options which will allow you to run simple or complicated test using the generated soapUI project XML." + Environment.NewLine + Environment.NewLine + "Prerequisite:" + Environment.NewLine + "1.) you should have SoapUI 5.0.0 or above installation folder on your Machine." + Environment.NewLine + "2.) SoapUI ProjectXML." + Environment.NewLine + "3.) Values/Properties in case you need to add some on the top of the existing data under the project XML." + Environment.NewLine + "4.) String for validation if needs to verify the output." + Environment.NewLine + Environment.NewLine + "Validation: The action will pass if :" + Environment.NewLine + "1.)ignore validation checkbox is unchecked and No step came back with Failed/unknown status." + Environment.NewLine + "2.)The Ignore Validation checkbox is checked and The entered Validation string for output has been found in the response" + Environment.NewLine + Environment.NewLine + "Validation: The action will be failed if :" + Environment.NewLine + "1.)Ignore Validation is unchecked and at lease one step came back with Failed status." + Environment.NewLine + "2.)Ignore Validation checkbox is checked and The entered Validation string has not been found in the response for at lease one step");
}
public override string ActionEditPage { get { return "WebServices.ActSoapUIEditPage"; } }
public override bool ObjectLocatorConfigsNeeded { get { return false; } }
public override bool ValueConfigsNeeded { get { return false; } }
public override eImageType Image { get { return eImageType.Exchange; } }
// return the list of platforms this action is supported on
public override List<ePlatformType> Platforms
{
get
{
if (mPlatforms.Count == 0)
{
mPlatforms.Add(ePlatformType.WebServices);
}
return mPlatforms;
}
}
public new static partial class Fields
{
public static string XMLFile = "XMLFile";
public static string ImportFile = "ImportFile";
public static string IgnoreValidation = "IgnoreValidation";
public static string TestCase = "TestCase";
public static string TestSuite = "TestSuite";
public static string TestCasePropertiesRequiered = "TestCasePropertiesRequiered";
public static string TestCasePropertiesRequieredControlEnabled = "TestCasePropertiesRequieredControlEnabled";
public static string PropertiesOrPlaceHolders = "PropertiesOrPlaceHolders";
public static string Domain = "Domain";
public static string EndPoint = "EndPoint";
public static string HostPort = "HostPort";
public static string Username = "Username";
public static string Password = "Password";
public static string PasswordWSS = "PasswordWSS";
public static string PasswordWSSType = "PasswordWSSType";
public static string UIrelated = "UIrelated";
public static string isActionExecuted = "isActionExecuted";
public static string AddXMLResponse = "AddXMLResponse";
}
public bool PropertiesRequieredControlEnabled_Value
{
get
{
bool returnValue = true;
if (Boolean.TryParse((GetInputParamValue(ActSoapUI.Fields.TestCasePropertiesRequieredControlEnabled)), out returnValue))
{
return returnValue;
}
else
return false;
}
}
public bool AddXMLResponse_Value
{
get
{
bool returnValue = true;
if (Boolean.TryParse((GetInputParamValue(ActSoapUI.Fields.AddXMLResponse)), out returnValue))
{
return returnValue;
}
else
return false;
}
}
[IsSerializedForLocalRepository]
public ObservableList<ActSoapUiInputValue> AllProperties = new ObservableList<ActSoapUiInputValue>();
[IsSerializedForLocalRepository]
public ObservableList<ActSoapUiInputValue> TempProperties = new ObservableList<ActSoapUiInputValue>();
[IsSerializedForLocalRepository]
public ObservableList<ActInputValue> SystemProperties = new ObservableList<ActInputValue>();
[IsSerializedForLocalRepository]
public ObservableList<ActInputValue> GlobalProperties = new ObservableList<ActInputValue>();
[IsSerializedForLocalRepository]
public ObservableList<ActInputValue> ProjectProperties = new ObservableList<ActInputValue>();
[IsSerializedForLocalRepository]
public ObservableList<ActInputValue> TestCaseProperties = new ObservableList<ActInputValue>();
[IsSerializedForLocalRepository]
public ObservableList<ActInputValue> ProjectInnerProperties = new ObservableList<ActInputValue>();
[IsSerializedForLocalRepository]
public ObservableList<ActInputValue> TestSuiteProperties = new ObservableList<ActInputValue>();
[IsSerializedForLocalRepository]
public ObservableList<ActInputValue> TestStepProperties = new ObservableList<ActInputValue>();
[IsSerializedForLocalRepository]
public ObservableList<ActInputValue> TestSuitePlaceHolder = new ObservableList<ActInputValue>();
public override List<ObservableList<ActInputValue>> GetInputValueListForVEProcessing()
{
List<ObservableList<ActInputValue>> list = new List<ObservableList<ActInputValue>>();
list.Add(SystemProperties);
list.Add(GlobalProperties);
list.Add(ProjectProperties);
list.Add(TestCaseProperties);
list.Add(TestSuiteProperties);
list.Add(TestStepProperties);
list.Add(TestSuitePlaceHolder);
list.Add(ProjectInnerProperties);
// convert ObservableList<ActSoapUiInputValue> to ObservableList<ActInputValue>
list.Add(ConvertActSoapUiToActInputValue(AllProperties));
return list;
}
private ObservableList<ActInputValue> ConvertActSoapUiToActInputValue(ObservableList<ActSoapUiInputValue> list)
{
ObservableList<ActInputValue> obList = new ObservableList<ActInputValue>();
foreach (var item in list)
{
obList.Add(item);
}
return obList;
}
public enum ePasswordWSSType
{
[EnumValueDescription("Text")]
Text,
[EnumValueDescription("Digest")]
Digest
}
public override String ActionType
{
get
{
return "SoapUI Test Runner";
}
}
private string mLastExecutionFolderPath = string.Empty;
public string LastExecutionFolderPath
{
get
{
return mLastExecutionFolderPath;
}
set
{
mLastExecutionFolderPath = value;
OnPropertyChanged(Fields.isActionExecuted);
}
}
public bool isActionExecuted
{
get
{
return (System.IO.Directory.Exists(LastExecutionFolderPath));
}
}
}
} | 44.985075 | 1,440 | 0.662464 | [
"Apache-2.0"
] | fainagof/Ginger | Ginger/GingerCore/Actions/WebServices/ActSoapUI.cs | 9,043 | C# |
// License
// --------------------------------------------------------------------------------------------------------------------
// (C) Copyright 2021 Cato Léan Trütschel and contributors
// (github.com/CatoLeanTruetschel/AsyncQueryableAdapterPrototype)
//
// 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
//
// 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.
// --------------------------------------------------------------------------------------------------------------------
#pragma warning disable VSTHRD200
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using AsyncQueryableAdapter;
using AsyncQueryableAdapterPrototype.Tests.Utils;
using Microsoft.Extensions.Options;
using Xunit;
using AsyncQueryable = System.Linq.AsyncQueryable;
namespace AsyncQueryableAdapterPrototype.Tests
{
public abstract partial class QueryAdapterSpecificationV2
{
#region ElementAtOrDefaultAsyncWithDoubleSourceWithIndex tests
[Fact]
public async Task ElementAtOrDefaultAsyncWithDoubleSourceWithIndexIsEquivalentToElementAtOrDefaultTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'source' parameter
var source = GetQueryable<double>();
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<double>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Arrange 'expectedResult' parameter
var expectedResult = Enumerable.ElementAtOrDefault<double>(source, index);
// Act
var result = await AsyncQueryable.ElementAtOrDefaultAsync<double>(asyncSource, index, cancellationToken).ConfigureAwait(false);
// Assert
AssertHelper.Equal(expectedResult, result);
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithDoubleSourceWithIndexCanceledCancellationTokenThrowsOperationCanceledExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<double>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
using var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
// Act
// -
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<double>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithDoubleSourceWithIndexNullSourceThrowsArgumentNullExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
IAsyncQueryable<double> asyncSource = null!;
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Act
// -
// Assert
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<double>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
#endregion
#region ElementAtOrDefaultAsyncWithNullableDecimalSourceWithIndex tests
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableDecimalSourceWithIndexIsEquivalentToElementAtOrDefaultTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'source' parameter
var source = GetQueryable<decimal?>();
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<decimal?>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Arrange 'expectedResult' parameter
var expectedResult = Enumerable.ElementAtOrDefault<decimal?>(source, index);
// Act
var result = await AsyncQueryable.ElementAtOrDefaultAsync<decimal?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
// Assert
AssertHelper.Equal(expectedResult, result);
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableDecimalSourceWithIndexCanceledCancellationTokenThrowsOperationCanceledExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<decimal?>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
using var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
// Act
// -
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<decimal?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableDecimalSourceWithIndexNullSourceThrowsArgumentNullExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
IAsyncQueryable<decimal?> asyncSource = null!;
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Act
// -
// Assert
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<decimal?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
#endregion
#region ElementAtOrDefaultAsyncWithNullableSingleSourceWithIndex tests
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableSingleSourceWithIndexIsEquivalentToElementAtOrDefaultTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'source' parameter
var source = GetQueryable<float?>();
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<float?>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Arrange 'expectedResult' parameter
var expectedResult = Enumerable.ElementAtOrDefault<float?>(source, index);
// Act
var result = await AsyncQueryable.ElementAtOrDefaultAsync<float?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
// Assert
AssertHelper.Equal(expectedResult, result);
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableSingleSourceWithIndexCanceledCancellationTokenThrowsOperationCanceledExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<float?>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
using var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
// Act
// -
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<float?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableSingleSourceWithIndexNullSourceThrowsArgumentNullExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
IAsyncQueryable<float?> asyncSource = null!;
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Act
// -
// Assert
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<float?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
#endregion
#region ElementAtOrDefaultAsyncWithNullableDoubleSourceWithIndex tests
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableDoubleSourceWithIndexIsEquivalentToElementAtOrDefaultTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'source' parameter
var source = GetQueryable<double?>();
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<double?>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Arrange 'expectedResult' parameter
var expectedResult = Enumerable.ElementAtOrDefault<double?>(source, index);
// Act
var result = await AsyncQueryable.ElementAtOrDefaultAsync<double?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
// Assert
AssertHelper.Equal(expectedResult, result);
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableDoubleSourceWithIndexCanceledCancellationTokenThrowsOperationCanceledExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<double?>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
using var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
// Act
// -
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<double?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableDoubleSourceWithIndexNullSourceThrowsArgumentNullExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
IAsyncQueryable<double?> asyncSource = null!;
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Act
// -
// Assert
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<double?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
#endregion
#region ElementAtOrDefaultAsyncWithDecimalSourceWithIndex tests
[Fact]
public async Task ElementAtOrDefaultAsyncWithDecimalSourceWithIndexIsEquivalentToElementAtOrDefaultTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'source' parameter
var source = GetQueryable<decimal>();
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<decimal>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Arrange 'expectedResult' parameter
var expectedResult = Enumerable.ElementAtOrDefault<decimal>(source, index);
// Act
var result = await AsyncQueryable.ElementAtOrDefaultAsync<decimal>(asyncSource, index, cancellationToken).ConfigureAwait(false);
// Assert
AssertHelper.Equal(expectedResult, result);
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithDecimalSourceWithIndexCanceledCancellationTokenThrowsOperationCanceledExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<decimal>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
using var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
// Act
// -
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<decimal>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithDecimalSourceWithIndexNullSourceThrowsArgumentNullExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
IAsyncQueryable<decimal> asyncSource = null!;
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Act
// -
// Assert
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<decimal>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
#endregion
#region ElementAtOrDefaultAsyncWithSingleSourceWithIndex tests
[Fact]
public async Task ElementAtOrDefaultAsyncWithSingleSourceWithIndexIsEquivalentToElementAtOrDefaultTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'source' parameter
var source = GetQueryable<float>();
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<float>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Arrange 'expectedResult' parameter
var expectedResult = Enumerable.ElementAtOrDefault<float>(source, index);
// Act
var result = await AsyncQueryable.ElementAtOrDefaultAsync<float>(asyncSource, index, cancellationToken).ConfigureAwait(false);
// Assert
AssertHelper.Equal(expectedResult, result);
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithSingleSourceWithIndexCanceledCancellationTokenThrowsOperationCanceledExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<float>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
using var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
// Act
// -
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<float>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithSingleSourceWithIndexNullSourceThrowsArgumentNullExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
IAsyncQueryable<float> asyncSource = null!;
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Act
// -
// Assert
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<float>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
#endregion
#region ElementAtOrDefaultAsyncWithNullableInt64SourceWithIndex tests
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableInt64SourceWithIndexIsEquivalentToElementAtOrDefaultTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'source' parameter
var source = GetQueryable<long?>();
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<long?>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Arrange 'expectedResult' parameter
var expectedResult = Enumerable.ElementAtOrDefault<long?>(source, index);
// Act
var result = await AsyncQueryable.ElementAtOrDefaultAsync<long?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
// Assert
Assert.Equal(expectedResult, result);
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableInt64SourceWithIndexCanceledCancellationTokenThrowsOperationCanceledExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<long?>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
using var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
// Act
// -
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<long?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableInt64SourceWithIndexNullSourceThrowsArgumentNullExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
IAsyncQueryable<long?> asyncSource = null!;
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Act
// -
// Assert
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<long?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
#endregion
#region ElementAtOrDefaultAsyncWithNullableInt32SourceWithIndex tests
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableInt32SourceWithIndexIsEquivalentToElementAtOrDefaultTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'source' parameter
var source = GetQueryable<int?>();
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<int?>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Arrange 'expectedResult' parameter
var expectedResult = Enumerable.ElementAtOrDefault<int?>(source, index);
// Act
var result = await AsyncQueryable.ElementAtOrDefaultAsync<int?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
// Assert
Assert.Equal(expectedResult, result);
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableInt32SourceWithIndexCanceledCancellationTokenThrowsOperationCanceledExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<int?>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
using var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
// Act
// -
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<int?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithNullableInt32SourceWithIndexNullSourceThrowsArgumentNullExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
IAsyncQueryable<int?> asyncSource = null!;
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Act
// -
// Assert
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<int?>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
#endregion
#region ElementAtOrDefaultAsyncWithInt64SourceWithIndex tests
[Fact]
public async Task ElementAtOrDefaultAsyncWithInt64SourceWithIndexIsEquivalentToElementAtOrDefaultTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'source' parameter
var source = GetQueryable<long>();
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<long>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Arrange 'expectedResult' parameter
var expectedResult = Enumerable.ElementAtOrDefault<long>(source, index);
// Act
var result = await AsyncQueryable.ElementAtOrDefaultAsync<long>(asyncSource, index, cancellationToken).ConfigureAwait(false);
// Assert
Assert.Equal(expectedResult, result);
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithInt64SourceWithIndexCanceledCancellationTokenThrowsOperationCanceledExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<long>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
using var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
// Act
// -
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<long>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithInt64SourceWithIndexNullSourceThrowsArgumentNullExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
IAsyncQueryable<long> asyncSource = null!;
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Act
// -
// Assert
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<long>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
#endregion
#region ElementAtOrDefaultAsyncWithInt32SourceWithIndex tests
[Fact]
public async Task ElementAtOrDefaultAsyncWithInt32SourceWithIndexIsEquivalentToElementAtOrDefaultTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'source' parameter
var source = GetQueryable<int>();
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<int>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Arrange 'expectedResult' parameter
var expectedResult = Enumerable.ElementAtOrDefault<int>(source, index);
// Act
var result = await AsyncQueryable.ElementAtOrDefaultAsync<int>(asyncSource, index, cancellationToken).ConfigureAwait(false);
// Assert
Assert.Equal(expectedResult, result);
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithInt32SourceWithIndexCanceledCancellationTokenThrowsOperationCanceledExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
var asyncSource = queryAdapter.GetAsyncQueryable<int>();
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
using var cancellationTokenSource = new CancellationTokenSource();
var cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel();
// Act
// -
// Assert
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<int>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
[Fact]
public async Task ElementAtOrDefaultAsyncWithInt32SourceWithIndexNullSourceThrowsArgumentNullExceptionTest()
{
// Arrange
// Arrange 'queryAdapter' parameter
var queryAdapter = await GetQueryAdapterAsync(DisallowAll);
// Arrange 'asyncSource' parameter
IAsyncQueryable<int> asyncSource = null!;
// Arrange 'index' parameter
var index = 5;
// Arrange 'cancellationToken' parameter
var cancellationToken = CancellationToken.None;
// Act
// -
// Assert
await Assert.ThrowsAsync<ArgumentNullException>(async () =>
{
await AsyncQueryable.ElementAtOrDefaultAsync<int>(asyncSource, index, cancellationToken).ConfigureAwait(false);
});
}
#endregion
}
}
| 35.796137 | 147 | 0.600384 | [
"Apache-2.0"
] | CatoLeanTruetschel/AsyncQueryableAdapterPrototype | test/AsyncQueryableAdapterPrototype.Specification/Generated/QueryAdapterSpecification.ElementAtOrDefault.cs | 33,364 | C# |
using OctoFinancial.Data.Interfaces;
namespace OctoFinancial.Persistence.Interfaces
{
public interface ITransactionProvider
{
ITransaction[] LoadTransactions();
}
} | 19.555556 | 46 | 0.784091 | [
"MIT"
] | PanCave/OctoFinancial | projects/OctoFinancial.Persistence.Interfaces/ITransactionProvider.cs | 178 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using System.Collections.Generic;
namespace DataStructures
{
[TestClass]
public class GenericLinkedList
{
[TestMethod]
public void Add()
{
string expected = "foo";
LinkedList<string> linkedList = new LinkedList<string>();
linkedList.AddFirst(expected);
string actual = linkedList.First();
Assert.AreEqual(expected, actual);
}
}
}
| 24.333333 | 69 | 0.618395 | [
"MIT"
] | mbreault/csharp | dotnetcore/data_structures/DataStructures/Generic/GenericLinkedList.cs | 513 | C# |
//---------------------------------------------------------------------
// <copyright file="ObservableBackedBindingList`.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
namespace System.Windows.Forms.Data
{
/// <summary>
/// Extends <see cref="SortableBindingList{T}"/> to create a sortable binding list that stays in
/// sync with an underlying <see cref="ObservableCollection{T}"/>. That is, when items are added
/// or removed from the binding list, they are added or removed from the ObservableCollecion, and
/// vice-versa.
/// </summary>
/// <typeparam name="T">The list element type.</typeparam>
internal class ObservableBackedConvertableBindingList<T, U> : SortableBindingList<T>
{
private bool _addingNewInstance;
private T? _addNewInstance;
private T? _cancelNewInstance;
private readonly ObservableCollection<U> _observableCollection;
private bool _inCollectionChanged;
private bool _changingObservableCollection;
private TypeConverter _typeConverter;
/// <summary>
/// Initializes a new instance of a binding list backed by the given <see cref="ObservableCollection{T}"/>
/// </summary>
/// <param name="observableCollection">The observable collection.</param>
public ObservableBackedConvertableBindingList(ObservableCollection<U> observableCollection, TypeConverter elementTypeConverter)
: base(observableCollection.Select(item => (T)elementTypeConverter.ConvertFrom(item)).ToList())
{
_observableCollection = observableCollection;
_observableCollection.CollectionChanged += ObservableCollectionChanged;
_typeConverter = elementTypeConverter;
}
/// <summary>
/// Creates a new item to be added to the binding list.
/// </summary>
/// <returns>The new item.</returns>
protected override object AddNewCore()
{
_addingNewInstance = true;
_addNewInstance = (T)base.AddNewCore();
return _addNewInstance;
}
/// <summary>
/// Cancels adding of a new item that was started with AddNew.
/// </summary>
/// <param name="itemIndex">Index of the item.</param>
public override void CancelNew(int itemIndex)
{
if (itemIndex >= 0 && itemIndex < Count && Equals(base[itemIndex], _addNewInstance))
{
_cancelNewInstance = _addNewInstance;
_addNewInstance = default;
_addingNewInstance = false;
}
base.CancelNew(itemIndex);
}
/// <summary>
/// Removes all items from the binding list and underlying ObservableCollection.
/// </summary>
protected override void ClearItems()
{
foreach (var entity in Items)
{
RemoveFromObservableCollection(entity);
}
base.ClearItems();
}
/// <summary>
/// Ends the process of adding a new item that was started with AddNew.
/// </summary>
/// <param name="itemIndex">Index of the item.</param>
public override void EndNew(int itemIndex)
{
if (itemIndex >= 0 && itemIndex < Count && Equals(base[itemIndex], _addNewInstance))
{
AddToObservableCollection(_addNewInstance);
_addNewInstance = default;
_addingNewInstance = false;
}
base.EndNew(itemIndex);
}
/// <summary>
/// Inserts the item into the binding list at the given index.
/// </summary>
/// <param name="index">The index.</param>
/// <param name="item">The item.</param>
protected override void InsertItem(int index, T item)
{
base.InsertItem(index, item);
if (!_addingNewInstance && index >= 0 && index <= Count)
{
AddToObservableCollection(item);
}
}
/// <summary>
/// Removes the item at the specified index.
/// </summary>
/// <param name="index">The index.</param>
protected override void RemoveItem(int index)
{
if (index >= 0 && index < Count && Equals(base[index], _cancelNewInstance))
{
_cancelNewInstance = default;
}
else
{
RemoveFromObservableCollection(base[index]);
}
base.RemoveItem(index);
}
/// <summary>
/// Sets the item into the list at the given position.
/// </summary>
/// <param name="index">The index to insert at.</param>
/// <param name="item">The item.</param>
protected override void SetItem(int index, T item)
{
var entity = base[index];
base.SetItem(index, item);
if (index >= 0 && index < Count)
{
// Check to see if the user is trying to set an item that is currently being added via AddNew
// If so then the list should not continue the AddNew; but instead add the item
// that is being passed in.
if (Equals(entity, _addNewInstance))
{
_addNewInstance = default;
_addingNewInstance = false;
}
else
{
RemoveFromObservableCollection(entity);
}
AddToObservableCollection(item);
}
}
/// <summary>
/// Event handler to update the binding list when the underlying observable collection changes.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">Data indicating how the collection has changed.</param>
private void ObservableCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// Don't try to change the binding list if the original change came from the binding list
// and the ObervableCollection is just being changed to match it.
if (!_changingObservableCollection)
{
try
{
// We are about to change the underlying binding list. We want to prevent those
// changes trying to go back into the ObservableCollection, so we set a flag
// to prevent that.
_inCollectionChanged = true;
if (e.Action == NotifyCollectionChangedAction.Reset)
{
Clear();
}
if (e.Action == NotifyCollectionChangedAction.Remove ||
e.Action == NotifyCollectionChangedAction.Replace)
{
foreach (T entity in e.OldItems)
{
Remove(entity);
}
}
if (e.Action == NotifyCollectionChangedAction.Add ||
e.Action == NotifyCollectionChangedAction.Replace)
{
foreach (T entity in e.NewItems)
{
Add(entity);
}
}
}
finally
{
_inCollectionChanged = false;
}
}
}
/// <summary>
/// Adds the item to the underlying observable collection.
/// </summary>
/// <param name="item">The item.</param>
private void AddToObservableCollection(T? item)
{
// Don't try to change the ObervableCollection if the original change
// came from the ObservableCollection
if (!_inCollectionChanged)
{
try
{
// We are about to change the ObservableCollection based on the binding list.
// We don't want to try to put that change into the ObservableCollection again,
// so we set a flag to prevent this.
_changingObservableCollection = true;
_observableCollection.Add((U)_typeConverter.ConvertTo(item, typeof(U))!);
}
finally
{
_changingObservableCollection = false;
}
}
}
/// <summary>
/// Removes the item from the underlying from observable collection.
/// </summary>
/// <param name="item">The item.</param>
private void RemoveFromObservableCollection(T item)
{
// Don't try to change the ObervableCollection if the original change
// came from the ObservableCollection
if (!_inCollectionChanged)
{
try
{
// We are about to change the ObservableCollection based on the binding list.
// We don't want to try to put that change into the ObservableCollection again,
// so we set a flag to prevent this.
_changingObservableCollection = true;
_observableCollection.Remove((U)_typeConverter.ConvertTo(item, typeof(U))!);
}
finally
{
_changingObservableCollection = false;
}
}
}
}
}
| 38.81323 | 135 | 0.530426 | [
"MIT"
] | KlausLoeffelmann/BlackBoard | src/CS/Blackboard/WinFormsSupport/BindingListExtension/ObservableBackedConvertableBindingList.cs | 9,977 | C# |
using System.Collections.Generic;
using UnityEngine;
public class Selection : MonoBehaviour {
public HexMap map;
HashSet<Hex> selected;
public void Add(Hex hex) {
selected.Add(hex);
}
public HashSet<Hex> Selected {
get { return selected; }
}
public enum State {
RISING_ANIMATION,
NOT_DRAGGING,
DRAGGING,
SINKING_ANIMATION,
FINISHED
}
State currentState = State.RISING_ANIMATION;
float dragStartAngle;
float dragStartRotation;
float rotationVelocity;
public State CurrentState {
get { return currentState; }
}
void Awake() {
selected = new HashSet<Hex>();
}
float AngleDiff(float start, float end) {
float normalizedStart = start;
float normalizedEnd = end;
// Rotate all angles into 0 ~ 180 segment to simplify diff calc
while (Mathf.Abs(normalizedEnd - normalizedStart) > 180) {
normalizedStart = (normalizedStart + 90) % 360f;
normalizedEnd = (normalizedEnd + 90) % 360f;
}
return normalizedEnd - normalizedStart;
}
float SnapRotation(float angle) {
return Mathf.Round((angle % 360f) / 60f) * 60f;
}
Vector3 MouseWorldPosition => Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 SelectionCenter => transform.TransformPoint(Vector3.zero);
Vector3 MouseOffsetFromSelectionCenter => MouseWorldPosition - SelectionCenter;
bool ClickedInSelectedRing {
get {
Vector3 offsetWithoutTransform = transform.InverseTransformVector(MouseOffsetFromSelectionCenter);
Vector3 clickPositionBeforeTransform = transform.parent.position + offsetWithoutTransform;
Hex clickedHex = map.HexAtPosition(clickPositionBeforeTransform);
return selected.Contains(clickedHex);
}
}
float MouseAngle {
get {
float result = Vector2.Angle(Vector2.up, MouseOffsetFromSelectionCenter);
if (MouseOffsetFromSelectionCenter.x > 0) {
result = 360f - result;
}
return result;
}
}
public float CurrentRotation {
get { return transform.eulerAngles.z; }
private set {
float newValue = value % 360f;
if (newValue < 0) {
newValue += 360f;
}
transform.eulerAngles = new Vector3(0, 0, newValue);
}
}
float TargetRotation {
get {
float dragRotation = AngleDiff(dragStartAngle, MouseAngle);
float snappedDragRotation = SnapRotation(dragRotation);
return dragStartRotation + snappedDragRotation;
}
}
float DiffToTargetRotation => AngleDiff(CurrentRotation, TargetRotation);
void UpdateRotationVelocity() {
float force = DiffToTargetRotation;
float damping = -rotationVelocity * 10f;
rotationVelocity += Time.deltaTime * (force + damping);
}
void HandleSnap() {
if (Mathf.Abs(DiffToTargetRotation) < 1 && Mathf.Abs(rotationVelocity) < 0.1f) {
CurrentRotation = TargetRotation;
rotationVelocity = 0;
if (!Input.GetMouseButton(0)) {
currentState = State.NOT_DRAGGING;
}
}
}
const float FLOAT_HEIGHT = 0.3f;
const float RISE_SPEED = 2f;
void AnimateRise() {
Vector3 newPosition = transform.localPosition + Time.deltaTime * RISE_SPEED * Vector3.up;
if (newPosition.y >= FLOAT_HEIGHT) {
newPosition.y = FLOAT_HEIGHT;
currentState = State.NOT_DRAGGING;
}
transform.localPosition = newPosition;
}
void AnimateSink() {
Vector3 newPosition = transform.localPosition + Time.deltaTime * RISE_SPEED * Vector3.down;
if (newPosition.y <= 0) {
newPosition.y = 0;
currentState = State.FINISHED;
}
transform.localPosition = newPosition;
}
void Update() {
switch (currentState) {
case State.RISING_ANIMATION:
{
AnimateRise();
break;
}
case State.NOT_DRAGGING:
{
if (Input.GetMouseButtonDown(0) && ClickedInSelectedRing) {
dragStartAngle = MouseAngle;
dragStartRotation = SnapRotation(CurrentRotation);
currentState = State.DRAGGING;
} else if (Input.GetMouseButtonUp(0)) {
currentState = State.SINKING_ANIMATION;
}
break;
}
case State.DRAGGING:
{
UpdateRotationVelocity();
CurrentRotation += rotationVelocity;
HandleSnap();
break;
}
case State.SINKING_ANIMATION:
{
AnimateSink();
break;
}
}
}
}
| 26.434524 | 104 | 0.655033 | [
"MIT"
] | kfischer-okarin/HexagonRotate-Unity | Assets/Selection.cs | 4,443 | C# |
//using System;
//using System.Diagnostics;
//using System.IO;
//using System.Net.Http;
//using System.Text;
//using System.Threading;
//using FluentAssertions;
//using FunctionalTests.Base;
//using Microsoft.AspNetCore.Builder;
//using Microsoft.AspNetCore.Hosting;
//using Microsoft.AspNetCore.TestHost;
//using Microsoft.Extensions.DependencyInjection;
//using Microsoft.Extensions.Diagnostics.HealthChecks;
//using Xunit;
//namespace FunctionalTests.HealthChecks.Publisher.Prometheus
//{
// [Collection("execution")]
// public class prometheus_publisher_should : IDisposable
// {
// private const string PrometheusEndpoint = "http://localhost";
// private const string JobName = "myjob";
// private readonly TestServer _fakeEndpoint;
// private readonly HttpClient _fakePrometheusGatewayClient;
// private readonly AutoResetEvent _finishedTrigger;
// private string _publishedResult;
// private static readonly TimeSpan TimeoutForPublishingResults = TimeSpan.FromSeconds(15);
// public prometheus_publisher_should()
// {
// _finishedTrigger = new AutoResetEvent(false);
// _publishedResult = string.Empty;
// _fakeEndpoint = new TestServer(new WebHostBuilder()
// .Configure(app =>
// {
// app.Run(async context =>
// {
// using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8))
// {
// _publishedResult = await reader.ReadToEndAsync();
// Debug.WriteLine(_publishedResult);
// _finishedTrigger.Set();
// }
// });
// }));
// _fakePrometheusGatewayClient = _fakeEndpoint.CreateClient();
// }
// public void Dispose()
// {
// _finishedTrigger?.Dispose();
// _fakePrometheusGatewayClient?.Dispose();
// _fakeEndpoint?.Dispose();
// }
// [SkipOnAppVeyor]
// public void publish_healthy_result_when_health_checks_are()
// {
// var sut = new TestServer(new WebHostBuilder()
// .UseStartup<DefaultStartup>()
// .ConfigureServices(services =>
// {
// services.AddHealthChecks()
// .AddCheck("fake", check => HealthCheckResult.Healthy())
// .AddPrometheusGatewayPublisher(_fakePrometheusGatewayClient, PrometheusEndpoint, JobName);
// }));
// _finishedTrigger.WaitOne(TimeoutForPublishingResults);
// _publishedResult.Should().ContainCheckAndResult("fake", HealthStatus.Healthy);
// }
// [SkipOnAppVeyor]
// public void publish_unhealthy_result_when_health_checks_are()
// {
// var sut = new TestServer(new WebHostBuilder()
// .UseStartup<DefaultStartup>()
// .ConfigureServices(services =>
// {
// services.AddHealthChecks()
// .AddCheck("unhealthy", check => HealthCheckResult.Unhealthy())
// .AddPrometheusGatewayPublisher(_fakePrometheusGatewayClient, PrometheusEndpoint, JobName);
// }));
// _finishedTrigger.WaitOne(TimeoutForPublishingResults);
// _publishedResult.Should().ContainCheckAndResult("unhealthy", HealthStatus.Unhealthy);
// }
// [SkipOnAppVeyor]
// public void publish_all_results_included_when_there_are_three_checks_with_different_results()
// {
// var sut = new TestServer(new WebHostBuilder()
// .UseStartup<DefaultStartup>()
// .ConfigureServices(services =>
// {
// services.AddHealthChecks()
// .AddCheck("unhealthy", check => HealthCheckResult.Unhealthy())
// .AddCheck("healthy", check => HealthCheckResult.Healthy())
// .AddCheck("degraded", check => HealthCheckResult.Degraded())
// .AddPrometheusGatewayPublisher(_fakePrometheusGatewayClient, PrometheusEndpoint, JobName);
// }));
// _finishedTrigger.WaitOne(TimeoutForPublishingResults);
// _publishedResult.Should().ContainCheckAndResult("unhealthy", HealthStatus.Unhealthy);
// _publishedResult.Should().ContainCheckAndResult("healthy", HealthStatus.Healthy);
// _publishedResult.Should().ContainCheckAndResult("degraded", HealthStatus.Degraded);
// }
// }
//} | 42.241071 | 116 | 0.59015 | [
"Apache-2.0"
] | 697765/AspNetCore.Diagnostics.HealthChecks | test/FunctionalTests/HealthChecks.Publisher.Prometheus/PrometheusPublisherTests.cs | 4,733 | C# |
// Copyright 2018 Esri.
//
// 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 Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI.Controls;
using Foundation;
using System;
using UIKit;
namespace ArcGISRuntime.Samples.FeatureLayerRenderingModeScene
{
[Register("FeatureLayerRenderingModeScene")]
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Feature layer rendering mode (scene)",
category: "Layers",
description: "Render features in a scene statically or dynamically by setting the feature layer rendering mode.",
instructions: "Tap the button to trigger the same zoom animation on both static and dynamicly rendered scenes.",
tags: new[] { "3D", "dynamic", "feature layer", "features", "rendering", "static" })]
public class FeatureLayerRenderingModeScene : UIViewController
{
// Hold references to UI controls.
private SceneView _staticSceneView;
private SceneView _dynamicSceneView;
private UIStackView _stackView;
private UIBarButtonItem _zoomButton;
// Points for demonstrating zoom.
private readonly MapPoint _zoomedOutPoint = new MapPoint(-118.37, 34.46, SpatialReferences.Wgs84);
private readonly MapPoint _zoomedInPoint = new MapPoint(-118.45, 34.395, SpatialReferences.Wgs84);
// Viewpoints for each zoom level.
private Camera _zoomedOutCamera;
private Camera _zoomedInCamera;
// URI for the feature service.
private const string FeatureService = "https://sampleserver6.arcgisonline.com/arcgis/rest/services/Energy/Geology/FeatureServer/";
// Hold the current zoom state.
private bool _zoomed;
public FeatureLayerRenderingModeScene()
{
Title = "Feature layer rendering mode (Scene)";
}
private void Initialize()
{
// Initialize the cameras (viewpoints) with two points.
_zoomedOutCamera = new Camera(_zoomedOutPoint, 42000, 0, 0, 0);
_zoomedInCamera = new Camera(_zoomedInPoint, 2500, 90, 75, 0);
// Create the scene for displaying the feature layer in static mode.
Scene staticScene = new Scene
{
InitialViewpoint = new Viewpoint(_zoomedOutPoint, _zoomedOutCamera)
};
// Create the scene for displaying the feature layer in dynamic mode.
Scene dynamicScene = new Scene
{
InitialViewpoint = new Viewpoint(_zoomedOutPoint, _zoomedOutCamera)
};
foreach (string identifier in new[] { "8", "9", "0" })
{
// Create the table.
ServiceFeatureTable serviceTable = new ServiceFeatureTable(new Uri(FeatureService + identifier));
// Create and add the static layer.
FeatureLayer staticLayer = new FeatureLayer(serviceTable)
{
RenderingMode = FeatureRenderingMode.Static
};
staticScene.OperationalLayers.Add(staticLayer);
// Create and add the dynamic layer.
FeatureLayer dynamicLayer = (FeatureLayer)staticLayer.Clone();
dynamicLayer.RenderingMode = FeatureRenderingMode.Dynamic;
dynamicScene.OperationalLayers.Add(dynamicLayer);
}
// Add the scenes to the scene views.
_staticSceneView.Scene = staticScene;
_dynamicSceneView.Scene = dynamicScene;
}
private void _zoomButton_TouchUpInside(object sender, EventArgs e)
{
// Zoom out if zoomed.
if (_zoomed)
{
_staticSceneView.SetViewpointCameraAsync(_zoomedOutCamera, new TimeSpan(0, 0, 5));
_dynamicSceneView.SetViewpointCameraAsync(_zoomedOutCamera, new TimeSpan(0, 0, 5));
}
else // Zoom in otherwise.
{
_staticSceneView.SetViewpointCameraAsync(_zoomedInCamera, new TimeSpan(0, 0, 5));
_dynamicSceneView.SetViewpointCameraAsync(_zoomedInCamera, new TimeSpan(0, 0, 5));
}
// Toggle zoom state.
_zoomed = !_zoomed;
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Initialize();
}
public override void LoadView()
{
// Create the views.
View = new UIView { BackgroundColor = ApplicationTheme.BackgroundColor };
_staticSceneView = new SceneView();
_staticSceneView.TranslatesAutoresizingMaskIntoConstraints = false;
_dynamicSceneView = new SceneView();
_dynamicSceneView.TranslatesAutoresizingMaskIntoConstraints = false;
_stackView = new UIStackView(new UIView[] { _staticSceneView, _dynamicSceneView });
_stackView.TranslatesAutoresizingMaskIntoConstraints = false;
_stackView.Distribution = UIStackViewDistribution.FillEqually;
_stackView.Axis = View.TraitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Compact ? UILayoutConstraintAxis.Horizontal : UILayoutConstraintAxis.Vertical;
_zoomButton = new UIBarButtonItem();
_zoomButton.Title = "Zoom";
UIToolbar toolbar = new UIToolbar();
toolbar.TranslatesAutoresizingMaskIntoConstraints = false;
toolbar.Items = new[]
{
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
_zoomButton,
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace)
};
UILabel staticLabel = new UILabel
{
Text = "Static",
BackgroundColor = UIColor.FromWhiteAlpha(0f, .6f),
TextColor = UIColor.White,
TextAlignment = UITextAlignment.Center,
TranslatesAutoresizingMaskIntoConstraints = false
};
UILabel dynamicLabel = new UILabel
{
Text = "Dynamic",
BackgroundColor = UIColor.FromWhiteAlpha(0f, .6f),
TextColor = UIColor.White,
TextAlignment = UITextAlignment.Center,
TranslatesAutoresizingMaskIntoConstraints = false
};
// Add the views.
View.AddSubviews(_stackView, toolbar, staticLabel, dynamicLabel);
// Lay out the views.
NSLayoutConstraint.ActivateConstraints(new[]
{
_stackView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor),
_stackView.BottomAnchor.ConstraintEqualTo(toolbar.TopAnchor),
_stackView.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
_stackView.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
toolbar.LeadingAnchor.ConstraintEqualTo(View.LeadingAnchor),
toolbar.TrailingAnchor.ConstraintEqualTo(View.TrailingAnchor),
toolbar.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor),
staticLabel.TopAnchor.ConstraintEqualTo(_staticSceneView.TopAnchor),
staticLabel.HeightAnchor.ConstraintEqualTo(40),
staticLabel.LeadingAnchor.ConstraintEqualTo(_staticSceneView.LeadingAnchor),
staticLabel.TrailingAnchor.ConstraintEqualTo(_staticSceneView.TrailingAnchor),
dynamicLabel.TopAnchor.ConstraintEqualTo(_dynamicSceneView.TopAnchor),
dynamicLabel.HeightAnchor.ConstraintEqualTo(40),
dynamicLabel.LeadingAnchor.ConstraintEqualTo(_dynamicSceneView.LeadingAnchor),
dynamicLabel.TrailingAnchor.ConstraintEqualTo(_dynamicSceneView.TrailingAnchor)
});
}
public override void TraitCollectionDidChange(UITraitCollection previousTraitCollection)
{
base.TraitCollectionDidChange(previousTraitCollection);
if (View.TraitCollection.VerticalSizeClass == UIUserInterfaceSizeClass.Compact)
{
_stackView.Axis = UILayoutConstraintAxis.Horizontal;
}
else
{
_stackView.Axis = UILayoutConstraintAxis.Vertical;
}
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
// Subscribe to events.
_zoomButton.Clicked += _zoomButton_TouchUpInside;
}
public override void ViewDidDisappear(bool animated)
{
base.ViewDidDisappear(animated);
// Unsubscribe from events, per best practice.
_zoomButton.Clicked -= _zoomButton_TouchUpInside;
}
}
} | 42.709091 | 175 | 0.640485 | [
"Apache-2.0"
] | Druffl3/arcgis-runtime-samples-dotnet | src/iOS/Xamarin.iOS/Samples/Layers/FeatureLayerRenderingModeScene/FeatureLayerRenderingModeScene.cs | 9,396 | 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;
using Pulumi.Utilities;
namespace Pulumi.GoogleNative.DataCatalog.V1Beta1
{
public static class GetEntryGroup
{
/// <summary>
/// Gets an EntryGroup.
/// </summary>
public static Task<GetEntryGroupResult> InvokeAsync(GetEntryGroupArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetEntryGroupResult>("google-native:datacatalog/v1beta1:getEntryGroup", args ?? new GetEntryGroupArgs(), options.WithVersion());
/// <summary>
/// Gets an EntryGroup.
/// </summary>
public static Output<GetEntryGroupResult> Invoke(GetEntryGroupInvokeArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.Invoke<GetEntryGroupResult>("google-native:datacatalog/v1beta1:getEntryGroup", args ?? new GetEntryGroupInvokeArgs(), options.WithVersion());
}
public sealed class GetEntryGroupArgs : Pulumi.InvokeArgs
{
[Input("entryGroupId", required: true)]
public string EntryGroupId { get; set; } = null!;
[Input("location", required: true)]
public string Location { get; set; } = null!;
[Input("project")]
public string? Project { get; set; }
[Input("readMask")]
public string? ReadMask { get; set; }
public GetEntryGroupArgs()
{
}
}
public sealed class GetEntryGroupInvokeArgs : Pulumi.InvokeArgs
{
[Input("entryGroupId", required: true)]
public Input<string> EntryGroupId { get; set; } = null!;
[Input("location", required: true)]
public Input<string> Location { get; set; } = null!;
[Input("project")]
public Input<string>? Project { get; set; }
[Input("readMask")]
public Input<string>? ReadMask { get; set; }
public GetEntryGroupInvokeArgs()
{
}
}
[OutputType]
public sealed class GetEntryGroupResult
{
/// <summary>
/// Timestamps about this EntryGroup. Default value is empty timestamps.
/// </summary>
public readonly Outputs.GoogleCloudDatacatalogV1beta1SystemTimestampsResponse DataCatalogTimestamps;
/// <summary>
/// Entry group description, which can consist of several sentences or paragraphs that describe entry group contents. Default value is an empty string.
/// </summary>
public readonly string Description;
/// <summary>
/// A short name to identify the entry group, for example, "analytics data - jan 2011". Default value is an empty string.
/// </summary>
public readonly string DisplayName;
/// <summary>
/// The resource name of the entry group in URL format. Example: * projects/{project_id}/locations/{location}/entryGroups/{entry_group_id} Note that this EntryGroup and its child resources may not actually be stored in the location in this name.
/// </summary>
public readonly string Name;
[OutputConstructor]
private GetEntryGroupResult(
Outputs.GoogleCloudDatacatalogV1beta1SystemTimestampsResponse dataCatalogTimestamps,
string description,
string displayName,
string name)
{
DataCatalogTimestamps = dataCatalogTimestamps;
Description = description;
DisplayName = displayName;
Name = name;
}
}
}
| 35.638095 | 253 | 0.64698 | [
"Apache-2.0"
] | AaronFriel/pulumi-google-native | sdk/dotnet/DataCatalog/V1Beta1/GetEntryGroup.cs | 3,742 | C# |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// 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. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System.Text;
namespace Microsoft.PythonTools.Analysis.Infrastructure {
internal static class StringBuilderExtensions {
public static StringBuilder TrimEnd(this StringBuilder sb) {
while (sb.Length > 0 && char.IsWhiteSpace(sb[sb.Length - 1])) {
sb.Length -= 1;
}
return sb;
}
public static StringBuilder EnsureEndsWithSpace(this StringBuilder sb, int count = 1, bool allowLeading = false) {
if (sb.Length == 0 && !allowLeading) {
return sb;
}
for (var i = sb.Length - 1; i >= 0 && char.IsWhiteSpace(sb[i]); i--) {
count--;
}
if (count > 0) {
sb.Append(new string(' ', count));
}
return sb;
}
}
}
| 34.466667 | 122 | 0.625403 | [
"Apache-2.0"
] | DalavanCloud/python-language-server | src/Analysis/Engine/Impl/Infrastructure/Extensions/StringBuilderExtensions.cs | 1,553 | C# |
using Ardalis.Specification;
using FrontDesk.Core.SyncedAggregates;
namespace FrontDesk.Core.SyncedAggregates.Specifications
{
public class ClientsIncludePatientsSpecification : Specification<Client>
{
public ClientsIncludePatientsSpecification()
{
Query
.Include(client => client.Patients)
.OrderBy(client => client.FullName);
}
}
}
| 23.5 | 74 | 0.734043 | [
"MIT"
] | KunalChoudhary521/pluralsight-ddd-fundamentals | FrontDesk/src/FrontDesk.Core/SyncedAggregates/Specifications/Client/ClientsIncludePatientsSpecification.cs | 378 | C# |
// <copyright file="CompanyResponseStorageProvider.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
namespace Microsoft.Teams.Apps.CannedResponses.Common.Providers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Microsoft.Teams.Apps.CannedResponses.Common.Interfaces;
using Microsoft.Teams.Apps.CannedResponses.Models;
using Microsoft.WindowsAzure.Storage.Table;
/// <summary>
/// Implements storage provider which helps in storing, updating, deleting company responses data in Microsoft Azure Table storage.
/// </summary>
public class CompanyResponseStorageProvider : BaseStorageProvider, ICompanyResponseStorageProvider
{
/// <summary>
/// Represents company response entity name.
/// </summary>
private const string CompanyResponseEntity = "CompanyResponseEntity";
/// <summary>
/// Represents user id string.
/// </summary>
private const string UserId = "UserId";
/// <summary>
/// Initializes a new instance of the <see cref="CompanyResponseStorageProvider"/> class.
/// Handles Microsoft Azure Table storage read write operations.
/// </summary>
/// <param name="options">A set of key/value application configuration properties for Microsoft Azure Table storage.</param>
public CompanyResponseStorageProvider(IOptions<StorageSetting> options)
: base(options?.Value.ConnectionString, CompanyResponseEntity)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
}
/// <summary>
/// Get company responses data from Microsoft Azure Table storage.
/// </summary>
/// <returns>A task that holds company response entity data in collection.</returns>
public async Task<IEnumerable<CompanyResponseEntity>> GetCompanyResponsesDataAsync()
{
await this.EnsureInitializedAsync();
string userIdCondition = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, Constants.CompanyResponseEntityPartitionKey);
TableQuery<CompanyResponseEntity> query = new TableQuery<CompanyResponseEntity>().Where(userIdCondition);
TableContinuationToken continuationToken = null;
var companyResponseCollection = new List<CompanyResponseEntity>();
do
{
var queryResult = await this.ResponsesCloudTable.ExecuteQuerySegmentedAsync(query, continuationToken);
if (queryResult?.Results != null)
{
companyResponseCollection.AddRange(queryResult.Results);
continuationToken = queryResult.ContinuationToken;
}
}
while (continuationToken != null);
return companyResponseCollection;
}
/// <summary>
/// Get company responses from Microsoft Azure Table storage.
/// </summary>
/// <param name="userId">Id of the user to fetch the responses submitted by him.</param>
/// <returns>A task that represent collection to hold company responses data.</returns>
public async Task<IEnumerable<CompanyResponseEntity>> GetUserCompanyResponseAsync(string userId)
{
await this.EnsureInitializedAsync();
string partitionKeyCondition = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, Constants.CompanyResponseEntityPartitionKey);
string userIdCondition = TableQuery.GenerateFilterCondition(UserId, QueryComparisons.Equal, userId);
string combinedFilterCondition = TableQuery.CombineFilters(partitionKeyCondition, TableOperators.And, userIdCondition);
TableQuery<CompanyResponseEntity> query = new TableQuery<CompanyResponseEntity>().Where(combinedFilterCondition);
TableContinuationToken continuationToken = null;
var userRequestCollection = new List<CompanyResponseEntity>();
do
{
var queryResult = await this.ResponsesCloudTable.ExecuteQuerySegmentedAsync(query, continuationToken);
if (queryResult?.Results != null)
{
userRequestCollection.AddRange(queryResult.Results);
continuationToken = queryResult.ContinuationToken;
}
}
while (continuationToken != null);
return userRequestCollection?.OrderByDescending(request => request.LastUpdatedDate);
}
/// <summary>
/// Delete company response details data in Microsoft Azure Table storage.
/// </summary>
/// <param name="entity">Holds company response detail entity data.</param>
/// <returns>A task that represents company response entity data is deleted.</returns>
public async Task<bool> DeleteEntityAsync(CompanyResponseEntity entity)
{
await this.EnsureInitializedAsync();
TableOperation deleteOperation = TableOperation.Delete(entity);
var result = await this.ResponsesCloudTable.ExecuteAsync(deleteOperation);
return result.HttpStatusCode == (int)HttpStatusCode.NoContent;
}
/// <summary>
/// Stores or update company response data in Microsoft Azure Table storage.
/// </summary>
/// <param name="companyResponseEntity">Holds company response detail entity data.</param>
/// <returns>A task that represents company response entity data is saved or updated.</returns>
public async Task<bool> UpsertConverationStateAsync(CompanyResponseEntity companyResponseEntity)
{
var result = await this.StoreOrUpdateEntityAsync(companyResponseEntity);
return result.HttpStatusCode == (int)HttpStatusCode.NoContent;
}
/// <summary>
/// Get already saved company response detail from Microsoft Azure Table storage table.
/// </summary>
/// <param name="responseId">Appropriate row data will be fetched based on the response id received from the bot.</param>
/// <returns><see cref="Task"/>Already saved entity detail.</returns>
public async Task<CompanyResponseEntity> GetCompanyResponseEntityAsync(string responseId)
{
await this.EnsureInitializedAsync();
// "When there is no company response created and messaging extension is open by Admin, table initialization is required
// before creating search index or data-source or indexer." In this case response id will be null.
if (string.IsNullOrEmpty(responseId))
{
return null;
}
var searchOperation = TableOperation.Retrieve<CompanyResponseEntity>(Constants.CompanyResponseEntityPartitionKey, responseId);
var searchResult = await this.ResponsesCloudTable.ExecuteAsync(searchOperation);
return (CompanyResponseEntity)searchResult.Result;
}
/// <summary>
/// Stores or update company response details data in Microsoft Azure Table storage.
/// </summary>
/// <param name="entity">Holds company response detail entity data.</param>
/// <returns>A task that represents a company response data that is saved or updated.</returns>
private async Task<TableResult> StoreOrUpdateEntityAsync(CompanyResponseEntity entity)
{
try
{
await this.EnsureInitializedAsync();
TableOperation addOrUpdateOperation = TableOperation.InsertOrReplace(entity);
return await this.ResponsesCloudTable.ExecuteAsync(addOrUpdateOperation);
}
catch (Exception)
{
throw;
}
}
}
}
| 47.452941 | 163 | 0.660469 | [
"MIT"
] | ArpitSuresh98/msteams-app-cannedresponse | Source/Microsoft.Teams.Apps.CannedResponses/Common/Providers/CompanyResponseStorageProvider.cs | 8,069 | C# |
namespace LearningCenter.Web.ViewModels.Administration.Dashboard
{
public class IndexViewModel
{
public int SettingsCount { get; set; }
}
}
| 20.125 | 65 | 0.695652 | [
"MIT"
] | NikolayStefanov/Learning-Center | Web/LearningCenter.Web.ViewModels/Administration/Dashboard/IndexViewModel.cs | 163 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;
namespace Microsoft.Azure.Devices.Provisioning.Samples
{
public class Program
{
private const string VerificationCertificatePath = "verificationCertificate.cer";
public static int Main(string[] args)
{
if (args.Length < 3)
{
Console.WriteLine("Usage:");
Console.WriteLine(
"\tGroupCertificateVerificationSample <certificate.pfx> <certificatepassword> <verificationCode>");
return -1;
}
string certificatePath = args[0];
string certificatePassword = args[1];
string verificationCode = args[2];
var certificate = new X509Certificate2(
certificatePath,
certificatePassword,
X509KeyStorageFlags.Exportable);
if (!certificate.HasPrivateKey)
{
Console.WriteLine("ERROR: The certificate does not have a private key.");
return 1;
}
X509Certificate2 verificationCertificate =
VerificationCertificateGenerator.GenerateSignedCertificate(certificate, verificationCode);
File.WriteAllText(
VerificationCertificatePath,
Convert.ToBase64String(verificationCertificate.Export(X509ContentType.Cert)));
Console.WriteLine(
$"Verification certificate ({verificationCertificate.Subject}; {verificationCertificate.Thumbprint})" +
$" was written to {VerificationCertificatePath}.");
return 0;
}
}
}
| 34.574074 | 119 | 0.61489 | [
"MIT"
] | CIPop-test/azure-iot-sdk-csharp | provisioning/service/samples/GroupCertificateVerificationSample/Program.cs | 1,869 | C# |
namespace Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Helpers
{
public class AzureTableStorageClientFactory : IAzureTableStorageClientFactory
{
private IAzureTableStorageClient _tableStorageClient;
public AzureTableStorageClientFactory() : this(null)
{
}
public AzureTableStorageClientFactory(IAzureTableStorageClient customClient)
{
_tableStorageClient = customClient;
}
public IAzureTableStorageClient CreateClient(string storageConnectionString, string tableName)
{
if (_tableStorageClient == null)
{
_tableStorageClient = new AzureTableStorageClient(storageConnectionString, tableName);
}
return _tableStorageClient;
}
}
} | 32.6 | 102 | 0.678528 | [
"MIT"
] | Anchinga/TechnicalCommunityContent | IoT/Azure IoT Suite/Session 3 - Building Practical IoT Solutions/Solutions/Demo 3.2/Common/Helpers/AzureTableStorageClientFactory.cs | 817 | C# |
using System;
using System.Threading.Tasks;
namespace AlinSpace.Commands
{
/// <summary>
/// Default implementation of <see cref="ICommand{TParameter}"/>.
/// </summary>
public class Command<TParameter> : AbstractCommand<TParameter>
{
private readonly bool verifyCanExecuteBeforeExecution;
private readonly bool continueOnCapturedContext;
private Func<TParameter, Task> executeFunc;
private Func<TParameter, bool> canExecuteFunc;
/// <summary>
/// Static factory method.
/// </summary>
/// <param name="verifyCanExecuteBeforeExecution">
/// This flag indicates whether or not the can execute shall should be called and checked before execution.
/// </param>
/// <param name="continueOnCapturedContext">
/// This flag indicates whether or not the command shall be executed on the captured context.
/// </param>
/// <returns>Async command.</returns>
public static Command<TParameter> New(
bool verifyCanExecuteBeforeExecution = false,
bool continueOnCapturedContext = true)
{
return new Command<TParameter>(
verifyCanExecuteBeforeExecution,
continueOnCapturedContext);
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="verifyCanExecuteBeforeExecution">
/// This flag indicates whether or not the can execute shall should be called and checked before execution.
/// </param>
/// <param name="continueOnCapturedContext">
/// This flag indicates whether or not the command shall be executed on the captured context.
/// </param>
public Command(
bool verifyCanExecuteBeforeExecution = false,
bool continueOnCapturedContext = true)
{
this.verifyCanExecuteBeforeExecution = verifyCanExecuteBeforeExecution;
this.continueOnCapturedContext = continueOnCapturedContext;
}
/// <summary>
/// On can execute callback.
/// </summary>
/// <param name="executeFunc"></param>
/// <returns>Async command.</returns>
public Command<TParameter> OnCanExecute(Func<TParameter, bool> canExecuteFunc)
{
this.canExecuteFunc = canExecuteFunc;
return this;
}
/// <summary>
/// On execute asynchronously callback.
/// </summary>
/// <param name="executeAction"></param>
/// <returns>Async command.</returns>
public Command<TParameter> OnExecuteAsync(Func<TParameter, Task> executeFunc)
{
this.executeFunc = executeFunc;
return this;
}
/// <summary>
/// Can execute.
/// </summary>
/// <param name="parameter">Parameter.</param>
/// <returns>True if can execute; false otherwise.</returns>
public override bool CanExecute(TParameter parameter = default)
{
if (canExecuteFunc == null)
return true;
return canExecuteFunc(parameter);
}
/// <summary>
/// Execute command asynchronously.
/// </summary>
/// <param name="parameter">Command parameter.</param>
/// <returns>Task.</returns>
public override async Task ExecuteAsync(TParameter parameter = default)
{
if (executeFunc == null)
return;
if (verifyCanExecuteBeforeExecution)
{
if (!CanExecute(parameter))
return;
}
await executeFunc(parameter).ConfigureAwait(continueOnCapturedContext);
}
}
}
| 34.888889 | 115 | 0.590499 | [
"MIT"
] | onixion/AlinSpace.Command | AlinSpace.Commands/Command/Command.Generic.cs | 3,770 | C# |
using System.Text;
using ExtensionMethods = PeNet.Utilities.ExtensionMethods;
namespace PeNet
{
/// <summary>
/// Represents an exported function.
/// </summary>
public class ExportFunction
{
/// <summary>
/// Create a new ExportFunction object.
/// </summary>
/// <param name="name">Name of the function.</param>
/// <param name="address">Address of function.</param>
/// <param name="ordinal">Ordinal of the function.</param>
public ExportFunction(string name, uint address, ushort ordinal)
{
Name = name;
Address = address;
Ordinal = ordinal;
}
/// <summary>
/// Create a new ExportFunction object.
/// </summary>
/// <param name="name">Name of the function.</param>
/// <param name="address">Address of function.</param>
/// <param name="ordinal">Ordinal of the function.</param>
/// <param name="forwardName">Name of the DLL and function this export forwards to.</param>
public ExportFunction(string name, uint address, ushort ordinal, string forwardName)
{
Name = name;
Address = address;
Ordinal = ordinal;
ForwardName = forwardName;
}
/// <summary>
/// Function name.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Function RVA.
/// </summary>
public uint Address { get; }
/// <summary>
/// Function Ordinal.
/// </summary>
public ushort Ordinal { get; }
/// <summary>
/// Function name if the function is
/// forwarded to another DLL.
/// Format "DLLName.ExportName".
/// </summary>
public string ForwardName { get; }
/// <summary>
/// True if the export has a name and is not forwarded.
/// </summary>
public bool HasName => !string.IsNullOrEmpty(Name);
/// <summary>
/// True if the export has an ordinal.
/// </summary>
public bool HasOrdinal => Ordinal != 0;
/// <summary>
/// True if the export is forwared and has
/// a ForwardName.
/// </summary>
public bool HasForwad => !string.IsNullOrEmpty(ForwardName);
}
} | 31.102564 | 99 | 0.52803 | [
"Apache-2.0"
] | iceman63/PeNet | src/PeNet/ExportFunction.cs | 2,428 | C# |
using System;
using System.IO;
using System.Text;
using Axiom.Animating;
using Axiom.MathLib;
namespace Axiom.Serialization {
/// <summary>
/// Summary description for OgreSkeletonSerializer.
/// </summary>
public class OgreSkeletonSerializer : Serializer {
#region Member variables
// Create a logger for use in this class
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(OgreSkeletonSerializer));
private Skeleton skeleton;
#endregion
#region Constructors
public OgreSkeletonSerializer() {
version = "[Serializer_v1.10]";
}
#endregion
#region Methods
public void ImportSkeleton(Stream stream, Skeleton skeleton) {
// store a local reference to the mesh for modification
this.skeleton = skeleton;
BinaryMemoryReader reader = new BinaryMemoryReader(stream, System.Text.Encoding.ASCII);
// start off by taking a look at the header
ReadFileHeader(reader);
SkeletonChunkID chunkID = 0;
while (!IsEOF(reader)) {
chunkID = ReadChunk(reader);
switch (chunkID) {
case SkeletonChunkID.Bone:
ReadBone(reader);
break;
case SkeletonChunkID.BoneParent:
ReadBoneParent(reader);
break;
case SkeletonChunkID.Animation:
ReadAnimation(reader);
break;
case SkeletonChunkID.AttachmentPoint:
ReadAttachmentPoint(reader);
break;
default:
log.Warn("Can only parse bones, parents, and animations at the top level during skeleton loading.");
log.Warn("Unexpected chunk: " + chunkID.ToString());
break;
} // switch
} // while
// assume bones are stored in binding pose
skeleton.SetBindingPose();
}
protected SkeletonChunkID ReadChunk(BinaryMemoryReader reader) {
return (SkeletonChunkID)ReadFileChunk(reader);
}
/// <summary>
/// Reads animation information from the file.
/// </summary>
protected void ReadAnimation(BinaryMemoryReader reader) {
// name of the animation
string name = ReadString(reader);
// length in seconds of the animation
float length = ReadFloat(reader);
// create an animation from the skeleton
Animation anim = skeleton.CreateAnimation(name, length);
// keep reading all keyframes for this track
if (!IsEOF(reader)) {
SkeletonChunkID chunkID = ReadChunk(reader);
while (!IsEOF(reader) && (chunkID == SkeletonChunkID.AnimationTrack)) {
// read the animation track
ReadAnimationTrack(reader, anim);
// read the next chunk id
// If we're not end of file get the next chunk ID
if (!IsEOF(reader)) {
chunkID = ReadChunk(reader);
}
}
// backpedal to the start of the chunk
if (!IsEOF(reader)) {
Seek(reader, -ChunkOverheadSize);
}
}
}
/// <summary>
/// Reads an animation track.
/// </summary>
protected void ReadAnimationTrack(BinaryMemoryReader reader, Animation anim) {
// read the bone handle to apply this track to
ushort boneHandle = ReadUShort(reader);
// get a reference to the target bone
Bone targetBone = skeleton.GetBone(boneHandle);
// create an animation track for this bone
NodeAnimationTrack track = anim.CreateNodeTrack(boneHandle, targetBone);
// keep reading all keyframes for this track
if (!IsEOF(reader)) {
SkeletonChunkID chunkID = ReadChunk(reader);
while (!IsEOF(reader) && (chunkID == SkeletonChunkID.KeyFrame)) {
// read the key frame
ReadKeyFrame(reader, track);
// read the next chunk id
// If we're not end of file get the next chunk ID
if (!IsEOF(reader)) {
chunkID = ReadChunk(reader);
}
}
// backpedal to the start of the chunk
if (!IsEOF(reader)) {
Seek(reader, -ChunkOverheadSize);
}
}
}
/// <summary>
/// Reads bone information from the file.
/// </summary>
protected void ReadBone(BinaryMemoryReader reader) {
// bone name
string name = ReadString(reader);
ushort handle = ReadUShort(reader);
// create a new bone
Bone bone = skeleton.CreateBone(name, handle);
// read and set the position of the bone
Vector3 position = ReadVector3(reader);
bone.Position = position;
// read and set the orientation of the bone
Quaternion q = ReadQuat(reader);
bone.Orientation = q;
}
/// <summary>
/// Reads bone information from the file.
/// </summary>
protected void ReadBoneParent(BinaryMemoryReader reader) {
// all bones should have been created by this point, so this establishes the heirarchy
Bone child, parent;
ushort childHandle, parentHandle;
// child bone
childHandle = ReadUShort(reader);
// parent bone
parentHandle = ReadUShort(reader);
// get references to father and son bones
parent = skeleton.GetBone(parentHandle);
child = skeleton.GetBone(childHandle);
// attach the child to the parent
parent.AddChild(child);
}
/// <summary>
/// Reads an animation track section.
/// </summary>
/// <param name="track"></param>
protected void ReadKeyFrame(BinaryMemoryReader reader, NodeAnimationTrack track) {
float time = ReadFloat(reader);
// create a new keyframe with the specified length
TransformKeyFrame keyFrame = track.CreateNodeKeyFrame(time);
// read orientation
Quaternion rotate = ReadQuat(reader);
keyFrame.Rotation = rotate;
// read translation
Vector3 translate = ReadVector3(reader);
keyFrame.Translate = translate;
// read scale if it is in there
if (currentChunkLength >= 50) {
Vector3 scale = ReadVector3(reader);
keyFrame.Scale = scale;
} else {
keyFrame.Scale = Vector3.UnitScale;
}
}
/// <summary>
/// Reads bone information from the file.
/// </summary>
protected void ReadAttachmentPoint(BinaryMemoryReader reader) {
// bone name
string name = ReadString(reader);
ushort boneHandle = ReadUShort(reader);
// read and set the position of the bone
Vector3 position = ReadVector3(reader);
// read and set the orientation of the bone
Quaternion q = ReadQuat(reader);
// create the attachment point
AttachmentPoint ap = skeleton.CreateAttachmentPoint(name, boneHandle, q, position);
}
public void ExportSkeleton(Skeleton skeleton, string fileName) {
this.skeleton = skeleton;
FileStream stream = new FileStream(fileName, FileMode.Create);
try {
BinaryWriter writer = new BinaryWriter(stream);
WriteFileHeader(writer, version);
WriteSkeleton(writer);
} finally {
if (stream != null)
stream.Close();
}
}
protected void WriteSkeleton(BinaryWriter writer) {
for (ushort i = 0; i < skeleton.BoneCount; ++i) {
Bone bone = skeleton.GetBone(i);
WriteBone(writer, bone);
}
for (ushort i = 0; i < skeleton.BoneCount; ++i) {
Bone bone = skeleton.GetBone(i);
if (bone.Parent != null)
WriteBoneParent(writer, bone, (Bone)bone.Parent);
}
for (int i = 0; i < skeleton.AnimationCount; ++i) {
Animation anim = skeleton.GetAnimation(i);
WriteAnimation(writer, anim);
}
for (int i = 0; i < skeleton.AttachmentPoints.Count; ++i) {
AttachmentPoint ap = skeleton.AttachmentPoints[i];
WriteAttachmentPoint(writer, ap, skeleton.GetBone(ap.ParentBone));
}
}
protected void WriteBone(BinaryWriter writer, Bone bone) {
long start_offset = writer.Seek(0, SeekOrigin.Current);
WriteChunk(writer, SkeletonChunkID.Bone, 0);
WriteString(writer, bone.Name);
WriteUShort(writer, bone.Handle);
WriteVector3(writer, bone.Position);
WriteQuat(writer, bone.Orientation);
if (bone.ScaleFactor != Vector3.UnitScale)
WriteVector3(writer, bone.ScaleFactor);
long end_offset = writer.Seek(0, SeekOrigin.Current);
writer.Seek((int)start_offset, SeekOrigin.Begin);
WriteChunk(writer, SkeletonChunkID.Bone, (int)(end_offset - start_offset));
writer.Seek((int)end_offset, SeekOrigin.Begin);
}
protected void WriteBoneParent(BinaryWriter writer, Bone bone, Bone parent) {
long start_offset = writer.Seek(0, SeekOrigin.Current);
WriteChunk(writer, SkeletonChunkID.BoneParent, 0);
WriteUShort(writer, bone.Handle);
WriteUShort(writer, parent.Handle);
long end_offset = writer.Seek(0, SeekOrigin.Current);
writer.Seek((int)start_offset, SeekOrigin.Begin);
WriteChunk(writer, SkeletonChunkID.BoneParent, (int)(end_offset - start_offset));
writer.Seek((int)end_offset, SeekOrigin.Begin);
}
protected void WriteAnimation(BinaryWriter writer, Animation anim) {
long start_offset = writer.Seek(0, SeekOrigin.Current);
WriteChunk(writer, SkeletonChunkID.Animation, 0);
WriteString(writer, anim.Name);
WriteFloat(writer, anim.Length);
foreach (NodeAnimationTrack track in anim.NodeTracks.Values)
WriteAnimationTrack(writer, track);
long end_offset = writer.Seek(0, SeekOrigin.Current);
writer.Seek((int)start_offset, SeekOrigin.Begin);
WriteChunk(writer, SkeletonChunkID.Animation, (int)(end_offset - start_offset));
writer.Seek((int)end_offset, SeekOrigin.Begin);
}
protected void WriteAnimationTrack(BinaryWriter writer, NodeAnimationTrack track) {
long start_offset = writer.Seek(0, SeekOrigin.Current);
WriteChunk(writer, SkeletonChunkID.AnimationTrack, 0);
WriteUShort(writer, (ushort)track.Handle);
for (ushort i = 0; i < track.KeyFrames.Count; i++) {
TransformKeyFrame keyFrame = track.GetNodeKeyFrame(i);
WriteKeyFrame(writer, keyFrame);
}
long end_offset = writer.Seek(0, SeekOrigin.Current);
writer.Seek((int)start_offset, SeekOrigin.Begin);
WriteChunk(writer, SkeletonChunkID.AnimationTrack, (int)(end_offset - start_offset));
writer.Seek((int)end_offset, SeekOrigin.Begin);
}
protected void WriteKeyFrame(BinaryWriter writer, TransformKeyFrame keyFrame) {
long start_offset = writer.Seek(0, SeekOrigin.Current);
WriteChunk(writer, SkeletonChunkID.KeyFrame, 0);
WriteFloat(writer, keyFrame.Time);
WriteQuat(writer, keyFrame.Rotation);
WriteVector3(writer, keyFrame.Translate);
if (keyFrame.Scale != Vector3.UnitScale)
WriteVector3(writer, keyFrame.Scale);
long end_offset = writer.Seek(0, SeekOrigin.Current);
writer.Seek((int)start_offset, SeekOrigin.Begin);
WriteChunk(writer, SkeletonChunkID.KeyFrame, (int)(end_offset - start_offset));
writer.Seek((int)end_offset, SeekOrigin.Begin);
}
protected void WriteAttachmentPoint(BinaryWriter writer, AttachmentPoint ap, Bone bone) {
long start_offset = writer.Seek(0, SeekOrigin.Current);
WriteChunk(writer, SkeletonChunkID.AttachmentPoint, 0);
WriteString(writer, ap.Name);
WriteUShort(writer, bone.Handle);
WriteVector3(writer, ap.Position);
WriteQuat(writer, ap.Orientation);
long end_offset = writer.Seek(0, SeekOrigin.Current);
writer.Seek((int)start_offset, SeekOrigin.Begin);
WriteChunk(writer, SkeletonChunkID.AttachmentPoint, (int)(end_offset - start_offset));
writer.Seek((int)end_offset, SeekOrigin.Begin);
}
#endregion Methods
}
/// <summary>
/// Chunk ID's that can be found within the Ogre .skeleton format.
/// </summary>
public enum SkeletonChunkID {
Header = 0x1000,
Bone = 0x2000,
BoneParent = 0x3000,
Animation = 0x4000,
AnimationTrack = 0x4100,
KeyFrame = 0x4110,
// TODO: AnimationLink = 0x5000,
// Multiverse Addition
AttachmentPoint = 0x6000,
}
}
| 37.528 | 124 | 0.566475 | [
"MIT"
] | AustralianDisabilityLimited/MultiversePlatform | axiom/Engine/Serialization/OgreSkeletonReader.cs | 14,073 | C# |
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using Arbor.App.Extensions.ExtensionMethods;
using JetBrains.Annotations;
using Milou.Deployer.Web.Agent;
namespace Milou.Deployer.Web.IisHost.Areas.Deployment.Signaling
{
public class LogSubscribers
{
public ConcurrentDictionary<DeploymentTargetId, HashSet<string>> TargetMapping { get; } = new();
public ImmutableHashSet<string> TryGetTargetSubscribers([NotNull] DeploymentTargetId deploymentTargetId)
{
bool tryGetTargetSubscribers = TargetMapping.TryGetValue(deploymentTargetId, out var subscribers);
if (!tryGetTargetSubscribers)
{
return ImmutableHashSet<string>.Empty;
}
return subscribers.SafeToImmutableArray().ToImmutableHashSet();
}
}
} | 33.807692 | 112 | 0.718999 | [
"MIT"
] | niklaslundberg/milou.deployer | src/Milou.Deployer.Web.IisHost/Areas/Deployment/Signaling/LogSubscribers.cs | 881 | C# |
namespace Serenity.Data.Mapping
{
/// <summary>
/// Specifies that field can not be null.
/// </summary>
/// <seealso cref="SetFieldFlagsAttribute" />
public class NotNullAttribute : SetFieldFlagsAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="NotNullAttribute"/> class.
/// </summary>
public NotNullAttribute()
: base(FieldFlags.NotNull)
{
}
}
} | 26.666667 | 84 | 0.55625 | [
"MIT"
] | ArsenioInojosa/Serenity | src/Serenity.Net.Data/Mapping/NotNullAttribute.cs | 482 | C# |
/*
* Copyright 2010-2013 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.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.Route53.Model
{
/// <summary>
/// <para>A complex type that contains the value of the <c>Value</c> element for the current resource record set.</para>
/// </summary>
public class ResourceRecord
{
private string value;
/// <summary>
/// The value of the <c>Value</c> element for the current resource record set.
///
/// <para>
/// <b>Constraints:</b>
/// <list type="definition">
/// <item>
/// <term>Length</term>
/// <description>0 - 4000</description>
/// </item>
/// </list>
/// </para>
/// </summary>
public string Value
{
get { return this.value; }
set { this.value = value; }
}
/// <summary>
/// Sets the Value property
/// </summary>
/// <param name="value">The value to set for the Value property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ResourceRecord WithValue(string value)
{
this.value = value;
return this;
}
// Check to see if Value property is set
internal bool IsSetValue()
{
return this.value != null;
}
}
}
| 31.485714 | 177 | 0.584392 | [
"Apache-2.0"
] | mahanthbeeraka/dataservices-sdk-dotnet | AWSSDK/Amazon.Route53/Model/ResourceRecord.cs | 2,204 | C# |
using System;
using NCore;
using NCore.Reflections;
using PineCone.Annotations;
using PineCone.Resources;
namespace PineCone.Structures.Schemas
{
[Serializable]
public class StructureProperty : IStructureProperty
{
private readonly DynamicGetter _getter;
private readonly DynamicSetter _setter;
public string Name { get; private set; }
public string Path { get; private set; }
public Type DataType { get; private set; }
public IStructureProperty Parent { get; private set; }
public bool IsRootMember { get; private set; }
public bool IsUnique
{
get { return UniqueMode.HasValue; }
}
public UniqueModes? UniqueMode { get; private set; }
public bool IsEnumerable { get; private set; }
public bool IsElement { get; private set; }
public Type ElementDataType { get; private set; }
public bool IsReadOnly { get; private set; }
public StructureProperty(StructurePropertyInfo info, DynamicGetter getter, DynamicSetter setter = null)
{
_getter = getter;
_setter = setter;
Parent = info.Parent;
Name = info.Name;
DataType = info.DataType;
IsRootMember = info.Parent == null;
IsReadOnly = _setter == null;
UniqueMode = info.UniqueMode;
var isSimpleOrValueType = DataType.IsSimpleType() || DataType.IsValueType;
IsEnumerable = !isSimpleOrValueType && DataType.IsEnumerableType();
IsElement = Parent != null && (Parent.IsElement || Parent.IsEnumerable);
ElementDataType = IsEnumerable ? DataType.GetEnumerableElementType() : null;
if (IsUnique && !isSimpleOrValueType)
throw new PineConeException(ExceptionMessages.StructureProperty_Ctor_UniqueOnNonSimpleType);
Path = PropertyPathBuilder.BuildPath(this);
}
public virtual object GetValue(object item)
{
return _getter.GetValue(item);
}
public virtual void SetValue(object target, object value)
{
if (IsReadOnly)
throw new PineConeException(ExceptionMessages.StructureProperty_Setter_IsReadOnly.Inject(Path));
_setter.SetValue(target, value);
}
}
} | 32.078947 | 113 | 0.611977 | [
"MIT"
] | danielwertheim/PineCone | Source/Projects/PineCone/Structures/Schemas/StructureProperty.cs | 2,440 | C# |
using UnityEngine;
using System.Collections;
public class MoveRandomDirectionScript : MonoBehaviour {
public float xMinimum = -1f;
public float xMaximum = 1f;
public float yMinimum = -1;
public float yMaximum = 1;
public float speedMultiplier = 0.1f;
private float xSpeed, ySpeed;
private Transform transform;
void Awake() {
xSpeed = speedMultiplier * Random.Range(xMinimum, xMaximum);
ySpeed = speedMultiplier * Random.Range(yMinimum, yMaximum);
transform = GetComponent<Transform>();
}
void Start () {
}
void Update () {
transform.Translate(new Vector3(xSpeed, ySpeed, 0));
}
}
| 22.862069 | 68 | 0.666667 | [
"MIT"
] | Stovich/InvasionForever | Assets/Scripts/MoveRandomDirectionScript.cs | 665 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mecha.Wpf.Settings
{
public enum Accent
{
Blue,
Red,
Green,
Purple,
Orange,
Lime,
Emerald,
Teal,
Cyan,
Cobalt,
Indigo,
Violet,
Pink,
Magenta,
Crimson,
Amber,
Yellow,
Brown,
Olive,
Steel,
Mauve,
Taupe,
Sienna
}
}
| 14.888889 | 33 | 0.479478 | [
"MIT"
] | marektoman/mechaview | MechaView/Mecha.Wpf.Settings/Accent.cs | 538 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.