content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using EconRentCar.Core;
using EconRentCar.DataModel;
using EconRentCar.Logics.ViewModels;
using EconRentCar.Logics.Services;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
namespace EconRentCar.Api.Controllers
{
[Authorize(Policy = "ApiUser")]
[ApiController]
public class VehiculosController : EntityBaseApiController<Vehiculo, VehiculoVm>
{
public VehiculosController(IVehiculoService _service, IMapper _mapper):
base(_service, _mapper, "Modelo,TipoVehiculo,TipoCombustible,Rentas.Vehiculo,Rentas.Empleado,Rentas.Cliente")
{
}
}
} | 29.5 | 121 | 0.769231 | [
"MIT"
] | erickconcepcion/EconRentCarWeb | EconRentCarWeb/EconRentCar.Api/Controllers/VehiculosController.cs | 769 | 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.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.RedisEnterpriseCache.Support
{
/// <summary>The current provisioning state.</summary>
public partial struct PrivateEndpointConnectionProvisioningState :
System.IEquatable<PrivateEndpointConnectionProvisioningState>
{
public static Microsoft.Azure.PowerShell.Cmdlets.RedisEnterpriseCache.Support.PrivateEndpointConnectionProvisioningState Creating = @"Creating";
public static Microsoft.Azure.PowerShell.Cmdlets.RedisEnterpriseCache.Support.PrivateEndpointConnectionProvisioningState Deleting = @"Deleting";
public static Microsoft.Azure.PowerShell.Cmdlets.RedisEnterpriseCache.Support.PrivateEndpointConnectionProvisioningState Failed = @"Failed";
public static Microsoft.Azure.PowerShell.Cmdlets.RedisEnterpriseCache.Support.PrivateEndpointConnectionProvisioningState Succeeded = @"Succeeded";
/// <summary>
/// the value for an instance of the <see cref="PrivateEndpointConnectionProvisioningState" /> Enum.
/// </summary>
private string _value { get; set; }
/// <summary>Conversion from arbitrary object to PrivateEndpointConnectionProvisioningState</summary>
/// <param name="value">the value to convert to an instance of <see cref="PrivateEndpointConnectionProvisioningState" />.</param>
internal static object CreateFrom(object value)
{
return new PrivateEndpointConnectionProvisioningState(System.Convert.ToString(value));
}
/// <summary>Compares values of enum type PrivateEndpointConnectionProvisioningState</summary>
/// <param name="e">the value to compare against this instance.</param>
/// <returns><c>true</c> if the two instances are equal to the same value</returns>
public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.RedisEnterpriseCache.Support.PrivateEndpointConnectionProvisioningState e)
{
return _value.Equals(e._value);
}
/// <summary>
/// Compares values of enum type PrivateEndpointConnectionProvisioningState (override for Object)
/// </summary>
/// <param name="obj">the value to compare against this instance.</param>
/// <returns><c>true</c> if the two instances are equal to the same value</returns>
public override bool Equals(object obj)
{
return obj is PrivateEndpointConnectionProvisioningState && Equals((PrivateEndpointConnectionProvisioningState)obj);
}
/// <summary>Returns hashCode for enum PrivateEndpointConnectionProvisioningState</summary>
/// <returns>The hashCode of the value</returns>
public override int GetHashCode()
{
return this._value.GetHashCode();
}
/// <summary>
/// Creates an instance of the <see cref="PrivateEndpointConnectionProvisioningState" Enum class./>
/// </summary>
/// <param name="underlyingValue">the value to create an instance for.</param>
private PrivateEndpointConnectionProvisioningState(string underlyingValue)
{
this._value = underlyingValue;
}
/// <summary>Returns string representation for PrivateEndpointConnectionProvisioningState</summary>
/// <returns>A string for this value.</returns>
public override string ToString()
{
return this._value;
}
/// <summary>
/// Implicit operator to convert string to PrivateEndpointConnectionProvisioningState
/// </summary>
/// <param name="value">the value to convert to an instance of <see cref="PrivateEndpointConnectionProvisioningState" />.</param>
public static implicit operator PrivateEndpointConnectionProvisioningState(string value)
{
return new PrivateEndpointConnectionProvisioningState(value);
}
/// <summary>
/// Implicit operator to convert PrivateEndpointConnectionProvisioningState to string
/// </summary>
/// <param name="e">the value to convert to an instance of <see cref="PrivateEndpointConnectionProvisioningState" />.</param>
public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.RedisEnterpriseCache.Support.PrivateEndpointConnectionProvisioningState e)
{
return e._value;
}
/// <summary>Overriding != operator for enum PrivateEndpointConnectionProvisioningState</summary>
/// <param name="e1">the value to compare against <see cref="e2" /></param>
/// <param name="e2">the value to compare against <see cref="e1" /></param>
/// <returns><c>true</c> if the two instances are not equal to the same value</returns>
public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.RedisEnterpriseCache.Support.PrivateEndpointConnectionProvisioningState e1, Microsoft.Azure.PowerShell.Cmdlets.RedisEnterpriseCache.Support.PrivateEndpointConnectionProvisioningState e2)
{
return !e2.Equals(e1);
}
/// <summary>Overriding == operator for enum PrivateEndpointConnectionProvisioningState</summary>
/// <param name="e1">the value to compare against <see cref="e2" /></param>
/// <param name="e2">the value to compare against <see cref="e1" /></param>
/// <returns><c>true</c> if the two instances are equal to the same value</returns>
public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.RedisEnterpriseCache.Support.PrivateEndpointConnectionProvisioningState e1, Microsoft.Azure.PowerShell.Cmdlets.RedisEnterpriseCache.Support.PrivateEndpointConnectionProvisioningState e2)
{
return e2.Equals(e1);
}
}
} | 55.107143 | 261 | 0.692644 | [
"MIT"
] | 3quanfeng/azure-powershell | src/RedisEnterpriseCache/generated/api/Support/PrivateEndpointConnectionProvisioningState.cs | 6,061 | C# |
// -----------------------------------------------------------------------
// <copyright file="ProbeUpdateException.cs" company="Petabridge, LLC">
// Copyright (C) 2015 - 2019 Petabridge, LLC <https://petabridge.com>
// </copyright>
// -----------------------------------------------------------------------
using System;
using Akka.HealthCheck.Transports;
namespace Akka.HealthCheck
{
/// <summary>
/// Thrown when a probe fails to update its underlying <see cref="IStatusTransport" />
/// </summary>
public sealed class ProbeUpdateException : Exception
{
public ProbeUpdateException(ProbeKind probeKind, string message, Exception innerException)
: base(message, innerException)
{
ProbeKind = probeKind;
}
public ProbeKind ProbeKind { get; }
}
} | 33.56 | 98 | 0.539928 | [
"Apache-2.0"
] | Aaronontheweb/akkadotnet-healthcheck | src/Akka.HealthCheck/ProbeUpdateException.cs | 841 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright>
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.VisualStudio.TestTools.UnitTesting
{
using System;
public static class Assert
{
public static void AreEqual<T>(T expected, T actual)
{
Xunit.Assert.Equal(expected, actual);
}
public static void AreEqual<T>(T expected, T actual, string message)
{
Xunit.Assert.True(expected.Equals(actual), message);
}
public static void AreEqual<T>(T expected, T actual, string message, params object[] items)
{
Xunit.Assert.True(expected.Equals(actual), string.Format(message, items));
}
public static void IsNotNull(object result)
{
Xunit.Assert.NotNull(result);
}
public static void IsNotNull(object result, string message)
{
Xunit.Assert.True(result != null, message);
}
public static void IsFalse(bool expectedFalse)
{
Xunit.Assert.False(expectedFalse);
}
public static void IsFalse(bool expectedFalse, string message)
{
Xunit.Assert.False(expectedFalse, message);
}
public static void AreNotEqual(string notExpected, string actual, bool ignoreCase, string message)
{
Xunit.Assert.False(string.Equals(notExpected, actual, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal), message);
}
public static void AreNotEqual<T>(T notExpected, T actual, string message)
{
Xunit.Assert.False(notExpected.Equals(actual), message);
}
public static void AreNotEqual<T>(T notExpected, T actual)
{
Xunit.Assert.NotEqual(notExpected, actual);
}
public static void IsTrue(bool condition, string message)
{
Xunit.Assert.True(condition, message);
}
public static void IsTrue(bool condition)
{
Xunit.Assert.True(condition);
}
public static void Fail(string message)
{
Xunit.Assert.True(false, message);
}
}
} | 31.294872 | 152 | 0.542401 | [
"MIT"
] | fearthecowboy/xunit-vstest-shim | src/Xunit.Microsoft.VisualStudio.TestTools.UnitTesting/Assert.cs | 2,441 | C# |
namespace Chapter02.Examples.SOLID.BreakingD
{
public class Reader
{
public virtual string Read(string filePath)
{
// implementation how to read file contents
// complex logic
return "";
}
}
}
| 20.461538 | 55 | 0.552632 | [
"MIT"
] | PacktWorkshops/The-C-Sharp-Workshop | Chapter02/Examples/SOLID/BreakingD/Reader.cs | 268 | C# |
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
namespace Laison.Lapis.Identity.Application.Contracts
{
public interface IProfileAppService : IApplicationService
{
Task<ProfileDto> GetAsync();
Task<ProfileDto> UpdateAsync(UpdateProfileDto input);
Task ChangePasswordAsync(ChangePasswordInput input);
}
} | 25.857143 | 61 | 0.748619 | [
"MIT"
] | zwcm2007/Lapis.Framework | Laison.Lapis.Identity/src/Laison.Lapis.Identity.Application.Contracts/Profile/IProfileAppService.cs | 364 | C# |
using Amazon.DynamoDBv2.DocumentModel;
using Amazon.DynamoDBv2.Model;
using Amazon.Lambda.Core;
using Amazon.Lambda.DynamoDBEvents;
using Amazon.SQS;
using Amazon.SQS.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace ServerlessPizza.Router
{
public class Function
{
// Credentials, region are pulled from instance information
private AmazonSQSClient _client = new AmazonSQSClient();
public void FunctionHandler(DynamoDBEvent dynamoEvent, ILambdaContext context)
{
Console.WriteLine($"Incoming Event: {JsonConvert.SerializeObject(dynamoEvent)}");
// Process records and send SQS messages asynchronously
IEnumerable<Task<SendMessageResponse>> tasks = dynamoEvent.Records.Select(r => ProcessRecord(r));
// Wait for everything to finish, then exit
Task.WhenAll(tasks).Wait();
}
private Task<SendMessageResponse> ProcessRecord(DynamoDBEvent.DynamodbStreamRecord record)
{
string json = Document.FromAttributeMap(record.Dynamodb.NewImage).ToJson();
List<AttributeValue> events;
// Be prepared for anomalous records
try
{
events = record.Dynamodb.NewImage["events"].L;
}
catch (Exception)
{
Console.WriteLine($"Invalid record schema: {json}");
return default;
}
// If there aren't any events yet, send the order to Prep
if (events.Count == 0)
{
return SendSQSMessage("serverless-pizza-prep", json);
}
// Get the type (sequence number) of an event
int getEventType(AttributeValue e)
{
try
{
string type = e.M["type"].S;
switch (type)
{
case "Prep":
return 1;
case "Cook":
return 2;
case "Finish":
return 3;
case "Delivery":
return 4;
default:
return 0;
}
}
catch (Exception)
{
return 0;
}
}
// List items in a DynamoDB record are not sorted; find the event with the largest type number
var lastEvent = events.OrderBy(e => getEventType(e)).Last();
// If the event is still in progress, don't send a message
if (!lastEvent.M.ContainsKey("end"))
{
return default;
}
// Using early return enhances readability and keeps this switch statement at a reasonable level of indentation
switch (getEventType(lastEvent))
{
case 1: // Prep
return SendSQSMessage("serverless-pizza-cook", json);
case 2: // Cook
return SendSQSMessage("serverless-pizza-finish", json);
case 3: // Finish
return SendSQSMessage("serverless-pizza-deliver", json);
case 4: // Delivery
Console.WriteLine("Order delivered, nothing more to do.");
return default;
default:
Console.WriteLine($"Unknown event: {JsonConvert.SerializeObject(lastEvent)}");
return default;
}
}
private Task<SendMessageResponse> SendSQSMessage(string functionName, string payload)
{
Console.WriteLine($"Sending message to '{functionName}' queue");
// Environment variable set in Lambda console
string prefix = Environment.GetEnvironmentVariable("SqsUrlPrefix");
string url = prefix + functionName;
SendMessageRequest request = new SendMessageRequest(url, payload);
return _client.SendMessageAsync(request);
}
}
} | 36.68595 | 123 | 0.545168 | [
"MIT"
] | qccoders/serverless-pizza | src/router/Function.cs | 4,439 | C# |
using System;
public class Product
{
private string name;
private decimal cost;
public Product(string name, decimal cost)
{
this.Name = name;
this.Cost = cost;
}
public string Name
{
get { return this.name; }
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException("Name cannot be empty");
}
this.name = value;
}
}
public decimal Cost
{
get { return this.cost; }
set
{
if (value < 0)
{
throw new ArgumentException("Money cannot be negative");
}
this.cost = value;
}
}
}
| 17.666667 | 72 | 0.462264 | [
"MIT"
] | maio246/CSharp-OOP-Basic | E04. Shopping Spree/Product.cs | 744 | C# |
namespace CloudRoboticsDefTool
{
partial class EditAppMasterForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.updateButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.createButton = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.textBoxStorageKey = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.textBoxStorageAccount = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.textBoxAppId = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.textBoxAppInfoDevice = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.comboBoxStatus = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.textBoxDesc = new System.Windows.Forms.TextBox();
this.textBoxAppInfo = new System.Windows.Forms.TextBox();
this.groupBox2.SuspendLayout();
this.SuspendLayout();
//
// updateButton
//
this.updateButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.updateButton.Font = new System.Drawing.Font("Meiryo UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.updateButton.ForeColor = System.Drawing.SystemColors.ControlText;
this.updateButton.Location = new System.Drawing.Point(589, 802);
this.updateButton.Margin = new System.Windows.Forms.Padding(4);
this.updateButton.Name = "updateButton";
this.updateButton.Size = new System.Drawing.Size(154, 50);
this.updateButton.TabIndex = 9;
this.updateButton.Text = "Update";
this.updateButton.UseVisualStyleBackColor = true;
this.updateButton.Click += new System.EventHandler(this.updateButton_Click);
//
// cancelButton
//
this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.cancelButton.Font = new System.Drawing.Font("Meiryo UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.cancelButton.ForeColor = System.Drawing.SystemColors.ControlText;
this.cancelButton.Location = new System.Drawing.Point(791, 802);
this.cancelButton.Margin = new System.Windows.Forms.Padding(4);
this.cancelButton.Name = "cancelButton";
this.cancelButton.Size = new System.Drawing.Size(154, 50);
this.cancelButton.TabIndex = 10;
this.cancelButton.Text = "Cancel";
this.cancelButton.UseVisualStyleBackColor = true;
this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
//
// createButton
//
this.createButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.createButton.Font = new System.Drawing.Font("Meiryo UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.createButton.ForeColor = System.Drawing.SystemColors.ControlText;
this.createButton.Location = new System.Drawing.Point(386, 802);
this.createButton.Margin = new System.Windows.Forms.Padding(4);
this.createButton.Name = "createButton";
this.createButton.Size = new System.Drawing.Size(154, 50);
this.createButton.TabIndex = 8;
this.createButton.Text = "Create";
this.createButton.UseVisualStyleBackColor = true;
this.createButton.Click += new System.EventHandler(this.createButton_Click);
//
// groupBox2
//
this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox2.Controls.Add(this.textBoxStorageKey);
this.groupBox2.Controls.Add(this.label4);
this.groupBox2.Controls.Add(this.textBoxStorageAccount);
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Controls.Add(this.textBoxAppId);
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.Controls.Add(this.textBoxAppInfoDevice);
this.groupBox2.Controls.Add(this.label7);
this.groupBox2.Controls.Add(this.comboBoxStatus);
this.groupBox2.Controls.Add(this.label1);
this.groupBox2.Controls.Add(this.label5);
this.groupBox2.Controls.Add(this.label6);
this.groupBox2.Controls.Add(this.textBoxDesc);
this.groupBox2.Controls.Add(this.textBoxAppInfo);
this.groupBox2.Font = new System.Drawing.Font("Meiryo UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.groupBox2.ForeColor = System.Drawing.SystemColors.HotTrack;
this.groupBox2.Location = new System.Drawing.Point(13, 24);
this.groupBox2.Margin = new System.Windows.Forms.Padding(2, 4, 2, 4);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Padding = new System.Windows.Forms.Padding(2, 4, 2, 4);
this.groupBox2.Size = new System.Drawing.Size(1337, 752);
this.groupBox2.TabIndex = 43;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "RBFX App Master Table";
//
// textBoxStorageKey
//
this.textBoxStorageKey.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxStorageKey.ForeColor = System.Drawing.SystemColors.ControlText;
this.textBoxStorageKey.Location = new System.Drawing.Point(386, 144);
this.textBoxStorageKey.Margin = new System.Windows.Forms.Padding(7, 6, 7, 6);
this.textBoxStorageKey.Name = "textBoxStorageKey";
this.textBoxStorageKey.Size = new System.Drawing.Size(931, 38);
this.textBoxStorageKey.TabIndex = 2;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Meiryo UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label4.ForeColor = System.Drawing.SystemColors.ControlText;
this.label4.Location = new System.Drawing.Point(28, 96);
this.label4.Margin = new System.Windows.Forms.Padding(7, 0, 7, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(215, 30);
this.label4.TabIndex = 38;
this.label4.Text = "Storage Account:";
//
// textBoxStorageAccount
//
this.textBoxStorageAccount.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxStorageAccount.ForeColor = System.Drawing.SystemColors.ControlText;
this.textBoxStorageAccount.Location = new System.Drawing.Point(386, 94);
this.textBoxStorageAccount.Margin = new System.Windows.Forms.Padding(7, 6, 7, 6);
this.textBoxStorageAccount.Name = "textBoxStorageAccount";
this.textBoxStorageAccount.Size = new System.Drawing.Size(931, 38);
this.textBoxStorageAccount.TabIndex = 1;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Meiryo UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label3.ForeColor = System.Drawing.SystemColors.ControlText;
this.label3.Location = new System.Drawing.Point(28, 48);
this.label3.Margin = new System.Windows.Forms.Padding(7, 0, 7, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(105, 30);
this.label3.TabIndex = 33;
this.label3.Text = "App ID:";
//
// textBoxAppId
//
this.textBoxAppId.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxAppId.ForeColor = System.Drawing.SystemColors.ControlText;
this.textBoxAppId.Location = new System.Drawing.Point(386, 46);
this.textBoxAppId.Margin = new System.Windows.Forms.Padding(7, 6, 7, 6);
this.textBoxAppId.Name = "textBoxAppId";
this.textBoxAppId.Size = new System.Drawing.Size(931, 38);
this.textBoxAppId.TabIndex = 0;
//
// label2
//
this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Meiryo UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label2.ForeColor = System.Drawing.SystemColors.ControlText;
this.label2.Location = new System.Drawing.Point(28, 619);
this.label2.Margin = new System.Windows.Forms.Padding(7, 0, 7, 0);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(282, 30);
this.label2.TabIndex = 36;
this.label2.Text = "App Inof Device (Enc):";
//
// textBoxAppInfoDevice
//
this.textBoxAppInfoDevice.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxAppInfoDevice.ForeColor = System.Drawing.SystemColors.ControlText;
this.textBoxAppInfoDevice.Location = new System.Drawing.Point(386, 537);
this.textBoxAppInfoDevice.Margin = new System.Windows.Forms.Padding(7, 6, 7, 6);
this.textBoxAppInfoDevice.Multiline = true;
this.textBoxAppInfoDevice.Name = "textBoxAppInfoDevice";
this.textBoxAppInfoDevice.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxAppInfoDevice.Size = new System.Drawing.Size(931, 205);
this.textBoxAppInfoDevice.TabIndex = 7;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Font = new System.Drawing.Font("Meiryo UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label7.ForeColor = System.Drawing.SystemColors.ControlText;
this.label7.Location = new System.Drawing.Point(28, 268);
this.label7.Margin = new System.Windows.Forms.Padding(7, 0, 7, 0);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(154, 30);
this.label7.TabIndex = 33;
this.label7.Text = "Description:";
//
// comboBoxStatus
//
this.comboBoxStatus.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.comboBoxStatus.FormattingEnabled = true;
this.comboBoxStatus.Location = new System.Drawing.Point(386, 194);
this.comboBoxStatus.Margin = new System.Windows.Forms.Padding(2, 4, 2, 4);
this.comboBoxStatus.Name = "comboBoxStatus";
this.comboBoxStatus.Size = new System.Drawing.Size(931, 38);
this.comboBoxStatus.TabIndex = 3;
//
// label1
//
this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)));
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Meiryo UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label1.ForeColor = System.Drawing.SystemColors.ControlText;
this.label1.Location = new System.Drawing.Point(28, 424);
this.label1.Margin = new System.Windows.Forms.Padding(7, 0, 7, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(196, 30);
this.label1.TabIndex = 31;
this.label1.Text = "App Info (Enc):";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Meiryo UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label5.ForeColor = System.Drawing.SystemColors.ControlText;
this.label5.Location = new System.Drawing.Point(28, 196);
this.label5.Margin = new System.Windows.Forms.Padding(7, 0, 7, 0);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(97, 30);
this.label5.TabIndex = 30;
this.label5.Text = "Status:";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("Meiryo UI", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128)));
this.label6.ForeColor = System.Drawing.SystemColors.ControlText;
this.label6.Location = new System.Drawing.Point(28, 148);
this.label6.Margin = new System.Windows.Forms.Padding(7, 0, 7, 0);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(237, 30);
this.label6.TabIndex = 29;
this.label6.Text = "Storage Key (Enc):";
//
// textBoxDesc
//
this.textBoxDesc.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxDesc.ForeColor = System.Drawing.SystemColors.ControlText;
this.textBoxDesc.Location = new System.Drawing.Point(386, 244);
this.textBoxDesc.Margin = new System.Windows.Forms.Padding(7, 6, 7, 6);
this.textBoxDesc.Multiline = true;
this.textBoxDesc.Name = "textBoxDesc";
this.textBoxDesc.Size = new System.Drawing.Size(931, 88);
this.textBoxDesc.TabIndex = 4;
//
// textBoxAppInfo
//
this.textBoxAppInfo.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxAppInfo.ForeColor = System.Drawing.SystemColors.ControlText;
this.textBoxAppInfo.Location = new System.Drawing.Point(386, 344);
this.textBoxAppInfo.Margin = new System.Windows.Forms.Padding(7, 6, 7, 6);
this.textBoxAppInfo.Multiline = true;
this.textBoxAppInfo.Name = "textBoxAppInfo";
this.textBoxAppInfo.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.textBoxAppInfo.Size = new System.Drawing.Size(931, 181);
this.textBoxAppInfo.TabIndex = 5;
//
// EditAppMasterForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(13F, 24F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1354, 878);
this.Controls.Add(this.updateButton);
this.Controls.Add(this.cancelButton);
this.Controls.Add(this.createButton);
this.Controls.Add(this.groupBox2);
this.Margin = new System.Windows.Forms.Padding(2, 4, 2, 4);
this.Name = "EditAppMasterForm";
this.Text = "EditAppMasterForm";
this.Activated += new System.EventHandler(this.EditAppMasterForm_Activated);
this.Load += new System.EventHandler(this.EditAppMasterForm_Load);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button updateButton;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button createButton;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox textBoxStorageAccount;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textBoxAppId;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBoxAppInfoDevice;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.ComboBox comboBoxStatus;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox textBoxDesc;
private System.Windows.Forms.TextBox textBoxAppInfo;
private System.Windows.Forms.TextBox textBoxStorageKey;
}
} | 58.346269 | 169 | 0.629541 | [
"MIT"
] | seijim/cloud-robotics-azure-platform-v1-sdk | CloudRoboticsDefTool/CloudRoboticsDefTool/editAppMasterForm.Designer.cs | 19,548 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace TMDbApiDom.Dto.Movies
{
public class MovieExternalID
{
public string imdb_id { get; set; }
public string facebook_id { get; set; }
public string instagram_id { get; set; }
public string twitter_id { get; set; }
public int id { get; set; }
}
}
| 23.375 | 48 | 0.636364 | [
"MIT"
] | kiritodom53/TMDBApiDom | TMDbApiDom/Dto/Movies/MovieExternalID.cs | 376 | C# |
using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using Discord;
using Fclp;
using Fclp.Internals.Extensions;
using SkillBot.Utilities;
namespace SkillBot.Commands {
class UpdatePrices : ICommand {
public string GetCommandName()
{
return "update_prices";
}
public object ParseCommand(string[] args)
{
FluentCommandLineParser parser = new FluentCommandLineParser();
Arguments a = new Arguments();
string help;
parser.Setup<int?>('t', "take")
.SetDefault(null)
.Callback(take => a.Take = take);
parser.Setup<int>('s', "skip")
.SetDefault(0)
.Callback(skip => a.Skip = skip);
var result = parser.Parse(args);
help = HelpFormatter.GetHelpForCommand(parser);
// Showing mistakes and proper command usage
if (result.HasErrors) {
return $"{result.ErrorText}\r\n" +
$"Command Usage:\r\n" +
$"{help}";
}
// Showing help
if (result.HelpCalled) {
return $"Command Usage:\r\n{help}";
}
return a;
}
#pragma warning disable CS4014
public async void Handle(object args, MessageEventArgs e)
{
Arguments a = (Arguments) args;
Message m = await e.Channel.SendMessage("`Updating item prices...`");
Console.WriteLine("Updating items...");
DevelopmentEntities db = new DevelopmentEntities();
var items = a.Take == null ? db.Items : db.Items.Take(a.Take.Value).OrderBy(i => i.ItemId).Skip(a.Skip);
int count = items.Count() - 1;
// Rapidly updating items
items.ForEach(item =>
{
Item i = Runescape.GetItemInfo(item.ItemId, true).Result;
// Checking if response was successful
if (i != null)
item.Price = i.Price;
// Telling user there was an error and continuing
else
{
e.Channel.SendMessage($"`Error updating item \"{item.Name}\"`");
}
count--;
// Saving if all items have been updated
if (count <= 0)
{
m.Edit("`Updating item prices... Done.`");
}
else
{
Console.Write($"\r{count} items remaining.");
}
});
db.SaveChanges();
db.Dispose();
}
private struct Arguments
{
public int? Take { get; set; }
public int Skip { get; set; }
}
}
}
| 28.92 | 116 | 0.482711 | [
"Unlicense",
"MIT"
] | duke605/SkillBot | SkillBot/Commands/UpdatePrices.cs | 2,894 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using UniRx;
namespace Xamarin.Forms.Platform.Unity
{
public class EditorRenderer : ViewRenderer<Editor, UnityEngine.UI.InputField>
{
/*-----------------------------------------------------------------*/
#region Field
TextTracker _componentText;
#endregion
/*-----------------------------------------------------------------*/
#region MonoBehavior
protected override void Awake()
{
base.Awake();
var inputField = Control;
if (inputField != null)
{
inputField.lineType = UnityEngine.UI.InputField.LineType.MultiLineNewline;
inputField.OnValueChangedAsObservable()
.BlockReenter()
.Subscribe(value =>
{
var element = Element;
if (element != null)
{
element.Text = value;
}
}).AddTo(inputField);
_componentText = new TextTracker(inputField.textComponent);
}
}
#endregion
/*-----------------------------------------------------------------*/
#region Event Handler
protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
//_isInitiallyDefault = Element.IsDefault();
UpdateText();
UpdateTextColor();
UpdateFont();
}
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == Editor.TextProperty.PropertyName)
{
UpdateText();
}
else if (e.PropertyName == Editor.TextColorProperty.PropertyName)
{
UpdateTextColor();
}
else if (e.PropertyName == Editor.FontSizeProperty.PropertyName ||
e.PropertyName == Editor.FontAttributesProperty.PropertyName)
{
UpdateFont();
}
base.OnElementPropertyChanged(sender, e);
}
#endregion
/*-----------------------------------------------------------------*/
#region Internals
void UpdateText()
{
var inputField = Control;
if (inputField != null)
{
inputField.text = Element.Text;
}
}
void UpdateTextColor()
{
_componentText.UpdateTextColor(Element.TextColor);
}
void UpdateFont()
{
_componentText.UpdateFont(Element);
}
#endregion
}
}
| 20.482759 | 93 | 0.59638 | [
"MIT"
] | aosoft/Xamarin.Forms.Unity | Assets/Xamarin.Forms.Unity/Xamarin.Forms.Platform.Unity/Scripts/Renderers/EditorRenderer.cs | 2,378 | C# |
namespace Gastromio.Notification.Smtp
{
public class SmtpEmailConfiguration
{
public string ServerName { get; set; }
public int Port { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
} | 22.307692 | 46 | 0.572414 | [
"MIT"
] | marartz/FoodOrderSystem | src/Gastromio.Notification.Smtp/SmtpEmailConfiguration.cs | 292 | C# |
using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Description;
namespace Assimalign.Insights.Emails.Bindings
{
[Binding]
[ConnectionProvider(typeof(StorageAccountAttribute))]
[AttributeUsage(AttributeTargets.ReturnValue | AttributeTargets.Parameter)]
public class BlobAccessorAttribute : Attribute, IConnectionProvider
{
public BlobAccessorAttribute() { }
public BlobAccessorAttribute(bool ensureExists) => EnsureExists = ensureExists;
public BlobAccessorAttribute(string container, bool ensureExists = false)
{
Container = container;
EnsureExists = ensureExists;
}
public string Container { get; set; }
public string UseContainer { get; set; }
public bool EnsureExists { get; set; } = false;
public string Connection { get; set; }
}
}
| 27 | 87 | 0.686869 | [
"Apache-2.0"
] | Assimalign-LLC/asal-erp | src/web/domains/generic/Assimalign.Insights/Assimalign.Insights.Emails/Bindings/BlobAccessorAttribute.cs | 893 | C# |
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Wexflow.DotnetCore.Tests
{
[TestClass]
public class Wait
{
[TestInitialize]
public void TestInitialize()
{
}
[TestCleanup]
public void TestCleanup()
{
}
[TestMethod]
public void WaitTest()
{
Stopwatch stopwatch = Stopwatch.StartNew();
Helper.StartWorkflow(41);
stopwatch.Stop();
Assert.IsTrue(stopwatch.ElapsedMilliseconds > 30000);
}
}
}
| 21.344828 | 66 | 0.541195 | [
"MIT"
] | mohammad-matini/wexflow | tests/dotnet-core/Wexflow.DotnetCore.Tests/Wait.cs | 621 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Code.Grid;
using Code.Models;
using UnityEngine;
namespace Code.Helpers
{
/// <summary>
/// Contains methods for pathfinding
/// </summary>
public static class PathfindingHelper
{
//The cost of movement through difficult terrain
private static readonly Dictionary<TerrainType, int> TerrainMoveCost = new Dictionary<TerrainType, int>()
{
{ TerrainType.Normal,1 },
{ TerrainType.Difficult,4 }
};
/// <summary>
/// Calculates asynchronously the unit's pathfinding data for all its moves
/// </summary>
public static async Task<List<TilePathfindingData>> CalculateUnitAvailablePathsAsync(Vector3 unitPosition, GridTile[,] tileGrid)
{
var selectedTile = tileGrid[(int)unitPosition.x, (int)unitPosition.y];
#if UNITY_WEBGL && !UNITY_EDITOR
var unitPathfindingData = PathfindingHelper.CalculatePathfindingForAvailableMoves(tileGrid, selectedTile, selectedTile.CurrentUnit.Movement);
#else
var unitPathfindingData = await Task.Run(() => CalculatePathfindingForAvailableMoves(tileGrid, selectedTile, selectedTile.CurrentUnit.Movement));
#endif
return unitPathfindingData;
}
/// <summary>
/// Takes a tile's pathfinding data, and calculates the adjacent tiles' pathfinding data
/// </summary>
private static IEnumerable<TilePathfindingData> CalculateAdjacentTilePathfindingData(GridTile[,] tileGrid,TilePathfindingData sourceTilePathfindingData, IReadOnlyCollection<TilePathfindingData> analyzedTiles)
{
return (from adjacentTile in tileGrid.GetAdjacentGridTiles(sourceTilePathfindingData.DestinationGridTile)
where (adjacentTile.TerrainType != TerrainType.Impassable &&
(ReferenceEquals(adjacentTile.CurrentUnit, null) ||
adjacentTile.CurrentUnit.Faction != UnitFaction.Monster)) && analyzedTiles.All(x => x.DestinationGridTile != adjacentTile)
let tileMoveCost = sourceTilePathfindingData.MoveCost + TerrainMoveCost[adjacentTile.TerrainType]
select new TilePathfindingData(adjacentTile, sourceTilePathfindingData, tileMoveCost, 0)).ToList();
}
/// <summary>
/// Calculates and returns the tilePathfindingData of every available move for the selected unit in the grid, using Dijkstra pathfinding algorithm
/// </summary>
private static List<TilePathfindingData> CalculatePathfindingForAvailableMoves(GridTile[,] tileGrid, GridTile startingGridTile, int moveCount)
{
var remainingTilesToAnalyze = new List<TilePathfindingData>();
var analyzedTiles = new List<TilePathfindingData>();
//pathfindingData for the starting tile
var startingTilePathfindingData = new TilePathfindingData(startingGridTile,null,0,0);
remainingTilesToAnalyze.Add(startingTilePathfindingData);
//We check the adjacent tiles of the first tile in remainingTilesToAnalyze, then we remove that tile from the list and then we order the list by totalTilePathCost
do
{
var tileToAnalyze = remainingTilesToAnalyze[0];
var adjacentTilesPathfindingData = CalculateAdjacentTilePathfindingData(tileGrid, tileToAnalyze, analyzedTiles);
foreach (var tilePathfindingData in adjacentTilesPathfindingData)
{
var existingTilePathfindingData = remainingTilesToAnalyze.FirstOrDefault(x => x.DestinationGridTile == tilePathfindingData.DestinationGridTile);
//If we find a faster way to get to a tile that is already on the remainingTilesToAnalyze, we replace it with the new pathfinding data
if (existingTilePathfindingData != null && existingTilePathfindingData.MoveCost > tilePathfindingData.MoveCost)
{
remainingTilesToAnalyze.Remove(existingTilePathfindingData);
remainingTilesToAnalyze.Add(tilePathfindingData);
}
//if the destinationTile is not on the remainingTilesToAnalyze list, we add it
else if (existingTilePathfindingData == null)
{
remainingTilesToAnalyze.Add(tilePathfindingData);
}
}
analyzedTiles.Add(tileToAnalyze);
remainingTilesToAnalyze.Remove(tileToAnalyze);
remainingTilesToAnalyze = remainingTilesToAnalyze.OrderBy(x => x.TotalTilePathCost).ToList();
} while (remainingTilesToAnalyze.Any(x => x.MoveCost <= moveCount)); //we stop the pathfinding when all our moves cost more than the unit's movementSpeed
return analyzedTiles;
}
/// <summary>
/// Returns a list with the fastest tile path a unit can take to reach the selected tile
/// </summary>
public static IEnumerable<GridTile> GetPathToTile(IEnumerable<TilePathfindingData> pathfindingList, GridTile selectedGridTile)
{
var tileCursorInPathfindingList = pathfindingList.FirstOrDefault(x => x.DestinationGridTile == selectedGridTile); //the first tileCursor is our goal selectedTile
if (tileCursorInPathfindingList == null)
{
return null;
}
//We resolve the tilePath, going backwards from the destination TilePathfindingData, until we reach the start
var tilePath = new List<TilePathfindingData>();
do
{
tilePath.Add(tileCursorInPathfindingList);
tileCursorInPathfindingList = tileCursorInPathfindingList.ClosestSourceTilePathfindingData;
} while (tileCursorInPathfindingList != null);
tilePath.Reverse();
return tilePath.Select(x=>x.DestinationGridTile);
}
}
}
| 55.342342 | 216 | 0.664659 | [
"MIT"
] | gspentzas1991/Knight-Dudes | Assets/Code/Helpers/PathfindingHelper.cs | 6,145 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SFA.DAS.Encoding;
using SFA.DAS.Reservations.Application.Employers.Queries.GetLegalEntities;
using SFA.DAS.Reservations.Application.Exceptions;
using SFA.DAS.Reservations.Application.FundingRules.Commands.MarkRuleAsRead;
using SFA.DAS.Reservations.Application.FundingRules.Queries.GetAccountFundingRules;
using SFA.DAS.Reservations.Application.FundingRules.Queries.GetNextUnreadGlobalFundingRule;
using SFA.DAS.Reservations.Application.Reservations.Commands.CacheReservationCourse;
using SFA.DAS.Reservations.Application.Reservations.Commands.CacheReservationEmployer;
using SFA.DAS.Reservations.Application.Reservations.Queries.GetCachedReservation;
using SFA.DAS.Reservations.Application.Reservations.Queries.GetCourses;
using SFA.DAS.Reservations.Domain.Employers;
using SFA.DAS.Reservations.Domain.Interfaces;
using SFA.DAS.Reservations.Domain.Rules;
using SFA.DAS.Reservations.Domain.Rules.Api;
using SFA.DAS.Reservations.Infrastructure.Configuration;
using SFA.DAS.Reservations.Infrastructure.Exceptions;
using SFA.DAS.Reservations.Web.Filters;
using SFA.DAS.Reservations.Web.Infrastructure;
using SFA.DAS.Reservations.Web.Models;
namespace SFA.DAS.Reservations.Web.Controllers
{
[Authorize(Policy = nameof(PolicyNames.HasEmployerAccount))]
[ServiceFilter(typeof(LevyNotPermittedFilter))]
[Route("accounts/{employerAccountId}/reservations", Name = RouteNames.EmployerIndex)]
public class EmployerReservationsController : Controller
{
private readonly IMediator _mediator;
private readonly IEncodingService _encodingService;
private readonly IExternalUrlHelper _urlHelper;
private readonly ILogger<EmployerReservationsController> _logger;
private readonly ReservationsWebConfiguration _config;
public EmployerReservationsController(
IMediator mediator,
IEncodingService encodingService,
IOptions<ReservationsWebConfiguration> options,
IExternalUrlHelper urlHelper,
ILogger<EmployerReservationsController> logger)
{
_mediator = mediator;
_encodingService = encodingService;
_urlHelper = urlHelper;
_logger = logger;
_config = options.Value;
}
// GET
[ServiceFilter(typeof(NonEoiNotPermittedFilterAttribute))]
public async Task<IActionResult> Index()
{
var userAccountIdClaim = User.Claims.First(c => c.Type.Equals(EmployerClaims.IdamsUserIdClaimTypeIdentifier));
var response = await _mediator.Send(new GetNextUnreadGlobalFundingRuleQuery{Id = userAccountIdClaim.Value});
var nextGlobalRuleId = response?.Rule?.Id;
var nextGlobalRuleStartDate = response?.Rule?.ActiveFrom;
if (!nextGlobalRuleId.HasValue || nextGlobalRuleId.Value == 0|| !nextGlobalRuleStartDate.HasValue)
{
return RedirectToAction("Start", RouteData?.Values);
}
var viewModel = new FundingRestrictionNotificationViewModel
{
RuleId = nextGlobalRuleId.Value,
TypeOfRule = RuleType.GlobalRule,
RestrictionStartDate = nextGlobalRuleStartDate.Value,
BackLink = _config.EmployerDashboardUrl
};
return View("FundingRestrictionNotification", viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("saveRuleNotificationChoice",Name = RouteNames.EmployerSaveRuleNotificationChoice)]
public async Task<IActionResult> SaveRuleNotificationChoice(long ruleId, RuleType typeOfRule, bool markRuleAsRead)
{
if(!markRuleAsRead)
{
return RedirectToRoute(RouteNames.EmployerStart);
}
var userAccountIdClaim = HttpContext.User.Claims.First(c => c.Type.Equals(EmployerClaims.IdamsUserIdClaimTypeIdentifier));
var userId = userAccountIdClaim.Value;
var command = new MarkRuleAsReadCommand
{
Id = userId,
RuleId = ruleId,
TypeOfRule = typeOfRule
};
await _mediator.Send(command);
return RedirectToRoute(RouteNames.EmployerStart);
}
[HttpGet]
[Route("start",Name = RouteNames.EmployerStart)]
public async Task<IActionResult> Start(ReservationsRouteModel routeModel)
{
try
{
var viewModel = new EmployerStartViewModel
{
FindApprenticeshipTrainingUrl = _config.FindApprenticeshipTrainingUrl,
ApprenticeshipFundingRulesUrl = _config.ApprenticeshipFundingRulesUrl
};
var accountId = _encodingService.Decode(routeModel.EmployerAccountId, EncodingType.AccountId);
var response = await _mediator.Send(new GetAccountFundingRulesQuery{ AccountId = accountId});
var activeGlobalRuleType = response?.ActiveRule;
if (activeGlobalRuleType == null)
{
return View("Index", viewModel);
}
switch (activeGlobalRuleType)
{
case GlobalRuleType.FundingPaused:
return View("EmployerFundingPaused");
case GlobalRuleType.ReservationLimit:
return View("ReservationLimitReached", GenerateLimitReachedBackLink(routeModel));
default:
return View("Index", viewModel);
}
}
catch (ValidationException e)
{
_logger.LogInformation(e, e.Message);
return RedirectToRoute(RouteNames.Error500);
}
}
[HttpGet]
[Route("select-legal-entity/{id?}", Name = RouteNames.EmployerSelectLegalEntity)]
public async Task<IActionResult> SelectLegalEntity(ReservationsRouteModel routeModel)
{
try
{
GetCachedReservationResult cachedResponse = null;
if (routeModel.Id.HasValue)
{
cachedResponse = await _mediator.Send(new GetCachedReservationQuery {Id = routeModel.Id.Value});
}
var legalEntitiesResponse = await _mediator.Send(new GetLegalEntitiesQuery { AccountId = _encodingService.Decode(routeModel.EmployerAccountId, EncodingType.AccountId) });
if (legalEntitiesResponse.AccountLegalEntities.Count() == 1)
{
var accountLegalEntity = legalEntitiesResponse.AccountLegalEntities.First();
await CacheReservation(routeModel, accountLegalEntity, true);
return RedirectToRoute(RouteNames.EmployerSelectCourse, routeModel);
}
var viewModel = new SelectLegalEntityViewModel(routeModel, legalEntitiesResponse.AccountLegalEntities, cachedResponse?.AccountLegalEntityPublicHashedId);
return View("SelectLegalEntity", viewModel);
}
catch (ReservationLimitReachedException)
{
return View("ReservationLimitReached", GenerateLimitReachedBackLink(routeModel));
}
catch (GlobalReservationRuleException)
{
return View("EmployerFundingPaused");
}
catch (Exception e)
{
_logger.LogError(e, e.Message);
return RedirectToRoute(RouteNames.Error500);
}
}
private async Task CacheReservation(ReservationsRouteModel routeModel, AccountLegalEntity accountLegalEntity, bool employerHasSingleLegalEntity = false)
{
var reservationId = routeModel.Id ?? Guid.NewGuid();
await _mediator.Send(new CacheReservationEmployerCommand
{
Id = reservationId,
AccountId = accountLegalEntity.AccountId,
AccountLegalEntityId = accountLegalEntity.AccountLegalEntityId,
AccountLegalEntityName = accountLegalEntity.AccountLegalEntityName,
AccountLegalEntityPublicHashedId = accountLegalEntity.AccountLegalEntityPublicHashedId,
EmployerHasSingleLegalEntity = employerHasSingleLegalEntity
});
routeModel.Id = reservationId;
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("select-legal-entity/{id?}", Name = RouteNames.EmployerSelectLegalEntity)]
public async Task<IActionResult> PostSelectLegalEntity(ReservationsRouteModel routeModel, ConfirmLegalEntityViewModel viewModel)
{
try
{
if (!ModelState.IsValid)
{
var legalEntitiesResponse = await _mediator.Send(new GetLegalEntitiesQuery { AccountId = _encodingService.Decode(routeModel.EmployerAccountId, EncodingType.AccountId) });
var requestViewModel = new SelectLegalEntityViewModel(routeModel, legalEntitiesResponse.AccountLegalEntities, viewModel.LegalEntity);
return View("SelectLegalEntity", requestViewModel);
}
var decodedAccountId = _encodingService.Decode(routeModel.EmployerAccountId, EncodingType.AccountId);
var response = await _mediator.Send(new GetLegalEntitiesQuery {AccountId = decodedAccountId });
var selectedAccountLegalEntity = response.AccountLegalEntities.Single(model =>
model.AccountLegalEntityPublicHashedId == viewModel.LegalEntity);
await CacheReservation(routeModel, selectedAccountLegalEntity);
return RedirectToRoute(RouteNames.EmployerSelectCourse, routeModel);
}
catch (ValidationException e)
{
foreach (var member in e.ValidationResult.MemberNames)
{
ModelState.AddModelError(member.Split('|')[0], member.Split('|')[1]);
}
var legalEntitiesResponse = await _mediator.Send(new GetLegalEntitiesQuery { AccountId = _encodingService.Decode(routeModel.EmployerAccountId, EncodingType.AccountId) });
var requestViewModel = new SelectLegalEntityViewModel(routeModel, legalEntitiesResponse.AccountLegalEntities, viewModel.LegalEntity);
return View("SelectLegalEntity", requestViewModel);
}
catch (ReservationLimitReachedException)
{
return View("ReservationLimitReached", GenerateLimitReachedBackLink(routeModel));
}
}
[HttpGet]
[Route("{id}/select-course",Name = RouteNames.EmployerSelectCourse)]
public async Task<IActionResult> SelectCourse(ReservationsRouteModel routeModel)
{
var viewModel = await BuildEmployerSelectCourseViewModel(routeModel, routeModel.FromReview);
if (viewModel == null)
{
return View("Index");
}
return View("SelectCourse",viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
[Route("{id}/select-course", Name = RouteNames.EmployerSelectCourse)]
public async Task<IActionResult> PostSelectCourse(ReservationsRouteModel routeModel, PostSelectCourseViewModel postViewModel)
{
if (!ModelState.IsValid)
{
var viewModel = await BuildEmployerSelectCourseViewModel(routeModel, postViewModel.ApprenticeTrainingKnown);
if (viewModel == null)
{
return View("Index");
}
return View("SelectCourse",viewModel);
}
if (postViewModel.ApprenticeTrainingKnown == false)
{
return RedirectToRoute(RouteNames.EmployerCourseGuidance, routeModel);
}
try
{
await _mediator.Send(new CacheReservationCourseCommand
{
Id = routeModel.Id.Value,
SelectedCourseId = postViewModel.SelectedCourseId
});
return RedirectToRoute(RouteNames.EmployerApprenticeshipTraining, new ReservationsRouteModel
{
Id = routeModel.Id,
EmployerAccountId = routeModel.EmployerAccountId,
CohortReference = routeModel.CohortReference
});
}
catch (ValidationException e)
{
foreach (var member in e.ValidationResult.MemberNames)
{
ModelState.AddModelError(member.Split('|')[0], member.Split('|')[1]);
}
var viewModel = await BuildEmployerSelectCourseViewModel(routeModel, postViewModel.ApprenticeTrainingKnown, true);
return View("SelectCourse", viewModel);
}
catch (CachedReservationNotFoundException)
{
throw new ArgumentException("Reservation not found", nameof(routeModel.Id));
}
}
[HttpGet]
[Route("{id}/course-guidance", Name = RouteNames.EmployerCourseGuidance)]
public IActionResult CourseGuidance(ReservationsRouteModel routeModel)
{
var model = new CourseGuidanceViewModel
{
DashboardUrl = _urlHelper.GenerateDashboardUrl(routeModel.EmployerAccountId),
BackRouteName = RouteNames.EmployerSelectCourse,
ProviderPermissionsUrl = _urlHelper.GenerateUrl(new UrlParameters
{
SubDomain = "permissions",
Controller = "providers",
Id = routeModel.EmployerAccountId,
Folder = "accounts"
}),
FindApprenticeshipTrainingUrl = _config.FindApprenticeshipTrainingUrl
};
return View("CourseGuidance", model);
}
private async Task<EmployerSelectCourseViewModel> BuildEmployerSelectCourseViewModel(
ReservationsRouteModel routeModel,
bool? apprenticeTrainingKnownOrFromReview,
bool failedValidation = false)
{
var cachedReservation = await _mediator.Send(new GetCachedReservationQuery { Id = routeModel.Id.Value });
if (cachedReservation == null)
{
return null;
}
var getCoursesResponse = await _mediator.Send(new GetCoursesQuery());
var courseViewModels = getCoursesResponse.Courses.Select(course => new CourseViewModel(course, failedValidation? null : cachedReservation.CourseId));
var viewModel = new EmployerSelectCourseViewModel
{
ReservationId = routeModel.Id.Value,
Courses = courseViewModels,
BackLink = GenerateBackLink(routeModel, cachedReservation),
CohortReference = cachedReservation.CohortRef,
ApprenticeTrainingKnown = !string.IsNullOrEmpty(cachedReservation.CourseId) ? true : apprenticeTrainingKnownOrFromReview,
IsEmptyCohortFromSelect = cachedReservation.IsEmptyCohortFromSelect
};
return viewModel;
}
private string GenerateBackLink(ReservationsRouteModel routeModel, GetCachedReservationResult result)
{
if (!string.IsNullOrEmpty(result.CohortRef) || result.IsEmptyCohortFromSelect)
{
return _urlHelper.GenerateCohortDetailsUrl(result.UkPrn, routeModel.EmployerAccountId, result.CohortRef, result.IsEmptyCohortFromSelect);
}
if (routeModel.FromReview.HasValue && routeModel.FromReview.Value)
return RouteNames.EmployerReview;
if (result.EmployerHasSingleLegalEntity)
return RouteNames.EmployerStart;
return RouteNames.EmployerSelectLegalEntity;
}
private string GenerateLimitReachedBackLink(ReservationsRouteModel routeModel)
{
if (!string.IsNullOrEmpty(routeModel.CohortReference))
{
return _urlHelper.GenerateCohortDetailsUrl(null, routeModel.EmployerAccountId, routeModel.CohortReference);
}
return Url.RouteUrl(RouteNames.EmployerManage, routeModel);
}
}
}
| 42.848101 | 190 | 0.635746 | [
"MIT"
] | FeatureToggleStudy/das-reservations | src/SFA.DAS.Reservations.Web/Controllers/EmployerReservationsController.cs | 16,927 | C# |
namespace VAdvantage.Model
{
/** Generated Model - DO NOT CHANGE */
using System;
using System.Text;
using VAdvantage.DataBase;
using VAdvantage.Common;
using VAdvantage.Classes;
using VAdvantage.Process;
using VAdvantage.Model;
using VAdvantage.Utility;
using System.Data;
/** Generated Model for CM_Subscribe
* @author Jagmohan Bhatt (generated)
* @version Vienna Framework 1.1.1 - $Id$ */
public class X_CM_Subscribe : PO
{
public X_CM_Subscribe (Context ctx, int CM_Subscribe_ID, Trx trxName) : base (ctx, CM_Subscribe_ID, trxName)
{
/** if (CM_Subscribe_ID == 0)
{
SetCM_Subscribe_ID (0);
}
*/
}
public X_CM_Subscribe (Ctx ctx, int CM_Subscribe_ID, Trx trxName) : base (ctx, CM_Subscribe_ID, trxName)
{
/** if (CM_Subscribe_ID == 0)
{
SetCM_Subscribe_ID (0);
}
*/
}
/** Load Constructor
@param ctx context
@param rs result set
@param trxName transaction
*/
public X_CM_Subscribe (Context ctx, DataRow rs, Trx trxName) : base(ctx, rs, trxName)
{
}
/** Load Constructor
@param ctx context
@param rs result set
@param trxName transaction
*/
public X_CM_Subscribe (Ctx ctx, DataRow rs, Trx trxName) : base(ctx, rs, trxName)
{
}
/** Load Constructor
@param ctx context
@param rs result set
@param trxName transaction
*/
public X_CM_Subscribe (Ctx ctx, IDataReader dr, Trx trxName) : base(ctx, dr, trxName)
{
}
/** Static Constructor
Set Table ID By Table Name
added by ->Harwinder */
static X_CM_Subscribe()
{
Table_ID = Get_Table_ID(Table_Name);
model = new KeyNamePair(Table_ID,Table_Name);
}
/** Serial Version No */
//static long serialVersionUID 27687125081137L;
/** Last Updated Timestamp 2014-07-10 7:12:44 PM */
public static long updatedMS = 1404999764348L;
/** AD_Table_ID=1000239 */
public static int Table_ID;
// =1000239;
/** TableName=CM_Subscribe */
public static String Table_Name="CM_Subscribe";
protected static KeyNamePair model;
protected Decimal accessLevel = new Decimal(7);
/** AccessLevel
@return 7 - System - Client - Org
*/
protected override int Get_AccessLevel()
{
return Convert.ToInt32(accessLevel.ToString());
}
/** Load Meta Data
@param ctx context
@return PO Info
*/
protected override POInfo InitPO (Ctx ctx)
{
POInfo poi = POInfo.GetPOInfo (ctx, Table_ID);
return poi;
}
/** Load Meta Data
@param ctx context
@return PO Info
*/
protected override POInfo InitPO(Context ctx)
{
POInfo poi = POInfo.GetPOInfo (ctx, Table_ID);
return poi;
}
/** Info
@return info
*/
public override String ToString()
{
StringBuilder sb = new StringBuilder ("X_CM_Subscribe[").Append(Get_ID()).Append("]");
return sb.ToString();
}
/** Set Table.
@param AD_Table_ID Database Table information */
public void SetAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID <= 0) Set_Value ("AD_Table_ID", null);
else
Set_Value ("AD_Table_ID", AD_Table_ID);
}
/** Get Table.
@return Database Table information */
public int GetAD_Table_ID()
{
Object ii = Get_Value("AD_Table_ID");
if (ii == null) return 0;
return Convert.ToInt32(ii);
}
/** Set User/Contact.
@param AD_User_ID User within the system - Internal or Customer/Prospect Contact. */
public void SetAD_User_ID (int AD_User_ID)
{
if (AD_User_ID <= 0) Set_Value ("AD_User_ID", null);
else
Set_Value ("AD_User_ID", AD_User_ID);
}
/** Get User/Contact.
@return User within the system - Internal or Customer/Prospect Contact. */
public int GetAD_User_ID()
{
Object ii = Get_Value("AD_User_ID");
if (ii == null) return 0;
return Convert.ToInt32(ii);
}
/** Set Window.
@param AD_Window_ID Data entry or display window */
public void SetAD_Window_ID (int AD_Window_ID)
{
if (AD_Window_ID <= 0) Set_Value ("AD_Window_ID", null);
else
Set_Value ("AD_Window_ID", AD_Window_ID);
}
/** Get Window.
@return Data entry or display window */
public int GetAD_Window_ID()
{
Object ii = Get_Value("AD_Window_ID");
if (ii == null) return 0;
return Convert.ToInt32(ii);
}
/** Set CM_Subscribe_ID.
@param CM_Subscribe_ID CM_Subscribe_ID */
public void SetCM_Subscribe_ID (int CM_Subscribe_ID)
{
if (CM_Subscribe_ID < 1) throw new ArgumentException ("CM_Subscribe_ID is mandatory.");
Set_ValueNoCheck ("CM_Subscribe_ID", CM_Subscribe_ID);
}
/** Get CM_Subscribe_ID.
@return CM_Subscribe_ID */
public int GetCM_Subscribe_ID()
{
Object ii = Get_Value("CM_Subscribe_ID");
if (ii == null) return 0;
return Convert.ToInt32(ii);
}
/** Set Export.
@param Export_ID Export */
public void SetExport_ID (String Export_ID)
{
if (Export_ID != null && Export_ID.Length > 50)
{
log.Warning("Length > 50 - truncated");
Export_ID = Export_ID.Substring(0,50);
}
Set_ValueNoCheck ("Export_ID", Export_ID);
}
/** Get Export.
@return Export */
public String GetExport_ID()
{
return (String)Get_Value("Export_ID");
}
/** Set Record ID.
@param Record_ID Direct internal record ID */
public void SetRecord_ID (int Record_ID)
{
if (Record_ID <= 0) Set_Value ("Record_ID", null);
else
Set_Value ("Record_ID", Record_ID);
}
/** Get Record ID.
@return Direct internal record ID */
public int GetRecord_ID()
{
Object ii = Get_Value("Record_ID");
if (ii == null) return 0;
return Convert.ToInt32(ii);
}
}
}
| 23.783019 | 108 | 0.733241 | [
"Apache-2.0"
] | AsimKhan2019/ERP-CMR-DMS | ViennaAdvantageWeb/ModelLibrary/ModelAD/X_CM_Subscribe.cs | 5,042 | C# |
/*
Written by Peter O. in 2013.
Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/
If you like this, you should donate to Peter O.
at: http://peteroupc.github.io/
*/
using System;
namespace PeterO.Numbers {
internal static class BigNumberFlags {
internal const int FlagNegative = 1;
internal const int FlagQuietNaN = 4;
internal const int FlagSignalingNaN = 8;
internal const int FlagInfinity = 2;
internal const int FlagSpecial = FlagQuietNaN | FlagSignalingNaN |
FlagInfinity;
internal const int FlagNaN = FlagQuietNaN | FlagSignalingNaN;
internal const int UnderflowFlags = EContext.FlagInexact |
EContext.FlagSubnormal | EContext.FlagUnderflow | EContext.FlagRounded;
internal const int LostDigitsFlags = EContext.FlagLostDigits |
EContext.FlagInexact | EContext.FlagRounded;
internal const int FiniteOnly = 0;
internal const int FiniteAndNonFinite = 1;
}
}
| 32.366667 | 75 | 0.748713 | [
"MIT"
] | gebogebogebo/WebAuthnModokiDesktop | Source/WebAuthnModokiDesktop/WebAuthnModokiDesktop/OSS/Numbers/BigNumberFlags.cs | 971 | 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 Evran_Barkod.Properties
{
/// <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 Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <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 ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Evran_Barkod.Properties.Resources", typeof(Resources).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;
}
}
}
}
| 38.625 | 178 | 0.60338 | [
"MIT"
] | furkanevran/Evran-Barkod | Evran Barkod/Properties/Resources.Designer.cs | 2,783 | C# |
using System;
namespace Milvasoft.Helpers.DataAccess.EfCore.Attributes;
/// <summary>
/// Specifies that the value field value should be encrypted.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MilvaEncryptedAttribute : Attribute
{
}
| 25.416667 | 85 | 0.777049 | [
"MIT"
] | Milvasoft/Milvasoft | Milvasoft.Helpers/DataAccess/EfCore/Attributes/MilvaEncryptedAttribute.cs | 307 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.linkedmall.Model.V20180116;
namespace Aliyun.Acs.linkedmall.Transform.V20180116
{
public class NotifyPayOrderStatusResponseUnmarshaller
{
public static NotifyPayOrderStatusResponse Unmarshall(UnmarshallerContext context)
{
NotifyPayOrderStatusResponse notifyPayOrderStatusResponse = new NotifyPayOrderStatusResponse();
notifyPayOrderStatusResponse.HttpResponse = context.HttpResponse;
notifyPayOrderStatusResponse.Code = context.StringValue("NotifyPayOrderStatus.Code");
notifyPayOrderStatusResponse.Message = context.StringValue("NotifyPayOrderStatus.Message");
return notifyPayOrderStatusResponse;
}
}
}
| 38.585366 | 99 | 0.770544 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-linkedmall/Linkedmall/Transform/V20180116/NotifyPayOrderStatusResponseUnmarshaller.cs | 1,582 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.PowerBI.Api.Models
{
using Newtonsoft.Json;
/// <summary>
/// Defines values for DatasourceUserAccessRight.
/// </summary>
/// <summary>
/// Determine base value for a given allowed value if exists, else return
/// the value itself
/// </summary>
[JsonConverter(typeof(DatasourceUserAccessRightConverter))]
public struct DatasourceUserAccessRight : System.IEquatable<DatasourceUserAccessRight>
{
private DatasourceUserAccessRight(string underlyingValue)
{
UnderlyingValue=underlyingValue;
}
/// <summary>
/// No permission to access the data source. Only applies when updating
/// user permissions.
/// </summary>
public static readonly DatasourceUserAccessRight None = "None";
/// <summary>
/// Datasets owned by the user have read access to the data source
/// </summary>
public static readonly DatasourceUserAccessRight Read = "Read";
/// <summary>
/// The user can override the effective identity for Power BI Embedded
/// </summary>
public static readonly DatasourceUserAccessRight ReadOverrideEffectiveIdentity = "ReadOverrideEffectiveIdentity";
/// <summary>
/// Underlying value of enum DatasourceUserAccessRight
/// </summary>
private readonly string UnderlyingValue;
/// <summary>
/// Returns string representation for DatasourceUserAccessRight
/// </summary>
public override string ToString()
{
return UnderlyingValue.ToString();
}
/// <summary>
/// Compares enums of type DatasourceUserAccessRight
/// </summary>
public bool Equals(DatasourceUserAccessRight e)
{
return UnderlyingValue.Equals(e.UnderlyingValue);
}
/// <summary>
/// Implicit operator to convert string to DatasourceUserAccessRight
/// </summary>
public static implicit operator DatasourceUserAccessRight(string value)
{
return new DatasourceUserAccessRight(value);
}
/// <summary>
/// Implicit operator to convert DatasourceUserAccessRight to string
/// </summary>
public static implicit operator string(DatasourceUserAccessRight e)
{
return e.UnderlyingValue;
}
/// <summary>
/// Overriding == operator for enum DatasourceUserAccessRight
/// </summary>
public static bool operator == (DatasourceUserAccessRight e1, DatasourceUserAccessRight e2)
{
return e2.Equals(e1);
}
/// <summary>
/// Overriding != operator for enum DatasourceUserAccessRight
/// </summary>
public static bool operator != (DatasourceUserAccessRight e1, DatasourceUserAccessRight e2)
{
return !e2.Equals(e1);
}
/// <summary>
/// Overrides Equals operator for DatasourceUserAccessRight
/// </summary>
public override bool Equals(object obj)
{
return obj is DatasourceUserAccessRight && Equals((DatasourceUserAccessRight)obj);
}
/// <summary>
/// Returns for hashCode DatasourceUserAccessRight
/// </summary>
public override int GetHashCode()
{
return UnderlyingValue.GetHashCode();
}
}
}
| 32.122807 | 121 | 0.61988 | [
"MIT"
] | DhyanRathore/PowerBI-CSharp | sdk/PowerBI.Api/Source/Models/DatasourceUserAccessRight.cs | 3,662 | 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.Runtime.InteropServices;
internal static partial class Interop
{
internal static partial class UiaCore
{
/// <summary>
/// The interface representing containers that manage selection.
/// </summary>
/// <remarks>
/// Client code uses this public interface; server implementers implent the
/// ISelectionProvider public interface instead.
/// </remarks>
[ComImport]
[Guid("fb8b03af-3bdf-48d4-bd36-1a65793be168")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface ISelectionProvider
{
/// <summary>
/// Get the currently selected elements
/// </summary>
/// <returns>An AutomationElement array containing the currently selected elements</returns>
[return: MarshalAs(UnmanagedType.SafeArray, SafeArraySubType = VarEnum.VT_UNKNOWN)]
object[]? /* IRawElementProviderSimple */ GetSelection();
/// <summary>
/// Indicates whether the control allows more than one element to be selected
/// </summary>
/// <returns>Boolean indicating whether the control allows more than one element to be selected</returns>
/// <remarks>If this is false, then the control is a single-select ccntrol</remarks>
BOOL CanSelectMultiple { get; }
/// <summary>
/// Indicates whether the control requires at least one element to be selected
/// </summary>
/// <returns>Boolean indicating whether the control requires at least one element to be selected</returns>
/// <remarks>If this is false, then the control allows all elements to be unselected</remarks>
BOOL IsSelectionRequired { get; }
}
}
}
| 43.851064 | 118 | 0.63804 | [
"MIT"
] | Amy-Li03/winforms | src/System.Windows.Forms.Primitives/src/Interop/UiaCore/Interop.ISelectionProvider.cs | 2,063 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GameOfLife
{
public class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
| 21.857143 | 70 | 0.795207 | [
"Apache-2.0"
] | teo-mateo/GameOfLifeWPF | GameOfLife/ObservableObject.cs | 461 | C# |
using Akka.Actor;
using Akka.Event;
using Akka.Logger.Serilog;
namespace DaaSDemo.Provisioning.Actors
{
/// <summary>
/// The base class for Receive-style actors.
/// </summary>
public abstract class ReceiveActorEx
: ReceiveActor
{
/// <summary>
/// Create a new <see cref="ReceiveActorEx"/>.
/// </summary>
protected ReceiveActorEx()
{
}
/// <summary>
/// The actor's logging facility.
/// </summary>
protected ILoggingAdapter Log { get; } = Context.GetLogger(new SerilogLogMessageFormatter());
}
} | 25 | 101 | 0.5728 | [
"MIT"
] | DimensionDataResearch/daas-demo | src/DaaSDemo.Provisioning/Actors/ReceiveActorEx.cs | 625 | C# |
using UnityEngine;
using UnityEngine.UI;
namespace alexnown
{
[ExecuteInEditMode]
public class GradientTextureGenerator : MonoBehaviour
{
private const string DefaultShaderName = "Unlit/BlendWithRotatable";
public Gradient Gradient;
[Range(0, 360)]
public int Angle;
[Range(64, 2048)]
public int TextureWidth = 256;
public TextureWrapMode WrapMode = TextureWrapMode.Clamp;
[Header("Material settings")]
public string TextureFieldName = "_SecondTex";
public string AngleFieldName = "_AngleDeg";
[Header("Target graphic")]
public GameObject GraphicGo = null;
public bool CreateMaterialByShader = true;
public Shader TargetShader = null;
private Material _material;
public Texture2D GenerateTexture(int width)
{
var texture = new Texture2D(width, 1, TextureFormat.ARGB32, false);
texture.wrapMode = WrapMode;
for (int i = 0; i < width; i++)
{
var color = Gradient.Evaluate((float)i / width);
texture.SetPixel(i, 0, color);
}
texture.Apply(false);
return texture;
}
private void Start()
{
InitializeTargetMaterial();
UpdateMaterial();
}
private void InitializeTargetMaterial()
{
if (CreateMaterialByShader)
{
_material = new Material(TargetShader);
SetMaterialToTargetGo(GraphicGo, _material);
}
else
{
_material = GetMaterialFromGraphicGo(GraphicGo);
_material = Instantiate(_material);
SetMaterialToTargetGo(GraphicGo, _material);
}
}
private void UpdateMaterial()
{
if (_material == null) return;
_material.SetFloat(AngleFieldName, Angle);
_material.SetTexture(TextureFieldName, GenerateTexture(TextureWidth));
}
private Material GetMaterialFromGraphicGo(GameObject graphicGo)
{
if (graphicGo == null) return null;
var graphic = graphicGo.GetComponent<Graphic>();
if (graphic != null) return graphic.defaultMaterial;
var rend = graphicGo.GetComponent<Renderer>();
if (rend != null) return rend.sharedMaterial;
return null;
}
private void SetMaterialToTargetGo(GameObject graphicGo, Material mat)
{
if (graphicGo == null) return;
var graphic = graphicGo.GetComponent<Graphic>();
if (graphic != null) graphic.material = mat;
var rend = graphicGo.GetComponent<Renderer>();
if (rend != null) rend.material = mat;
}
#if UNITY_EDITOR
private void OnDestroy()
{
if (!Application.isPlaying && CreateMaterialByShader && _material != null)
{
SetMaterialToTargetGo(GraphicGo, null);
DestroyImmediate(_material);
}
}
protected void OnValidate()
{
if (GraphicGo == null)
{
if (gameObject.GetComponent<Graphic>() != null || gameObject.GetComponent<Renderer>() != null)
GraphicGo = gameObject;
}
if (CreateMaterialByShader && TargetShader == null)
TargetShader = Shader.Find(DefaultShaderName);
if (Gradient == null)
{
Gradient = new Gradient();
Gradient.SetKeys(new[]
{
new GradientColorKey(new Color32(36,145,214,255), 0),
new GradientColorKey(new Color32(36, 211,214,255), 1)
},
new[] { new GradientAlphaKey(1, 0), new GradientAlphaKey(1, 1) });
}
InitializeTargetMaterial();
UpdateMaterial();
}
#endif
}
} | 33.131148 | 110 | 0.549728 | [
"MIT"
] | alexnown/UI-Forge | Assets/Tools/Scripts/Gradient/GradientTextureGenerator.cs | 4,044 | C# |
using Microsoft.VisualStudio.Shared.VSCodeDebugProtocol.Messages;
using Neo.VM;
using NeoDebug.Models;
using NeoDebug.VariableContainers;
using NeoFx;
using NeoFx.Models;
using NeoFx.Storage;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
namespace NeoDebug
{
partial class InteropService : IInteropService
{
private readonly IBlockchainStorage? blockchain;
private readonly TriggerType trigger = TriggerType.Application;
private readonly EmulatedStorage storage;
private readonly WitnessChecker witnessChecker = null!;
private readonly Action<OutputEvent> sendOutput;
private readonly IReadOnlyDictionary<(UInt160, string), DebugInfo.Event> events;
private readonly Dictionary<uint, Func<ExecutionEngine, bool>> methods = new Dictionary<uint, Func<ExecutionEngine, bool>>();
private readonly Dictionary<uint, string> methodNames = new Dictionary<uint, string>();
public InteropService(IBlockchainStorage? blockchain, EmulatedStorage storage, TriggerType trigger, WitnessChecker witnessChecker, Action<OutputEvent> sendOutput,
IEnumerable<(UInt160 scriptHash, DebugInfo.Event info)> events)
{
this.sendOutput = sendOutput;
this.blockchain = blockchain;
this.storage = storage;
this.witnessChecker = witnessChecker;
this.trigger = trigger;
this.events = events.ToDictionary(t => (t.scriptHash, t.info.Name), t => t.info);
RegisterAccount(Register);
RegisterAsset(Register);
RegisterBlock(Register);
RegisterBlockchain(Register);
RegisterContract(Register);
RegisterEnumerator(Register);
RegisterExecutionEngine(Register);
RegisterHeader(Register);
RegisterRuntime(Register);
RegisterStorage(Register);
RegisterTransaction(Register);
}
public IVariableContainer GetStorageContainer(IVariableContainerSession session, in UInt160 scriptHash)
{
return new EmulatedStorageContainer(session, scriptHash, storage);
}
static readonly Regex storageRegex = new Regex(@"^\$storage\[([0-9a-fA-F]{8})\]\.(key|value)$");
private EvaluateResponse EvaluateStorageExpression(IVariableContainerSession session, ReadOnlyMemory<byte> memory, string? typeHint)
{
switch (typeHint)
{
case "Boolean":
return new EvaluateResponse()
{
Result = (new BigInteger(memory.Span) != BigInteger.Zero).ToString(),
Type = "#Boolean",
};
case "Integer":
return new EvaluateResponse()
{
Result = new BigInteger(memory.Span).ToString(),
Type = "#Integer",
};
case "String":
return new EvaluateResponse()
{
Result = Encoding.UTF8.GetString(memory.Span),
Type = "#String",
};
default:
case "HexString":
return new EvaluateResponse()
{
Result = new BigInteger(memory.Span).ToHexString(),
Type = "#ByteArray"
};
case "ByteArray":
{
var variable = ByteArrayContainer.Create(session, memory, string.Empty, true);
return new EvaluateResponse()
{
Result = variable.Value,
VariablesReference = variable.VariablesReference,
Type = variable.Type,
};
}
}
}
public EvaluateResponse EvaluateStorageExpression(IVariableContainerSession session, in UInt160 scriptHash, EvaluateArguments args)
{
bool TryFindStorage(int keyHash, in UInt160 _scriptHash, out (ReadOnlyMemory<byte> key, StorageItem item) value)
{
foreach (var (key, item) in storage.EnumerateStorage(_scriptHash))
{
if (key.Span.GetSequenceHashCode() == keyHash)
{
value = (key, item);
return true;
}
}
value = default;
return false;
}
var (typeHint, index, name) = DebugSession.ParseEvalExpression(args.Expression);
var match = storageRegex.Match(name);
if (!index.HasValue && match.Success
&& int.TryParse(match.Groups[1].Value, NumberStyles.HexNumber, null, out var keyHash)
&& TryFindStorage(keyHash, scriptHash, out var _storage))
{
switch (match.Groups[2].Value)
{
case "key":
return EvaluateStorageExpression(session, _storage.key, typeHint);
case "value":
return EvaluateStorageExpression(session, _storage.item.Value, typeHint);
}
}
return DebugAdapter.FailedEvaluation;
}
protected void Register(string methodName, Func<ExecutionEngine, bool> handler, int price)
{
if (!HashHelpers.TryInteropMethodHash(methodName, out var value))
{
throw new ArgumentException(nameof(methodName));
}
methods.Add(value, handler);
methodNames.Add(value, methodName);
}
public string GetMethodName(uint methodHash)
=> methodNames.GetValueOrDefault(methodHash, string.Empty)!;
bool IInteropService.Invoke(byte[] method, ExecutionEngine engine)
{
static bool TryInteropMethodHash(Span<byte> method, out uint value)
{
if (method.Length == 4)
{
value = BitConverter.ToUInt32(method);
return true;
}
return HashHelpers.TryInteropMethodHash(method, out value);
}
if (TryInteropMethodHash(method, out var hash)
&& methods.TryGetValue(hash, out var func))
{
try
{
return func(engine);
}
catch (Exception ex)
{
var methodHex = new BigInteger(method).ToHexString();
sendOutput(new OutputEvent()
{
Category = OutputEvent.CategoryValue.Stderr,
Output = $"Exception in {methodHex} method: {ex}\n",
});
}
}
else
{
var methodHex = new BigInteger(method).ToHexString();
sendOutput(new OutputEvent()
{
Category = OutputEvent.CategoryValue.Stderr,
Output = $"Invalid interop method {methodHex}\n",
});
}
return false;
}
}
} | 38.612245 | 170 | 0.536866 | [
"MIT"
] | Anzimator1/neo-debugger | src/adapter2/InteropServices/InteropService.cs | 7,570 | C# |
using UnityEngine;
namespace kleberswf.tools.miniprofiler
{
#if UNITY_5
[HelpURL("http://kleber-swf.com/docs/mini-profiler/#framerate-value-provider")]
#endif
public class FramerateValueProvider : AbstractValueProvider
{
private int _frameCount;
private float _dt;
private float _fps;
public override void Refresh(float readInterval)
{
if (readInterval < Time.unscaledDeltaTime)
{
_fps = 1f / Time.unscaledDeltaTime;
return;
}
_frameCount++;
_dt += Time.unscaledDeltaTime;
if (_dt < 1f * readInterval) return;
_fps = _frameCount / _dt;
_frameCount = 0;
_dt -= 1f * readInterval;
}
public override float Value { get { return _fps; } }
}
} | 27.419355 | 80 | 0.571765 | [
"MIT"
] | IllusionMods/HSPlugins | UsefulStuff.Core/MiniProfiler/FramerateValueProvider.cs | 852 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Xaml.Interactions.Core
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using Windows.UI.Xaml;
using Microsoft.Xaml.Interactivity;
/// <summary>
/// An action that calls a method on a specified object when invoked.
/// </summary>
public sealed partial class CallMethodAction : DependencyObject, IAction
{
/// <summary>
/// Identifies the <seealso cref="MethodName"/> dependency property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly DependencyProperty MethodNameProperty = DependencyProperty.Register(
"MethodName",
typeof(string),
typeof(CallMethodAction),
new PropertyMetadata(null, new PropertyChangedCallback(CallMethodAction.OnMethodNameChanged)));
/// <summary>
/// Identifies the <seealso cref="TargetObject"/> dependency property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly DependencyProperty TargetObjectProperty = DependencyProperty.Register(
"TargetObject",
typeof(object),
typeof(CallMethodAction),
new PropertyMetadata(null, new PropertyChangedCallback(CallMethodAction.OnTargetObjectChanged)));
private Type _targetObjectType;
private List<MethodDescriptor> _methodDescriptors = new List<MethodDescriptor>();
private MethodDescriptor _cachedMethodDescriptor;
/// <summary>
/// Gets or sets the name of the method to invoke. This is a dependency property.
/// </summary>
public string MethodName
{
get
{
return (string)this.GetValue(CallMethodAction.MethodNameProperty);
}
set
{
this.SetValue(CallMethodAction.MethodNameProperty, value);
}
}
/// <summary>
/// Gets or sets the object that exposes the method of interest. This is a dependency property.
/// </summary>
public object TargetObject
{
get
{
return this.GetValue(CallMethodAction.TargetObjectProperty);
}
set
{
this.SetValue(CallMethodAction.TargetObjectProperty, value);
}
}
/// <summary>
/// Executes the action.
/// </summary>
/// <param name="sender">The <see cref="System.Object"/> that is passed to the action by the behavior. Generally this is <seealso cref="Microsoft.Xaml.Interactivity.IBehavior.AssociatedObject"/> or a target object.</param>
/// <param name="parameter">The value of this parameter is determined by the caller.</param>
/// <returns>True if the method is called; else false.</returns>
public object Execute(object sender, object parameter)
{
object target;
if (this.ReadLocalValue(CallMethodAction.TargetObjectProperty) != DependencyProperty.UnsetValue)
{
target = this.TargetObject;
}
else
{
target = sender;
}
if (target == null || string.IsNullOrEmpty(this.MethodName))
{
return false;
}
this.UpdateTargetType(target.GetType());
MethodDescriptor methodDescriptor = this.FindBestMethod(parameter);
if (methodDescriptor == null)
{
if (this.TargetObject != null)
{
throw new ArgumentException(string.Format(
CultureInfo.CurrentCulture,
ResourceHelper.CallMethodActionValidMethodNotFoundExceptionMessage,
this.MethodName,
this._targetObjectType));
}
return false;
}
ParameterInfo[] parameters = methodDescriptor.Parameters;
if (parameters.Length == 0)
{
methodDescriptor.MethodInfo.Invoke(target, parameters: null);
return true;
}
else if (parameters.Length == 2)
{
methodDescriptor.MethodInfo.Invoke(target, new object[] { target, parameter });
return true;
}
return false;
}
private MethodDescriptor FindBestMethod(object parameter)
{
TypeInfo parameterTypeInfo = parameter == null ? null : parameter.GetType().GetTypeInfo();
if (parameterTypeInfo == null)
{
return this._cachedMethodDescriptor;
}
MethodDescriptor mostDerivedMethod = null;
// Loop over the methods looking for the one whose type is closest to the type of the given parameter.
foreach (MethodDescriptor currentMethod in this._methodDescriptors)
{
TypeInfo currentTypeInfo = currentMethod.SecondParameterTypeInfo;
if (currentTypeInfo.IsAssignableFrom(parameterTypeInfo))
{
if (mostDerivedMethod == null || !currentTypeInfo.IsAssignableFrom(mostDerivedMethod.SecondParameterTypeInfo))
{
mostDerivedMethod = currentMethod;
}
}
}
return mostDerivedMethod ?? this._cachedMethodDescriptor;
}
private void UpdateTargetType(Type newTargetType)
{
if (newTargetType == this._targetObjectType)
{
return;
}
this._targetObjectType = newTargetType;
this.UpdateMethodDescriptors();
}
private void UpdateMethodDescriptors()
{
this._methodDescriptors.Clear();
this._cachedMethodDescriptor = null;
if (string.IsNullOrEmpty(this.MethodName) || this._targetObjectType == null)
{
return;
}
// Find all public methods that match the given name and have either no parameters,
// or two parameters where the first is of type Object.
foreach (MethodInfo method in this._targetObjectType.GetRuntimeMethods())
{
if (string.Equals(method.Name, this.MethodName, StringComparison.Ordinal)
&& method.ReturnType == typeof(void)
&& method.IsPublic)
{
ParameterInfo[] parameters = method.GetParameters();
if (parameters.Length == 0)
{
// There can be only one parameterless method of the given name.
this._cachedMethodDescriptor = new MethodDescriptor(method, parameters);
}
else if (parameters.Length == 2 && parameters[0].ParameterType == typeof(object))
{
this._methodDescriptors.Add(new MethodDescriptor(method, parameters));
}
}
}
// We didn't find a parameterless method, so we want to find a method that accepts null
// as a second parameter, but if we have more than one of these it is ambigious which
// we should call, so we do nothing.
if (this._cachedMethodDescriptor == null)
{
foreach (MethodDescriptor method in this._methodDescriptors)
{
TypeInfo typeInfo = method.SecondParameterTypeInfo;
if (!typeInfo.IsValueType || (typeInfo.IsGenericType && typeInfo.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
if (this._cachedMethodDescriptor != null)
{
this._cachedMethodDescriptor = null;
return;
}
else
{
this._cachedMethodDescriptor = method;
}
}
}
}
}
private static void OnMethodNameChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
CallMethodAction callMethodAction = (CallMethodAction)sender;
callMethodAction.UpdateMethodDescriptors();
}
private static void OnTargetObjectChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
CallMethodAction callMethodAction = (CallMethodAction)sender;
Type newType = args.NewValue != null ? args.NewValue.GetType() : null;
callMethodAction.UpdateTargetType(newType);
}
[DebuggerDisplay("{MethodInfo}")]
private class MethodDescriptor
{
public MethodDescriptor(MethodInfo methodInfo, ParameterInfo[] methodParameters)
{
this.MethodInfo = methodInfo;
this.Parameters = methodParameters;
}
public MethodInfo MethodInfo
{
get;
private set;
}
public ParameterInfo[] Parameters
{
get;
private set;
}
public int ParameterCount
{
get
{
return this.Parameters.Length;
}
}
public TypeInfo SecondParameterTypeInfo
{
get
{
if (this.ParameterCount < 2)
{
return null;
}
return this.Parameters[1].ParameterType.GetTypeInfo();
}
}
}
}
}
| 36.890071 | 230 | 0.551668 | [
"MIT"
] | ajpinedam/Uno.XamlBehaviors | src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Core/CallMethodAction.cs | 10,405 | C# |
/* Copyright 2010-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MongoDB.Bson;
using MongoDB.Driver.Linq.Linq3Implementation.Ast.Visitors;
namespace MongoDB.Driver.Linq.Linq3Implementation.Ast.Filters
{
internal sealed class AstMatchesNothingFilter : AstFilter
{
public override AstNodeType NodeType => AstNodeType.MatchesNothingFilter;
public override AstNode Accept(AstNodeVisitor visitor)
{
return visitor.VisitMatchesNothingFilter(this);
}
public override BsonValue Render()
{
return new BsonDocument("_id", new BsonDocument("$type", -1));
}
}
}
| 32.555556 | 81 | 0.722696 | [
"Apache-2.0"
] | BorisDog/mongo-csharp-driver | src/MongoDB.Driver/Linq/Linq3Implementation/Ast/Filters/AstMatchesNothingFilter.cs | 1,174 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using HolisticWare.Ph4ct3x.Judo.Views;
namespace HolisticWare.Xamarin.Forms.Services
{
public partial class NavigationService
{
public async Task PushPageSearchJudo()
{
if (_navigationPage != null)
{
await _navigationPage?.PushAsync(new SearchJudoka());
}
}
private static NavigationService _instance = null;
public static NavigationService Instance
{
get
{
if (_instance == null)
{
_instance = new NavigationService();
}
return _instance;
}
}
private readonly NavigationPage _navigationPage;
private NavigationService()
{
_navigationPage = Application.Current.MainPage as NavigationPage;
}
}
}
| 22.355556 | 77 | 0.567594 | [
"MIT"
] | HolisticWare-Applications/Ph4ct3x | samples/playground/Judo/HolisticWare.Ph4ct3x.Judo.UI.MVVM.Shared/Services/NavigationService.cs | 1,008 | C# |
#pragma checksum "C:\Users\andre\Documents\ProgramasUniBrasil\3SM-ES\ProjetoDefinitivo\AlimentosMarfim4.0\Trabalho-Bonilha\AlimentosMarfim\Areas\Identity\Pages\Account\ResetPasswordConfirmation.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "9fa2ad01473fa832304d2166b6c6d5536eb62725"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_Identity_Pages_Account_ResetPasswordConfirmation), @"mvc.1.0.razor-page", @"/Areas/Identity/Pages/Account/ResetPasswordConfirmation.cshtml")]
namespace AspNetCore
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
#nullable restore
#line 1 "C:\Users\andre\Documents\ProgramasUniBrasil\3SM-ES\ProjetoDefinitivo\AlimentosMarfim4.0\Trabalho-Bonilha\AlimentosMarfim\Areas\Identity\Pages\_ViewImports.cshtml"
using Microsoft.AspNetCore.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\andre\Documents\ProgramasUniBrasil\3SM-ES\ProjetoDefinitivo\AlimentosMarfim4.0\Trabalho-Bonilha\AlimentosMarfim\Areas\Identity\Pages\_ViewImports.cshtml"
using AlimentosMarfim.Areas.Identity;
#line default
#line hidden
#nullable disable
#nullable restore
#line 3 "C:\Users\andre\Documents\ProgramasUniBrasil\3SM-ES\ProjetoDefinitivo\AlimentosMarfim4.0\Trabalho-Bonilha\AlimentosMarfim\Areas\Identity\Pages\_ViewImports.cshtml"
using AlimentosMarfim.Areas.Identity.Pages;
#line default
#line hidden
#nullable disable
#nullable restore
#line 1 "C:\Users\andre\Documents\ProgramasUniBrasil\3SM-ES\ProjetoDefinitivo\AlimentosMarfim4.0\Trabalho-Bonilha\AlimentosMarfim\Areas\Identity\Pages\Account\_ViewImports.cshtml"
using AlimentosMarfim.Areas.Identity.Pages.Account;
#line default
#line hidden
#nullable disable
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"9fa2ad01473fa832304d2166b6c6d5536eb62725", @"/Areas/Identity/Pages/Account/ResetPasswordConfirmation.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c5e35354cce216519f20ecacf6222af13a0950d8", @"/Areas/Identity/Pages/_ViewImports.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"a2c6be556475077cb1a34e43057e115bc8f1a025", @"/Areas/Identity/Pages/Account/_ViewImports.cshtml")]
public class Areas_Identity_Pages_Account_ResetPasswordConfirmation : global::Microsoft.AspNetCore.Mvc.RazorPages.Page
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page", "./Login", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
#pragma warning restore 0649
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager
{
get
{
if (__backed__tagHelperScopeManager == null)
{
__backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope);
}
return __backed__tagHelperScopeManager;
}
}
private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
#nullable restore
#line 3 "C:\Users\andre\Documents\ProgramasUniBrasil\3SM-ES\ProjetoDefinitivo\AlimentosMarfim4.0\Trabalho-Bonilha\AlimentosMarfim\Areas\Identity\Pages\Account\ResetPasswordConfirmation.cshtml"
ViewData["Title"] = "Reset password confirmation";
#line default
#line hidden
#nullable disable
WriteLiteral("\r\n<h1>");
#nullable restore
#line 7 "C:\Users\andre\Documents\ProgramasUniBrasil\3SM-ES\ProjetoDefinitivo\AlimentosMarfim4.0\Trabalho-Bonilha\AlimentosMarfim\Areas\Identity\Pages\Account\ResetPasswordConfirmation.cshtml"
Write(ViewData["Title"]);
#line default
#line hidden
#nullable disable
WriteLiteral("</h1>\r\n<p>\r\n Your password has been reset. Please ");
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "9fa2ad01473fa832304d2166b6c6d5536eb627255308", async() => {
WriteLiteral("click here to log in");
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Page = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
WriteLiteral(".\r\n</p>\r\n");
}
#pragma warning restore 1998
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; }
[global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute]
public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<ResetPasswordConfirmationModel> Html { get; private set; }
public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<ResetPasswordConfirmationModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<ResetPasswordConfirmationModel>)PageContext?.ViewData;
public ResetPasswordConfirmationModel Model => ViewData.Model;
}
}
#pragma warning restore 1591
| 62.162602 | 298 | 0.776354 | [
"Apache-2.0"
] | LuiizFellipe/AlimentosMarfim | obj/Debug/netcoreapp3.1/Razor/Areas/Identity/Pages/Account/ResetPasswordConfirmation.cshtml.g.cs | 7,646 | C# |
/*
The MIT License (MIT)
Copyright (c) 2007 - 2019 Microting A/S
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.
*/
namespace Microting.EformMonitoringBase.Infrastructure.Enums
{
public enum RuleType
{
Select = 1,
CheckBox,
Number
}
}
| 36.764706 | 78 | 0.7728 | [
"MIT"
] | Gid733/eform-monitoring-base | Microting.EformMonitoringBase/Infrastructure/Enums/RuleType.cs | 1,252 | C# |
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using JuryApp.Core.Models.Collections;
using JuryApp.Core.Services;
using JuryApp.Core.Services.Interfaces;
using JuryApp.Services;
namespace JuryApp.ViewModels
{
public class TeamsViewModel : ViewModelBase
{
private INavigationServiceEx _navigationService;
private readonly ITeamService _teamService;
public Teams Teams { get; set; } = new Teams();
public RelayCommand<int> EditTeamCommand => new RelayCommand<int>(NavigateToEditTeamPage);
public TeamsViewModel(ITeamService teamService, INavigationServiceEx navigationService)
{
_teamService = teamService;
_navigationService = navigationService;
FetchListOfTeams();
_navigationService.Navigated += NavigationService_Navigated;
}
private void NavigationService_Navigated(object sender, Windows.UI.Xaml.Navigation.NavigationEventArgs e)
{
FetchListOfTeams();
}
private void NavigateToEditTeamPage(int selectedIndex)
{
if (selectedIndex == -1) return;
Messenger.Default.Send(Teams[selectedIndex]);
_navigationService.Navigate(typeof(EditTeamViewModel).FullName);
}
private async void FetchListOfTeams()
{
var teams = await _teamService.GetAllTeams();
Teams.Clear();
foreach (var team in teams)
{
Teams.Add(team);
}
}
}
}
| 28.428571 | 113 | 0.653894 | [
"MIT"
] | JegorRysskin/boektquizt-jordydriesjegor_enterprisemobile | Frontend/JuryApp/JuryApp/ViewModels/TeamsViewModel.cs | 1,594 | 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.AzureNextGen.Network.V20190901.Outputs
{
[OutputType]
public sealed class VpnClientConnectionHealthResponse
{
/// <summary>
/// List of allocated ip addresses to the connected p2s vpn clients.
/// </summary>
public readonly ImmutableArray<string> AllocatedIpAddresses;
/// <summary>
/// Total of the Egress Bytes Transferred in this connection.
/// </summary>
public readonly double TotalEgressBytesTransferred;
/// <summary>
/// Total of the Ingress Bytes Transferred in this P2S Vpn connection.
/// </summary>
public readonly double TotalIngressBytesTransferred;
/// <summary>
/// The total of p2s vpn clients connected at this time to this P2SVpnGateway.
/// </summary>
public readonly int? VpnClientConnectionsCount;
[OutputConstructor]
private VpnClientConnectionHealthResponse(
ImmutableArray<string> allocatedIpAddresses,
double totalEgressBytesTransferred,
double totalIngressBytesTransferred,
int? vpnClientConnectionsCount)
{
AllocatedIpAddresses = allocatedIpAddresses;
TotalEgressBytesTransferred = totalEgressBytesTransferred;
TotalIngressBytesTransferred = totalIngressBytesTransferred;
VpnClientConnectionsCount = vpnClientConnectionsCount;
}
}
}
| 35.1 | 86 | 0.678632 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Network/V20190901/Outputs/VpnClientConnectionHealthResponse.cs | 1,755 | C# |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
singleton GuiControlProfile( MissionAreaEditorProfile )
{
canKeyFocus = true;
opaque = true;
fillColor = "192 192 192";
category = "Editor";
};
| 27.846154 | 79 | 0.38674 | [
"MIT"
] | AnteSim/Verve | Demos/VerveTutorialBase/game/tools/missionAreaEditor/missionAreaEditor.ed.cs | 362 | C# |
using System;
using JustConveyor.Contracts;
namespace JustConveyor
{
internal class SupplierInstance
{
public string Name { get; set; }
public ConveySupplierContract Supplier { get; set; }
public int SuppliedPackagesCount { get; set; }
public int ErrorsCount { get; set; }
public DateTime? Started { get; set; }
public double PackagesPerSec => Started == null
? 0
: Math.Round(SuppliedPackagesCount/
(DateTime.Now - Started.Value).TotalSeconds, 3);
public string State { get; set; }
}
} | 28.857143 | 73 | 0.605611 | [
"BSD-3-Clause"
] | vsk-insurance-company/JustConveyor | src/JustConveyor/SupplierInstance.cs | 606 | C# |
using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace THNETII.WebServices.WebDav.Sample.Pages
{
public class IndexModel : PageModel
{
[SuppressMessage("Performance", "CA1822: Mark members as static")]
public void OnGet()
{
}
}
}
| 19.625 | 74 | 0.671975 | [
"MIT"
] | thnetii/webservices | sample/THNETII.WebServices.WebDav.Sample/Pages/Index.cshtml.cs | 314 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;
namespace NHS111.Web.Helpers
{
public static class Versioning
{
private static string _version;
private static readonly ConcurrentDictionary<string, string> _fileHashes = new ConcurrentDictionary<string, string>();
public static IPathProvider _pathProvider = new ServerPathProvider();
public static IFileIO _fileIO = new FileIO();
private static readonly object Locker = new object();
public static string GetWebsiteVersion()
{
if (_version == null)
{
_version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
return _version;
}
public static string GetVersionedUriRef(string uri)
{
if (_fileHashes.ContainsKey(uri)) return _fileHashes[uri];
var hashvalue = GenerateChecksum(uri);
var versionedUriRef = _pathProvider.ToAbsolute(String.Format("{0}?{1}", uri, hashvalue));
if (!_fileHashes.TryAdd(uri, versionedUriRef)) GetVersionedUriRef(uri);
return versionedUriRef;
}
private static string GenerateChecksum(string uri)
{
lock (Locker)
{
using (var reader = _fileIO.OpenRead(_pathProvider.MapPath(uri)))
{
using (var sha1 = System.Security.Cryptography.SHA1.Create())
{
var hash = sha1.ComputeHash(reader);
var hashvalue = string.Join("", hash.Select(b => b.ToString("x2")).ToArray());
return hashvalue;
}
}
}
}
}
public interface IPathProvider
{
string MapPath(string path);
string ToAbsolute(string virtualPath);
}
public interface IFileIO
{
Stream OpenRead(string filePath);
}
public class ServerPathProvider : IPathProvider
{
public string MapPath(string path)
{
return HttpContext.Current.Server.MapPath(path);
}
public string ToAbsolute(string virtualPath)
{
return VirtualPathUtility.ToAbsolute(virtualPath);
}
}
public class FileIO : IFileIO
{
public Stream OpenRead(string filePath)
{
return File.OpenRead(filePath);
}
}
} | 27.924731 | 126 | 0.577975 | [
"Apache-2.0"
] | NHSChoices/nhs111-online | NHS111/NHS111.Web/Helpers/Versioning.cs | 2,599 | 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>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("Hasan Akpurum hakpurum@gmail.com")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyCopyrightAttribute("Hasan Akpurum 2019-2020")]
[assembly: System.Reflection.AssemblyDescriptionAttribute("Backround jobs and worker. http://yazilimcigunlug.com")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")]
[assembly: System.Reflection.AssemblyProductAttribute("Jobnium")]
[assembly: System.Reflection.AssemblyTitleAttribute("Jobnium")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
// Generated by the MSBuild WriteCodeFragment class.
| 46 | 115 | 0.67893 | [
"MIT"
] | hakpurum/Jobnium | Jobnium/Jobnium/obj/Debug/netcoreapp2.0/Jobnium.AssemblyInfo.cs | 1,196 | C# |
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Alamut.Data.Paging;
using Microsoft.EntityFrameworkCore;
namespace Alamut.Data.NoSql
{
public static class DynamicCriteriaPaginationExtensions
{
/// <summary>
/// Creates an <see cref="IPaginated{T}" /> instance from the specified query.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query">The query.</param>
/// <param name="criteria"></param>
/// <returns></returns>
public static IPaginated<T> ToPaginated<T>(this IQueryable<T> query, DynamicPaginatedCriteria criteria) =>
query.ApplyCriteria(criteria)
.ToPaginated(criteria as IPaginatedCriteria);
/// <summary>
/// Creates an <see cref="IPaginated{T}" /> instance from the specified query.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="query">The query.</param>
/// <param name="criteria"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public static async Task<IPaginated<T>> ToPaginatedAsync<T>(this IQueryable<T> query,
DynamicPaginatedCriteria criteria, CancellationToken cancellationToken) =>
await query.ApplyCriteria(criteria)
.ToPaginatedAsync(criteria as IPaginatedCriteria, cancellationToken);
}
} | 41.085714 | 114 | 0.634214 | [
"MIT"
] | SorenZ/Alamut.Data | src/Alamut.Data/NoSql/DynamicCriteriaPaginationExtensions.cs | 1,440 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace ASPNET4YOU.AzureKeyVault
{
public class SampleKeyWrapping
{
private readonly SampleKeyVault vault;
public SampleKeyWrapping(SampleKeyVault sampleKeyVault)
{
vault = sampleKeyVault;
}
public async Task TestKeyWrapping()
{
byte[] localKey = Random.GenerateRandomNumber(32);
// Encrypt our local key with Key Vault and Store it in the database
byte[] encryptedKey = await vault.EncryptAsync(vault.CustomerMasterKeyId, localKey);
// Get our encrypted key from the database and decrypt it with the Key Vault.
byte[] decryptedKey = await vault.DecryptAsync(vault.CustomerMasterKeyId, encryptedKey);
// Now we have recovered the key with the Key Vault we can encrypt with AES locally.
byte[] iv = Random.GenerateRandomNumber(16);
byte[] encryptedData = AesEncryption.Encrypt(Encoding.UTF8.GetBytes("MEGA TOP SECRET STUFF"), decryptedKey, iv);
byte[] decryptedMessage = AesEncryption.Decrypt(encryptedData, decryptedKey, iv);
var encryptedText = Convert.ToBase64String(encryptedData);
var decryptedData = Encoding.UTF8.GetString(decryptedMessage);
}
}
}
| 38.081081 | 125 | 0.659333 | [
"MIT"
] | aspnet4you/AzureKeyVault | AzureKeyVaultSamples/SampleKeyWrapping.cs | 1,411 | C# |
using System;
namespace NetlifySharp
{
public partial class NetlifyException : Exception
{
}
} | 13.5 | 53 | 0.694444 | [
"MIT"
] | daveaglick/NetlifySharp | src/NetlifySharp/NetlifyException.cs | 110 | C# |
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Xml;
using ConscriptDesigner.Control;
using ZeldaWpf.Util;
namespace ConscriptDesigner.Anchorables {
public class OutputConsole : RequestCloseAnchorable {
//-----------------------------------------------------------------------------
// Classes
//-----------------------------------------------------------------------------
/// <summary>A text writer to hijack the console output.</summary>
private class OutputTextWriter : TextWriter {
/// <summary>The output console to write to.</summary>
private OutputConsole console;
/// <summary>Constructs the console text writer.</summary>
public OutputTextWriter(OutputConsole console) {
this.console = console;
}
/// <summary>Gets the encoding.</summary>
public override Encoding Encoding {
get { return Encoding.UTF8; }
}
/// <summary>Write text to the console.</summary>
public override void Write(string value) {
console.Write(value);
}
/// <summary>Write a character to the console.</summary>
public override void Write(char value) {
console.Write(value);
}
}
//-----------------------------------------------------------------------------
// Constants
//-----------------------------------------------------------------------------
/// <summary>The maximum number of lines allowed in the console.</summary>
private const int MaxLines = 400;
//-----------------------------------------------------------------------------
// Members
//-----------------------------------------------------------------------------
/// <summary>The scroll viewer for displaying the console log.</summary>
private ScrollViewer scrollViewer;
/// <summary>The stack panel for each line of text.</summary>
private VirtualizingStackPanel stackPanel;
/// <summary>The buffer for the text to be added to the output console.</summary>
private string buffer;
/// <summary>True if the console should be cleared during flush.</summary>
private bool requestClear;
/// <summary>Used to prevent duplication or loss of console text.</summary>
private static readonly object myLock = new object();
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
/// <summary>Constructs the output console.</summary>
public OutputConsole() {
Border border = CreateBorder();
this.scrollViewer = new ScrollViewer();
this.scrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
this.scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
this.scrollViewer.Background = new SolidColorBrush(Color.FromRgb(230, 231, 232));
this.scrollViewer.FontFamily = new FontFamily("Lucida Console");
this.scrollViewer.FontSize = 11;
this.scrollViewer.CanContentScroll = true;
TextOptions.SetTextFormattingMode(this.scrollViewer, TextFormattingMode.Display);
border.Child = this.scrollViewer;
this.stackPanel = new VirtualizingStackPanel();
this.scrollViewer.Content = this.stackPanel;
buffer = "";
requestClear = false;
ContinuousEvents.Start(0.02, TimerPriority.High, UpdateTimer);
Closed += OnAnchorableClosed;
AppendLine("");
Console.SetOut(new OutputTextWriter(this));
Title = "Output Console";
Content = border;
}
//-----------------------------------------------------------------------------
// XML Serialization
//-----------------------------------------------------------------------------
public override void ReadXml(XmlReader reader) {
base.ReadXml(reader);
DesignerControl.MainWindow.OutputConsole = this;
}
//-----------------------------------------------------------------------------
// Overrides
//-----------------------------------------------------------------------------
/// <summary>Focuses on the anchorable's content.</summary>
public override void Focus() {
scrollViewer.Focus();
}
//-----------------------------------------------------------------------------
// Event Handlers
//-----------------------------------------------------------------------------
/// <summary>Flushes the buffer into the console log.</summary>
private void UpdateTimer() {
FlushBuffer();
}
/// <summary>Called when closing to re-establish the proper console output channel.</summary>
private void OnAnchorableClosed(object sender, EventArgs e) {
// Return console output to its rightful owner
var standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
}
//-----------------------------------------------------------------------------
// Console Output
//-----------------------------------------------------------------------------
/// <summary>Clears the console.</summary>
public void Clear() {
lock (myLock) {
requestClear = true;
buffer = "";
}
}
/// <summary>Creates a new line if the current line isn't empty.</summary>
public void NewLine() {
FlushBuffer();
TextBlock textBlock = (TextBlock) stackPanel.Children[stackPanel.Children.Count - 1];
if (textBlock.Text != "")
AppendLine("");
}
/// <summary>Write a line to the console.</summary>
public void WriteLine(string line) {
Write(line + "\n");
}
/// <summary>Write text to the console.</summary>
public void Write(string text) {
lock (myLock) {
buffer += text;
}
}
/// <summary>Write a character to the console.</summary>
public void Write(char c) {
lock (myLock) {
buffer += new string(c, 1);
}
}
//-----------------------------------------------------------------------------
// Internal Methods
//-----------------------------------------------------------------------------
/// <summary>Flushes the buffer into the console log.</summary>
private void FlushBuffer() {
lock (myLock) {
// Don't flush again until the previous flush is finished
if (!buffer.Any() && !requestClear)
return;
if (requestClear) {
stackPanel.Children.Clear();
AppendLine("");
requestClear = false;
}
if (buffer.Any()) {
string[] lines = buffer.Replace("\r", "").Split('\n');
AppendText(lines[0]);
for (int i = 1; i < lines.Length; i++) {
AppendLine(lines[i]);
}
scrollViewer.ScrollToBottom();
buffer = "";
}
}
}
/// <summary>Appends text to the last line in the stack panel.</summary>
private void AppendText(string text) {
TextBlock textBlock = (TextBlock) stackPanel.Children[stackPanel.Children.Count - 1];
textBlock.Text += text;
}
/// <summary>Appends a line to the stack panel.</summary>
private void AppendLine(string text) {
TextBlock textBlock = new TextBlock();
textBlock.Padding = new Thickness(10, 1, 0, 0);
textBlock.Text = text;
stackPanel.Children.Add(textBlock);
while (stackPanel.Children.Count > MaxLines) {
stackPanel.Children.RemoveAt(0);
}
}
}
}
| 31.502183 | 95 | 0.548517 | [
"MIT"
] | trigger-death/ZeldaOracle | ZeldaOracle/ConscriptDesigner/Anchorables/OutputConsole.cs | 7,216 | C# |
using System.Collections.Generic;
using System.Linq;
using IEnumerableCorrelater.Interfaces;
namespace IEnumerableCorrelater.CollectionWrappers
{
static class CollectionWrapperFactory
{
public static ICollectionWrapper<T> ToCollectionWrapper<T>(this IEnumerable<T> collection)
{
switch (collection)
{
case T[] array: return new ArrayCollectionWrapper<T>(array);
case IList<T> list: return new ListCollectionWrapper<T>(list);
case string s: return new StringCollectionWrapper<T>(s);
case ICollectionWrapper<T> collectionWrapper: return collectionWrapper;
default: return new ArrayCollectionWrapper<T>(collection.ToArray());
}
}
}
}
| 35.681818 | 98 | 0.657325 | [
"MIT"
] | ZviRosenfeld/IEnumerableCompare | IEnumerableCorrelater/CollectionWrappers/CollectionWrapperFactory.cs | 787 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MpNG
{
public enum TargetTypes
{
None,
Mp3,
Png
}
}
| 13.5 | 33 | 0.643519 | [
"MIT"
] | DarkIrata/MpNG | MpNG/TargetTypes.cs | 218 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Il codice è stato generato da uno strumento.
// Versione runtime:4.0.30319.42000
//
// Le modifiche apportate a questo file possono provocare un comportamento non corretto e andranno perse se
// il codice viene rigenerato.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Sismio.Properties {
using System;
/// <summary>
/// Classe di risorse fortemente tipizzata per la ricerca di stringhe localizzate e così via.
/// </summary>
// Questa classe è stata generata automaticamente dalla classe StronglyTypedResourceBuilder.
// tramite uno strumento quale ResGen o Visual Studio.
// Per aggiungere o rimuovere un membro, modificare il file con estensione ResX ed eseguire nuovamente ResGen
// con l'opzione /str oppure ricompilare il progetto VS.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Restituisce l'istanza di ResourceManager nella cache utilizzata da questa classe.
/// </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("Sismio.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Esegue l'override della proprietà CurrentUICulture del thread corrente per tutte le
/// ricerche di risorse eseguite utilizzando questa classe di risorse fortemente tipizzata.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.IO.UnmanagedMemoryStream simile a System.IO.MemoryStream.
/// </summary>
internal static System.IO.UnmanagedMemoryStream alarm {
get {
return ResourceManager.GetStream("alarm", resourceCulture);
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap baseline_dashboard_white_36dp {
get {
object obj = ResourceManager.GetObject("baseline_dashboard_white_36dp", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap baseline_dashboard_white_48dp {
get {
object obj = ResourceManager.GetObject("baseline_dashboard_white_48dp", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap baseline_delete_forever_white_48dp {
get {
object obj = ResourceManager.GetObject("baseline_delete_forever_white_48dp", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap baseline_exit_to_app_white_48dp {
get {
object obj = ResourceManager.GetObject("baseline_exit_to_app_white_48dp", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap baseline_history_white_48dp {
get {
object obj = ResourceManager.GetObject("baseline_history_white_48dp", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap baseline_people_white_48dp {
get {
object obj = ResourceManager.GetObject("baseline_people_white_48dp", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap baseline_search_white_24dp {
get {
object obj = ResourceManager.GetObject("baseline_search_white_24dp", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap baseline_settings_input_antenna_white_48dp {
get {
object obj = ResourceManager.GetObject("baseline_settings_input_antenna_white_48dp", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap btndelete {
get {
object obj = ResourceManager.GetObject("btndelete", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap logo {
get {
object obj = ResourceManager.GetObject("logo", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Byte[].
/// </summary>
internal static byte[] Roboto_Light {
get {
object obj = ResourceManager.GetObject("Roboto_Light", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Byte[].
/// </summary>
internal static byte[] RobotoMono_Bold {
get {
object obj = ResourceManager.GetObject("RobotoMono_Bold", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Cerca una risorsa localizzata di tipo System.Byte[].
/// </summary>
internal static byte[] RobotoMono_Light {
get {
object obj = ResourceManager.GetObject("RobotoMono_Light", resourceCulture);
return ((byte[])(obj));
}
}
}
}
| 41.369458 | 172 | 0.580853 | [
"MIT"
] | arabello/sismio | Sismio/Sismio/Properties/Resources.Designer.cs | 8,404 | C# |
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Fan.Data
{
/// <summary>
/// Sql implementation of the <see cref="IMetaRepository"/> contract.
/// </summary>
public class SqlMetaRepository : EntityRepository<Meta>, IMetaRepository
{
public SqlMetaRepository(FanDbContext db) : base(db)
{
}
/// <summary>
/// Returns a <see cref="Meta"/> by its key (case-sensitive) and type, returns null if it's not found.
/// </summary>
/// <param name="key">The caller should pass this key in proper casing.</param>
/// <param name="type">The <see cref="EMetaType"/> of the meta.</param>
/// <returns></returns>
/// <remarks>
/// A meta record is unique by combination of key and type.
/// </remarks>
public async Task<Meta> GetAsync(string key, EMetaType type) =>
await _entities.SingleOrDefaultAsync(m => m.Key == key && m.Type == type);
public async Task<List<Meta>> GetListAsync(EMetaType type) =>
await _entities.Where(m => m.Type == type).ToListAsync();
}
} | 34.771429 | 110 | 0.606409 | [
"Apache-2.0"
] | URIS-2021-2022/tim-5---fanray-tim-5-fanray | src/Core/Fan/Data/SqlMetaRepository.cs | 1,219 | C# |
/* Copyright 2015-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using MongoDB.Driver.Core.Misc;
namespace MongoDB.Driver.Linq.Expressions
{
internal sealed class OrderByExpression : ExtensionExpression, ISourcedExpression
{
private readonly Expression _source;
private readonly ReadOnlyCollection<OrderByClause> _clauses;
public OrderByExpression(Expression source, IEnumerable<OrderByClause> clauses)
{
_source = Ensure.IsNotNull(source, nameof(source));
_clauses = Ensure.IsNotNull(clauses, "clauses") as ReadOnlyCollection<OrderByClause>;
if (_clauses == null)
{
_clauses = new List<OrderByClause>(clauses).AsReadOnly();
}
}
public ReadOnlyCollection<OrderByClause> Clauses
{
get { return _clauses; }
}
public Expression Source
{
get { return _source; }
}
public override ExtensionExpressionType ExtensionType
{
get { return ExtensionExpressionType.OrderBy; }
}
public override string ToString()
{
var clauseStrings = string.Join(", ", _clauses.Select(c => c.ToString()));
return string.Format("{0}.OrderBy({1})", _source.ToString(), clauseStrings);
}
public OrderByExpression Update(Expression source, ReadOnlyCollection<OrderByClause> clauses)
{
if (source != _source ||
clauses != _clauses)
{
return new OrderByExpression(source, clauses);
}
return this;
}
protected internal override Expression Accept(ExtensionExpressionVisitor visitor)
{
return visitor.VisitOrderBy(this);
}
}
}
| 32.987013 | 102 | 0.628346 | [
"MIT"
] | naivetang/2019MiniGame22 | Server/ThirdParty/MongoDBDriver/MongoDB.Driver/Linq/Expressions/OrderByExpression.cs | 2,540 | C# |
using NLog;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ScanMonitorApp
{
public class DocTextAndDateExtractor
{
private static Logger logger = LogManager.GetCurrentClassLogger();
const int MATCH_FACTOR_BUMP_FOR_TEXT_MONTH = 10;
const int MATCH_FACTOR_BUMP_FOR_4_DIGIT_YEAR = 10;
const int MATCH_FACTOR_BUMP_FOR_TOP_40_PC_OF_PAGE = 10;
const int MATCH_FACTOR_BUMP_FOR_DAY_MISSING = -5;
const int MATCH_FACTOR_BUMP_FOR_PAGE1 = 30;
const int MATCH_FACTOR_BUMP_FOR_PAGE2 = 10;
const int MAX_TEXT_ELEMS_TO_JOIN = 10;
const int MAX_SEP_CHARS_BETWEEN_DATE_ELEMS = 4;
const int MATCH_FACTOR_BUMP_FOR_EARLIEST_DATE = 40;
const int MATCH_FACTOR_BUMP_FOR_LATEST_DATE = 40;
// TEST TEST
const bool TEST_AGAINST_OLD_DATE_ALGORITHM = false;
const string longDateRegex = @"(((0)[1-9])|((1|2)[0-9])|(3[0-1])|([1-9]))?(\s*?)([a-zA-Z\,\.]?[a-zA-Z\,\.]?)-?(\s*?)-?(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|January|February|March|April|May|June|July|August|September|October|November|December)[,-]?(\s*?)[,-]?(((19)?[89]\d)|((2\s*?0\s*?)?[012345l]\s*?[\dl]))([^,]|$)";
const string USlongDateRegex = @"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec|January|February|March|April|May|June|July|August|September|October|November|December)(\s*?)(1-\s*)?(((0)[1-9])|((1|2)[0-9])|(3[0-1])|([1-9]))(\s*?)([a-zA-Z]?[a-zA-Z]?),(\s*?)(((19)?[8|9]\d)|((20)?[0|1|2]\d))";
const string shortDateLeadingZeroesRegex = @"(0[1-9]|[12][0-9]|3[01])\s?[-/.]\s?(0[1-9]|1[012])\s?[-/.]\s?((19|20)?(\d\d))";
const string shortDateNoLeadingZeroesRegex = @"([1-9]|[12][0-9]|3[01])\s?[-/.]\s?([1-9]|1[012])\s?[-/.]\s?((19|20)?(\d\d))";
const string shortDateSpacesRegex = @"(0[1-9]|[12][0-9]|3[01])\s?(0[1-9]|1[012])\s?((19|20)(\d\d))";
private static Dictionary<string, int> monthDict = new Dictionary<string, int>
{
{ "jan", 1 }, { "feb", 2 }, { "mar", 3 }, { "apr", 4 },
{ "may", 5 }, { "jun", 6 }, { "jul", 7 }, { "aug", 8 },
{ "sep", 9 }, { "oct", 10 }, { "nov", 11 }, { "dec", 12 },
};
public static string[] shortMonthStrings = new string[]
{
"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"
};
public static string ExtractTextFromPage(ScanPages scanPages, DocRectangle docRect, int pageNum)
{
int pageIdx = pageNum-1;
if ((pageIdx < 0) || (pageIdx >= scanPages.scanPagesText.Count))
return "";
// Get page to search
List<ScanTextElem> scanPageText = scanPages.scanPagesText[pageNum-1];
// Iterate text elements
foreach (ScanTextElem textElem in scanPageText)
{
// Check rectangle bounds
if (!docRect.Intersects(textElem.bounds))
continue;
// Return first match
return textElem.text;
}
return "";
}
public static List<ExtractedDate> ExtractDatesFromDoc(ScanPages scanPages, string dateExpr, out int bestDateIdx)
{
bestDateIdx = 0;
List<ExtractedDate> datesResult = new List<ExtractedDate>();
if (scanPages == null)
return datesResult;
// Extract location rectangles from doctype
List<ExprParseTerm> parseTerms = DocTypesMatcher.ParseDocMatchExpression(dateExpr, 0);
bool bAtLeastOneExprSearched = false;
string lastDateSearchTerm = "";
double lastDateSearchMatchFactor = 0;
bool latestDateRequested = false;
bool earliestDateRequested = false;
foreach (ExprParseTerm parseTerm in parseTerms)
{
if (parseTerm.termType == ExprParseTerm.ExprParseTermType.exprTerm_Text)
{
if (lastDateSearchTerm != "")
{
SearchForDateItem(scanPages, lastDateSearchTerm, new DocRectangle(0, 0, 100, 100), lastDateSearchMatchFactor, datesResult, ref latestDateRequested, ref earliestDateRequested);
bAtLeastOneExprSearched = true;
}
lastDateSearchTerm = dateExpr.Substring(parseTerm.stPos, parseTerm.termLen);
// Reset matchFactor for next search term
lastDateSearchMatchFactor = 0;
}
else if (parseTerm.termType == ExprParseTerm.ExprParseTermType.exprTerm_Location)
{
string locStr = dateExpr.Substring(parseTerm.stPos, parseTerm.termLen);
DocRectangle lastDateSearchRect = new DocRectangle(locStr);
SearchForDateItem(scanPages, lastDateSearchTerm, lastDateSearchRect, lastDateSearchMatchFactor, datesResult, ref latestDateRequested, ref earliestDateRequested);
lastDateSearchTerm = "";
lastDateSearchMatchFactor = 0;
bAtLeastOneExprSearched = true;
}
else if (parseTerm.termType == ExprParseTerm.ExprParseTermType.exprTerm_MatchFactor)
{
if (dateExpr.Length > parseTerm.stPos + 1)
{
string valStr = dateExpr.Substring(parseTerm.stPos + 1, parseTerm.termLen-1);
Double.TryParse(valStr, out lastDateSearchMatchFactor);
}
}
}
// There may be one last expression still to find - but be sure that at least one is searched for
if ((lastDateSearchTerm != "") || (!bAtLeastOneExprSearched))
SearchForDateItem(scanPages, lastDateSearchTerm, new DocRectangle(0, 0, 100, 100), lastDateSearchMatchFactor, datesResult, ref latestDateRequested, ref earliestDateRequested);
// If required check for the earliest and/or latest dates and bump their factors
DateTime earliestDate = DateTime.MaxValue;
DateTime latestDate = DateTime.MinValue;
int earliestIdx = -1;
int latestIdx = -1;
for (int dateIdx = 0; dateIdx < datesResult.Count; dateIdx++)
{
if (earliestDate > datesResult[dateIdx].dateTime)
{
earliestDate = datesResult[dateIdx].dateTime;
earliestIdx = dateIdx;
}
if (latestDate < datesResult[dateIdx].dateTime)
{
latestDate = datesResult[dateIdx].dateTime;
latestIdx = dateIdx;
}
}
if (earliestDateRequested && (earliestIdx != -1))
datesResult[earliestIdx].matchFactor += MATCH_FACTOR_BUMP_FOR_EARLIEST_DATE;
if (latestDateRequested && (latestIdx != -1))
datesResult[latestIdx].matchFactor += MATCH_FACTOR_BUMP_FOR_LATEST_DATE;
// Find the best date index based on highest match factor
bestDateIdx = 0;
double highestDateMatchFactor = 0;
for (int dateIdx = 0; dateIdx < datesResult.Count; dateIdx++)
{
if (highestDateMatchFactor < datesResult[dateIdx].matchFactor)
{
bestDateIdx = dateIdx;
highestDateMatchFactor = datesResult[dateIdx].matchFactor;
}
}
return datesResult;
}
public static void SearchForDateItem(ScanPages scanPages, string dateSearchTerm, DocRectangle dateDocRect, double matchFactor, List<ExtractedDate> datesResult,
ref bool latestDateRequested, ref bool earliestDateRequested, int limitToPageNumN = -1, bool ignoreWhitespace = false)
{
// Get date search info
DateSrchInfo dateSrchInfo = GetDateSearchInfo(dateSearchTerm);
if (dateSrchInfo.bEarliestDate)
earliestDateRequested = true;
if (dateSrchInfo.bLatestDate)
latestDateRequested = true;
// Find first and last pages to search
int firstPageIdx = 0;
int lastPageIdxPlusOne = scanPages.scanPagesText.Count;
if (limitToPageNumN != -1)
{
firstPageIdx = limitToPageNumN - 1;
lastPageIdxPlusOne = limitToPageNumN;
}
// Iterate pages
for (int pageIdx = firstPageIdx; pageIdx < lastPageIdxPlusOne; pageIdx++)
{
List<ScanTextElem> scanPageText = scanPages.scanPagesText[pageIdx];
string joinedText = ""; // This maybe used if ~join macrocommand used
int joinCount = 0;
double matchFactorForThisPage = matchFactor + (pageIdx == 0 ? MATCH_FACTOR_BUMP_FOR_PAGE1 : (pageIdx == 1 ? MATCH_FACTOR_BUMP_FOR_PAGE2 : 0));
// Iterate text elements
foreach (ScanTextElem textElem in scanPageText)
{
// Check that the text contains at least two digits together to avoid wasting time looking for dates where there can be none
if (!Regex.IsMatch(textElem.text, @"\d\d"))
continue;
// Check rectangle bounds
if (!dateDocRect.Intersects(textElem.bounds))
continue;
// Check for join
if (dateSrchInfo.bJoinTextInRect)
{
if (joinCount < MAX_TEXT_ELEMS_TO_JOIN)
joinedText += textElem.text + " ";
joinCount++;
continue;
}
// Search within the found text
SearchWithinString(textElem.text, textElem.bounds, dateSearchTerm, dateSrchInfo, matchFactorForThisPage, pageIdx, datesResult, ignoreWhitespace);
}
// If joined then search just once
if (dateSrchInfo.bJoinTextInRect)
SearchWithinString(joinedText, dateDocRect, dateSearchTerm, dateSrchInfo, matchFactorForThisPage, pageIdx, datesResult, ignoreWhitespace);
}
// TEST TEST TEST
#if TEST_AGAINST_OLD_DATE_ALGORITHM
{
List<ExtractedDate> testDatesResult = new List<ExtractedDate>();
SearchForDateItem2(scanPages, dateSearchTerm, dateDocRect, matchFactor, testDatesResult, limitToPageNumN);
stp2.Stop();
Console.WriteLine("File: " + scanPages.uniqName + " OldTime = " + stp2.ElapsedMilliseconds.ToString() + " NewTime = " + stp.ElapsedMilliseconds.ToString());
foreach (ExtractedDate newD in datesResult)
{
bool bFound = false;
foreach (ExtractedDate oldD in testDatesResult)
{
if (oldD.dateTime == newD.dateTime)
{
bFound = true;
break;
}
}
if (!bFound)
{
Console.WriteLine("Date Mismatch New=" + newD.dateTime.ToLongDateString());
}
}
foreach (ExtractedDate oldD in testDatesResult)
{
bool bFound = false;
foreach (ExtractedDate newD in datesResult)
{
if (oldD.dateTime == newD.dateTime)
{
bFound = true;
break;
}
}
if (!bFound)
{
Console.WriteLine("Date Mismatch Old=" + oldD.dateTime.ToLongDateString());
}
}
}
#endif
}
private static void SearchWithinString(string inStr, DocRectangle textBounds, string dateSearchTerm, DateSrchInfo dateSrchInfo, double matchFactor, int pageIdx, List<ExtractedDate> datesResult, bool ignoreWhitespace)
{
int numDatesFoundInString = 0;
int year = -1;
// Use regex to find financial
if (dateSrchInfo.bFinancialYearEnd)
{
const string finYearEndRegex = @"year end.{0,16}?\s?((19|20)?(\d\d))";
Match fyMatch = Regex.Match(inStr, finYearEndRegex, RegexOptions.IgnoreCase);
if (fyMatch.Success)
{
if (fyMatch.Groups.Count > 1)
{
// Add result
year = Convert.ToInt32(fyMatch.Groups[1].Value);
AddCompletedDateToList(inStr, textBounds, 100, year, 4, 5, false, false, fyMatch.Index, fyMatch.Length, dateSrchInfo, pageIdx+1, datesResult);
numDatesFoundInString++;
}
}
}
// Start at the beginning of the string
string s = inStr;
if (ignoreWhitespace)
s = s.Replace(" ", "");
int dateSrchPos = 0;
int chIdx = 0;
string curStr = "";
int day = -1;
int month = -1;
bool bMonthFromChars = false;
year = -1;
s = s.ToLower();
bool strIsDigits = false;
int firstMatchPos = -1;
int lastMatchPos = 0;
int commaCount = 0;
bool bRangeIndicatorFound = false;
int numSepChars = 0;
for (chIdx = 0; chIdx < s.Length; chIdx++)
{
char ch = s[chIdx];
bool bResetNeeded = false;
// Search element
DateElemSrch el = null;
int minChars = 1;
int maxChars = 9;
if (dateSrchPos < dateSrchInfo.dateEls.Count)
{
el = dateSrchInfo.dateEls[dateSrchPos];
minChars = el.minChars;
maxChars = el.maxChars;
}
// Check if digits required
if ((el == null) || (el.isDigits))
{
char testCh = ch;
if ((testCh == 'l') || (testCh == 'o'))
{
if (((strIsDigits) && (curStr.Length > 0)) || ((chIdx+1 < s.Length) && (Char.IsDigit(s[chIdx+1]))))
{
if (testCh == 'l')
testCh = '1';
else if (testCh == 'o')
testCh = '0';
else if (testCh == 'i')
testCh = '1';
}
}
if (Char.IsDigit(testCh))
{
numSepChars = 0;
// Ignore if it's a zero and we're not allowed leading zeroes
// if ((el != null) && (!el.allowLeadingZeroes) && (curStrPos == 0) && (ch == '0'))
// continue;
if (!strIsDigits)
curStr = "";
curStr += testCh;
strIsDigits = true;
if (curStr.Length < minChars)
continue;
// Check max chars
if (curStr.Length > maxChars)
{
curStr = "";
continue;
}
// Check if the next char is also a digit - if not then we've found what we're looking for
if (((chIdx + 1 >= s.Length) || (!Char.IsDigit(s[chIdx + 1]))) && (curStr != "0"))
{
// Is this a day / month or year??
DateElemSrch.DateElType elType = DateElemSrch.DateElType.DE_NONE;
if (el != null)
elType = el.dateElType;
else
{
// Handle one and two digit numbers
if (curStr.Length <= 2)
{
// Already had a char based month?
if (bMonthFromChars)
{
if (!dateSrchInfo.bIsUsDate)
elType = DateElemSrch.DateElType.DE_YEAR;
else
elType = DateElemSrch.DateElType.DE_DAY;
}
else
{
// Position for standard month?
if ((dateSrchPos == 1) && (!dateSrchInfo.bIsUsDate))
elType = DateElemSrch.DateElType.DE_MONTH;
// Position for US month?
else if ((dateSrchPos == 0) && (dateSrchInfo.bIsUsDate))
elType = DateElemSrch.DateElType.DE_MONTH;
else if (dateSrchPos < 2)
elType = DateElemSrch.DateElType.DE_DAY;
else if ((dateSrchPos > 0) && (curStr.Length == 2))
elType = DateElemSrch.DateElType.DE_YEAR;
}
}
else if (curStr.Length == 4)
{
// Num digits == 4
if (dateSrchPos > 0)
elType = DateElemSrch.DateElType.DE_YEAR;
}
}
// Handle the value
if (elType == DateElemSrch.DateElType.DE_DAY)
{
Int32.TryParse(curStr, out day);
if ((day < 1) || (day > 31))
day = -1;
}
else if (elType == DateElemSrch.DateElType.DE_MONTH)
{
Int32.TryParse(curStr, out month);
if ((month < 1) || (month > 12))
month = -1;
bMonthFromChars = false;
}
else if (elType == DateElemSrch.DateElType.DE_YEAR)
{
Int32.TryParse(curStr, out year);
if (curStr.Length == 2)
{
if ((year < 0) || (year > 100))
year = -1;
}
else if (curStr.Length == 4)
{
if ((year < 1800) || (year > 2200))
year = -1;
}
// If no date formatting string is used then year must be the last item
if ((el == null) && (year != -1))
bResetNeeded = true;
}
else
{
curStr = "";
continue;
}
if (firstMatchPos == -1)
firstMatchPos = chIdx - curStr.Length;
lastMatchPos = chIdx;
dateSrchPos++;
curStr = "";
}
}
}
if ((el == null) || (!el.isDigits))
{
if (Char.IsLetter(ch))
{
if (strIsDigits)
curStr = "";
strIsDigits = false;
// Check we're still looking for a month value
if (month != -1)
{
numSepChars++;
continue;
}
// Form a sub-string to test for month names
curStr += ch;
// Check for range indicator
if (numDatesFoundInString == 1)
{
if (chIdx - curStr.Length - 1 > 0)
{
string testStr = s.Substring(chIdx - curStr.Length - 1);
if (testStr.Contains(" to") || testStr.Contains(" to"))
bRangeIndicatorFound = true;
}
}
// No point checking for month strings until 3 chars got
if (curStr.Length < 3)
continue;
// Check for a month name
if (shortMonthStrings.Any(curStr.Contains))
{
for (int monIdx = 0; monIdx < shortMonthStrings.Length; monIdx++)
if (curStr.Contains(shortMonthStrings[monIdx]))
{
month = monIdx + 1;
bMonthFromChars = true;
break;
}
if (firstMatchPos == -1)
firstMatchPos = chIdx - curStr.Length;
lastMatchPos = chIdx;
dateSrchPos++;
curStr = "";
numSepChars = 0;
// Move chIdx on to skip to next non letter
while ((chIdx < s.Length-1) && (Char.IsLetter(s[chIdx+1])))
chIdx++;
// Check for another valid month string in next few chars to detect ranges without a year
// e.g. should find ranges like 3 Jan - 4 Mar 2011 or 1st Jan to 31st May 2013
// but exlude ranges like 3 Jan 2012 - 4 Mar 2012 which would be seen as two separate dates
if (!dateSrchInfo.bNoDateRanges)
{
string strNextStr = "";
bool bStrRangeIndicatorFound = false;
int digitGroups = 0;
bool isInDigitGroup = false;
for (int chNext = chIdx+1; (chNext < s.Length) && (chNext < chIdx + 15); chNext++)
{
// Count the groups of digits
// (if we find two groups then break out as it's probably a range that contains separate years)
if (Char.IsDigit(s[chNext]))
{
if (!isInDigitGroup)
{
isInDigitGroup = true;
digitGroups++;
if (digitGroups >= 2)
break;
}
}
// Form a string from letters found
else if (Char.IsLetter(s[chNext]))
{
isInDigitGroup = false;
strNextStr += s[chNext];
// Check if the string contains "to"
if (strNextStr.Length >= 2)
if (strNextStr.Contains("to"))
bStrRangeIndicatorFound = true;
// Check if the string contains a short month name
if (bStrRangeIndicatorFound && (strNextStr.Length >= 3))
if (shortMonthStrings.Any(strNextStr.Contains))
{
bResetNeeded = true;
break;
}
}
else
{
// Check punctuation - this assumes a - is a range seperator
isInDigitGroup = false;
if (s[chNext] == '-')
bStrRangeIndicatorFound = true;
strNextStr = "";
}
}
}
else
{
bResetNeeded = true;
}
}
}
}
// Check for whitespace/punctuation/etc
if (!Char.IsLetterOrDigit(ch))
{
if ((day != -1) || (month != -1) || (year != -1))
{
numSepChars++;
if (numSepChars > MAX_SEP_CHARS_BETWEEN_DATE_ELEMS)
{
bResetNeeded = true;
numSepChars = 0;
}
}
curStr = "";
switch (ch)
{
case ':':
{
if (!dateSrchInfo.bAllowColons)
bResetNeeded = true;
break;
}
case ',':
{
commaCount++;
if ((!dateSrchInfo.bAllowTwoCommas) && (commaCount > 1))
bResetNeeded = true;
break;
}
case '.':
{
if (!dateSrchInfo.bAllowDots)
bResetNeeded = true;
break;
}
case '-':
{
if (numDatesFoundInString == 1)
bRangeIndicatorFound = true;
break;
}
}
}
// Check for complete date
if ((year != -1) && (month != -1) && ((day != -1) || (bMonthFromChars)))
{
// Add result
AddCompletedDateToList(s, textBounds, matchFactor, year, month, day, bMonthFromChars, bRangeIndicatorFound, firstMatchPos,
lastMatchPos, dateSrchInfo, pageIdx+1, datesResult);
numDatesFoundInString++;
// Start again to see if another date can be found
curStr = "";
bResetNeeded = true;
}
// Restart the process of finding a date if required
if (bResetNeeded)
{
dateSrchPos = 0;
day = -1;
month = -1;
year = -1;
bMonthFromChars = false;
strIsDigits = false;
firstMatchPos = -1;
bResetNeeded = false;
commaCount = 0;
numSepChars = 0;
}
}
}
private static void AddCompletedDateToList(string srcStr, DocRectangle textBounds, double matchFactor, int year, int month, int day, bool bMonthFromChars,
bool bRangeIndicatorFound, int firstMatchPos, int lastMatchPos, DateSrchInfo dateSrchInfo, int pageNum, List<ExtractedDate> datesResult)
{
double finalMatchFactor = matchFactor;
ExtractedDate fd = new ExtractedDate();
if (bRangeIndicatorFound)
finalMatchFactor += 10;
// Bump the match factor for dates in the top 40% of page - letterhead dates
if (textBounds.Y < 40)
finalMatchFactor += MATCH_FACTOR_BUMP_FOR_TOP_40_PC_OF_PAGE;
// Year
if (year < 80)
{
year += 2000;
fd.yearWas2Digit = true;
}
else if (year < 100)
{
year += 1900;
fd.yearWas2Digit = true;
}
else
{
finalMatchFactor += MATCH_FACTOR_BUMP_FOR_4_DIGIT_YEAR;
}
// Month
if (bMonthFromChars)
finalMatchFactor += MATCH_FACTOR_BUMP_FOR_TEXT_MONTH;
// Check for bump
if (dateSrchInfo.bPlusOneMonth)
{
month += 1;
if (month > 12)
{
month = 1;
year++;
}
}
// Day
if (day == -1)
{
day = 1;
fd.dayWasMissing = true;
finalMatchFactor += MATCH_FACTOR_BUMP_FOR_DAY_MISSING;
}
if (day > DateTime.DaysInMonth(year, month))
day = DateTime.DaysInMonth(year, month);
if (day < 1)
day = 1;
// Create datetime
DateTime dt = DateTime.MinValue;
try
{
dt = new DateTime(year, month, day);
}
catch
{
}
// Add date to list
fd.foundInText = srcStr;
fd.pageNum = pageNum;
fd.posnInText = firstMatchPos;
fd.matchLength = lastMatchPos-firstMatchPos+1;
fd.dateTime = dt;
fd.dateMatchType = ExtractedDate.DateMatchType.LongDate;
fd.locationOfDateOnPagePercent = textBounds;
fd.matchFactor = finalMatchFactor;
datesResult.Add(fd);
}
private static DateSrchInfo GetDateSearchInfo(string dateSearchTerm)
{
DateSrchInfo dateSrchInfo = new DateSrchInfo();
// Extract flags
dateSrchInfo.bIsUsDate = (dateSearchTerm.IndexOf("~USDate", StringComparison.OrdinalIgnoreCase) >= 0);
dateSrchInfo.bAllowColons = (dateSearchTerm.IndexOf("~AllowColons", StringComparison.OrdinalIgnoreCase) >= 0);
dateSrchInfo.bAllowDots = (dateSearchTerm.IndexOf("~AllowDots", StringComparison.OrdinalIgnoreCase) >= 0);
dateSrchInfo.bAllowTwoCommas = (dateSearchTerm.IndexOf("~AllowTwoCommas", StringComparison.OrdinalIgnoreCase) >= 0);
dateSrchInfo.bPlusOneMonth = (dateSearchTerm.IndexOf("~PlusOneMonth", StringComparison.OrdinalIgnoreCase) >= 0);
dateSrchInfo.bJoinTextInRect = (dateSearchTerm.IndexOf("~join", StringComparison.OrdinalIgnoreCase) >= 0);
dateSrchInfo.bNoDateRanges = (dateSearchTerm.IndexOf("~NoDateRanges", StringComparison.OrdinalIgnoreCase) >= 0);
dateSrchInfo.bLatestDate = (dateSearchTerm.IndexOf("~latest", StringComparison.OrdinalIgnoreCase) >= 0);
dateSrchInfo.bEarliestDate = (dateSearchTerm.IndexOf("~earliest", StringComparison.OrdinalIgnoreCase) >= 0);
dateSrchInfo.bFinancialYearEnd = (dateSearchTerm.IndexOf("~finYearEnd", StringComparison.OrdinalIgnoreCase) >= 0);
// Pattern str
string patternStr = "";
int squigPos = dateSearchTerm.IndexOf('~');
if (squigPos >= 0)
patternStr = dateSearchTerm.Substring(0, squigPos).ToLower();
// Find order of elements
bool bDayFound = false;
bool bMonthFound = false;
bool bYearFound = false;
for (int chIdx = 0; chIdx < patternStr.Length; chIdx++)
{
char ch = patternStr[chIdx];
// Handle day pattern = d or dd
if (!bDayFound && (ch == 'd'))
{
DateElemSrch el = new DateElemSrch();
el.dateElType = DateElemSrch.DateElType.DE_DAY;
el.isDigits = true;
el.minChars = 1;
el.maxChars = 2;
el.allowLeadingZeroes = false;
dateSrchInfo.dateEls.Add(el);
bDayFound = true;
}
// Handle month pattern = m or mm or mmm or mmmm
if (!bMonthFound && (ch == 'm'))
{
DateElemSrch el = new DateElemSrch();
el.dateElType = DateElemSrch.DateElType.DE_MONTH;
el.isDigits = true;
el.minChars = 1;
el.maxChars = 2;
el.allowLeadingZeroes = false;
if ((chIdx + 1 < patternStr.Length) && (patternStr[chIdx + 1] == 'm'))
{
el.allowLeadingZeroes = true;
if ((chIdx + 2 < patternStr.Length) && (patternStr[chIdx + 2] == 'm'))
{
el.isDigits = false;
el.minChars = 3;
el.maxChars = 3;
if ((chIdx + 3 < patternStr.Length) && (patternStr[chIdx + 3] == 'm'))
{
el.isDigits = false;
el.minChars = 3;
el.minChars = 9;
}
}
}
dateSrchInfo.dateEls.Add(el);
bMonthFound = true;
}
// Handle year pattern = yy or yyyy
if (!bYearFound && (ch == 'y'))
{
DateElemSrch el = new DateElemSrch();
el.dateElType = DateElemSrch.DateElType.DE_YEAR;
el.isDigits = true;
el.minChars = 2;
el.maxChars = 2;
el.allowLeadingZeroes = false;
if ((chIdx + 2 < patternStr.Length) && (patternStr[chIdx + 2] == 'y'))
el.minChars = 4;
el.maxChars = 4;
dateSrchInfo.dateEls.Add(el);
bYearFound = true;
}
}
return dateSrchInfo;
}
private class DateSrchInfo
{
public List<DateElemSrch> dateEls = new List<DateElemSrch>();
public bool bIsUsDate = false;
public bool bAllowColons = false;
public bool bAllowTwoCommas = false;
public bool bAllowDots = false;
public bool bPlusOneMonth = false;
public bool bJoinTextInRect = false;
public bool bNoDateRanges = false;
public bool bLatestDate = false;
public bool bEarliestDate = false;
public bool bFinancialYearEnd = false;
}
private class DateElemSrch
{
public enum DateElType
{
DE_NONE, DE_DAY, DE_MONTH, DE_YEAR
}
public DateElType dateElType = DateElType.DE_DAY;
public bool isDigits = false;
public int minChars = 1;
public int maxChars = 2;
public bool allowLeadingZeroes = true;
}
public static void SearchForDateItem2(ScanPages scanPages, string dateSearchTerm, DocRectangle dateDocRect, double matchFactor, List<ExtractedDate> datesResult, int limitToPageNumN = -1)
{
int firstPageIdx = 0;
int lastPageIdxPlusOne = scanPages.scanPagesText.Count;
if (limitToPageNumN != -1)
{
firstPageIdx = limitToPageNumN - 1;
lastPageIdxPlusOne = limitToPageNumN;
}
for (int pageIdx = firstPageIdx; pageIdx < lastPageIdxPlusOne; pageIdx++)
{
List<ScanTextElem> scanPageText = scanPages.scanPagesText[pageIdx];
foreach (ScanTextElem textElem in scanPageText)
{
// Check if there are at least two digits together in the text (any date format requires this at least)
if (!Regex.IsMatch(textElem.text, @"\d\d"))
continue;
// Check bounds
if (dateDocRect.Intersects(textElem.bounds))
{
// See which date formats to try
bool bTryLong = false;
bool bTryShort = false;
bool bTryUS = false;
bool bTryNoZeroes = false;
bool bTrySpaceSeparated = false;
if (dateSearchTerm.IndexOf("~long", StringComparison.OrdinalIgnoreCase) >= 0)
bTryLong = true;
if (dateSearchTerm.IndexOf("~short", StringComparison.OrdinalIgnoreCase) >= 0)
bTryShort = true;
if (dateSearchTerm.IndexOf("~US", StringComparison.OrdinalIgnoreCase) >= 0)
bTryUS = true;
if (dateSearchTerm.IndexOf("~No0", StringComparison.OrdinalIgnoreCase) >= 0)
bTryNoZeroes = true;
if (dateSearchTerm.IndexOf("~Spaces", StringComparison.OrdinalIgnoreCase) >= 0)
bTrySpaceSeparated = true;
if (!(bTryLong | bTryShort))
{
bTryLong = true;
bTryShort = true;
bTryUS = true;
bTryNoZeroes = true;
bTrySpaceSeparated = true;
}
// Get match text if any
string matchText = dateSearchTerm;
int squigPos = dateSearchTerm.IndexOf('~');
if (squigPos >= 0)
matchText = dateSearchTerm.Substring(0, squigPos);
double matchResultFactor = 0;
if (textElem.text.IndexOf(matchText, StringComparison.OrdinalIgnoreCase) >= 0)
matchResultFactor = matchFactor;
// Try to find dates
if (bTryLong)
{
MatchCollection ldMatches = Regex.Matches(textElem.text, longDateRegex, RegexOptions.IgnoreCase);
CoerceMatchesToDates(datesResult, matchResultFactor, textElem, ldMatches, ExtractedDate.DateMatchType.LongDate, 13, 11, 1);
if (bTryUS)
{
MatchCollection usldMatches = Regex.Matches(textElem.text, USlongDateRegex, RegexOptions.IgnoreCase);
CoerceMatchesToDates(datesResult, matchResultFactor, textElem, usldMatches, ExtractedDate.DateMatchType.USLongDate, 14, 1, 4);
}
}
if (bTryShort)
{
MatchCollection sdlzMatches = Regex.Matches(textElem.text, shortDateLeadingZeroesRegex, RegexOptions.IgnoreCase);
CoerceMatchesToDates(datesResult, matchResultFactor, textElem, sdlzMatches, ExtractedDate.DateMatchType.ShortDateLeadingZeroes, 3, 2, 1);
if (bTryNoZeroes)
{
MatchCollection sdnlzMatches = Regex.Matches(textElem.text, shortDateNoLeadingZeroesRegex, RegexOptions.IgnoreCase);
CoerceMatchesToDates(datesResult, matchResultFactor, textElem, sdnlzMatches, ExtractedDate.DateMatchType.ShortDateNoLeadingZeroes, 3, 2, 1);
}
if (bTrySpaceSeparated)
{
MatchCollection sdspMatches = Regex.Matches(textElem.text, shortDateSpacesRegex, RegexOptions.IgnoreCase);
CoerceMatchesToDates(datesResult, matchResultFactor, textElem, sdspMatches, ExtractedDate.DateMatchType.ShortDateNoLeadingZeroes, 3, 2, 1);
}
}
}
}
}
}
private static void CoerceMatchesToDates(List<ExtractedDate> datesResult, double matchResultFactor, ScanTextElem textElem, MatchCollection matches, ExtractedDate.DateMatchType matchType, int yearGroupIdx, int monthGroupIdx, int dayGroupIdx)
{
foreach (Match match in matches)
{
ExtractedDate fd = new ExtractedDate();
try
{
string yrStr = match.Groups[yearGroupIdx].Value.Replace(" ", "");
yrStr = yrStr.ToLower().Replace("l", "1");
yrStr = yrStr.ToLower().Replace("o", "0");
int year = Convert.ToInt32(yrStr);
if (year < 80)
{
year += 2000;
fd.yearWas2Digit = true;
}
else if (year < 100)
{
year += 1900;
fd.yearWas2Digit = true;
}
int month = 1;
if (Char.IsDigit(match.Groups[monthGroupIdx].Value, 0))
month = Convert.ToInt32(match.Groups[2].Value);
else
month = monthDict[match.Groups[monthGroupIdx].Value.ToLower().Substring(0, 3)];
int day = 1;
fd.dayWasMissing = true;
if (match.Groups[dayGroupIdx].Value.Trim() != "")
{
day = Convert.ToInt32(match.Groups[dayGroupIdx].Value);
fd.dayWasMissing = false;
}
if (year > DateTime.MaxValue.Year)
year = DateTime.MaxValue.Year;
if (year < DateTime.MinValue.Year)
year = DateTime.MinValue.Year;
if (day > DateTime.DaysInMonth(year, month))
day = DateTime.DaysInMonth(year, month);
if (day < 1)
day = 1;
DateTime dt = new DateTime(year, month, day);
// Add date to list
fd.foundInText = textElem.text;
fd.posnInText = match.Index;
fd.matchLength = match.Length;
fd.dateTime = dt;
fd.dateMatchType = matchType;
fd.locationOfDateOnPagePercent = textElem.bounds;
fd.matchFactor = matchResultFactor;
datesResult.Add(fd);
}
catch
{
}
}
}
}
public class ExtractedDate
{
public enum DateMatchType
{
None,
LongDate,
USLongDate,
ShortDateLeadingZeroes,
ShortDateNoLeadingZeroes,
ShortDateSpaceSeparators
};
public DateTime dateTime;
public int pageNum;
public DocRectangle locationOfDateOnPagePercent;
public bool yearWas2Digit = false;
public bool dayWasMissing = false;
public int posnInText = 0;
public int matchLength = 0;
public DateMatchType dateMatchType = DateMatchType.None;
public double matchFactor = 0;
public string foundInText;
}
}
| 46.204 | 336 | 0.439507 | [
"MIT"
] | robdobsn/ScanMonitor | ScanMonitorApp/ScanMonitorApp/DocTextAndDateExtractor.cs | 46,206 | C# |
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using AspnetboilerplateDemo.Countries.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AspnetboilerplateDemo.Countries
{
public interface ICountryAppServices : IAsyncCrudAppService<CountryDto, int, PagedCountryResultRequestDto, CreateCountryDto, CountryDto>
{
Task<CountryDto> GetCountryForEdit(EntityDto input);
}
}
| 28.764706 | 140 | 0.807771 | [
"MIT"
] | arvindaspnetdev/AspNetZeroDemo | aspnet-core/src/AspnetboilerplateDemo.Application/Countries/ICountryAppServices.cs | 491 | C# |
using CoreML;
namespace BuildIt.ML
{
public class Feature
{
public string Name { get; set; }
public virtual MLFeatureType Type { get; set; }
}
} | 15.909091 | 55 | 0.6 | [
"MIT"
] | builttoroam/BuildIt | src/BuildIt.ML/BuildIt.ML/Platforms/Ios/Feature.cs | 177 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MasodikvalodiCSsharpProjekt
{
class Program
{
static void Main(string[] args)
{
/* int szam = 0;
Console.WriteLine("Kérek két számot: ");
//bool egeszSzam = Int32.TryParse(Console.ReadLine(), out szam);
// Console.WriteLine($"A bekért szám: {szam}");
do
{
Console.Write("Kérek egy számot: ");
egeszSzam = Int32.TryParse(Console.ReadLine(), out szam);
} while (egeszSzam);
Console.WriteLine($"A bekért szám: {szam}");*/
/* string kimenet = "";
Console.Write("kérek egy egész számot: ");
int szam = Convert.ToInt32(Console.ReadLine());
kimenet += szam;
while (szam % 2==0)
{
kimenet += 2 + "*";
szam = szam / 2;
}
kimenet += "=" + szam;
Console.WriteLine(kimenet);*/
/* string kimenet = "";
Console.Write("Kérek egy pozitiv egész számot: ");
int szam = Convert.ToInt32(Console.ReadLine());
kimenet += szam + "=";
int egesz = 0;
int tort = szam;
while (szam -3>0)
{
szam = szam - 3;
egesz++;
tort = szam - 3;*/
/* string alma = "";
while (alma!="alma")
{
Console.WriteLine("Kérek egy gyümölcsöt: ");
alma = Console.ReadLine();
}
Console.WriteLine("Az alma gyüm;ölcs: ");*/
//27.feladat:
//32.feladat:
Console.WriteLine("Kérek egy pozitív egész számot: ");
int szam = Int32.Parse(Console.ReadLine());
for (int i = 1; i < 11; i++)
{
Console.Write($"{szam}*{i}={szam * i}");
}
//34.feladat:
Console.ReadKey(true);
}
}
}
| 26.939024 | 78 | 0.436849 | [
"MIT"
] | SzucsRoland99/gyakorlasfo | MasodikvalodiCSsharpProjekt/MasodikvalodiCSsharpProjekt/Program.cs | 2,236 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the guardduty-2017-11-28.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.GuardDuty.Model
{
/// <summary>
/// This is the response object from the GetInvitationsCount operation.
/// </summary>
public partial class GetInvitationsCountResponse : AmazonWebServiceResponse
{
private int? _invitationsCount;
/// <summary>
/// Gets and sets the property InvitationsCount. The number of received invitations.
/// </summary>
public int InvitationsCount
{
get { return this._invitationsCount.GetValueOrDefault(); }
set { this._invitationsCount = value; }
}
// Check to see if InvitationsCount property is set
internal bool IsSetInvitationsCount()
{
return this._invitationsCount.HasValue;
}
}
} | 31.226415 | 107 | 0.689426 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/GuardDuty/Generated/Model/GetInvitationsCountResponse.cs | 1,655 | C# |
using System.IO;
namespace Twilio.OwlFinance.Infrastructure.Docusign
{
public class FileHelpers
{
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
}
} | 24.352941 | 68 | 0.524155 | [
"MIT"
] | jonedavis/OwlFinanceDemo | api/projects/Twilio.OwlFinance.Infrastructure.Docusign/FileHelpers.cs | 416 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace AccessibilityInsights.Automation
{
/// <summary>
/// Class to stop AccessibilityInsights (via StopCommand.Execute). Can only be successfully called after
/// a successful call to StartCommand.Execute
/// </summary>
public static class StopCommand
{
/// <summary>
/// Execute the Stop command. Used by both .NET and by PowerShell entry points
/// </summary>
/// <returns>A StopCommandResult that describes the result of the command</returns>
public static StopCommandResult Execute()
{
return ExecutionWrapper.ExecuteCommand(() =>
{
AutomationSession.ClearInstance();
return new StopCommandResult
{
Completed = true,
SummaryMessage = DisplayStrings.SuccessStop,
Succeeded = true,
};
}, ErrorCommandResultFactory);
}
private static StopCommandResult ErrorCommandResultFactory(string errorDetail)
{
return new StopCommandResult
{
Completed = false,
SummaryMessage = errorDetail,
Succeeded = false,
};
}
}
}
| 35.585366 | 109 | 0.568197 | [
"MIT"
] | babylonbee/accessibility-insights-windows | src/AccessibilityInsights.Automation/StopCommand.cs | 1,419 | C# |
using System;
using System.Collections.Generic;
using KoiVM.AST.IL;
using KoiVM.VM;
namespace KoiVM.VMIL.Transforms {
public class FixMethodRefTransform : IPostTransform {
HashSet<VMRegisters> saveRegs;
public void Initialize(ILPostTransformer tr) {
saveRegs = tr.Runtime.Descriptor.Data.LookupInfo(tr.Method).UsedRegister;
}
public void Transform(ILPostTransformer tr) {
tr.Instructions.VisitInstrs(VisitInstr, tr);
}
void VisitInstr(ILInstrList instrs, ILInstruction instr, ref int index, ILPostTransformer tr) {
var rel = instr.Operand as ILRelReference;
if (rel == null)
return;
var methodRef = rel.Target as ILMethodTarget;
if (methodRef == null)
return;
methodRef.Resolve(tr.Runtime);
}
}
} | 25.9 | 98 | 0.711712 | [
"CC0-1.0"
] | ElektroKill/KoiVM | KoiVM/VMIL/Transforms/FixMethodRefTransform.cs | 779 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("Geometry")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Geometry")]
[assembly: AssemblyCopyright("Copyright © T.Yoshimura 2019-2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("04380d3c-f0d8-4bc1-a61c-c6a23c299b0b")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// リビジョン
//
[assembly: AssemblyVersion("1.1.*")]
| 28.125 | 66 | 0.743333 | [
"MIT"
] | tk-yoshimura/Geometry | Geometry/Properties/AssemblyInfo.cs | 1,383 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Reflection;
using System.Text;
using FLS.Data.WebApi;
namespace FLS.Server.Data.DbEntities
{
public partial class ExtensionValue : IFLSMetaData
{
public ExtensionValue()
{
}
public Guid ExtensionValueId { get; set; }
[Required]
[StringLength(100)]
public string ExtensionValueName { get; set; }
[Required]
[StringLength(100)]
public string ExtensionValueKeyName { get; set; }
public string ExtensionStringValue { get; set; }
public byte[] ExtensionBinaryValue { get; set; }
public Guid? ClubId { get; set; }
public bool IsDefault { get; set; }
public string Comment { get; set; }
[Column(TypeName = "datetime2")]
public DateTime CreatedOn { get; set; }
public Guid CreatedByUserId { get; set; }
[Column(TypeName = "datetime2")]
public DateTime? ModifiedOn { get; set; }
public Guid? ModifiedByUserId { get; set; }
[Column(TypeName = "datetime2")]
public DateTime? DeletedOn { get; set; }
public Guid? DeletedByUserId { get; set; }
public int? RecordState { get; set; }
public Guid OwnerId { get; set; }
public int OwnershipType { get; set; }
public bool IsDeleted { get; set; }
public virtual Club Club { get; set; }
public Guid Id
{
get { return ExtensionValueId; }
set { ExtensionValueId = value; }
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
Type type = GetType();
sb.Append("[");
sb.Append(type.Name);
sb.Append(" -> ");
foreach (FieldInfo info in type.GetFields())
{
sb.Append(string.Format("{0}: {1}, ", info.Name, info.GetValue(this)));
}
Type tColl = typeof(ICollection<>);
foreach (PropertyInfo info in type.GetProperties())
{
Type t = info.PropertyType;
if (t.IsGenericType && tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) ||
t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl)
|| (t.Namespace != null && t.Namespace.Contains("FLS.Server.Data.DbEntities")))
{
continue;
}
sb.Append(string.Format("{0}: {1}, ", info.Name, info.GetValue(this, null)));
}
sb.Append(" <- ");
sb.Append(type.Name);
sb.AppendLine("]");
return sb.ToString();
}
}
}
| 28.019231 | 104 | 0.547701 | [
"MIT"
] | flightlog/flsserver | src/FLS.Server.Data/DbEntities/ExtensionValue.cs | 2,914 | C# |
namespace AdminAssistant.Infra.DAL;
public interface IDatabasePersistable
{
int PrimaryKey { get; }
bool IsNew => PrimaryKey == Constants.NewRecordID;
}
| 20.25 | 54 | 0.746914 | [
"MIT"
] | SimonGeering/AdminAssistant | src/AdminAssistant/Infra/DAL/IDatabasePersistable.cs | 162 | C# |
using Microsoft.EntityFrameworkCore.Migrations;
namespace TestApp.Migrations
{
public partial class upgraditemorder : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
| 18.5 | 71 | 0.66967 | [
"MIT"
] | hasan-ak1996/boilerplate | aspnet-core/src/TestApp.EntityFrameworkCore/Migrations/20201014144454_upgrad-item-order.cs | 335 | C# |
using BeardedPlatypus.OrbitCamera.Core;
using UnityEngine;
using UnityEngine.UI;
using Zenject;
namespace BeardedPlatypus.OrbitCamera.Samples
{
/// <summary>
/// <see cref="CameraInstaller"/> provides the Samples specific dependency to
/// construct the camera logic.
/// </summary>
public class CameraInstaller : MonoInstaller
{
[SerializeField] private Button resetViewButton;
[SerializeField] private ResetDataScriptableObject resetData;
public override void InstallBindings()
{
Container.Bind<Button>()
.FromInstance(resetViewButton)
.AsSingle()
.WhenInjectedInto<ResetViewController>();
Container.Bind<ResetDataScriptableObject>()
.FromInstance(resetData)
.AsSingle();
Container.Bind<ResetViewController>()
.To<ResetViewController>()
.AsSingle();
Container.Bind<IBindings>()
.To<Bindings>()
.FromNewComponentOnNewGameObject()
.AsSingle();
}
}
} | 33.857143 | 81 | 0.571308 | [
"MIT"
] | BeardedPlatypus/orbit-camera | Assets/Scripts/OrbitCamera.Samples/CameraInstaller.cs | 1,185 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 02.05.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.LessThanOrEqual.Complete.SByte.NullableInt16{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.SByte;
using T_DATA2 =System.Nullable<System.Int16>;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__02__VN
public static class TestSet_504__param__02__VN
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
T_DATA2 vv2=null;
var recs=db.testTable.Where(r => vv1 /*OP{*/ <= /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001
//-----------------------------------------------------------------------
[Test]
public static void Test_002()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
T_DATA2 vv2=null;
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ <= /*}OP*/ vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002
};//class TestSet_504__param__02__VN
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.LessThanOrEqual.Complete.SByte.NullableInt16
| 27.841667 | 142 | 0.534271 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/LessThanOrEqual/Complete/SByte/NullableInt16/TestSet_504__param__02__VN.cs | 3,343 | 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 DistanceAndDirectionLibrary.Properties {
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()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DistanceAndDirectionLibrary.Properties.Resources", typeof(Resources).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)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Enter value.
/// </summary>
public static string AEEnterValue {
get {
return ResourceManager.GetString("AEEnterValue", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid coordinate.
/// </summary>
public static string AEInvalidCoordinate {
get {
return ResourceManager.GetString("AEInvalidCoordinate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid input.
/// </summary>
public static string AEInvalidInput {
get {
return ResourceManager.GetString("AEInvalidInput", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The number must be positive.
/// </summary>
public static string AEMustBePositive {
get {
return ResourceManager.GetString("AEMustBePositive", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The number of radials must be between {0} and {1}.
/// </summary>
public static string AENumOfRadials {
get {
return ResourceManager.GetString("AENumOfRadials", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The number of rings must be between {0} and {1}.
/// </summary>
public static string AENumOfRings {
get {
return ResourceManager.GetString("AENumOfRings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cancel.
/// </summary>
public static string ButtonCancel {
get {
return ResourceManager.GetString("ButtonCancel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to OK.
/// </summary>
public static string ButtonOK {
get {
return ResourceManager.GetString("ButtonOK", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Distance and Direction.
/// </summary>
public static string DistanceDirectionLabel {
get {
return ResourceManager.GetString("DistanceDirectionLabel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ending Point should not be the same as the Starting Point.
/// </summary>
public static string EndPointAndStartPointSameError {
get {
return ResourceManager.GetString("EndPointAndStartPointSameError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Distance and Bearing.
/// </summary>
public static string EnumBearingAndDistance {
get {
return ResourceManager.GetString("EnumBearingAndDistance", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to DD.
/// </summary>
public static string EnumCTDD {
get {
return ResourceManager.GetString("EnumCTDD", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to DDM.
/// </summary>
public static string EnumCTDDM {
get {
return ResourceManager.GetString("EnumCTDDM", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to DMS.
/// </summary>
public static string EnumCTDMS {
get {
return ResourceManager.GetString("EnumCTDMS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to GARS.
/// </summary>
public static string EnumCTGARS {
get {
return ResourceManager.GetString("EnumCTGARS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to MGRS.
/// </summary>
public static string EnumCTMGRS {
get {
return ResourceManager.GetString("EnumCTMGRS", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Default Map Unit.
/// </summary>
public static string EnumCTNone {
get {
return ResourceManager.GetString("EnumCTNone", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to USNG.
/// </summary>
public static string EnumCTUSNG {
get {
return ResourceManager.GetString("EnumCTUSNG", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to UTM.
/// </summary>
public static string EnumCTUTM {
get {
return ResourceManager.GetString("EnumCTUTM", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Degrees.
/// </summary>
public static string EnumDegrees {
get {
return ResourceManager.GetString("EnumDegrees", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Diameter.
/// </summary>
public static string EnumDiameter {
get {
return ResourceManager.GetString("EnumDiameter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Feet.
/// </summary>
public static string EnumFeet {
get {
return ResourceManager.GetString("EnumFeet", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Feet / Hour.
/// </summary>
public static string EnumFeetHour {
get {
return ResourceManager.GetString("EnumFeetHour", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Feet / Second.
/// </summary>
public static string EnumFeetSec {
get {
return ResourceManager.GetString("EnumFeetSec", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Full.
/// </summary>
public static string EnumFull {
get {
return ResourceManager.GetString("EnumFull", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Geodetic.
/// </summary>
public static string EnumGeodesic {
get {
return ResourceManager.GetString("EnumGeodesic", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Great Elliptic.
/// </summary>
public static string EnumGreatElliptic {
get {
return ResourceManager.GetString("EnumGreatElliptic", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Kilometers.
/// </summary>
public static string EnumKilometers {
get {
return ResourceManager.GetString("EnumKilometers", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Kilometers / Hour.
/// </summary>
public static string EnumKilometersHour {
get {
return ResourceManager.GetString("EnumKilometersHour", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Kilometers / Second.
/// </summary>
public static string EnumKilometersSec {
get {
return ResourceManager.GetString("EnumKilometersSec", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Loxodrome.
/// </summary>
public static string EnumLoxodrome {
get {
return ResourceManager.GetString("EnumLoxodrome", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Meters.
/// </summary>
public static string EnumMeters {
get {
return ResourceManager.GetString("EnumMeters", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Meters / Hour.
/// </summary>
public static string EnumMetersHour {
get {
return ResourceManager.GetString("EnumMetersHour", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Meters / Second.
/// </summary>
public static string EnumMetersSec {
get {
return ResourceManager.GetString("EnumMetersSec", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Miles.
/// </summary>
public static string EnumMiles {
get {
return ResourceManager.GetString("EnumMiles", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Miles / Hour.
/// </summary>
public static string EnumMilesHour {
get {
return ResourceManager.GetString("EnumMilesHour", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Miles / Second.
/// </summary>
public static string EnumMilesSec {
get {
return ResourceManager.GetString("EnumMilesSec", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Mils.
/// </summary>
public static string EnumMils {
get {
return ResourceManager.GetString("EnumMils", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Nautical Miles.
/// </summary>
public static string EnumNauticalMile {
get {
return ResourceManager.GetString("EnumNauticalMile", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Nautical Miles / Hour.
/// </summary>
public static string EnumNauticalMilesHour {
get {
return ResourceManager.GetString("EnumNauticalMilesHour", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Nautical Miles / Second.
/// </summary>
public static string EnumNauticalMilesSec {
get {
return ResourceManager.GetString("EnumNauticalMilesSec", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Points.
/// </summary>
public static string EnumPoints {
get {
return ResourceManager.GetString("EnumPoints", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Radius.
/// </summary>
public static string EnumRadius {
get {
return ResourceManager.GetString("EnumRadius", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Semi.
/// </summary>
public static string EnumSemi {
get {
return ResourceManager.GetString("EnumSemi", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Yards.
/// </summary>
public static string EnumYards {
get {
return ResourceManager.GetString("EnumYards", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to delete features from layer: .
/// </summary>
public static string ErrorDeleteFailed {
get {
return ResourceManager.GetString("ErrorDeleteFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Required feature layer was not found: .
/// </summary>
public static string ErrorFeatureClassNotFound {
get {
return ResourceManager.GetString("ErrorFeatureClassNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Feature Create Error.
/// </summary>
public static string ErrorFeatureCreateTitle {
get {
return ResourceManager.GetString("ErrorFeatureCreateTitle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Please provide a valid feature class name.
/// </summary>
public static string FeatureClassNameError {
get {
return ResourceManager.GetString("FeatureClassNameError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The operation requires a valid spatial reference.
/// </summary>
public static string InvalidSpatialReferenceError {
get {
return ResourceManager.GetString("InvalidSpatialReferenceError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to KMZ Exported Successfully.
/// </summary>
public static string KMZExportComplete {
get {
return ResourceManager.GetString("KMZExportComplete", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Angle.
/// </summary>
public static string LabelAngle {
get {
return ResourceManager.GetString("LabelAngle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Axis.
/// </summary>
public static string LabelAxisGroup {
get {
return ResourceManager.GetString("LabelAxisGroup", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Units.
/// </summary>
public static string LabelAxisUnits {
get {
return ResourceManager.GetString("LabelAxisUnits", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Center Point.
/// </summary>
public static string LabelCenterPoint {
get {
return ResourceManager.GetString("LabelCenterPoint", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Clear.
/// </summary>
public static string LabelClearGraphics {
get {
return ResourceManager.GetString("LabelClearGraphics", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to From.
/// </summary>
public static string LabelCreateCircleFrom {
get {
return ResourceManager.GetString("LabelCreateCircleFrom", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Create Ellipse with.
/// </summary>
public static string LabelCreateEllipseWith {
get {
return ResourceManager.GetString("LabelCreateEllipseWith", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Create Feature.
/// </summary>
public static string LabelCreateFeature {
get {
return ResourceManager.GetString("LabelCreateFeature", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Direction / Azimuth.
/// </summary>
public static string LabelDirectionAzimuth {
get {
return ResourceManager.GetString("LabelDirectionAzimuth", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Display Coordinate.
/// </summary>
public static string LabelDisplayCoordinate {
get {
return ResourceManager.GetString("LabelDisplayCoordinate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Distance Calculator.
/// </summary>
public static string LabelDistanceCalculator {
get {
return ResourceManager.GetString("LabelDistanceCalculator", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Distance / Length.
/// </summary>
public static string LabelDistanceLength {
get {
return ResourceManager.GetString("LabelDistanceLength", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ellipse Type.
/// </summary>
public static string LabelEllipseType {
get {
return ResourceManager.GetString("LabelEllipseType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ending Point.
/// </summary>
public static string LabelEndingPoint {
get {
return ResourceManager.GetString("LabelEndingPoint", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to From:.
/// </summary>
public static string LabelFrom {
get {
return ResourceManager.GetString("LabelFrom", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Interactive.
/// </summary>
public static string LabelInteractive {
get {
return ResourceManager.GetString("LabelInteractive", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Interval Between Rings.
/// </summary>
public static string LabelInterval {
get {
return ResourceManager.GetString("LabelInterval", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Major.
/// </summary>
public static string LabelMajorAxis {
get {
return ResourceManager.GetString("LabelMajorAxis", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Map Point.
/// </summary>
public static string LabelMapPoint {
get {
return ResourceManager.GetString("LabelMapPoint", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Minor.
/// </summary>
public static string LabelMinorAxis {
get {
return ResourceManager.GetString("LabelMinorAxis", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Number of Radials.
/// </summary>
public static string LabelNumberOfRadials {
get {
return ResourceManager.GetString("LabelNumberOfRadials", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Number of Rings.
/// </summary>
public static string LabelNumberOfRings {
get {
return ResourceManager.GetString("LabelNumberOfRings", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Angle.
/// </summary>
public static string LabelOrientationAngle {
get {
return ResourceManager.GetString("LabelOrientationAngle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Orientation.
/// </summary>
public static string LabelOrientationGroup {
get {
return ResourceManager.GetString("LabelOrientationGroup", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Units.
/// </summary>
public static string LabelOrientationUnit {
get {
return ResourceManager.GetString("LabelOrientationUnit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Radius.
/// </summary>
public static string LabelRadius {
get {
return ResourceManager.GetString("LabelRadius", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Radius / Diameter.
/// </summary>
public static string LabelRadiusDiameter {
get {
return ResourceManager.GetString("LabelRadiusDiameter", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Center Point.
/// </summary>
public static string LabelRangeRingsCenterPoint {
get {
return ResourceManager.GetString("LabelRangeRingsCenterPoint", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Distance between Rings.
/// </summary>
public static string LabelRangeRingsDistanceBetween {
get {
return ResourceManager.GetString("LabelRangeRingsDistanceBetween", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Number of Radials.
/// </summary>
public static string LabelRangeRingsNumberofRadials {
get {
return ResourceManager.GetString("LabelRangeRingsNumberofRadials", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Rate.
/// </summary>
public static string LabelRate {
get {
return ResourceManager.GetString("LabelRate", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Save As.
/// </summary>
public static string LabelSaveAs {
get {
return ResourceManager.GetString("LabelSaveAs", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Starting Point.
/// </summary>
public static string LabelStartingPoint {
get {
return ResourceManager.GetString("LabelStartingPoint", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Circle.
/// </summary>
public static string LabelTabCircle {
get {
return ResourceManager.GetString("LabelTabCircle", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ellipse.
/// </summary>
public static string LabelTabEllipse {
get {
return ResourceManager.GetString("LabelTabEllipse", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Line.
/// </summary>
public static string LabelTabLines {
get {
return ResourceManager.GetString("LabelTabLines", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Rings.
/// </summary>
public static string LabelTabRange {
get {
return ResourceManager.GetString("LabelTabRange", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Time.
/// </summary>
public static string LabelTime {
get {
return ResourceManager.GetString("LabelTime", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Point is out of bounds.
/// </summary>
public static string MsgOutOfAOI {
get {
return ResourceManager.GetString("MsgOutOfAOI", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Properties.
/// </summary>
public static string TitleEditProperties {
get {
return ResourceManager.GetString("TitleEditProperties", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Edit Properties.
/// </summary>
public static string TooltipEditProperties {
get {
return ResourceManager.GetString("TooltipEditProperties", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Map Point Tool.
/// </summary>
public static string TooltipMapPointTool {
get {
return ResourceManager.GetString("TooltipMapPointTool", resourceCulture);
}
}
}
}
| 33.90899 | 193 | 0.527494 | [
"Apache-2.0"
] | CTLocalGovTeam/distance-direction-addin-dotnet | source/addins/DistanceAndDirectionLibrary/Properties/Resources.Designer.cs | 30,554 | C# |
using DAL.DbContexts;
using DAL.Madals;
using DAL.Services;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace DAL.Repositories
{
public class SuplierRepository : ISuplierRepository
{
private readonly UpvcContext context;
public SuplierRepository()
{
context = new UpvcContext();
}
public async Task<bool> DeleteSuplier(string id)
{
FilterDefinition<suplier> filter = Builders<suplier>.Filter.Eq(m => m.Id, id);
DeleteResult deleteResult = await context
.supliers
.DeleteOneAsync(filter);
return deleteResult.IsAcknowledged && deleteResult.DeletedCount > 0;
}
public async Task<IEnumerable<suplier>> GetSuplier()
{
return await context.supliers.Find(x => true).ToListAsync();
}
public async Task<suplier> GetSuplierByPan(string pan)
{
return await context.supliers.Find<suplier>(a => a.pan.Equals(pan)).FirstOrDefaultAsync();
}
public async Task<suplier> GetSuplierID(string ID)
{
return await context.supliers.Find<suplier>(a => a.Id.Equals(ID)).FirstOrDefaultAsync();
}
public async Task<bool> InserSuplier(suplier _suplier)
{
try
{
await context.supliers.InsertOneAsync(_suplier);
return true;
}
catch
{
return false;
}
}
public async Task<bool> UpdateSuplier(suplier _sup)
{
try
{
ReplaceOneResult updateResult = await context.supliers.ReplaceOneAsync(g => g.pan == _sup.pan, replacement: _sup);
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
| 28.164384 | 130 | 0.543288 | [
"MIT"
] | guna785/UPVC | upvcDesign/DAL/Repositories/SuplierRepository.cs | 2,058 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using log4net;
using Rejseplanen.ZimmerBot.AddOn.Schemas;
using ZimmerBot.Core.Processors;
using ZimmerBot.Core.Utilities;
namespace Rejseplanen.ZimmerBot.AddOn
{
/// <summary>
/// This class exposes various Rejseplanen functions to be used in ZimmerBot.
/// </summary>
public static class RejseplanenProcessor
{
static ILog Logger = LogManager.GetLogger(typeof(RejseplanenProcessor));
public static ProcessorOutput FindStop(ProcessorInput input)
{
string name = input.GetParameter<string>(0);
var parameters = new Dictionary<string, object>();
Logger.Debug($"Looking for station '{name}' in Rejseplanen");
try
{
RejseplanenAPI api = new RejseplanenAPI();
LocationList locations = api.GetLocations(name);
if (locations.Items != null && locations.Items.Length > 0)
{
StopLocation stop = locations.Items[0] as StopLocation;
CoordLocation coord = locations.Items[0] as CoordLocation;
if (stop != null)
{
parameters["stopName"] = stop.name;
return new ProcessorOutput(parameters);
}
}
return new ProcessorOutput("empty", null);
}
catch (Exception ex)
{
Logger.Error("Failed to access Rejseplanen", ex);
return new ProcessorOutput("error", null);
}
}
public static ProcessorOutput FindNextDepartures(ProcessorInput input)
{
string station = input.GetParameter<string>(0);
string types = input.GetOptionalParameter<string>(1, "toget bussen metro");
var parameters = new Dictionary<string, object>();
Logger.Debug($"Looking for departures from '{station}' in Rejseplanen");
try
{
RejseplanenAPI api = new RejseplanenAPI();
LocationList locations = api.GetLocations(station);
StopLocation location = locations.Items.OfType<StopLocation>().FirstOrDefault();
if (location != null)
{
DepartureBoard departures = api.GetDepartureBoard(location.id, types);
if (departures != null && departures.Departure != null)
{
var result = departures.Departure.Select(d =>
new
{
date = d.date,
time = d.time,
direction = d.direction,
line = d.name
}).Take(5).ToList();
parameters["stop"] = location.name;
parameters["result"] = result;
return new ProcessorOutput(parameters);
}
}
return new ProcessorOutput("empty", null);
}
catch (Exception ex)
{
Logger.Error("Failed to access Rejseplanen", ex);
return new ProcessorOutput("error", null);
}
}
}
}
| 29.39604 | 89 | 0.588414 | [
"MIT"
] | JornWildt/ZimmerBot | Rejseplanen.ZimmerBot.AddOn/RejseplanenProcessor.cs | 2,971 | C# |
namespace NAudioDemo.AudioPlaybackDemo
{
partial class WasapiOutSettingsPanel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.comboBoxWaspai = new System.Windows.Forms.ComboBox();
this.checkBoxWasapiEventCallback = new System.Windows.Forms.CheckBox();
this.checkBoxWasapiExclusiveMode = new System.Windows.Forms.CheckBox();
this.SuspendLayout();
//
// comboBoxWaspai
//
this.comboBoxWaspai.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxWaspai.FormattingEnabled = true;
this.comboBoxWaspai.Location = new System.Drawing.Point(3, 3);
this.comboBoxWaspai.Name = "comboBoxWaspai";
this.comboBoxWaspai.Size = new System.Drawing.Size(232, 21);
this.comboBoxWaspai.TabIndex = 20;
//
// checkBoxWasapiEventCallback
//
this.checkBoxWasapiEventCallback.AutoSize = true;
this.checkBoxWasapiEventCallback.Location = new System.Drawing.Point(3, 30);
this.checkBoxWasapiEventCallback.Name = "checkBoxWasapiEventCallback";
this.checkBoxWasapiEventCallback.Size = new System.Drawing.Size(98, 17);
this.checkBoxWasapiEventCallback.TabIndex = 19;
this.checkBoxWasapiEventCallback.Text = "Event Callback";
this.checkBoxWasapiEventCallback.UseVisualStyleBackColor = true;
//
// checkBoxWasapiExclusiveMode
//
this.checkBoxWasapiExclusiveMode.AutoSize = true;
this.checkBoxWasapiExclusiveMode.Location = new System.Drawing.Point(134, 30);
this.checkBoxWasapiExclusiveMode.Name = "checkBoxWasapiExclusiveMode";
this.checkBoxWasapiExclusiveMode.Size = new System.Drawing.Size(101, 17);
this.checkBoxWasapiExclusiveMode.TabIndex = 18;
this.checkBoxWasapiExclusiveMode.Text = "Exclusive Mode";
this.checkBoxWasapiExclusiveMode.UseVisualStyleBackColor = true;
//
// WasapiOutSettingsPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.comboBoxWaspai);
this.Controls.Add(this.checkBoxWasapiEventCallback);
this.Controls.Add(this.checkBoxWasapiExclusiveMode);
this.Name = "WasapiOutSettingsPanel";
this.Size = new System.Drawing.Size(245, 57);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox comboBoxWaspai;
private System.Windows.Forms.CheckBox checkBoxWasapiEventCallback;
private System.Windows.Forms.CheckBox checkBoxWasapiExclusiveMode;
}
}
| 43.406977 | 107 | 0.627645 | [
"MIT"
] | Albeoris/Pulse | Pulse.UI/Controls/AudioPlayback/WasapiOutSettingsPanel.Designer.cs | 3,735 | C# |
using System;
namespace ICalendar.ComponentProperties
{
//TODO: change the signature to UTC-OFFSET
public class Tzoffsetto : ComponentProperty<TimeSpan>
{
public override string Name => "TZOFFSETTO";
}
} | 22.9 | 57 | 0.703057 | [
"MIT"
] | UHCalendarTeam/ANtICalendar | src/ICalendar/ComponentProperties/TimeZone/TZoffsetto.cs | 231 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dotnetNES.Engine.Main;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight;
namespace dotnetNES.Client.Models
{
public class CPUFlags : ObservableObject
{
public string Accumulator { get; set; }
public string XRegister { get; set; }
public string YRegister { get; set; }
public string StackPointer { get; set; }
public string ProgramCounter { get; set; }
public int RawProgramCounter { get; set; }
public long CycleCount { get; set; }
public bool CarryFlag { get; set; }
public bool ZeroFlag { get; set; }
public bool DisableInterruptFlag { get; set; }
public bool DecimalFlag { get; set; }
public bool OverflowFlag { get; set; }
public bool NegativeFlag { get; set; }
public string FlagsRegister { get; set; }
public void UpdateFlags(dotnetNES.Engine.Main.Engine engine)
{
Accumulator = engine.GetAccumulator();
XRegister = engine.GetXRegister();
YRegister = engine.GetYRegister();
StackPointer = engine.GetStackPointer();
ProgramCounter = engine.GetProgramCounter();
RawProgramCounter = engine.GetRawProgramCounter();
CarryFlag = engine.GetCarryFlag();
ZeroFlag = engine.GetZeroFlag();
DisableInterruptFlag = engine.GetDisableInterruptFlag();
DecimalFlag = engine.GetDecimalFlag();
OverflowFlag = engine.GetOverflowFlag();
NegativeFlag = engine.GetNegativeFlag();
CycleCount = engine.GetProcessorCycles();
FlagsRegister = engine.GetFlagsRegister();
}
}
}
| 37.729167 | 68 | 0.64053 | [
"MIT"
] | aaronmell/dotnetNES | dotnetNES.Client/Models/CPUFlags.cs | 1,813 | C# |
using UnityEngine;
/// <summary>
/// This script should be attached to the card game object to display card`s rotation correctly.
/// </summary>
[ExecuteInEditMode]
public class BetterCardRotation : MonoBehaviour {
public RectTransform CardFront;
public RectTransform CardBack;
void Update()
{
if (Camera.main == null)
return;
var showFront = Vector3.Dot(transform.forward, Camera.main.transform.forward) > 0;
CardFront.gameObject.SetActive(showFront);
CardBack.gameObject.SetActive(!showFront);
}
}
| 24.782609 | 96 | 0.684211 | [
"MIT"
] | n4gava/card-game | Assets/Scripts/Visual/Card/BetterCardRotation.cs | 572 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BrokeProtocol.API;
namespace BPGroupEditor
{
class ExtensionMethods
{
public static string GroupNameTypeToInfo(GroupType grptype)
{
if (grptype == GroupType.AccountID)
return "Enter the users SteamID64 or registered account name if Steam auth is disabled. Example: 76561198088598550 or NongBenz";
if (grptype == GroupType.ConnectionIP)
return "Enter users IPv4. Example: \"127.0.0.1\"";
if (grptype == GroupType.JobIndex)
return "Enter user JobID. Example: \"3\"";
if (grptype == GroupType.JobName)
return "Enter user job name. Example: \"Police\"";
if (grptype == GroupType.JobGroupIndex)
return "Enter user job group index. \"0 = Citizen(Most Jobs), 1 = Criminal(Gang Member), 2 = LawEnforcement(SpecOps, Police)\" Example: \"2\"";
else
{
return "The identifier of the scriptable trigger the user is currently in. (if any) Example: \"SomeStringIdentifier\"";
}
}
}
}
| 39.387097 | 159 | 0.613432 | [
"MIT"
] | Lamingtonn/BPGroupEditor | Extension/ExtensionMethods.cs | 1,223 | C# |
using System.Linq;
using System.Collections.Generic;
using GoogleTestAdapter.Common;
using GoogleTestAdapter.Model;
using GoogleTestAdapter.Runners;
using GoogleTestAdapter.Framework;
using GoogleTestAdapter.ProcessExecution.Contracts;
using GoogleTestAdapter.Scheduling;
using GoogleTestAdapter.Settings;
using GoogleTestAdapter.TestResults;
namespace GoogleTestAdapter
{
public class GoogleTestExecutor
{
private readonly ILogger _logger;
private readonly SettingsWrapper _settings;
private readonly IDebuggedProcessExecutorFactory _processExecutorFactory;
private readonly IExitCodeTestsReporter _exitCodeTestsReporter;
private readonly SchedulingAnalyzer _schedulingAnalyzer;
private ITestRunner _runner;
private bool _canceled;
public GoogleTestExecutor(ILogger logger, SettingsWrapper settings, IDebuggedProcessExecutorFactory processExecutorFactory, IExitCodeTestsReporter exitCodeTestsReporter)
{
_logger = logger;
_settings = settings;
_processExecutorFactory = processExecutorFactory;
_exitCodeTestsReporter = exitCodeTestsReporter;
_schedulingAnalyzer = new SchedulingAnalyzer(logger);
}
public void RunTests(IEnumerable<TestCase> testCasesToRun, ITestFrameworkReporter reporter, bool isBeingDebugged)
{
TestCase[] testCasesToRunAsArray = testCasesToRun as TestCase[] ?? testCasesToRun.ToArray();
_logger.LogInfo("Running " + testCasesToRunAsArray.Length + " tests...");
lock (this)
{
if (_canceled)
{
return;
}
ComputeTestRunner(reporter, isBeingDebugged);
}
_runner.RunTests(testCasesToRunAsArray, isBeingDebugged, _processExecutorFactory);
_exitCodeTestsReporter.ReportExitCodeTestCases(_runner.ExecutableResults, isBeingDebugged);
if (_settings.ParallelTestExecution)
_schedulingAnalyzer.PrintStatisticsToDebugOutput();
}
public void Cancel()
{
lock (this)
{
_canceled = true;
_runner?.Cancel();
}
}
private void ComputeTestRunner(ITestFrameworkReporter reporter, bool isBeingDebugged)
{
if (_settings.ParallelTestExecution && !isBeingDebugged)
{
_runner = new ParallelTestRunner(reporter, _logger, _settings, _schedulingAnalyzer);
}
else
{
_runner = new PreparingTestRunner(reporter, _logger, _settings, _schedulingAnalyzer);
if (_settings.ParallelTestExecution && isBeingDebugged)
{
_logger.DebugInfo(
"Parallel execution is selected in options, but tests are executed sequentially because debugger is attached.");
}
}
}
}
} | 34.954023 | 177 | 0.649129 | [
"Apache-2.0"
] | csoltenborn/GoogleTestAdapter | GoogleTestAdapter/Core/GoogleTestExecutor.cs | 3,043 | C# |
using System;
using System.Net;
using System.Threading.Tasks;
namespace PlaylistGrabber
{
public interface IWebClientWrapper
{
Task DownloadFileTaskAsync(Uri uri, string destinationPath);
}
public class WebClientWrapper : IWebClientWrapper
{
public async Task DownloadFileTaskAsync(Uri uri, string destinationPath)
{
using var webClient = new WebClient();
await webClient.DownloadFileTaskAsync(uri, destinationPath).ConfigureAwait(false);
}
}
}
| 25.142857 | 94 | 0.693182 | [
"MIT"
] | jasonracey/PlaylistGrabber | PlaylistGrabber/WebClientWrapper.cs | 530 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace OSharp.AutoMapper.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </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("OSharp.AutoMapper.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 使用此强类型资源类,为所有资源查找
/// 重写当前线程的 CurrentUICulture 属性。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| 38.453125 | 183 | 0.589191 | [
"Apache-2.0"
] | VictorTzeng/osharp | src/OSharp.AutoMapper/Properties/Resources.Designer.cs | 2,811 | C# |
using System.Threading;
using TechTalk.SpecFlow;
namespace Behavioral.Automation.Bindings
{
[Binding]
public sealed class DebugBinding
{
[Given("wait")]
[When("wait")]
[Then("wait")]
public void Wait()
{
Thread.Sleep(5000);
}
}
}
| 17.111111 | 40 | 0.545455 | [
"Apache-2.0"
] | PavelAAlexeevQ/Behavioral.Automation | Bindings/DebugBinding.cs | 310 | C# |
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
using UnrealBuildTool;
public class UE4EditorServices : ModuleRules
{
public UE4EditorServices(TargetInfo Target)
{
PublicIncludePaths.Add("Runtime/Launch/Public");
PublicIncludePaths.Add("Runtime/Launch/Private"); // Yuck. Required for RequiredProgramMainCPPInclude.h. (Also yuck).
PrivateDependencyModuleNames.AddRange(
new string[] {
"Core",
"DesktopPlatform",
"Json",
"Projects",
}
);
}
}
| 22.318182 | 119 | 0.720978 | [
"MIT"
] | armroyce/Unreal | UnrealEngine-4.11.2-release/Engine/Source/Programs/Mac/UE4EditorServices/UE4EditorServices.Build.cs | 493 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqToVdf
{
public static class VdfReaderExtensions
{
public static VdfReaderToken CheckNext(this StreamReader reader)
{
var next = reader.Peek();
if (IsEmpty(next)) return VdfReaderToken.Empty;
if (IsLimiter(next)) return VdfReaderToken.Limiter;
if (IsBlockStart(next)) return VdfReaderToken.BlockStart;
if (IsBlockEnd(next)) return VdfReaderToken.BlockEnd;
return VdfReaderToken.Other;
}
public static void ReadEmpty(this StreamReader reader)
{
while (IsEmpty(reader.Peek()))
reader.Read();
}
public static bool ReadLimiter(this StreamReader reader)
{
return IsLimiter(reader.Read());
}
public static bool ReadBlockStart(this StreamReader reader)
{
return IsBlockStart(reader.Read());
}
public static bool ReadBlockEnd(this StreamReader reader)
{
return IsBlockEnd(reader.Read());
}
public static string ReadText(this StreamReader reader)
{
var sb = new StringBuilder();
while (!IsLimiter(reader.Peek()))
sb.Append((char)reader.Read());
if (sb.Length == 0)
return null;
return sb.ToString();
}
private static bool IsEmpty(int value)
{
return value == 9 || value == 10 || value == 13 || value == 32;
}
private static bool IsLimiter(int value)
{
return value == 34;
}
private static bool IsBlockStart(int value)
{
return value == 123;
}
private static bool IsBlockEnd(int value)
{
return value == 125;
}
}
}
| 26.052632 | 75 | 0.558586 | [
"MIT"
] | porohkun/LinqToVdf | LinqToVdf/VdfReaderExtensions.cs | 1,982 | 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("Cosmos.Debug.Kernel")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Cosmos")]
[assembly: AssemblyProduct("Cosmos.Debug.Kernel")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dab57676-747b-4a09-9120-6d0cd4b06df3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("Cosmos.Core, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e3ef5198fa2f8926f006b5d2053eb3b3c875e74695675a6b97bd27ba6b0c5cbee26710c04277f7975927ace4a037692eddb71340a4c3f11e06c645c6a4cebad303301228943b39378bf3222f9432ff9c72c31d1a5e936db6cf9f18c23bd52a43c091fc803ce2139cd390a9678553d1e6061656c3d0196ddbd2233143fc433195")]
[assembly: InternalsVisibleTo("Cosmos.HAL, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e3ef5198fa2f8926f006b5d2053eb3b3c875e74695675a6b97bd27ba6b0c5cbee26710c04277f7975927ace4a037692eddb71340a4c3f11e06c645c6a4cebad303301228943b39378bf3222f9432ff9c72c31d1a5e936db6cf9f18c23bd52a43c091fc803ce2139cd390a9678553d1e6061656c3d0196ddbd2233143fc433195")]
[assembly: InternalsVisibleTo("Cosmos.System, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e3ef5198fa2f8926f006b5d2053eb3b3c875e74695675a6b97bd27ba6b0c5cbee26710c04277f7975927ace4a037692eddb71340a4c3f11e06c645c6a4cebad303301228943b39378bf3222f9432ff9c72c31d1a5e936db6cf9f18c23bd52a43c091fc803ce2139cd390a9678553d1e6061656c3d0196ddbd2233143fc433195")]
[assembly: InternalsVisibleTo("Cosmos.IL2CPU, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e3ef5198fa2f8926f006b5d2053eb3b3c875e74695675a6b97bd27ba6b0c5cbee26710c04277f7975927ace4a037692eddb71340a4c3f11e06c645c6a4cebad303301228943b39378bf3222f9432ff9c72c31d1a5e936db6cf9f18c23bd52a43c091fc803ce2139cd390a9678553d1e6061656c3d0196ddbd2233143fc433195")]
[assembly: InternalsVisibleTo("Cosmos.Compiler.Tests.SimpleWriteLine.Kernel, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e3ef5198fa2f8926f006b5d2053eb3b3c875e74695675a6b97bd27ba6b0c5cbee26710c04277f7975927ace4a037692eddb71340a4c3f11e06c645c6a4cebad303301228943b39378bf3222f9432ff9c72c31d1a5e936db6cf9f18c23bd52a43c091fc803ce2139cd390a9678553d1e6061656c3d0196ddbd2233143fc433195")]
[assembly: InternalsVisibleTo("Cosmos.TestRunner.TestController, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e3ef5198fa2f8926f006b5d2053eb3b3c875e74695675a6b97bd27ba6b0c5cbee26710c04277f7975927ace4a037692eddb71340a4c3f11e06c645c6a4cebad303301228943b39378bf3222f9432ff9c72c31d1a5e936db6cf9f18c23bd52a43c091fc803ce2139cd390a9678553d1e6061656c3d0196ddbd2233143fc433195")]
[assembly: InternalsVisibleTo("Cosmos.Common, PublicKey=0024000004800000940000000602000000240000525341310004000001000100e3ef5198fa2f8926f006b5d2053eb3b3c875e74695675a6b97bd27ba6b0c5cbee26710c04277f7975927ace4a037692eddb71340a4c3f11e06c645c6a4cebad303301228943b39378bf3222f9432ff9c72c31d1a5e936db6cf9f18c23bd52a43c091fc803ce2139cd390a9678553d1e6061656c3d0196ddbd2233143fc433195")]
| 92.466667 | 411 | 0.881279 | [
"BSD-3-Clause"
] | mmkhmmkh/Cosmos | source/Cosmos.Debug.Kernel/Properties/AssemblyInfo.cs | 4,164 | C# |
namespace WalletWasabi.Fluent.Models;
public class RestartNeededEventArgs : EventArgs
{
public bool IsRestartNeeded { get; init; }
}
| 19.285714 | 47 | 0.792593 | [
"MIT"
] | CAnorbo/WalletWasabi | WalletWasabi.Fluent/Models/RestartNeededEventArgs.cs | 135 | C# |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) Upendo Ventures, LLC
//
// 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
using System.Globalization;
using System.Xml;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Upgrade.Internals;
using Upendo.Modules.UpendoPrompt.Entities.Interfaces;
namespace Upendo.Modules.UpendoPrompt.Components
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Instrumentation;
using DotNetNuke.Services.Installer.Packages;
using Upendo.Modules.UpendoPrompt.Entities;
public class PackagesController
{
private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(PackagesController));
public PackagesController()
{
// do nothing
}
public string GetPackageBackupPath()
{
try
{
var folderPath = Path.Combine(DotNetNuke.Common.Globals.ApplicationMapPath, DotNetNuke.Services.Installer.Util.BackupInstallPackageFolder);
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
return folderPath;
}
catch (Exception e)
{
LogError(e);
throw;
}
}
public List<AvailablePackagesDto> GetAvailablePackages(string packageType)
{
var packages = new List<AvailablePackagesDto>();
string packagePath;
if (this.HasAvailablePackage(packageType, out packagePath))
{
var validpackages = new Dictionary<string, PackageInfo>();
var invalidPackages = new List<string>();
foreach (string file in Directory.GetFiles(packagePath))
{
if (file.ToLower().EndsWith(".zip") || file.ToLower().EndsWith(".resources"))
{
PackageController.ParsePackage(file, packagePath, validpackages, invalidPackages);
}
}
if (packageType.ToLowerInvariant() == "corelanguagepack")
{
this.GetAvaialableLanguagePacks(validpackages);
}
packages.Add(new AvailablePackagesDto()
{
PackageType = packageType,
ValidPackages = validpackages.Values.Select(p => new PackageInfoSlimDto(Null.NullInteger, p)).ToList(),
InvalidPackages = invalidPackages,
});
}
return packages;
}
public bool HasAvailablePackage(string packageType, out string rootPath)
{
var type = packageType;
switch (packageType.ToLowerInvariant())
{
case "authsystem":
case "auth_system":
type = PackageTypes.AuthSystem.ToString();
rootPath = Globals.ApplicationMapPath + "\\Install\\AuthSystem";
break;
case "javascriptlibrary":
case "javascript_library":
rootPath = Globals.ApplicationMapPath + "\\Install\\JavaScriptLibrary";
break;
case "extensionlanguagepack":
type = PackageTypes.Language.ToString();
rootPath = Globals.ApplicationMapPath + "\\Install\\Language";
break;
case "corelanguagepack":
rootPath = Globals.ApplicationMapPath + "\\Install\\Language";
return true; // core languages should always marked as have available packages.
case "module":
case "skin":
case "container":
case "provider":
case "library":
rootPath = Globals.ApplicationMapPath + "\\Install\\" + packageType;
break;
default:
type = string.Empty;
rootPath = string.Empty;
break;
}
/*
// original code in DNN Platform
if (!string.IsNullOrEmpty(type) && Directory.Exists(rootPath) &&
(Directory.GetFiles(rootPath, "*.zip").Length > 0 ||
Directory.GetFiles(rootPath, "*.resources").Length > 0))
{
return true;
}
*/
if (!string.IsNullOrEmpty(type) && Directory.Exists(rootPath) &&
(Directory.GetFiles(rootPath, "*.zip").Length > 0))
{
return true;
}
return false;
}
private void GetAvaialableLanguagePacks(IDictionary<string, PackageInfo> validPackages)
{
try
{
StreamReader myResponseReader = UpdateService.GetLanguageList();
var xmlDoc = new XmlDocument { XmlResolver = null };
xmlDoc.Load(myResponseReader);
XmlNodeList languages = xmlDoc.SelectNodes("available/language");
if (languages != null)
{
var installedPackages = PackageController.Instance.GetExtensionPackages(Null.NullInteger, p => p.PackageType == "CoreLanguagePack");
var installedLanguages = installedPackages.Select(package => LanguagePackController.GetLanguagePackByPackage(package.PackageID)).ToList();
foreach (XmlNode language in languages)
{
string cultureCode = "";
string version = "";
foreach (XmlNode child in language.ChildNodes)
{
if (child.Name == "culturecode")
{
cultureCode = child.InnerText;
}
if (child.Name == "version")
{
version = child.InnerText;
}
}
if (!string.IsNullOrEmpty(cultureCode) && !string.IsNullOrEmpty(version) && version.Length == 6)
{
var myCIintl = new CultureInfo(cultureCode, true);
version = version.Insert(4, ".").Insert(2, ".");
var package = new PackageInfo { Owner = "DotNetNuke Update Service", Name = "LanguagePack-" + myCIintl.Name, FriendlyName = myCIintl.NativeName };
package.Name = myCIintl.NativeName;
package.PackageType = "CoreLanguagePack";
package.Description = cultureCode;
Version ver = null;
Version.TryParse(version, out ver);
package.Version = ver;
if (
installedLanguages.Any(
l =>
LocaleController.Instance.GetLocale(l.LanguageID).Code.ToLowerInvariant().Equals(cultureCode.ToLowerInvariant())
&& installedPackages.First(p => p.PackageID == l.PackageID).Version >= ver))
{
continue;
}
if (validPackages.Values.Any(p => p.Name == package.Name))
{
var existPackage = validPackages.Values.First(p => p.Name == package.Name);
if (package.Version > existPackage.Version)
{
existPackage.Version = package.Version;
}
}
else
{
validPackages.Add(cultureCode, package);
}
}
}
}
}
catch (Exception)
{
// suppress for now - need to decide what to do when webservice is unreachable
// throw;
// same problem happens in InstallWizard.aspx.cs in BindLanguageList method
}
}
#region Helper Methods
protected void LogError(Exception ex)
{
if (ex != null)
{
Logger.Error(ex.Message, ex);
if (ex.InnerException != null)
{
Logger.Error(ex.InnerException.Message, ex.InnerException);
}
}
}
#endregion
}
} | 41.608163 | 174 | 0.510987 | [
"MIT"
] | UpendoVentures/Upendo-Dnn-Prompt | Modules/UpendoPrompt/Components/PackagesController.cs | 10,196 | C# |
using System;
using NUnit.Framework;
namespace WebGL.UnitTests
{
[TestFixture]
public class TexSubImage2D : BaseTest
{
[Test(Description = "")]
public void ShouldDoMagic()
{
throw new NotImplementedException();
}
}
} | 18.533333 | 48 | 0.593525 | [
"Apache-2.0"
] | jdarc/webgl.net | WebGL.UnitTests/conformance/v100/TexSubImage2D.cs | 280 | C# |
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Spring.Web.UI.Controls
{
/// <summary>
/// May be used to wrap controls for databinding that don't accept unknown attributes.
/// </summary>
[ParseChildren(false)]
public class DataBindingAdapter : WebControl
{
private Control wrappedControl;
/// <summary>
/// Overridden to ensure only 1 control is wrapped by this adapter
/// </summary>
/// <param name="obj"></param>
protected override void AddParsedSubObject(object obj)
{
if(obj is Control && (wrappedControl == null) && (!(obj is LiteralControl)))
{
wrappedControl = (Control) obj;
this.Controls.Add(wrappedControl);
}
else if(!(obj is LiteralControl))
{
throw new HttpException(
string.Format("DataBindingAdapter can only have 1 non-literal child", new object[] { obj.GetType().Name }));
}
}
/// <summary>
/// Returns the control wrapped by this adapter or null.
/// </summary>
public Control WrappedControl
{
get { return this.wrappedControl; }
}
/// <summary>
/// Overridden to render wrapped control only.
/// </summary>
protected override void Render(HtmlTextWriter writer)
{
if (wrappedControl != null)
{
wrappedControl.RenderControl(writer);
}
}
}
} | 29.884615 | 128 | 0.56242 | [
"Apache-2.0"
] | MaferYangPointJun/Spring.net | src/Spring/Spring.Web/Web/UI/Controls/DataBindingAdapter.cs | 1,554 | C# |
namespace CarManufacturer
{
public class StartUp
{
static void Main(string[] args)
{
Tire[] tires = new Tire[4]
{
new Tire(1, 2.5),
new Tire(1, 2.1),
new Tire(2, 0.5),
new Tire(2, 2.3),
};
Engine engine = new Engine(560, 6300);
Car car = new Car("Lamborgihi", "Urus", 2010, 250, 9, engine, tires);
}
}
}
| 22.238095 | 81 | 0.4197 | [
"MIT"
] | vassdeniss/software-university-courses | csharp-advanced/11.Classes/L04.CarEngineAndTires/StartUp.cs | 469 | C# |
/****
* Created by; Rohit Khanolkar
* Date Created: 2/14/2022
*
* Last Edited by: NA
* Last edited: 2/14/2022
*
*
* Description: Create a randomly generated cloud
****/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Cloud : MonoBehaviour
{
[Header("Set in Inspector")]
public GameObject cloudSphere;
public int numberSpheresMin = 6;
public int numberSpheresMax = 10;
public Vector2 sphereScaleRangeX = new Vector2(4, 8);
public Vector2 sphereScaleRangeY = new Vector2(3, 4);
public Vector2 sphereScaleRangeZ = new Vector2(2, 4);
public Vector3 sphereOffsetScale = new Vector3(5, 2, 1);
public float scaleYMin = 2f;
private List<GameObject> spheres;
// Start is called before the first frame update
void Start()
{
spheres = new List<GameObject>();
int num = Random.Range(numberSpheresMin, numberSpheresMax);
for(int i = 0; i < num; i++)
{
GameObject sp = Instantiate<GameObject>(cloudSphere);
spheres.Add(sp);
Transform spTrans = sp.transform;
spTrans.SetParent(this.transform);
//randomly assign a position
Vector3 offset = Random.insideUnitSphere;
offset.x *= sphereOffsetScale.x;
offset.y *= sphereOffsetScale.y;
offset.z *= sphereOffsetScale.z;
spTrans.localPosition = offset;
//randomly assign scale
Vector3 scale = Vector3.one;
scale.x = Random.Range(sphereScaleRangeX.x, sphereScaleRangeX.y);
scale.y = Random.Range(sphereScaleRangeY.x, sphereScaleRangeY.y);
scale.y = Random.Range(sphereScaleRangeZ.x, sphereScaleRangeZ.y);
//adjust Y scale by X distance from core
scale.y *= 1 - (Mathf.Abs(offset.x) / sphereOffsetScale.x);
scale.y = Mathf.Max(scale.y, scaleYMin);
spTrans.localScale = scale;
}
}
// Update is called once per frame
void Update()
{
// if (Input.GetKeyDown(KeyCode.Space))
// {
// Restart();
// }
}
void Restart()
{
foreach (GameObject sp in spheres)
{
Destroy(sp);
}
Start();
}
}
| 24.010417 | 77 | 0.597831 | [
"MIT"
] | rsk8262/MissionDemolition | MissionDemolition-Unity/Assets/Scripts/Cloud.cs | 2,305 | C# |
// <copyright file="ItemExtensions.cs" company="MUnique">
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace MUnique.OpenMU.GameLogic
{
using System;
using System.Collections.Generic;
using System.Linq;
using MUnique.OpenMU.DataModel.Configuration.Items;
using MUnique.OpenMU.DataModel.Entities;
using MUnique.OpenMU.Persistence;
/// <summary>
/// Extension methods for <see cref="Item"/>.
/// </summary>
public static class ItemExtensions
{
private static readonly byte[] AdditionalDurabilityPerLevel = { 0, 1, 2, 3, 4, 6, 8, 10, 12, 14, 17, 21, 26, 32, 39, 47 };
/// <summary>
/// Gets the maximum durability of the item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>The maximum durability of the item.</returns>
/// <remarks>
/// I think this is more like the durability which can be dropped.
/// Some items can be stacked up to 255 pieces, which increases the durability value.
/// </remarks>
public static byte GetMaximumDurabilityOfOnePiece(this Item item)
{
if (item.Definition.ItemSlot == null)
{
// Items which are not wearable don't have a "real" durability. If the item is stackable, durability means number of pieces in this case
return 1; // TODO: check if this makes sense for all cases
}
var result = item.Definition.Durability + AdditionalDurabilityPerLevel[item.Level];
if (item.ItemOptions.Any(link => link.ItemOption.OptionType == ItemOptionTypes.AncientOption))
{
result += 20;
}
else if (item.ItemOptions.Any(link => link.ItemOption.OptionType == ItemOptionTypes.Excellent))
{
// TODO: archangel weapons, but I guess it's not a big issue if we don't, because of their already high durability
result += 15;
}
return (byte)Math.Min(byte.MaxValue, result);
}
/// <summary>
/// Gets the item data which is relvant for the visual appearance of an item.
/// </summary>
/// <param name="item">The item.</param>
/// <returns>The item data which is relvant for the visual appearance of an item.</returns>
public static ItemAppearance GetAppearance(this Item item)
{
var appearance = new TemporaryItemAppearance
{
Definition = item.Definition,
ItemSlot = item.ItemSlot,
Level = item.Level,
};
item.ItemOptions
.Where(option => option.ItemOption.OptionType?.IsVisible ?? false)
.Select(option => option.ItemOption.OptionType)
.ForEach(appearance.VisibleOptions.Add);
return appearance;
}
/// <summary>
/// Creates a persistent instance of the given <see cref="ItemAppearance"/> and returns it.
/// </summary>
/// <param name="itemAppearance">The item appearance.</param>
/// <param name="persistenceContext">The persistence context where the object should be added.</param>
/// <returns>A persistent instance of the given <see cref="ItemAppearance"/>.</returns>
public static ItemAppearance MakePersistent(this ItemAppearance itemAppearance, IContext persistenceContext)
{
var persistent = persistenceContext.CreateNew<ItemAppearance>();
persistent.ItemSlot = itemAppearance.ItemSlot;
persistent.Definition = itemAppearance.Definition;
persistent.Level = itemAppearance.Level;
itemAppearance.VisibleOptions.ForEach(o => persistent.VisibleOptions.Add(o));
return persistent;
}
private sealed class TemporaryItemAppearance : ItemAppearance
{
public override ICollection<ItemOptionType> VisibleOptions => base.VisibleOptions ?? (base.VisibleOptions = new List<ItemOptionType>());
}
}
}
| 44.329787 | 152 | 0.618431 | [
"MIT"
] | hatalaef/OpenMU | src/GameLogic/ItemExtensions.cs | 4,169 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MusicSwitcher : MonoBehaviour {
private MusicManager mcMan;
public int NewTrack;
public bool SwitchOnStart;
// Use this for initialization
void Start () {
mcMan = FindObjectOfType<MusicManager>();
if (SwitchOnStart)
{
mcMan.SwitchTrack(NewTrack);
gameObject.SetActive(false);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.gameObject.name == "Player")
{
mcMan.SwitchTrack(NewTrack);
gameObject.SetActive(false); // So you won't reset the track multiple times
}
}
}
| 21.878788 | 88 | 0.632964 | [
"MIT"
] | MartinListwan/GameDesign | Assets/Scripts/MusicSwitcher.cs | 724 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using AppKit;
namespace LogJoint.UI.Postprocessing.TimeSeriesVisualizer
{
public partial class LegendItemView : NSView
{
#region Constructors
// Called when created from unmanaged code
public LegendItemView(IntPtr handle) : base(handle)
{
Initialize();
}
// Called when created directly from a XIB file
[Export("initWithCoder:")]
public LegendItemView(NSCoder coder) : base(coder)
{
Initialize();
}
// Shared initialization code
void Initialize()
{
}
#endregion
}
}
| 18.090909 | 57 | 0.720268 | [
"MIT"
] | logjointfork/logjoint | trunk/platforms/osx/logjoint.mac/ui/Postprocessors/TimeSeriesWindow/Legend/Item/LegendItemView.cs | 599 | C# |
using Akka.Streams.Stage;
using Amqp;
using System.Threading.Tasks;
namespace Akka.Streams.Amqp.V1
{
public sealed class AmqpSinkStage<T> : GraphStageWithMaterializedValue<SinkShape<T>, Task>
{
public Inlet<T> In { get; }
public override SinkShape<T> Shape { get; }
public IAmpqSinkSettings<T> AmpqSourceSettings { get; }
public override ILogicAndMaterializedValue<Task> CreateLogicAndMaterializedValue(Attributes inheritedAttributes)
{
var promise = new TaskCompletionSource<Done>();
var logic = new AmqpSinkStageLogic(this, promise, Shape);
return new LogicAndMaterializedValue<Task>(logic, promise.Task);
}
public AmqpSinkStage(IAmpqSinkSettings<T> ampqSourceSettings)
{
In = new Inlet<T>("AmqpSink.in");
Shape = new SinkShape<T>(In);
AmpqSourceSettings = ampqSourceSettings;
}
private class AmqpSinkStageLogic : GraphStageLogic
{
private readonly AmqpSinkStage<T> stage;
private readonly TaskCompletionSource<Done> promise;
private readonly SenderLink sender;
public AmqpSinkStageLogic(AmqpSinkStage<T> amqpSinkStage, TaskCompletionSource<Done> promise, SinkShape<T> shape) : base(shape)
{
stage = amqpSinkStage;
this.promise = promise;
sender = amqpSinkStage.AmpqSourceSettings.GetSenderLink();
SetHandler(stage.In, () =>
{
var elem = Grab(stage.In);
sender.Send(new Message(amqpSinkStage.AmpqSourceSettings.GetBytes(elem)));
Pull(stage.In);
},
onUpstreamFinish: () => promise.SetResult(Done.Instance),
onUpstreamFailure: ex => promise.SetException(ex)
);
}
public override void PreStart()
{
base.PreStart();
Pull(stage.In);
}
public override void PostStop()
{
sender.Close();
base.PostStop();
}
}
}
}
| 34.625 | 139 | 0.569495 | [
"Apache-2.0"
] | AndreSteenbergen/Alpakka | Amqp.V1/Akka.Streams.Amqp.V1/AmqpSinkStage.cs | 2,218 | C# |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
using System.Collections.Generic;
namespace Npoi.Core.POIFS.Storage
{
/// <summary>
/// A list of SmallDocumentBlocks instances, and methods to manage the list
/// @author Marc Johnson (mjohnson at apache dot org)
/// </summary>
public class SmallDocumentBlockList : BlockListImpl
{
/// <summary>
/// Initializes a new instance of the <see cref="SmallDocumentBlockList"/> class.
/// </summary>
/// <param name="blocks">a list of SmallDocumentBlock instances</param>
public SmallDocumentBlockList(List<SmallDocumentBlock> blocks)
{
SetBlocks((ListManagedBlock[])blocks.ToArray());
}
}
} | 41.531915 | 89 | 0.606045 | [
"Apache-2.0"
] | Arch/Npoi.Core | src/Npoi.Core/POIFS/Storage/SmallDocumentBlockList.cs | 1,954 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using BL; // BL katmanını kullandık
using Entity; // Entity katmanını kullandık
namespace KutuphaneOtomasyonu
{
public partial class OgrAnaForm : Form
{
public OgrAnaForm(int oid)
{
//Giris Yapan Ogrencinin id sini aliyoruz.
InitializeComponent();
OgrID = oid;
}
//Ogrenci ID yi kullanmak için global olarak tanımladım.
int OgrID;
//Form ekranını Tutup Sürkleyip Monitörün istediğimiz bir bölgesine koymamızı sağlayan kod blokları
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool ReleaseCapture();
//panel1 yani form1 deki üst taraftaki paneli mouseDown eventi ile sürükleyip mönitörümüzün istediğimiz kısmına getire biliriz.
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void buttonClose_Click(object sender, EventArgs e)
{
System.Windows.Forms.Application.Exit(); // Buton' a tıklanınca uyguylamayı kapattık
}
private void OgrAnaForm_Load(object sender, EventArgs e)
{
//butona tikladığımızda panel2 ye göstermek istediğimiz form penceresini getiriyoruz.
panel4.Controls.Clear();
OgrBilgileri c1 = new OgrBilgileri(OgrID);
c1.Dock = DockStyle.Fill;
c1.TopLevel = false;
c1.FormBorderStyle = FormBorderStyle.None;
panel4.Controls.Add(c1);
c1.Show();
OgrenciVeri ogrenci = new OgrenciVeri() // Ogrenci veriden nesne oluşturuldu
{
OgrenciId = OgrID //Id ogrenci ıd ' ye aktarıldı
};
//Ogrenci bilgileri labellara aktarıldı
ogrenci = OgrenciBL.ogrenciIdBilgi(ogrenci);
//Ogrencinin Adini ve Soy adinin lbl a yazdırdım.
lblUserName.Text = ogrenci.OgrenciAd + " " + ogrenci.OgrenciSoyad;
}
private void button6_Click(object sender, EventArgs e)
{
GirisMainForm gorevliGiris = new GirisMainForm(); //Nesne oluşturuldu
this.Hide(); //aktif form kapatıldı
gorevliGiris.Show(); // oluşturulan nesneden yeni form açıldı
}
private void button3_Click(object sender, EventArgs e)
{
//ekranGetir fonksiyonu ile panel4 un icerisine istediğim formu getiriyorum.
ekranGetir(new OgrKitapIslemleri(OgrID), sender);
}
private void button1_Click(object sender, EventArgs e)
{
//ekranGetir fonksiyonu ile panel4 un icerisine istediğim formu getiriyorum.
ekranGetir(new OgrBilgileri(OgrID), sender);
}
private void button2_Click(object sender, EventArgs e)
{
//ekranGetir fonksiyonu ile panel4 un icerisine istediğim formu getiriyorum.
ekranGetir(new BorcOde(OgrID), sender);
}
private void button5_Click(object sender, EventArgs e)
{
//ekranGetir fonksiyonu ile panel4 un icerisine istediğim formu getiriyorum.
ekranGetir(new OgrGrafik(OgrID), sender);
}
private void button4_Click(object sender, EventArgs e)
{
//ekranGetir fonksiyonu ile panel4 un icerisine istediğim formu getiriyorum.
ekranGetir(new KitapDetay(OgrID), sender);
}
private void ekranGetir(Form c1,object sender)
{
//butona tikladığımızda panel2 ye göstermek istediğimiz form penceresini getiriyoruz.
panel4.Controls.Clear();
c1.Dock = DockStyle.Fill;
c1.TopLevel = false;
c1.FormBorderStyle = FormBorderStyle.None;
panel4.Controls.Add(c1);
c1.Show();
//Hangi butona basılı olduğunu belirlemek için panel5 in Lokasyonunu butonun sağ kenarına ayarlıyorum.
panel5.Location = new Point((sender as Button).Location.X + 180, (sender as Button).Location.Y);
}
}
}
| 38.918033 | 135 | 0.623631 | [
"MIT"
] | Huseyinarkin/KutuphaneOtomasyonu | KutuphaneOtomasyonu/OgrAnaForm.cs | 4,824 | C# |
using System;
using System.Linq.Expressions;
using DNA_API.Models;
namespace DNA_API.Helpers
{
public class PaginationHelper
{
internal static Expression<Func<ViewInvoice, bool>> CustomerInvoicesQuery(string searchString) {
Expression<Func<ViewInvoice, bool>> search = null;
DateTime dateValue;
DateTime.TryParse(searchString, out dateValue);
if (searchString == "" || searchString == null)
{
search = item => item.Id == item.Id;
} else
{
search = item => item.Id.ToString().StartsWith(searchString)
|| item.Subtotal.ToString().StartsWith(searchString)
|| dateValue.Date == item.InvoiceDate.Date;
}
return search;
}
internal static Expression<Func<ViewInvoice, Object>> SortCustomerInvoices(string sortString) {
Expression<Func<ViewInvoice, Object>> orderByFunc = null;
switch (sortString)
{
case "gst":
orderByFunc = item => item.GST;
break;
case "invoiceDate":
orderByFunc = item => item.InvoiceDate;
break;
case "paid":
orderByFunc = item => item.Paid;
break;
case "subtotal":
orderByFunc = item => item.Subtotal;
break;
default:
orderByFunc = item => item.Id;
break;
}
return orderByFunc;
}
}
} | 30.548387 | 104 | 0.43717 | [
"MIT"
] | dan933/dna-invoice-application-public | API/DNA-API/Helpers/PaginationHelper.cs | 1,894 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace KO_Angular_Demo.Controllers
{
public class AngularController : Controller
{
// GET: Angular
public ActionResult Index()
{
return View();
}
[Authorize]
public ActionResult Example()
{
return View();
}
public ActionResult Resource()
{
return View();
}
public ActionResult Additional()
{
return View();
}
}
}
| 17.647059 | 47 | 0.533333 | [
"MIT"
] | joshuadeanhall/TrainingAndDemos | KnockoutAngularDemo/KO_Angular_Demo/Controllers/AngularController.cs | 602 | C# |
using UnityEngine;
using System;
using System.Collections.Generic;
[Serializable]
public class SPBoundingBox
{
public Bounds Bounds;
private Bounds _liveBounds;
public Dictionary<string, object> Serialize()
{
return new Dictionary<string, object>()
{
{"XMin", Bounds.min.x},
{"XMax", Bounds.max.x},
{"YMin", Bounds.min.y},
{"YMax", Bounds.max.y},
{"ZMin", Bounds.min.z},
{"ZMax", Bounds.max.z}
};
}
public static SPBoundingBox Deserialize(Dictionary<string, object> element)
{
Bounds b = new Bounds ();
Vector3 min = new Vector3 ();
if (element.ContainsKey ("XMin") )
min.x = Convert.ToSingle(element["XMin"]);
if (element.ContainsKey ("YMin"))
min.y = Convert.ToSingle(element["YMin"]);
if (element.ContainsKey ("ZMin"))
min.z = Convert.ToSingle(element["ZMin"]);
Vector3 max = new Vector3 ();
if (element.ContainsKey ("XMax") )
max.x = Convert.ToSingle(element["XMax"]);
if (element.ContainsKey ("YMax"))
max.y = Convert.ToSingle(element["YMax"]);
if (element.ContainsKey ("ZMax"))
max.z = Convert.ToSingle(element["ZMax"]);
b.min = min;
b.max = max;
SPBoundingBox box = new SPBoundingBox ();
box.Bounds = b;
return box;
}
}
| 22.924528 | 76 | 0.655144 | [
"MIT"
] | pollend/Parkitect_Mod_Bootstrap | Needs/SPBoundingBox.cs | 1,217 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using NBitcoin;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace Ztm.Data.Entity.Postgres.Migrations
{
public partial class InitializeWebApiCallbackHistory : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_WebApiCallbacks_TransactionId",
table: "WebApiCallbacks");
migrationBuilder.DropColumn(
name: "TransactionId",
table: "WebApiCallbacks");
migrationBuilder.RenameColumn(
name: "RequestTime",
table: "WebApiCallbacks",
newName: "RegisteredTime");
migrationBuilder.RenameColumn(
name: "RequestIp",
table: "WebApiCallbacks",
newName: "RegisteredIp");
migrationBuilder.AddColumn<bool>(
name: "Completed",
table: "WebApiCallbacks",
nullable: false,
defaultValue: false);
migrationBuilder.CreateTable(
name: "WebApiCallbackHistories",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn),
CallbackId = table.Column<Guid>(nullable: false),
Status = table.Column<string>(nullable: false),
InvokedTime = table.Column<DateTime>(nullable: false),
Data = table.Column<string>(type: "jsonb", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_WebApiCallbackHistories", x => x.Id);
table.ForeignKey(
name: "FK_WebApiCallbackHistories_WebApiCallbacks_CallbackId",
column: x => x.CallbackId,
principalTable: "WebApiCallbacks",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_WebApiCallbackHistories_CallbackId",
table: "WebApiCallbackHistories",
column: "CallbackId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "WebApiCallbackHistories");
migrationBuilder.DropColumn(
name: "Completed",
table: "WebApiCallbacks");
migrationBuilder.RenameColumn(
name: "RegisteredTime",
table: "WebApiCallbacks",
newName: "RequestTime");
migrationBuilder.RenameColumn(
name: "RegisteredIp",
table: "WebApiCallbacks",
newName: "RequestIp");
migrationBuilder.AddColumn<uint256>(
name: "TransactionId",
table: "WebApiCallbacks",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_WebApiCallbacks_TransactionId",
table: "WebApiCallbacks",
column: "TransactionId");
}
}
}
| 36.378947 | 114 | 0.538773 | [
"MIT"
] | firoorg/ztm | src/Ztm.Data.Entity.Postgres/Migrations/20191024065745_InitializeWebApiCallbackHistory.cs | 3,458 | C# |
using System;
using System.Collections.Generic;
using Moq;
using NUnit.Framework;
namespace Shuttle.Recall.Tests
{
[TestFixture]
public class EventStreamTests
{
[Test]
public void Should_be_able_to_handle_concurrency_invariant_check()
{
var stream = new EventStream(Guid.NewGuid(), 5, new List<object>(), new Mock<IEventMethodInvoker>().Object);
Assert.DoesNotThrow(() => stream.ConcurrencyInvariant(5));
Assert.Throws<EventStreamConcurrencyException>(() => stream.ConcurrencyInvariant(10));
}
[Test]
public void Should_be_able_to_apply_empty_invariant()
{
EventStream stream = null;
Assert.Throws<EventStreamEmptyException>(() => stream.EmptyInvariant());
stream = new EventStream(new Guid(), new Mock<IEventMethodInvoker>().Object);
Assert.Throws<EventStreamEmptyException>(() => stream.EmptyInvariant());
}
}
} | 31.71875 | 121 | 0.631527 | [
"BSD-3-Clause"
] | JTOne123/Shuttle.Recall | Shuttle.Recall.Tests/EventStreamTests.cs | 1,017 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/codecapi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows;
namespace TerraFX.Interop.UnitTests
{
/// <summary>Provides validation of the <see cref="CODECAPI_AVDecDDStereoDownMixMode" /> struct.</summary>
public static unsafe partial class CODECAPI_AVDecDDStereoDownMixModeTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="CODECAPI_AVDecDDStereoDownMixMode" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(CODECAPI_AVDecDDStereoDownMixMode).GUID, Is.EqualTo(IID_CODECAPI_AVDecDDStereoDownMixMode));
}
/// <summary>Validates that the <see cref="CODECAPI_AVDecDDStereoDownMixMode" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<CODECAPI_AVDecDDStereoDownMixMode>(), Is.EqualTo(sizeof(CODECAPI_AVDecDDStereoDownMixMode)));
}
/// <summary>Validates that the <see cref="CODECAPI_AVDecDDStereoDownMixMode" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(CODECAPI_AVDecDDStereoDownMixMode).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="CODECAPI_AVDecDDStereoDownMixMode" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(CODECAPI_AVDecDDStereoDownMixMode), Is.EqualTo(1));
}
}
}
| 43.066667 | 146 | 0.69969 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | tests/Interop/Windows/um/codecapi/CODECAPI_AVDecDDStereoDownMixModeTests.cs | 1,940 | 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.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.NavigateTo;
using Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[Shared]
[ExportLspMethod(Methods.WorkspaceSymbolName, mutatesSolutionState: false)]
internal class WorkspaceSymbolsHandler : IRequestHandler<WorkspaceSymbolParams, SymbolInformation[]>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public WorkspaceSymbolsHandler()
{
}
public TextDocumentIdentifier? GetTextDocumentIdentifier(WorkspaceSymbolParams request) => null;
public async Task<SymbolInformation[]> HandleRequestAsync(WorkspaceSymbolParams request, RequestContext context, CancellationToken cancellationToken)
{
var solution = context.Solution;
var searchTasks = Task.WhenAll(solution.Projects.Select(project => SearchProjectAsync(project, request, cancellationToken)));
return (await searchTasks.ConfigureAwait(false)).SelectMany(s => s).ToArray();
// local functions
static async Task<ImmutableArray<SymbolInformation>> SearchProjectAsync(Project project, WorkspaceSymbolParams request, CancellationToken cancellationToken)
{
var searchService = project.LanguageServices.GetService<INavigateToSearchService_RemoveInterfaceAboveAndRenameThisAfterInternalsVisibleToUsersUpdate>();
if (searchService != null)
{
// TODO - Update Kinds Provided to return all necessary symbols.
// https://github.com/dotnet/roslyn/projects/45#card-20033822
var items = await searchService.SearchProjectAsync(
project,
ImmutableArray<Document>.Empty,
request.Query,
searchService.KindsProvided,
cancellationToken).ConfigureAwait(false);
var projectSymbolsTasks = Task.WhenAll(items.Select(item => CreateSymbolInformation(item, cancellationToken)));
return (await projectSymbolsTasks.ConfigureAwait(false)).ToImmutableArray();
}
return ImmutableArray.Create<SymbolInformation>();
static async Task<SymbolInformation> CreateSymbolInformation(INavigateToSearchResult result, CancellationToken cancellationToken)
{
return new SymbolInformation
{
Name = result.Name,
Kind = ProtocolConversions.NavigateToKindToSymbolKind(result.Kind),
Location = await ProtocolConversions.TextSpanToLocationAsync(result.NavigableItem.Document, result.NavigableItem.SourceSpan, cancellationToken).ConfigureAwait(false),
};
}
}
}
}
}
| 48.57971 | 190 | 0.671838 | [
"MIT"
] | BrianFreemanAtlanta/roslyn | src/Features/LanguageServer/Protocol/Handler/Symbols/WorkspaceSymbolsHandler.cs | 3,354 | C# |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DevExpress.GridDemo {
public class Quote : ModelObject {
string name = String.Empty;
double currentValue;
double previousValue;
public string Name {
get { return name; }
set {
if (Name == value)
return;
this.name = value;
RaisePropertyChanged("Name");
}
}
public double CurrentValue {
get { return currentValue; }
set {
if (CurrentValue == value)
return;
this.currentValue = value;
RaisePropertyChanged("CurrentValue");
}
}
public double PreviousValue {
get { return previousValue; }
set {
if (PreviousValue == value)
return;
this.previousValue = value;
RaisePropertyChanged("PreviousValue");
}
}
public Quote Clone() {
Quote result = new Quote();
result.Name = this.Name;
result.CurrentValue = this.CurrentValue;
result.PreviousValue = this.PreviousValue;
return result;
}
}
public class MarketSimulator {
readonly ObservableCollection<Quote> quotes;
readonly DateTime now;
readonly Random random;
public MarketSimulator() {
this.now = DateTime.Now;
this.random = new Random((int)now.Ticks);
this.quotes = new ObservableCollection<Quote>();
PopulateQuotes();
}
public ObservableCollection<Quote> Quotes { get { return quotes; } }
void PopulateQuotes() {
quotes.Add(new Quote() { Name = "MSFT", CurrentValue = 42.01, PreviousValue = 42.01 });
quotes.Add(new Quote() { Name = "GOOG", CurrentValue = 510.66, PreviousValue = 510.66 });
quotes.Add(new Quote() { Name = "AAPL", CurrentValue = 118.9, PreviousValue = 118.9 });
quotes.Add(new Quote() { Name = "IBM", CurrentValue = 155.48, PreviousValue = 155.48 });
quotes.Add(new Quote() { Name = "HPQ", CurrentValue = 37.74, PreviousValue = 37.74 });
quotes.Add(new Quote() { Name = "T", CurrentValue = 32.96, PreviousValue = 32.96 });
quotes.Add(new Quote() { Name = "VZ", CurrentValue = 46.11, PreviousValue = 46.11 });
quotes.Add(new Quote() { Name = "YHOO", CurrentValue = 43.73, PreviousValue = 43.73 });
}
public void SimulateNextStep() {
int index = random.Next(0, quotes.Count);
UpdateQuoteNotify(index);
}
void UpdateQuoteNotify(int index) {
Quote quote = quotes[index].Clone();
UpdateQuote(quote);
quotes[index] = quote;
}
void UpdateQuote(Quote quote) {
double value = quote.CurrentValue;
quote.PreviousValue = value;
int percentChange = random.Next(0, 201) - 100;
double newValue = value + value * (5 * percentChange / 10000.0); // single change should be change less than 5%
if (newValue < 0)
newValue = value - value * (5 * percentChange / 10000.0); // single change should be change less than 5%
quote.CurrentValue = newValue;
}
}
}
| 34.504854 | 123 | 0.544738 | [
"MIT"
] | devbrsa/fConcBook | Chapter.14/Components/devexpress-grid-16.2.2.0/samples/GridDemo/GridDemo/BusinessModel/Quote.cs | 3,556 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics.CodeAnalysis;
using BuildXL.Utilities.Instrumentation.Common;
namespace BuildXL.Processes.Tracing
{
// disable warning regarding 'missing XML comments on public API'. We don't need docs for these values
#pragma warning disable 1591
/// <summary>
/// Defines event IDs corresponding to events in <see cref="Logger" />
/// </summary>
public enum LogEventId
{
None = 0,
PipProcessDisallowedFileAccess = 9,
PipProcessFileAccess = 10,
PipProcessStartFailed = 11,
PipProcessFinished = 12,
PipProcessFinishedFailed = 13,
PipProcessFileNotFound = 14,
PipProcessTookTooLongWarning = 15,
PipProcessTookTooLongError = 16,
PipProcessStandardOutput = 17,
PipProcessStandardError = 18,
ReadWriteFileAccessConvertedToReadMessage = 19,
PipProcessDisallowedTempFileAccess = 20,
ReadWriteFileAccessConvertedToReadWarning = 21,
PipProcessFileAccessTableEntry = 22,
PipInvalidDetoursDebugFlag1 = 23,
PipInvalidDetoursDebugFlag2 = 24,
PipProcessFinishedDetourFailures = 26,
PipProcessCommandLineTooLong = 32,
PipProcessInvalidWarningRegex = 39,
PipProcessChildrenSurvivedError = 41,
PipProcessChildrenSurvivedKilled = 42,
PipProcessChildrenSurvivedTooMany = 43,
PipProcessMissingExpectedOutputOnCleanExit = 44,
PipProcessWroteToStandardErrorOnCleanExit = 45,
PipProcessOutputPreparationFailed = 46,
PipProcessPreserveOutputDirectoryFailedToMakeFilePrivate = 53,
PipProcessPreserveOutputDirectorySkipMakeFilesPrivate = 54,
#pragma warning disable 618
PipProcessError = SharedLogEventId.PipProcessError,
PipProcessWarning = SharedLogEventId.PipProcessWarning,
#pragma warning restore 618
PipProcessOutput = 66,
PipProcessResponseFileCreationFailed = 74,
PipProcessStartExternalTool = 78,
PipProcessFinishedExternalTool = 79,
PipProcessStartExternalVm = 80,
PipProcessFinishedExternalVm = 81,
PipProcessExternalExecution = 82,
RetryStartPipDueToErrorPartialCopyDuringDetours = 85,
PipProcessStandardInputException = 86,
PipProcessInvalidErrorRegex = 89,
PipProcessChangeAffectedInputsWrittenFileCreationFailed = 90,
PipProcessNeedsExecuteExternalButExecuteInternal = 92,
LogPhaseDuration = 93,
PipProcessDisallowedFileAccessAllowlistedCacheable = 264,
PipProcessDisallowedFileAccessAllowlistedNonCacheable = 269,
FileAccessAllowlistFailedToParsePath = 274,
CannotProbeOutputUnderSharedOpaque = 275,
//// Reserved = 306,
//// Reserved = 307,
PipFailSymlinkCreation = 308,
//// Reserved = 309,
PipProcessMessageParsingError = 311,
PipExitedUncleanly = 314,
PipStandardIOFailed = 316,
PipRetryDueToExitedWithAzureWatsonExitCode = 317,
DuplicateWindowsEnvironmentVariableEncountered = 336,
PipProcessDisallowedNtCreateFileAccessWarning = 480,
PipProcessExpectedMissingOutputs = 504,
//// Additional Process Isolation
PipProcessIgnoringPathWithWildcardsFileAccess = 800,
PipProcessIgnoringPathOfSpecialDeviceFileAccess = 801,
PipProcessFailedToParsePathOfFileAccess = 802,
Process = 803,
SharedOpaqueOutputsDeletedLazily = 874,
CannotReadSidebandFileError = 875,
CannotReadSidebandFileWarning = 876,
CannotDeleteSharedOpaqueOutputFile = 877,
ResumeOrSuspendProcessError = 878,
// Temp files/directory cleanup
PipTempDirectoryCleanupWarning = 2201,
PipTempDirectorySetupWarning = 2203,
PipTempSymlinkRedirectionError = 2205,
PipTempSymlinkRedirection = 2206,
PipFailedToCreateDumpFile = 2210,
PipOutputNotAccessed = 2603,
LogInternalDetoursErrorFileNotEmpty = 2919,
LogGettingInternalDetoursErrorFile = 2920,
LogMessageCountSemaphoreExists = 2923,
LogFailedToCreateDirectoryForInternalDetoursFailureFile = 2925,
LogMismatchedDetoursVerboseCount = 2927,
LogDetoursMaxHeapSize = 2928,
// Moved to BuildXL.Native
// MoreBytesWrittenThanBufferSize = 2930,
//DominoProcessesStart = 4400,
PipProcessUncacheableAllowlistNotAllowedInDistributedBuilds = 4401,
//DominoProcessesEnd = 4499,
//// Detours
BrokeredDetoursInjectionFailed = 10100,
LogDetoursDebugMessage = 10101,
LogAppleSandboxPolicyGenerated = 10102,
LogMacKextFailure = 10103,
//// Container related errors
FailedToMergeOutputsToOriginalLocation = 12202,
// Moved to BuildXL.Native
// FailedToCleanUpContainer = 12203,
// WarningSettingUpContainer = 12204,
PipInContainerStarted = 12206,
PipInContainerStarting = 12207,
PipSpecifiedToRunInContainerButIsolationIsNotSupported = 12208,
FailedToCreateHardlinkOnMerge = 12209,
DoubleWriteAllowedDueToPolicy = 12210,
DisallowedDoubleWriteOnMerge = 12211,
DumpSurvivingPipProcessChildrenStatus = 12213,
//// Special tool errors
PipProcessToolErrorDueToHandleToFileBeingUsed = 14300,
}
}
| 35.980769 | 107 | 0.688936 | [
"MIT"
] | shivanshu3/BuildXL | Public/Src/Engine/Processes/Tracing/LogEventId.cs | 5,615 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.