source
stringclasses 1
value | id
stringlengths 40
40
| language
stringclasses 2
values | date
stringclasses 1
value | author
stringclasses 1
value | url
stringclasses 1
value | title
stringclasses 1
value | extra
stringlengths 528
1.53k
| quality_signals
stringlengths 139
178
| text
stringlengths 6
1.05M
|
---|---|---|---|---|---|---|---|---|---|
TheStack | e07cf17de2d560466cdb1b40cebba9ad558bf1ff | C#code:C# | {"size": 12910, "ext": "cs", "max_stars_repo_path": "obj/Debug/netcoreapp2.1/Razor/Views/Shared/ProductItem.g.cshtml.cs", "max_stars_repo_name": "RainManVays/MiniMarket", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "obj/Debug/netcoreapp2.1/Razor/Views/Shared/ProductItem.g.cshtml.cs", "max_issues_repo_name": "RainManVays/MiniMarket", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "obj/Debug/netcoreapp2.1/Razor/Views/Shared/ProductItem.g.cshtml.cs", "max_forks_repo_name": "RainManVays/MiniMarket", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 52.9098360656, "max_line_length": 305, "alphanum_fraction": 0.6498063517} | #pragma checksum "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "2f59520e5faced05d2feda3f12a2a19e2ac8429a"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared_ProductItem), @"mvc.1.0.view", @"/Views/Shared/ProductItem.cshtml")]
[assembly:global::Microsoft.AspNetCore.Mvc.Razor.Compilation.RazorViewAttribute(@"/Views/Shared/ProductItem.cshtml", typeof(AspNetCore.Views_Shared_ProductItem))]
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;
#line 1 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\_ViewImports.cshtml"
using MiniMarket;
#line default
#line hidden
#line 2 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\_ViewImports.cshtml"
using MiniMarket.Models;
#line default
#line hidden
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"2f59520e5faced05d2feda3f12a2a19e2ac8429a", @"/Views/Shared/ProductItem.cshtml")]
[global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"80a45bd8c1fac61c6de84d4c277f720d840cac8e", @"/Views/_ViewImports.cshtml")]
public class Views_Shared_ProductItem : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<MiniMarket.Models.Product>
{
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "AddToOrder", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Order", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "POST", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes);
#line hidden
#pragma warning disable 0169
private string __tagHelperStringValueBuffer;
#pragma warning restore 0169
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext;
private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner();
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.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper;
private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper;
#pragma warning disable 1998
public async override global::System.Threading.Tasks.Task ExecuteAsync()
{
BeginContext(34, 2, true);
WriteLiteral("\r\n");
EndContext();
#line 3 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
if (Model.isVisible)
{
#line default
#line hidden
BeginContext(62, 86, true);
WriteLiteral(" <div class=\"col-md-3 product__item\">\r\n <div class=\"card mb-3 box-shadow\">\r\n");
EndContext();
#line 7 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
if (Model.Image != null)
{
#line default
#line hidden
BeginContext(202, 61, true);
WriteLiteral(" <img class=\"card-img-top product__item-image\"");
EndContext();
BeginWriteAttribute("src", " src=\"", 263, "\"", 326, 1);
#line 9 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
WriteAttributeValue("", 269, Url.Action("GetProductImage","Product",new { Model.Id }), 269, 57, false);
#line default
#line hidden
EndWriteAttribute();
BeginContext(327, 5, true);
WriteLiteral(" />\r\n");
EndContext();
#line 10 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
}
else
{
#line default
#line hidden
BeginContext(380, 61, true);
WriteLiteral(" <div class=\"product__item-image\"> NAN</div>\r\n");
EndContext();
#line 14 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
}
#line default
#line hidden
BeginContext(456, 76, true);
WriteLiteral(" <div class=\"card-body\">\r\n <h4 class=\"card-title\">");
EndContext();
BeginContext(533, 10, false);
#line 16 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
Write(Model.Name);
#line default
#line hidden
EndContext();
BeginContext(543, 49, true);
WriteLiteral("</h4>\r\n <h5 class=\"card-subtitle\">");
EndContext();
BeginContext(593, 11, false);
#line 17 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
Write(Model.Price);
#line default
#line hidden
EndContext();
BeginContext(604, 5, true);
WriteLiteral(" р / ");
EndContext();
BeginContext(610, 12, false);
#line 17 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
Write(Model.Weight);
#line default
#line hidden
EndContext();
BeginContext(622, 47, true);
WriteLiteral(" гр</h5>\r\n <p class=\"card-text\">");
EndContext();
BeginContext(670, 17, false);
#line 18 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
Write(Model.Description);
#line default
#line hidden
EndContext();
BeginContext(687, 141, true);
WriteLiteral("</p>\r\n </div>\r\n <div class=\"card-footer bg-transparent\">\r\n <div class=\"btn-group\">\r\n ");
EndContext();
BeginContext(828, 744, false);
__tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "f56578e0e5164d13ba97c164c959bd6e", async() => {
BeginContext(895, 26, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(922, 23, false);
#line 23 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
Write(Html.AntiForgeryToken());
#line default
#line hidden
EndContext();
BeginContext(945, 61, true);
WriteLiteral("\r\n <div>\r\n ");
EndContext();
BeginContext(1007, 69, false);
#line 25 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
Write(Html.Hidden("controller", ViewContext.RouteData.Values["controller"]));
#line default
#line hidden
EndContext();
BeginContext(1076, 30, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1107, 61, false);
#line 26 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
Write(Html.Hidden("action", ViewContext.RouteData.Values["action"]));
#line default
#line hidden
EndContext();
BeginContext(1168, 30, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1199, 56, false);
#line 27 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
Write(Html.Hidden("value", ViewContext.RouteData.Values["id"]));
#line default
#line hidden
EndContext();
BeginContext(1255, 30, true);
WriteLiteral("\r\n ");
EndContext();
BeginContext(1286, 25, false);
#line 28 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
Write(Html.HiddenFor(x => x.Id));
#line default
#line hidden
EndContext();
BeginContext(1311, 254, true);
WriteLiteral("\r\n <div class=\"form-group\">\r\n <input type=\"submit\" value=\"Купить\" class=\"btn btn-sm btn-outline-danger\" />\r\n </div>\r\n </div>\r\n ");
EndContext();
}
);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>();
__tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_0.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Controller = (string)__tagHelperAttribute_1.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1);
__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_2.Value;
__tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2);
await __tagHelperRunner.RunAsync(__tagHelperExecutionContext);
if (!__tagHelperExecutionContext.Output.IsContentModified)
{
await __tagHelperExecutionContext.SetOutputContentAsync();
}
Write(__tagHelperExecutionContext.Output);
__tagHelperExecutionContext = __tagHelperScopeManager.End();
EndContext();
BeginContext(1572, 78, true);
WriteLiteral("\r\n </div>\r\n\r\n </div>\r\n </div>\r\n\r\n </div>\r\n");
EndContext();
#line 40 "C:\Users\LDF\Documents\GIT\MiniMarket\Views\Shared\ProductItem.cshtml"
}
#line default
#line hidden
}
#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<MiniMarket.Models.Product> Html { get; private set; }
}
}
#pragma warning restore 1591
|
||||
TheStack | e07e7fa409c61436f984ee8fcd6f00b386e6af0b | C#code:C# | {"size": 5209, "ext": "cs", "max_stars_repo_path": "tests/MassTransit.Azure.Table.Tests/Turnout/Submitting_a_bunch_of_jobs.cs", "max_stars_repo_name": "NooNameR/MassTrans", "max_stars_repo_stars_event_min_datetime": "2015-01-03T20:54:46.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T19:38:05.000Z", "max_issues_repo_path": "tests/MassTransit.Azure.Table.Tests/Turnout/Submitting_a_bunch_of_jobs.cs", "max_issues_repo_name": "NooNameR/MassTrans", "max_issues_repo_issues_event_min_datetime": "2015-01-07T15:58:40.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:18:21.000Z", "max_forks_repo_path": "tests/MassTransit.Azure.Table.Tests/Turnout/Submitting_a_bunch_of_jobs.cs", "max_forks_repo_name": "NooNameR/MassTrans", "max_forks_repo_forks_event_min_datetime": "2015-01-07T17:18:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T14:32:55.000Z"} | {"max_stars_count": 4222.0, "max_issues_count": 1756.0, "max_forks_count": 1352.0, "avg_line_length": 34.4966887417, "max_line_length": 139, "alphanum_fraction": 0.5521213285} | namespace MassTransit.Azure.Table.Tests.Turnout
{
using System;
using System.Linq;
using System.Threading.Tasks;
using Contracts.JobService;
using Definition;
using JobService;
using JobService.Configuration;
using NUnit.Framework;
using Tests;
using Util;
[TestFixture]
[Category("Flaky")]
public class Submitting_a_bunch_of_jobs :
AzureTableInMemoryTestFixture
{
[Test]
[Order(1)]
public async Task Should_get_the_job_accepted()
{
IRequestClient<SubmitJob<CrunchTheNumbers>> requestClient = Bus.CreateRequestClient<SubmitJob<CrunchTheNumbers>>();
for (var i = 0; i < Count; i++)
{
Response<JobSubmissionAccepted> response = await requestClient.GetResponse<JobSubmissionAccepted>(new
{
JobId = _jobIds[i],
Job = new {Duration = TimeSpan.FromSeconds(1)}
});
}
ConsumeContext<JobCompleted>[] completed = await Task.WhenAll(_completed.Select(x => x.Task));
}
[Test]
[Order(4)]
public async Task Should_have_published_the_job_completed_event()
{
ConsumeContext<JobCompleted>[] completed = await Task.WhenAll(_completed.Select(x => x.Task));
}
[Test]
[Order(3)]
public async Task Should_have_published_the_job_started_event()
{
ConsumeContext<JobStarted>[] started = await Task.WhenAll(_started.Select(x => x.Task));
}
[Test]
[Order(2)]
public async Task Should_have_published_the_job_submitted_event()
{
ConsumeContext<JobSubmitted>[] submitted = await Task.WhenAll(_submitted.Select(x => x.Task));
}
Guid[] _jobIds;
TaskCompletionSource<ConsumeContext<JobCompleted>>[] _completed;
TaskCompletionSource<ConsumeContext<JobSubmitted>>[] _submitted;
TaskCompletionSource<ConsumeContext<JobStarted>>[] _started;
const int Count = 10;
[OneTimeSetUp]
public async Task Arrange()
{
_jobIds = new Guid[Count];
for (var i = 0; i < _jobIds.Length; i++)
_jobIds[i] = NewId.NextGuid();
}
protected override void ConfigureInMemoryBus(IInMemoryBusFactoryConfigurator configurator)
{
base.ConfigureInMemoryBus(configurator);
var options = new ServiceInstanceOptions()
.SetEndpointNameFormatter(KebabCaseEndpointNameFormatter.Instance);
configurator.ServiceInstance(options, instance =>
{
instance.ConfigureJobServiceEndpoints(x =>
{
x.SlotWaitTime = TimeSpan.FromSeconds(1);
x.SagaPartitionCount = 16;
x.FinalizeCompleted = true;
x.UseAzureTableSagaRepository(() => TestCloudTable);
});
instance.ReceiveEndpoint(instance.EndpointNameFormatter.Message<CrunchTheNumbers>(), e =>
{
e.Consumer(() => new CrunchTheNumbersConsumer(), cfg =>
{
cfg.Options<JobOptions<CrunchTheNumbers>>(o => o.SetJobTimeout(TimeSpan.FromSeconds(90)).SetConcurrentJobLimit(3));
});
e.UseMessageScheduler(e.InputAddress);
});
});
}
protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
{
_submitted = new TaskCompletionSource<ConsumeContext<JobSubmitted>>[Count];
_started = new TaskCompletionSource<ConsumeContext<JobStarted>>[Count];
_completed = new TaskCompletionSource<ConsumeContext<JobCompleted>>[Count];
for (var i = 0; i < Count; i++)
{
_submitted[i] = GetTask<ConsumeContext<JobSubmitted>>();
_started[i] = GetTask<ConsumeContext<JobStarted>>();
_completed[i] = GetTask<ConsumeContext<JobCompleted>>();
}
configurator.Handler<JobSubmitted>(context =>
{
for (var i = 0; i < Count; i++)
{
if (_jobIds[i] == context.Message.JobId)
_submitted[i].TrySetResult(context);
}
return TaskUtil.Completed;
});
configurator.Handler<JobStarted>(context =>
{
for (var i = 0; i < Count; i++)
{
if (_jobIds[i] == context.Message.JobId)
_started[i].TrySetResult(context);
}
return TaskUtil.Completed;
});
configurator.Handler<JobCompleted>(context =>
{
for (var i = 0; i < Count; i++)
{
if (_jobIds[i] == context.Message.JobId)
_completed[i].TrySetResult(context);
}
return TaskUtil.Completed;
});
}
}
}
|
||||
TheStack | e07f3fe61fb212e4dab68be56e1fe8b974a7c2b8 | C#code:C# | {"size": 2228, "ext": "cs", "max_stars_repo_path": "VectorObjects/Objects/PathVObject/EllipseVObject/EllipseVObject.cs", "max_stars_repo_name": "aurigma/WinControls", "max_stars_repo_stars_event_min_datetime": "2018-10-18T05:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-18T05:13:54.000Z", "max_issues_repo_path": "VectorObjects/Objects/PathVObject/EllipseVObject/EllipseVObject.cs", "max_issues_repo_name": "aurigma/WinControls", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "VectorObjects/Objects/PathVObject/EllipseVObject/EllipseVObject.cs", "max_forks_repo_name": "aurigma/WinControls", "max_forks_repo_forks_event_min_datetime": "2020-10-20T02:04:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-10-20T02:04:21.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 35.3650793651, "max_line_length": 150, "alphanum_fraction": 0.6261220826} | // Copyright (c) 2018 Aurigma Inc. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace Aurigma.GraphicsMill.WinControls
{
/// <summary>
/// Ellipse vector object. Hm, nothing else to say...
/// </summary>
[System.Serializable]
public class EllipseVObject : PathVObject
{
public EllipseVObject(System.Drawing.RectangleF rectangle)
: base("ellipse")
{
_path = new System.Drawing.Drawing2D.GraphicsPath();
_path.AddEllipse(rectangle);
}
public EllipseVObject(float x, float y, float width, float height)
: base("ellipse")
{
_path = new System.Drawing.Drawing2D.GraphicsPath();
_path.AddEllipse(x, y, width, height);
}
protected EllipseVObject(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
if (info == null)
throw new System.ArgumentNullException("info");
_path = BinarySerializer.DeserializePath((byte[])info.GetValue(SerializationNames.Path, typeof(byte[])));
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && _path != null)
_path.Dispose();
}
[System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
if (info == null)
throw new System.ArgumentNullException("info");
base.GetObjectData(info, context);
info.AddValue(SerializationNames.Path, BinarySerializer.Serialize(_path));
}
protected override System.Drawing.Drawing2D.GraphicsPath Path
{
get
{
return _path;
}
}
private System.Drawing.Drawing2D.GraphicsPath _path;
}
} |
||||
TheStack | e07f8e6d9dd31716ef20845d6d3676ff6083b193 | C#code:C# | {"size": 7220, "ext": "cs", "max_stars_repo_path": "src/libraries/BEditor.Compute/PlatformLayer/DeviceInfo.cs", "max_stars_repo_name": "tomo0611/BEditor", "max_stars_repo_stars_event_min_datetime": "2021-02-24T10:15:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-09T08:28:51.000Z", "max_issues_repo_path": "src/libraries/BEditor.Compute/PlatformLayer/DeviceInfo.cs", "max_issues_repo_name": "tomo0611/BEditor", "max_issues_repo_issues_event_min_datetime": "2021-02-22T17:36:43.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-14T10:19:23.000Z", "max_forks_repo_path": "src/libraries/BEditor.Compute/PlatformLayer/DeviceInfo.cs", "max_forks_repo_name": "tomo0611/BEditor", "max_forks_repo_forks_event_min_datetime": "2021-06-10T10:18:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-17T10:12:43.000Z"} | {"max_stars_count": 82.0, "max_issues_count": 181.0, "max_forks_count": 6.0, "avg_line_length": 33.5813953488, "max_line_length": 118, "alphanum_fraction": 0.5278393352} | // DeviceInfo.cs
//
// Copyright (C) BEditor
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using BEditor.Compute.OpenCL;
namespace BEditor.Compute.PlatformLayer
{
/// <summary>
/// Represents the OpenCL device info.
/// </summary>
public unsafe class DeviceInfo
{
private readonly Dictionary<string, byte[]> _infos = new();
internal DeviceInfo(void* platform, int index)
{
Index = index;
// get a device
uint count = 0;
CL.GetDeviceIDs(platform, (long)CLDeviceType.CL_DEVICE_TYPE_ALL, 0, null, &count).CheckError();
var devices = (void**)Marshal.AllocCoTaskMem((int)(count * IntPtr.Size));
try
{
CL.GetDeviceIDs(platform, (long)CLDeviceType.CL_DEVICE_TYPE_ALL, count, devices, &count).CheckError();
// get device infos
foreach (long info in Enum.GetValues(typeof(CLDeviceInfo)))
{
var a = Enum.GetName(typeof(CLDeviceInfo), info);
var size = IntPtr.Zero;
CL.GetDeviceInfo(devices[index], info, IntPtr.Zero, null, &size).CheckError();
var value = new byte[(int)size];
fixed (byte* valuePointer = value)
{
CL.GetDeviceInfo(devices[index], info, size, valuePointer, null).CheckError();
_infos.Add(Enum.GetName(typeof(CLDeviceInfo), info)!, value);
}
}
}
finally
{
Marshal.FreeCoTaskMem(new IntPtr(devices));
}
}
/// <summary>
/// Gets the index of devices in the platform.
/// </summary>
public int Index { get; }
/// <summary>
/// Gets the keys.
/// </summary>
public List<string> Keys => _infos.Keys.ToList();
/// <summary>
/// Gets the value as string.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Returns the value.</returns>
public string GetValueAsString(string key)
{
return Encoding.UTF8.GetString(_infos[key], 0, _infos[key].Length).Trim();
}
/// <summary>
/// Gets the value as boolean.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Returns the value.</returns>
public bool GetValueAsBool(string key)
{
return BitConverter.ToBoolean(_infos[key], 0);
}
/// <summary>
/// Gets the value as 32-bit unsigned integer.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Returns the value.</returns>
public uint GetValueAsUInt(string key)
{
return BitConverter.ToUInt32(_infos[key], 0);
}
/// <summary>
/// Gets the value as 64-bit unsigned integer.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Returns the value.</returns>
public ulong GetValueAsULong(string key)
{
return BitConverter.ToUInt64(_infos[key], 0);
}
/// <summary>
/// Gets the value as native unsigned integer.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Returns the value.</returns>
public ulong GetValueAsSizeT(string key)
{
if (IntPtr.Size == 4)
{
return BitConverter.ToUInt32(_infos[key], 0);
}
else
{
return BitConverter.ToUInt64(_infos[key], 0);
}
}
/// <summary>
/// Gets the value as native unsigned integer.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Returns the value.</returns>
public ulong[] GetValueAsSizeTArray(string key)
{
if (IntPtr.Size == 4)
{
var num = _infos[key].Length / 4;
var array = new ulong[num];
for (var i = 0; i < num; i++)
{
array[i] = BitConverter.ToUInt32(_infos[key], 4 * i);
}
return array;
}
else
{
var num = _infos[key].Length / 8;
var array = new ulong[num];
for (var i = 0; i < num; i++)
{
array[i] = BitConverter.ToUInt64(_infos[key], 8 * i);
}
return array;
}
}
/// <summary>
/// Gets the value as <see cref="CLDeviceType"/>.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Returns the value.</returns>
public CLDeviceType GetValueAsClDeviceType(string key)
{
return (CLDeviceType)BitConverter.ToInt64(_infos[key], 0);
}
/// <summary>
/// Gets the value as <see cref="CLDeviceFpConfig"/>.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Returns the value.</returns>
public CLDeviceFpConfig GetValueAsClDeviceFpConfig(string key)
{
return (CLDeviceFpConfig)BitConverter.ToInt64(_infos[key], 0);
}
/// <summary>
/// Gets the value as <see cref="CLDeviceMemoryCacheType"/>.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Returns the value.</returns>
public CLDeviceMemoryCacheType GetValueAsClDeviceMemCacheType(string key)
{
return (CLDeviceMemoryCacheType)BitConverter.ToInt64(_infos[key], 0);
}
/// <summary>
/// Gets the value as <see cref="CLDeviceLocalMemoryType"/>.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Returns the value.</returns>
public CLDeviceLocalMemoryType GetValueAsClDeviceLocalMemType(string key)
{
return (CLDeviceLocalMemoryType)BitConverter.ToInt64(_infos[key], 0);
}
/// <summary>
/// Gets the value as <see cref="CLDeviceExecCapabilities"/>.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Returns the value.</returns>
public CLDeviceExecCapabilities GetValueAsClDeviceExecCapabilities(string key)
{
return (CLDeviceExecCapabilities)BitConverter.ToInt64(_infos[key], 0);
}
/// <summary>
/// Gets the value as <see cref="CLCommandQueueProperties"/>.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>Returns the value.</returns>
public CLCommandQueueProperties GetValueAsClCommandQueueProperties(string key)
{
return (CLCommandQueueProperties)BitConverter.ToInt64(_infos[key], 0);
}
}
} |
||||
TheStack | e07fd9d5bc891ec722a655dd819ff85c7370402b | C#code:C# | {"size": 1127, "ext": "cs", "max_stars_repo_path": "WalletWasabi.Tests/UnitTests/Crypto/ZeroKnowledge/StatementTests.cs", "max_stars_repo_name": "zero77/WalletWasabi", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WalletWasabi.Tests/UnitTests/Crypto/ZeroKnowledge/StatementTests.cs", "max_issues_repo_name": "zero77/WalletWasabi", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WalletWasabi.Tests/UnitTests/Crypto/ZeroKnowledge/StatementTests.cs", "max_forks_repo_name": "zero77/WalletWasabi", "max_forks_repo_forks_event_min_datetime": "2020-09-30T11:07:17.000Z", "max_forks_repo_forks_event_max_datetime": "2020-09-30T11:07:17.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 36.3548387097, "max_line_length": 113, "alphanum_fraction": 0.7577639752} | using System;
using System.Collections.Generic;
using System.Text;
using WalletWasabi.Crypto.Groups;
using WalletWasabi.Crypto.ZeroKnowledge;
using Xunit;
namespace WalletWasabi.Tests.UnitTests.Crypto.ZeroKnowledge
{
public class StatementTests
{
[Fact]
public void Throws()
{
// Demonstrate when it shouldn't throw.
new Statement(Generators.G, Generators.Ga);
new Statement(Generators.G, Generators.Ga, Generators.Gg);
// Cannot miss generators.
Assert.ThrowsAny<ArgumentException>(() => new Statement(Generators.G));
// Infinity cannot pass through.
Assert.ThrowsAny<ArgumentException>(() => new Statement(GroupElement.Infinity, Generators.Ga));
Assert.ThrowsAny<ArgumentException>(() => new Statement(Generators.G, GroupElement.Infinity));
Assert.ThrowsAny<ArgumentException>(() => new Statement(GroupElement.Infinity, Generators.Ga, Generators.Gg));
Assert.ThrowsAny<ArgumentException>(() => new Statement(Generators.G, GroupElement.Infinity, Generators.Gg));
Assert.ThrowsAny<ArgumentException>(() => new Statement(Generators.G, Generators.Ga, GroupElement.Infinity));
}
}
}
|
||||
TheStack | e08096826b2183122e99ea6ad889817615fb2a74 | C#code:C# | {"size": 1061, "ext": "cs", "max_stars_repo_path": "Examples/BasicManagement/ZhuoFan.Wb.BasicService.Domain/Commands/User/UserCommand.cs", "max_stars_repo_name": "girvs/Girvs", "max_stars_repo_stars_event_min_datetime": "2020-07-21T02:50:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T07:51:59.000Z", "max_issues_repo_path": "Examples/BasicManagement/ZhuoFan.Wb.BasicService.Domain/Commands/User/UserCommand.cs", "max_issues_repo_name": "girvs/Girvs", "max_issues_repo_issues_event_min_datetime": "2021-12-23T08:59:28.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-23T08:59:28.000Z", "max_forks_repo_path": "Examples/BasicManagement/ZhuoFan.Wb.BasicService.Domain/Commands/User/UserCommand.cs", "max_forks_repo_name": "girvs/Girvs", "max_forks_repo_forks_event_min_datetime": "2021-08-12T03:00:11.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-12T03:00:11.000Z"} | {"max_stars_count": 6.0, "max_issues_count": 1.0, "max_forks_count": 1.0, "avg_line_length": 27.9210526316, "max_line_length": 59, "alphanum_fraction": 0.6286522149} | using System;
using Girvs.AuthorizePermission.Enumerations;
using Girvs.Driven.Commands;
using ZhuoFan.Wb.BasicService.Domain.Enumerations;
namespace ZhuoFan.Wb.BasicService.Domain.Commands.User
{
public abstract class UserCommand : Command
{
public Guid Id { get; set; }
public string UserAccount { get; protected set; }
public string UserPassword { get; protected set; }
public string UserName { get; protected set; }
public string ContactNumber { get; protected set; }
/// <summary>
/// 绑定其它相关服务的关键标识Id
/// </summary>
public Guid OtherId { get; protected set; }
public DataState State { get; protected set; }
public UserType UserType { get; protected set; }
public string NewPassword { get; protected set; }
public string OldPassword { get; protected set; }
/// <summary>
/// 租户ID
/// </summary>
public Guid? TenantId { get; protected set; }
public Guid[] RoleIds { get; protected set; }
}
} |
||||
TheStack | e08103a61ad60649828357bb20b70f1df62584e1 | C#code:C# | {"size": 1927, "ext": "cs", "max_stars_repo_path": "sdk/dotnet/Migrate/Outputs/ServersSolutionSummaryResponse.cs", "max_stars_repo_name": "pulumi-bot/pulumi-azure-native", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "sdk/dotnet/Migrate/Outputs/ServersSolutionSummaryResponse.cs", "max_issues_repo_name": "pulumi-bot/pulumi-azure-native", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "sdk/dotnet/Migrate/Outputs/ServersSolutionSummaryResponse.cs", "max_forks_repo_name": "pulumi-bot/pulumi-azure-native", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.6461538462, "max_line_length": 81, "alphanum_fraction": 0.6014530358} | // *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Migrate.Outputs
{
[OutputType]
public sealed class ServersSolutionSummaryResponse
{
/// <summary>
/// Gets or sets the count of servers assessed.
/// </summary>
public readonly int? AssessedCount;
/// <summary>
/// Gets or sets the count of servers discovered.
/// </summary>
public readonly int? DiscoveredCount;
/// <summary>
/// Gets the Instance type.
/// Expected value is 'Servers'.
/// </summary>
public readonly string InstanceType;
/// <summary>
/// Gets or sets the count of servers migrated.
/// </summary>
public readonly int? MigratedCount;
/// <summary>
/// Gets or sets the count of servers being replicated.
/// </summary>
public readonly int? ReplicatingCount;
/// <summary>
/// Gets or sets the count of servers test migrated.
/// </summary>
public readonly int? TestMigratedCount;
[OutputConstructor]
private ServersSolutionSummaryResponse(
int? assessedCount,
int? discoveredCount,
string instanceType,
int? migratedCount,
int? replicatingCount,
int? testMigratedCount)
{
AssessedCount = assessedCount;
DiscoveredCount = discoveredCount;
InstanceType = instanceType;
MigratedCount = migratedCount;
ReplicatingCount = replicatingCount;
TestMigratedCount = testMigratedCount;
}
}
}
|
||||
TheStack | e082a2c84bb4691a74444d4d4124aff28a975698 | C#code:C# | {"size": 364, "ext": "cs", "max_stars_repo_path": "FileServer.Infrastructure.Repository/Interfaces/IAlumnoRepository.cs", "max_stars_repo_name": "Fantasmy/FileServer", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FileServer.Infrastructure.Repository/Interfaces/IAlumnoRepository.cs", "max_issues_repo_name": "Fantasmy/FileServer", "max_issues_repo_issues_event_min_datetime": "2018-06-30T10:36:28.000Z", "max_issues_repo_issues_event_max_datetime": "2018-07-25T22:14:22.000Z", "max_forks_repo_path": "FileServer.Infrastructure.Repository/Interfaces/IAlumnoRepository.cs", "max_forks_repo_name": "Fantasmy/FileServer", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 20.0, "max_forks_count": null, "avg_line_length": 20.2222222222, "max_line_length": 46, "alphanum_fraction": 0.717032967} | using FileServer.Common.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileServer.Infrastructure.Repository
{
public interface IAlumnoRepository
{
//List<Alumno> GetAll();
Alumno Add(Alumno alumno);
//void ChangeOrigin(string origin);
}
}
|
||||
TheStack | e08559e8d9a28238460e9a3cdeb0bdaf7a38ddb2 | C#code:C# | {"size": 356, "ext": "cs", "max_stars_repo_path": "NextLevelSeven/Utility/Hl7StringOperations.cs", "max_stars_repo_name": "stoneson/NextLevelSeven", "max_stars_repo_stars_event_min_datetime": "2015-12-04T05:50:08.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-23T01:48:49.000Z", "max_issues_repo_path": "NextLevelSeven/Utility/Hl7StringOperations.cs", "max_issues_repo_name": "Joze01/NextLevelSeven", "max_issues_repo_issues_event_min_datetime": "2017-07-12T17:21:44.000Z", "max_issues_repo_issues_event_max_datetime": "2018-12-06T03:17:53.000Z", "max_forks_repo_path": "NextLevelSeven/Utility/Hl7StringOperations.cs", "max_forks_repo_name": "Joze01/NextLevelSeven", "max_forks_repo_forks_event_min_datetime": "2017-01-20T20:59:08.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-21T12:47:11.000Z"} | {"max_stars_count": 22.0, "max_issues_count": 6.0, "max_forks_count": 20.0, "avg_line_length": 23.7333333333, "max_line_length": 76, "alphanum_fraction": 0.5702247191} | using System;
namespace NextLevelSeven.Utility
{
public static class Hl7StringOperations
{
public static string NormalizeLineEndings(string s, char delimiter)
{
return s?
.Replace(Environment.NewLine, new string(delimiter, 1))
.Replace('\n', delimiter);
}
}
}
|
||||
TheStack | e0861228a14f69996585feae820688cd3617c4b8 | C#code:C# | {"size": 3388, "ext": "cs", "max_stars_repo_path": "Testing/unittest/Parsing/Handlers/WriteToStoreHandlerTests.NetFull.cs", "max_stars_repo_name": "larsw/dotnetrdf", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Testing/unittest/Parsing/Handlers/WriteToStoreHandlerTests.NetFull.cs", "max_issues_repo_name": "larsw/dotnetrdf", "max_issues_repo_issues_event_min_datetime": "2020-04-21T13:33:17.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-25T15:36:13.000Z", "max_forks_repo_path": "Testing/unittest/Parsing/Handlers/WriteToStoreHandlerTests.NetFull.cs", "max_forks_repo_name": "larsw/dotnetrdf", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 34.0, "max_forks_count": null, "avg_line_length": 35.2916666667, "max_line_length": 81, "alphanum_fraction": 0.6732585596} | /*
dotNetRDF is free and open source software licensed under the MIT License
-----------------------------------------------------------------------------
Copyright (c) 2009-2012 dotNetRDF Project ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using Xunit;
using VDS.RDF.Storage;
namespace VDS.RDF.Parsing.Handlers
{
/// <summary>
/// Summary description for WriteToStoreHandlerTests
/// </summary>
public partial class WriteToStoreHandlerTests
{
#if !NO_VIRTUOSO
[SkippableFact]
public void ParsingWriteToStoreHandlerVirtuoso()
{
VirtuosoManager virtuoso = VirtuosoTest.GetConnection();
this.TestWriteToStoreHandler(virtuoso);
}
[SkippableFact]
public void ParsingWriteToStoreHandlerDatasetsVirtuoso()
{
VirtuosoManager virtuoso = VirtuosoTest.GetConnection();
this.TestWriteToStoreDatasetsHandler(virtuoso);
}
[SkippableFact]
public void ParsingWriteToStoreHandlerBNodesAcrossBatchesVirtuoso()
{
VirtuosoManager virtuoso = VirtuosoTest.GetConnection();
this.TestWriteToStoreHandlerWithBNodes(virtuoso);
}
#endif
[SkippableFact]
public void ParsingWriteToStoreHandlerAllegroGraph()
{
AllegroGraphConnector agraph = AllegroGraphTests.GetConnection();
this.TestWriteToStoreHandler(agraph);
}
[SkippableFact]
public void ParsingWriteToStoreHandlerFuseki()
{
try
{
Options.UriLoaderCaching = false;
FusekiConnector fuseki = FusekiTest.GetConnection();
this.TestWriteToStoreHandler(fuseki);
}
finally
{
Options.UriLoaderCaching = true;
}
}
[SkippableFact]
public void ParsingWriteToStoreHandlerBNodesAcrossBatchesAllegroGraph()
{
AllegroGraphConnector agraph = AllegroGraphTests.GetConnection();
this.TestWriteToStoreHandlerWithBNodes(agraph);
}
[SkippableFact]
public void ParsingWriteToStoreHandlerBNodesAcrossBatchesFuseki()
{
FusekiConnector fuseki = FusekiTest.GetConnection();
this.TestWriteToStoreHandlerWithBNodes(fuseki);
}
}
}
|
||||
TheStack | e0866cd1d606150586a7893a165c7e60569780b3 | C#code:C# | {"size": 1077, "ext": "cshtml", "max_stars_repo_path": "Altairis.ReP.Web/Pages/Admin/Users/Create.cshtml", "max_stars_repo_name": "ridercz/FutLabIS", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Altairis.ReP.Web/Pages/Admin/Users/Create.cshtml", "max_issues_repo_name": "ridercz/FutLabIS", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Altairis.ReP.Web/Pages/Admin/Users/Create.cshtml", "max_forks_repo_name": "ridercz/FutLabIS", "max_forks_repo_forks_event_min_datetime": "2021-04-18T09:17:01.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-18T09:17:01.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 38.4642857143, "max_line_length": 130, "alphanum_fraction": 0.6044568245} | @page
@model Altairis.ReP.Web.Pages.Admin.Users.CreateModel
@{ this.ViewBag.Title = UI.Admin_Users_Create_Title; }
<form method="post">
<header>
@UI.Admin_Users_Create_Text
</header>
<p>
<label asp-for="Input.UserName"></label>:<br />
<input asp-for="Input.UserName" />
</p>
<p>
<label asp-for="Input.Email"></label>:<br />
<input asp-for="Input.Email" /><br />
<checkbox-list asp-for="Input.Language" asp-items="Model.AllLanguages" control-type="RadioButton" class="checkbox-list" />
</p>
<p>
<label asp-for="Input.PhoneNumber"></label>:<br />
<input asp-for="Input.PhoneNumber" />
</p>
<p><input asp-for="Input.IsMaster" /> <label asp-for="Input.IsMaster"></label></p>
<p><input asp-for="Input.IsAdministrator" /> <label asp-for="Input.IsAdministrator"></label></p>
<footer>
<div asp-validation-summary="All"></div>
<input type="submit" value="@UI._Submit" />
<a asp-page="Index" class="button secondary">@UI._Cancel</a>
</footer>
</form> |
||||
TheStack | e087b31477133a673af93cfa9359bb09b5d07946 | C#code:C# | {"size": 6690, "ext": "cs", "max_stars_repo_path": "samples/macOS/cs/netcore1.0/NonTableManagerSamples/TradingSettings/src/Program.cs", "max_stars_repo_name": "holgafx/gehtsoft", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "samples/macOS/cs/netcore1.0/NonTableManagerSamples/TradingSettings/src/Program.cs", "max_issues_repo_name": "holgafx/gehtsoft", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "samples/macOS/cs/netcore1.0/NonTableManagerSamples/TradingSettings/src/Program.cs", "max_forks_repo_name": "holgafx/gehtsoft", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 46.7832167832, "max_line_length": 125, "alphanum_fraction": 0.5430493274} | using System;
using ArgParser;
using fxcore2;
namespace TradingSettings
{
class Program
{
static void Main(string[] args)
{
O2GSession session = null;
SessionStatusListener statusListener = null;
try
{
Console.WriteLine("TradingSettings sample\n");
ArgumentParser argParser = new ArgumentParser(args, "TradingSettings");
argParser.AddArguments(ParserArgument.Login,
ParserArgument.Password,
ParserArgument.Url,
ParserArgument.Connection,
ParserArgument.SessionID,
ParserArgument.Pin);
argParser.ParseArguments();
if (!argParser.AreArgumentsValid)
{
argParser.PrintUsage();
return;
}
argParser.PrintArguments();
LoginParams loginParams = argParser.LoginParams;
session = O2GTransport.createSession();
statusListener = new SessionStatusListener(session, loginParams.SessionID, loginParams.Pin);
session.subscribeSessionStatus(statusListener);
statusListener.Reset();
session.login(loginParams.Login, loginParams.Password, loginParams.URL, loginParams.Connection);
if (statusListener.WaitEvents() && statusListener.Connected)
{
PrintTradingSettings(session);
Console.WriteLine("Done!");
}
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.ToString());
}
finally
{
if (session != null)
{
if (statusListener.Connected)
{
statusListener.Reset();
session.logout();
statusListener.WaitEvents();
}
session.unsubscribeSessionStatus(statusListener);
session.Dispose();
}
}
}
// Print trading settings of the first account
private static void PrintTradingSettings(O2GSession session)
{
O2GLoginRules loginRules = session.getLoginRules();
if (loginRules == null)
{
throw new Exception("Cannot get login rules");
}
O2GResponse accountsResponse = loginRules.getTableRefreshResponse(O2GTableType.Accounts);
if (accountsResponse == null)
{
throw new Exception("Cannot get response");
}
O2GResponse offersResponse = loginRules.getTableRefreshResponse(O2GTableType.Offers);
if (offersResponse == null)
{
throw new Exception("Cannot get response");
}
O2GTradingSettingsProvider tradingSettingsProvider = loginRules.getTradingSettingsProvider();
O2GResponseReaderFactory factory = session.getResponseReaderFactory();
if (factory == null)
{
throw new Exception("Cannot create response reader factory");
}
O2GAccountsTableResponseReader accountsReader = factory.createAccountsTableReader(accountsResponse);
O2GOffersTableResponseReader instrumentsReader = factory.createOffersTableReader(offersResponse);
O2GAccountRow account = accountsReader.getRow(0);
for (int i = 0; i < instrumentsReader.Count; i++)
{
O2GOfferRow instrumentRow = instrumentsReader.getRow(i);
string instrument = instrumentRow.Instrument;
int condDistStopForTrade = tradingSettingsProvider.getCondDistStopForTrade(instrument);
int condDistLimitForTrade = tradingSettingsProvider.getCondDistLimitForTrade(instrument);
int condDistEntryStop = tradingSettingsProvider.getCondDistEntryStop(instrument);
int condDistEntryLimit = tradingSettingsProvider.getCondDistEntryLimit(instrument);
int minQuantity = tradingSettingsProvider.getMinQuantity(instrument, account);
int maxQuantity = tradingSettingsProvider.getMaxQuantity(instrument, account);
int baseUnitSize = tradingSettingsProvider.getBaseUnitSize(instrument, account);
O2GMarketStatus marketStatus = tradingSettingsProvider.getMarketStatus(instrument);
int minTrailingStep = tradingSettingsProvider.getMinTrailingStep();
int maxTrailingStep = tradingSettingsProvider.getMaxTrailingStep();
double mmr = tradingSettingsProvider.getMMR(instrument, account);
double mmr2=0, emr=0, lmr=0;
bool threeLevelMargin = tradingSettingsProvider.getMargins(instrument, account, ref mmr2, ref emr, ref lmr);
string sMarketStatus = "unknown";
switch (marketStatus)
{
case O2GMarketStatus.MarketStatusOpen:
sMarketStatus = "Market Open";
break;
case O2GMarketStatus.MarketStatusClosed:
sMarketStatus = "Market Close";
break;
}
Console.WriteLine("Instrument: {0}, Status: {1}", instrument, sMarketStatus);
Console.WriteLine("Cond.Dist: ST={0}; LT={1}", condDistStopForTrade, condDistLimitForTrade);
Console.WriteLine("Cond.Dist entry stop={0}; entry limit={1}", condDistEntryStop,
condDistEntryLimit);
Console.WriteLine("Quantity: Min={0}; Max={1}. Base unit size={2}; MMR={3}", minQuantity,
maxQuantity, baseUnitSize, mmr);
if (threeLevelMargin)
{
Console.WriteLine("Three level margin: MMR={0}; EMR={1}; LMR={2}", mmr2, emr, lmr);
}
else
{
Console.WriteLine("Single level margin: MMR={0}; EMR={1}; LMR={2}", mmr2, emr, lmr);
}
Console.WriteLine("Trailing step: {0}-{1}", minTrailingStep, maxTrailingStep);
}
}
}
}
|
||||
TheStack | e0885ec69a37a433ef8b1002f080d9683430e21f | C#code:C# | {"size": 454, "ext": "cs", "max_stars_repo_path": "src/HotChocolate/AspNetCore/src/AspNetCore/GraphQLEndpointOptions.cs", "max_stars_repo_name": "Drakkonite/hotchocolate", "max_stars_repo_stars_event_min_datetime": "2018-06-27T06:45:08.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T21:16:35.000Z", "max_issues_repo_path": "src/HotChocolate/AspNetCore/src/AspNetCore/GraphQLEndpointOptions.cs", "max_issues_repo_name": "Drakkonite/hotchocolate", "max_issues_repo_issues_event_min_datetime": "2018-06-05T18:24:45.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T14:22:12.000Z", "max_forks_repo_path": "src/HotChocolate/AspNetCore/src/AspNetCore/GraphQLEndpointOptions.cs", "max_forks_repo_name": "Drakkonite/hotchocolate", "max_forks_repo_forks_event_min_datetime": "2018-06-05T19:58:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T02:53:02.000Z"} | {"max_stars_count": 3399.0, "max_issues_count": 3835.0, "max_forks_count": 587.0, "avg_line_length": 32.4285714286, "max_line_length": 81, "alphanum_fraction": 0.6255506608} | namespace HotChocolate.AspNetCore
{
internal sealed class GraphQLEndpointOptions
{
/// <summary>
/// Gets or sets the GraphQL endpoint.
/// If <see cref="GraphQLToolOptions.UseBrowserUrlAsGraphQLEndpoint"/> is
/// set to <c>true</c> the GraphQL endpoint must be a relative path;
/// otherwise, it must be an absolute URL.
/// </summary>
public string? GraphQLEndpoint { get; set; }
}
}
|
||||
TheStack | e0897216ad67100e307f1d886d7bce50e4cf1ff5 | C#code:C# | {"size": 548, "ext": "cs", "max_stars_repo_path": "src/WebPlex.Applications.CompactStore/Data/Repositories/OrderLineRepository.cs", "max_stars_repo_name": "m-sadegh-sh/WebPlex.Applications.CompactStore", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/WebPlex.Applications.CompactStore/Data/Repositories/OrderLineRepository.cs", "max_issues_repo_name": "m-sadegh-sh/WebPlex.Applications.CompactStore", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/WebPlex.Applications.CompactStore/Data/Repositories/OrderLineRepository.cs", "max_forks_repo_name": "m-sadegh-sh/WebPlex.Applications.CompactStore", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 39.1428571429, "max_line_length": 105, "alphanum_fraction": 0.7354014599} | namespace WebPlex.Applications.CompactStore.Data.Repositories {
using System.Data.Entity;
using System.Linq;
using WebPlex.Applications.CompactStore.Models;
public class OrderLineRepository : DbRepositoryBase<OrderLineModel>, IOrderLineRepository {
public OrderLineRepository(StoreContext context) : base(context) {}
protected override IQueryable<OrderLineModel> GetIncluded(IQueryable<OrderLineModel> queryable) {
return queryable.Include(ol => ol.Order).Include(ol => ol.Product);
}
}
}
|
||||
TheStack | e08f2f5820775d9dcab02a58f77debeb29ed8cfc | C#code:C# | {"size": 5734, "ext": "cs", "max_stars_repo_path": "microservices/OrganizationService.Host/OrganizationServiceHostModule.cs", "max_stars_repo_name": "burningmyself/microservice", "max_stars_repo_stars_event_min_datetime": "2019-05-31T09:34:04.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-19T18:19:49.000Z", "max_issues_repo_path": "microservices/OrganizationService.Host/OrganizationServiceHostModule.cs", "max_issues_repo_name": "burningmyself/microservice", "max_issues_repo_issues_event_min_datetime": "2021-05-08T23:41:33.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-26T11:13:18.000Z", "max_forks_repo_path": "microservices/OrganizationService.Host/OrganizationServiceHostModule.cs", "max_forks_repo_name": "burningmyself/microservice", "max_forks_repo_forks_event_min_datetime": "2020-06-12T20:36:36.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-12T20:36:36.000Z"} | {"max_stars_count": 20.0, "max_issues_count": 6.0, "max_forks_count": 1.0, "avg_line_length": 43.1127819549, "max_line_length": 167, "alphanum_fraction": 0.6480641786} | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using OrganizationService.EntityFrameworkCore;
using Volo.Abp;
using Volo.Abp.Auditing;
using Volo.Abp.AuditLogging.EntityFrameworkCore;
using Volo.Abp.Autofac;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore.SqlServer;
using Volo.Abp.EventBus.RabbitMq;
using Volo.Abp.Http.Client.IdentityModel;
using Volo.Abp.Identity;
using Volo.Abp.Localization;
using Volo.Abp.Modularity;
using Volo.Abp.PermissionManagement.EntityFrameworkCore;
using Volo.Abp.Security.Claims;
using Volo.Abp.SettingManagement.EntityFrameworkCore;
using Volo.Abp.Threading;
namespace OrganizationService.Host
{
[DependsOn(
typeof(AbpAutofacModule),
typeof(AbpEventBusRabbitMqModule),
typeof(AbpEntityFrameworkCoreSqlServerModule),
typeof(AbpPermissionManagementEntityFrameworkCoreModule),
typeof(AbpSettingManagementEntityFrameworkCoreModule),
//日志记录
typeof(AbpAuditLoggingEntityFrameworkCoreModule),
typeof(AbpHttpClientIdentityModelModule),
//组织机构模块
typeof(OrganizationServiceHttpApiModule),
typeof(OrganizationServiceEntityFrameworkCoreModule),
typeof(OrganizationServiceApplicationModule),
typeof(AbpIdentityHttpApiClientModule)
)]
public class OrganizationServiceHostModule : AbpModule
{
public override void ConfigureServices(ServiceConfigurationContext context)
{
var configuration = context.Services.GetConfiguration();
context.Services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(options =>
{
options.Authority = configuration["AuthServer:Authority"];
options.ApiName = configuration["AuthServer:ApiName"];
options.RequireHttpsMetadata = false;
//TODO: Should create an extension method for that (may require to create a new ABP package depending on the IdentityServer4.AccessTokenValidation)
options.InboundJwtClaimTypeMap["sub"] = AbpClaimTypes.UserId;
options.InboundJwtClaimTypeMap["role"] = AbpClaimTypes.Role;
options.InboundJwtClaimTypeMap["email"] = AbpClaimTypes.Email;
options.InboundJwtClaimTypeMap["email_verified"] = AbpClaimTypes.EmailVerified;
options.InboundJwtClaimTypeMap["phone_number"] = AbpClaimTypes.PhoneNumber;
options.InboundJwtClaimTypeMap["phone_number_verified"] = AbpClaimTypes.PhoneNumberVerified;
options.InboundJwtClaimTypeMap["name"] = AbpClaimTypes.UserName;
});
context.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new Info {Title = "OrganizationService Service API", Version = "v1"});
options.DocInclusionPredicate((docName, description) => true);
options.CustomSchemaIds(type => type.FullName);
var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, };
options.AddSecurityRequirement(security);//添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。
options.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
Name = "Authorization",//jwt默认的参数名称
In = "header",//jwt默认存放Authorization信息的位置(请求头中)
Type = "apiKey"
});
});
Configure<AbpLocalizationOptions>(options =>
{
options.Languages.Add(new LanguageInfo("en", "en", "English"));
});
Configure<AbpDbContextOptions>(options =>
{
options.UseSqlServer();
});
context.Services.AddMvc().AddJsonOptions(json =>
{
//统一设置JsonResult中的日期格式
json.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
context.Services.AddDistributedRedisCache(options =>
{
options.Configuration = configuration["Redis:Configuration"];
});
Configure<AbpAuditingOptions>(options =>
{
options.IsEnabledForGetRequests = true;
options.ApplicationName = "OrganizationService";
});
var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
context.Services.AddDataProtection()
.PersistKeysToStackExchangeRedis(redis, "Ms-DataProtection-Keys");
}
public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
var app = context.GetApplicationBuilder();
app.UseCorrelationId();
app.UseVirtualFiles();
app.UseAuthentication();
app.UseAbpRequestLocalization(); //TODO: localization?
app.UseSwagger();
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", "OrganizationServices Service API");
});
app.UseAuditing();
app.UseMvcWithDefaultRouteAndArea();
}
}
}
|
||||
TheStack | e08fab5af1593af505638ca5c154702478e421ae | C#code:C# | {"size": 15414, "ext": "cs", "max_stars_repo_path": "NetfoxCore/Framework/Snoopers/SnooperFacebook/SnooperFacebookMining.cs", "max_stars_repo_name": "pokornysimon/NetfoxDetective", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "NetfoxCore/Framework/Snoopers/SnooperFacebook/SnooperFacebookMining.cs", "max_issues_repo_name": "pokornysimon/NetfoxDetective", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetfoxCore/Framework/Snoopers/SnooperFacebook/SnooperFacebookMining.cs", "max_forks_repo_name": "pokornysimon/NetfoxDetective", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 37.231884058, "max_line_length": 131, "alphanum_fraction": 0.5536525237} | // Copyright (c) 2017 Jan Pluskal, Tomas Bruckner
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using Newtonsoft.Json.Linq;
using OpenQA.Selenium;
using SnooperFacebook.ModelsMining.Events;
using SnooperFacebook.ModelsMining.Person;
using SnooperFacebook.ModelsMining.Photos;
using SnooperFacebook.ModelsMining.Places;
using OpenQA.Selenium.PhantomJS;
namespace SnooperFacebook
{
/// <summary>
/// Class for data mining Facebook users. Needs connection to internet.
/// </summary>
public class SnooperFacebookMining
{
public int Iteration { get; set; } = 25;
public string Email { get; set; } = "[email protected]";
public string Password { get; set; } = "testtest";
private PhantomJSDriver _driver;
// connected to Facebook
public bool IsLoggedIn { get; private set; }
/// <summary>
/// Creates WebDriver and logs in Facebook using default account
/// </summary>
public SnooperFacebookMining(bool setDriver)
{
if(!setDriver) { return; }
this.SetDriver();
this.LogInFacebook();
}
/// <summary>
/// Creates WebDriver and logs in Facebook using specified account
/// </summary>
public SnooperFacebookMining(string email, string password)
{
this.Email = email;
this.Password = password;
this.SetDriver();
this.LogInFacebook();
}
/// <summary>
/// Quits webdriver (ends instance of phantomjs browser)
/// </summary>
public void QuitMining()
{
this._driver?.Quit();
this._driver = null;
this.IsLoggedIn = false;
}
/// <summary>
/// Singleton method for webdriver
/// </summary>
/// <returns>
/// True if new driver has been created
/// False if driver is already created
/// </returns>
public bool SetDriver()
{
if (this._driver != null) { return false; }
var driverService = PhantomJSDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;
this._driver = new PhantomJSDriver(driverService);
return true;
}
/// <summary>
/// Connects to Facebook using instance email and password properties
/// </summary>
/// <returns>
/// True if you are logged into Facebook
/// False if login failed
/// </returns>
public bool LogInFacebook()
{
this.SetDriver();
this._driver.Navigate().GoToUrl("https://www.facebook.com");
this._driver.FindElement(By.Id("email")).SendKeys(this.Email);
this._driver.FindElement(By.Id("pass")).SendKeys(this.Password);
try
{
this._driver.FindElement(By.Id("loginbutton")).Click();
}
catch
{
((IJavaScriptExecutor)this._driver).ExecuteScript("window.stop();");
this.IsLoggedIn = false;
return false;
}
this.IsLoggedIn = true;
return true;
}
/// <summary>
/// Parses all targeted user's friends
/// </summary>
/// <param name="user">Targeted username</param>
/// <returns>All targeted user's friends</returns>
public FacebookFriendlist GetFriendlist(string user)
{
//this._driver.Navigate().GoToUrl(string.Format("https://www.facebook.com/profile.php?id={0}&sk=friends", 1084537908));
this._driver.Navigate().GoToUrl(string.Format("https://www.facebook.com/{0}/friends", user));
// getting all friends from Facebook infinite scroll
var actualElementCount = this._driver.FindElements(By.CssSelector("ul")).Count;
int previousElementCount;
do
{
previousElementCount = actualElementCount;
((IJavaScriptExecutor) this._driver).ExecuteScript("scrollBy(0,3000)");
Thread.Sleep(3000);
actualElementCount = this._driver.FindElements(By.CssSelector("ul")).Count;
} while(actualElementCount != previousElementCount);
var elements = this._driver.FindElements(By.CssSelector("a[href*='friends_tab']"));
return ParseFriendlist(elements, user);
}
/// <summary>
/// Parses usernames from urls.
/// </summary>
/// <param name="friendLinkList"></param>
/// <param name="user"></param>
/// <returns></returns>
private static FacebookFriendlist ParseFriendlist(IEnumerable<IWebElement> friendLinkList, string user)
{
var friendList = new FacebookFriendlist()
{
Username = user
};
// url contains username
var regexNickname = new Regex(@"(https:\/\/www.facebook.com\/)(.*)(\?.*)");
// url contains user's id
var regexId = new Regex(@"(https:\/\/www.facebook.com\/profile\.php\?id=)(.*)(&fref.*)");
foreach (var friend in friendLinkList)
{
var friendLink = friend.GetAttribute("href");
var match = regexNickname.Match(friendLink);
if (!match.Success) continue;
var friendId = match.Groups[2].Value;
// some users dont have nickname, only id
if (friendId == "profile.php")
{
match = regexId.Match(friendLink);
friendId = match.Groups[2].Value;
}
if (!IsDuplicate(friendList.Friends, friendId))
{
friendList.Friends.Add(friendId);
}
}
return friendList;
}
/// <summary>
/// Checks for duplications in string array
/// </summary>
/// <param name="elements"></param>
/// <param name="newElement"></param>
/// <returns></returns>
private static bool IsDuplicate(IEnumerable<string> elements, string newElement)
{
return elements.Any(element => element == newElement);
}
/// <summary>
/// Parses mutual friends from two friendlists
/// </summary>
/// <param name="userList1"></param>
/// <param name="userList2"></param>
/// <returns>List of mutual friends</returns>
public FacebookMutualFriends GetMutualFriends(FacebookFriendlist userList1, FacebookFriendlist userList2)
{
var mutualFriends = new FacebookMutualFriends
{
MutualFriends = userList1.Friends.Where(userList2.Friends.Contains).ToList(),
};
mutualFriends.Participants.Add(userList1.Username);
mutualFriends.Participants.Add(userList2.Username);
return mutualFriends;
}
/// <summary>
/// Parses mutual friends from mutual list and friendlist
/// </summary>
/// <param name="mutualList"></param>
/// <param name="userList"></param>
/// <returns>Mutual friends</returns>
public FacebookMutualFriends GetMutualFriends(FacebookMutualFriends mutualList, FacebookFriendlist userList)
{
var mutualFriends = new FacebookMutualFriends
{
MutualFriends = mutualList.MutualFriends.Where(userList.Friends.Contains).ToList()
};
mutualFriends.Participants.Add(userList.Username);
foreach (var participant in mutualList.Participants)
{
mutualFriends.Participants.Add(participant);
}
return mutualFriends;
}
/// <summary>
/// Parses mutual friends from two mutual lists
/// </summary>
/// <param name="mutualList1"></param>
/// <param name="mutualList2"></param>
/// <returns>Mutual friends</returns>
public FacebookMutualFriends GetMutualFriends(FacebookMutualFriends mutualList1, FacebookMutualFriends mutualList2)
{
var mutualFriends = new FacebookMutualFriends
{
MutualFriends = mutualList1.MutualFriends.Where(mutualList2.MutualFriends.Contains).ToList()
};
foreach (var participant in mutualList1.Participants)
{
mutualFriends.Participants.Add(participant);
}
foreach (var participant in mutualList2.Participants)
{
mutualFriends.Participants.Add(participant);
}
return mutualFriends;
}
/// <summary>
/// Parses public information about specified user
/// </summary>
/// <param name="user">User's username</param>
/// <returns>User's public information</returns>
public FacebookPublicInfo GetFacebookPublicInfo(string user)
{
var webClient = new WebClient();
string downloadedString;
try
{
downloadedString = webClient.DownloadString(@"http://graph.facebook.com/" + user);
}
catch(Exception) {
return null;
}
var userPublicInfoJson = JObject.Parse(downloadedString);
if (userPublicInfoJson["error"] != null)
{
// invalid username
return null;
}
var facebookPublicProfile = new FacebookPublicInfo
{
Gender = (string)userPublicInfoJson["gender"],
Name = (string)userPublicInfoJson["name"],
Username = (string)userPublicInfoJson["username"],
Id = (ulong)userPublicInfoJson["id"],
ProfileLink = (string)userPublicInfoJson["link"],
Locale = (string)userPublicInfoJson["locale"]
};
return facebookPublicProfile;
}
/// <summary>
/// Downloads user's profile picture (always public)
/// </summary>
/// <param name="user">User's username or id</param>
/// <param name="filenamePath">where to download</param>
/// <returns>
/// True if download was successful
/// False if download failed
/// </returns>
public bool GetProfilePicture(string user, string filenamePath)
{
// filenamePath example D:\file.jpg
try
{
var webClient = new WebClient();
webClient.DownloadFile(@"http://graph.facebook.com/" + user + @"/picture?type=large", filenamePath);
return true;
}
catch(Exception)
{
return false;
}
}
/// <summary>
/// Parses events that specified user will be going to
/// </summary>
/// <param name="user">User's username</param>
/// <returns>List of upcoming events</returns>
public IEnumerable<FacebookUpcomingEvent> GetUpcomingEvents(string user)
{
this._driver.Navigate().GoToUrl(string.Format("https://www.facebook.com/{0}/upcoming_events", user));
var elements = this._driver.FindElements(By.CssSelector("a[href*='events']"));
return (from element in elements
where element.Text != string.Empty
where !element.Text.Contains("\r")
let url = element.GetAttribute("href")
where !url.Contains(string.Format("{0}", user))
select new FacebookUpcomingEvent()
{
UserId = user,
Url = url,
Name = element.Text
}).ToList();
}
/// <summary>
/// Parses events that specified user has visited
/// </summary>
/// <param name="user">User's username</param>
/// <returns>List of visited events</returns>
public IEnumerable<FacebookPastEvent> GetPastEvents(string user)
{
this._driver.Navigate().GoToUrl(string.Format("https://www.facebook.com/{0}/past_events", user));
var elements = this._driver.FindElements(By.CssSelector("a[href*='events']"));
return (from element in elements
where element.Text != string.Empty
where !element.Text.Contains("\r")
let url = element.GetAttribute("href")
where !url.Contains(string.Format("{0}", user))
select new FacebookPastEvent()
{
UserId = user,
Url = url,
Name = element.Text
}).ToList();
}
/// <summary>
/// Parses album names of specified user
/// </summary>
/// <param name="user">User's username</param>
/// <returns>List of album names</returns>
public IEnumerable<FacebookAlbum> ParseAlbums(string user)
{
this._driver.Navigate().GoToUrl(string.Format("https://www.facebook.com/{0}/photos_albums", user));
var elements = this._driver.FindElements(By.CssSelector("strong"));
return (from element in elements
where element.Text != string.Empty
select new FacebookAlbum()
{
UserId = user,
Name = element.Text
}).ToList();
}
/// <summary>
/// Parses places, that specified user recently visited
/// </summary>
/// <param name="user">User's username</param>
/// <returns>List of recent places</returns>
public IEnumerable<FacebookRecentPlace> GetRecentPlaces(string user)
{
this._driver.Navigate().GoToUrl(string.Format("https://www.facebook.com/{0}/places_recent", user));
var elements = this._driver.FindElements(By.CssSelector("a[href*='pages']"));
return (from element in elements
where element.Text != string.Empty
where !element.Text.Contains("Create")
select new FacebookRecentPlace()
{
UserId = user,
Name = element.Text,
Url = element.GetAttribute("href")
}).ToList();
}
}
}
|
||||
TheStack | e08fde803d5ac36717c69d7d48e561788ac96e5c | C#code:C# | {"size": 4558, "ext": "cs", "max_stars_repo_path": "MongoDB.Entities/DB.Sequence.cs", "max_stars_repo_name": "molinch/MongoDB.Entities", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MongoDB.Entities/DB.Sequence.cs", "max_issues_repo_name": "molinch/MongoDB.Entities", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MongoDB.Entities/DB.Sequence.cs", "max_forks_repo_name": "molinch/MongoDB.Entities", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 48.4893617021, "max_line_length": 140, "alphanum_fraction": 0.6428258008} | using MongoDB.Entities.Core;
using System.Threading;
using System.Threading.Tasks;
namespace MongoDB.Entities
{
public partial class DB
{
//NOTE: transaction support will not be added due to unpredictability with concurrency.
/// <summary>
/// Returns an atomically generated sequential number for the given Entity type everytime the method is called
/// </summary>
/// <typeparam name="T">The type of entity to get the next sequential number for</typeparam>
/// <param name="cancellation">An optional cancellation token</param>
public Task<ulong> NextSequentialNumberAsync<T>(CancellationToken cancellation = default) where T : IEntity
{
return NextSequentialNumberAsync<T>(DbName, cancellation);
}
/// <summary>
/// Returns an atomically generated sequential number for the given Entity type everytime the method is called
/// </summary>
/// <typeparam name="T">The type of entity to get the next sequential number for</typeparam>
/// <param name="cancellation">An optional cancellation token</param>
public static Task<ulong> NextSequentialNumberAsync<T>(string db = null, CancellationToken cancellation = default) where T : IEntity
{
return NextSequentialNumberAsync(GetCollectionName<T>(), db, cancellation);
}
/// <summary>
/// Returns an atomically generated sequential number for the given Entity type everytime the method is called
/// </summary>
/// <typeparam name="T">The type of entity to get the next sequential number for</typeparam>
public ulong NextSequentialNumber<T>() where T : IEntity
{
return Run.Sync(() => NextSequentialNumberAsync<T>(DbName));
}
/// <summary>
/// Returns an atomically generated sequential number for the given Entity type everytime the method is called
/// </summary>
/// <typeparam name="T">The type of entity to get the next sequential number for</typeparam>
public static ulong NextSequentialNumber<T>(string db = null) where T : IEntity
{
return Run.Sync(() => NextSequentialNumberAsync<T>(db));
}
/// <summary>
/// Returns an atomically generated sequential number for the given sequence name everytime the method is called
/// </summary>
/// <param name="sequenceName">The name of the sequence to get the next number for</param>
/// <param name="cancellation">An optional cancellation token</param>
public Task<ulong> NextSequentialNumberAsync(string sequenceName, CancellationToken cancellation = default)
{
return NextSequentialNumberAsync(sequenceName, DbName, cancellation);
}
/// <summary>
/// Returns an atomically generated sequential number for the given sequence name everytime the method is called
/// </summary>
/// <param name="sequenceName">The name of the sequence to get the next number for</param>
/// <param name="cancellation">An optional cancellation token</param>
public static Task<ulong> NextSequentialNumberAsync(string sequenceName, string db = null, CancellationToken cancellation = default)
{
return
new UpdateAndGet<SequenceCounter, ulong>(db: db)
.Match(s => s.ID == sequenceName)
.Modify(b => b.Inc(s => s.Count, 1ul))
.Option(o => o.IsUpsert = true)
.Project(s => s.Count)
.ExecuteAsync(cancellation);
}
/// <summary>
/// Returns an atomically generated sequential number for the given sequence name everytime the method is called
/// </summary>
/// <param name="sequenceName">The name of the sequence to get the next number for</param>
public ulong NextSequentialNumber(string sequenceName)
{
return Run.Sync(() => NextSequentialNumberAsync(sequenceName, DbName));
}
/// <summary>
/// Returns an atomically generated sequential number for the given sequence name everytime the method is called
/// </summary>
/// <param name="sequenceName">The name of the sequence to get the next number for</param>
public static ulong NextSequentialNumber(string sequenceName, string db = null)
{
return Run.Sync(() => NextSequentialNumberAsync(sequenceName, db));
}
}
}
|
||||
TheStack | e090f671e82ec2ee629561fac53e6097ae9f9672 | C#code:C# | {"size": 2345, "ext": "cs", "max_stars_repo_path": "src/WarCollege.Tests/ExperienceTests.cs", "max_stars_repo_name": "wildj79/WarCollege", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/WarCollege.Tests/ExperienceTests.cs", "max_issues_repo_name": "wildj79/WarCollege", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/WarCollege.Tests/ExperienceTests.cs", "max_forks_repo_name": "wildj79/WarCollege", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.4426229508, "max_line_length": 130, "alphanum_fraction": 0.6797441365} | // War College - Copyright (c) 2017 James Allred (wildj79 at gmail dot com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using WarCollege.Model;
using Xunit;
namespace WarCollege.Tests
{
public class ExperienceTests
{
const int Seed = 100;
[Theory]
[InlineData(20)]
[InlineData(-20)]
[InlineData(10)]
[InlineData(-10)]
[InlineData(100)]
[InlineData(-100)]
public void IsAmountAdded(int value)
{
var experience = new ExperiencePoints(Seed);
experience.AddExperience(value);
Assert.Equal(Seed + value, experience.TotalExperience);
Assert.Equal(Seed + value, experience.CurrentExperience);
}
[Theory]
[InlineData(20)]
[InlineData(-20)]
[InlineData(10)]
[InlineData(-10)]
[InlineData(100)]
[InlineData(-100)]
public void IsPropertyChangedRaised(int value)
{
var experience = new ExperiencePoints(Seed);
Assert.PropertyChanged(experience, nameof(ExperiencePoints.TotalExperience), () => experience.AddExperience(value));
Assert.PropertyChanged(experience, nameof(ExperiencePoints.CurrentExperience), () => experience.AddExperience(value));
}
}
}
|
||||
TheStack | e0910d7e815ccbaa4ac5fe5154a140bc1c7d3c61 | C#code:C# | {"size": 2560, "ext": "cs", "max_stars_repo_path": "src/Microsoft.Health.Fhir.Core/Features/Search/Parameters/DeleteSearchParameterBehavior.cs", "max_stars_repo_name": "shengdamao/fhir-server", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Microsoft.Health.Fhir.Core/Features/Search/Parameters/DeleteSearchParameterBehavior.cs", "max_issues_repo_name": "shengdamao/fhir-server", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Microsoft.Health.Fhir.Core/Features/Search/Parameters/DeleteSearchParameterBehavior.cs", "max_forks_repo_name": "shengdamao/fhir-server", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 46.5454545455, "max_line_length": 180, "alphanum_fraction": 0.67734375} | // -------------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// -------------------------------------------------------------------------------------------------
using System;
using System.Threading;
using System.Threading.Tasks;
using EnsureThat;
using MediatR;
using Microsoft.Health.Fhir.Core.Features.Persistence;
using Microsoft.Health.Fhir.Core.Messages.Delete;
using Microsoft.Health.Fhir.Core.Models;
namespace Microsoft.Health.Fhir.Core.Features.Search.Parameters
{
public class DeleteSearchParameterBehavior<TDeleteResourceRequest, TDeleteResourceResponse> : IPipelineBehavior<TDeleteResourceRequest, TDeleteResourceResponse>
where TDeleteResourceRequest : DeleteResourceRequest
{
private ISearchParameterUtilities _searchParameterUtilities;
private IFhirDataStore _fhirDataStore;
public DeleteSearchParameterBehavior(ISearchParameterUtilities searchParameterUtilities, IFhirDataStore fhirDataStore)
{
EnsureArg.IsNotNull(searchParameterUtilities, nameof(searchParameterUtilities));
EnsureArg.IsNotNull(fhirDataStore, nameof(fhirDataStore));
_searchParameterUtilities = searchParameterUtilities;
_fhirDataStore = fhirDataStore;
}
public async Task<TDeleteResourceResponse> Handle(TDeleteResourceRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TDeleteResourceResponse> next)
{
var deleteRequest = request as DeleteResourceRequest;
ResourceWrapper searchParamResource = null;
if (deleteRequest.ResourceKey.ResourceType.Equals(KnownResourceTypes.SearchParameter, StringComparison.Ordinal))
{
searchParamResource = await _fhirDataStore.GetAsync(deleteRequest.ResourceKey, cancellationToken);
}
var response = await next();
if (searchParamResource != null && searchParamResource.IsDeleted == false)
{
// Once the SearchParameter resource is removed from the data store, we can update the in
// memory SearchParameterDefinitionManager, and remove the status metadata from the data store
await _searchParameterUtilities.DeleteSearchParameterAsync(searchParamResource.RawResource);
}
return response;
}
}
}
|
||||
TheStack | e094b4a2c2942287f62f087a163caf614d664d2e | C#code:C# | {"size": 22354, "ext": "cs", "max_stars_repo_path": "Hoot/MGIndex/KeyStoreHF.cs", "max_stars_repo_name": "mgholam/hOOt", "max_stars_repo_stars_event_min_datetime": "2015-01-25T10:42:22.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T17:54:03.000Z", "max_issues_repo_path": "Hoot/MGIndex/KeyStoreHF.cs", "max_issues_repo_name": "nihoutao234/mgholamw", "max_issues_repo_issues_event_min_datetime": "2016-08-13T17:39:20.000Z", "max_issues_repo_issues_event_max_datetime": "2019-12-17T21:04:22.000Z", "max_forks_repo_path": "Hoot/MGIndex/KeyStoreHF.cs", "max_forks_repo_name": "nihoutao234/mgholamw", "max_forks_repo_forks_event_min_datetime": "2015-07-02T10:26:18.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-05T00:36:34.000Z"} | {"max_stars_count": 110.0, "max_issues_count": 3.0, "max_forks_count": 26.0, "avg_line_length": 33.5142428786, "max_line_length": 109, "alphanum_fraction": 0.4449762906} | using RaptorDB.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace RaptorDB
{
// high frequency key value store
public class KeyStoreHF : IKeyStoreHF
{
internal class AllocationBlock
{
public string key;
public byte keylen;
public int datalength;
public bool isCompressed;
public bool isBinaryJSON;
public bool deleteKey;
public List<int> Blocks = new List<int>();
public int blocknumber;
}
MGIndex<string> _keys;
StorageFileHF _datastore;
object _lock = new object();
ushort _BlockSize = 2048;
private const int _KILOBYTE = 1024;
ILog _log = LogManager.GetLogger(typeof(KeyStoreHF));
byte[] _blockheader = new byte[]{
0,0,0,0, // 0 block # (used for validate block reads and rebuild)
0,0,0,0, // 4 next block #
0, // 8 flags bits 0:iscompressed 1:isbinary 2:deletekey
0,0,0,0, // 9 data length (compute alloc blocks needed)
0, // 13 key length
0, // 14 key type 0=guid 1=string
};
private string _Path = "";
private string _S = Path.DirectorySeparatorChar.ToString();
private bool _isDirty = false;
private string _dirtyFilename = "temp.$";
public KeyStoreHF(string folder)
{
_Path = folder;
Directory.CreateDirectory(_Path);
if (_Path.EndsWith(_S) == false) _Path += _S;
if (File.Exists(_Path + _dirtyFilename))
{
_log.Error("Last shutdown failed, rebuilding data files...");
RebuildDataFiles();
}
_datastore = new StorageFileHF(_Path + "data.mghf", Global.HighFrequencyKVDiskBlockSize);
_keys = new MGIndex<string>(_Path, "keys.idx", 255, /*Global.PageItemCount,*/ false);
//_datastore.Initialize();
_BlockSize = _datastore.GetBlockSize();
}
// mgindex special storage for strings ctor -> no idx file
// use SaveData() GetData()
public KeyStoreHF(string folder, string filename)
{
_Path = folder;
Directory.CreateDirectory(_Path);
if (_Path.EndsWith(_S) == false) _Path += _S;
_datastore = new StorageFileHF(_Path + filename, Global.HighFrequencyKVDiskBlockSize);
//_datastore.Initialize();
_BlockSize = _datastore.GetBlockSize();
}
public int CountHF()
{
if (_keys != null)
return _keys.Count();
else
return 0;
}
public object GetObjectHF(string key)
{
lock (_lock)
{
int alloc;
if (_keys.Get(key, out alloc))
{
AllocationBlock ab = FillAllocationBlock(alloc);
if (ab.deleteKey == false)
{
byte[] data = readblockdata(ab);
return fastBinaryJSON.BJSON.ToObject(data);
}
}
}
return null;
}
public bool SetObjectHF(string key, object obj)
{
byte[] k = Helper.GetBytes(key);
if (k.Length > 255)
{
_log.Error("Key length > 255 : " + key);
throw new Exception("Key must be less than 255 characters");
//return false;
}
lock (_lock)
{
if (_isDirty == false)
WriteDirtyFile();
AllocationBlock ab = null;
int firstblock = 0;
if (_keys.Get(key, out firstblock))// key exists already
ab = FillAllocationBlock(firstblock);
SaveNew(key, k, obj);
if (ab != null)
{
// free old blocks
ab.Blocks.Add(ab.blocknumber);
_datastore.FreeBlocks(ab.Blocks);
}
return true;
}
}
public bool DeleteKeyHF(string key)
{
lock (_lock)
{
int alloc;
if (_keys.Get(key, out alloc))
{
if (_isDirty == false)
WriteDirtyFile();
byte[] keybytes = Helper.GetBytes(key);
AllocationBlock ab = FillAllocationBlock(alloc);
ab.keylen = (byte)keybytes.Length;
_keys.RemoveKey(key);// remove key from index
// write ab
ab.deleteKey = true;
ab.datalength = 0;
byte[] header = CreateAllocHeader(ab, keybytes);
_datastore.SeekBlock(ab.blocknumber);
_datastore.WriteBlockBytes(header, 0, header.Length);
// free old data blocks
_datastore.FreeBlocks(ab.Blocks);
return true;
}
}
return false;
}
public void CompactStorageHF()
{
lock (_lock)
{
try
{
_log.Debug("Compacting storage file ...");
if (Directory.Exists(_Path + "temp"))
Directory.Delete(_Path + "temp", true);
KeyStoreHF newfile = new KeyStoreHF(_Path + "temp");
string[] keys = _keys.GetKeys().Cast<string>().ToArray();
_log.Debug("Number of keys : " + keys.Length);
foreach (var k in keys)
{
newfile.SetObjectHF(k, GetObjectHF(k));
}
newfile.Shutdown();
_log.Debug("Compact done.");
// shutdown and move files and restart here
if (Directory.Exists(_Path + "old"))
Directory.Delete(_Path + "old", true);
Directory.CreateDirectory(_Path + "old");
_datastore.Shutdown();
_keys.Shutdown();
_log.Debug("Moving files...");
foreach (var f in Directory.GetFiles(_Path, "*.*"))
File.Move(f, _Path + "old" + _S + Path.GetFileName(f));
foreach (var f in Directory.GetFiles(_Path + "temp", "*.*"))
File.Move(f, _Path + Path.GetFileName(f));
Directory.Delete(_Path + "temp", true);
//Directory.Delete(_Path + "old", true); // FEATURE : delete or keep?
_log.Debug("Re-opening storage file");
_datastore = new StorageFileHF(_Path + "data.mghf", Global.HighFrequencyKVDiskBlockSize);
_keys = new MGIndex<string>(_Path, "keys.idx", 255, false);
_BlockSize = _datastore.GetBlockSize();
}
catch (Exception ex)
{
_log.Error(ex);
}
}
}
public string[] GetKeysHF()
{
lock (_lock)
return _keys.GetKeys().Cast<string>().ToArray(); // FEATURE : ugly and dirty !?
}
public bool ContainsHF(string key)
{
lock (_lock)
{
int i = 0;
return _keys.Get(key, out i);
}
}
public void Shutdown()
{
_datastore.Shutdown();
if (_keys != null)
{
_keys.Shutdown();
if (File.Exists(_Path + _dirtyFilename))
File.Delete(_Path + _dirtyFilename);
}
}
internal void FreeMemory()
{
if (_keys != null)
_keys.FreeMemory();
}
#region [ private methods ]
private byte[] readblockdata(AllocationBlock ab)
{
byte[] data = new byte[ab.datalength];
long offset = 0;
int len = ab.datalength;
int dbsize = _BlockSize - _blockheader.Length - ab.keylen;
ab.Blocks.ForEach(x =>
{
byte[] b = _datastore.ReadBlock(x);
int c = len;
if (c > dbsize) c = dbsize;
Buffer.BlockCopy(b, _blockheader.Length + ab.keylen, data, (int)offset, c);
offset += c;
len -= c;
});
if (ab.isCompressed)
data = MiniLZO.Decompress(data);
return data;
}
private object _dfile = new object();
private void WriteDirtyFile()
{
lock (_dfile)
{
_isDirty = true;
if (File.Exists(_Path + _dirtyFilename) == false)
File.WriteAllText(_Path + _dirtyFilename, "dirty");
}
}
private void SaveNew(string key, byte[] keybytes, object obj)
{
byte[] data;
AllocationBlock ab = new AllocationBlock();
ab.key = key;
ab.keylen = (byte)keybytes.Length;
data = fastBinaryJSON.BJSON.ToBJSON(obj);
ab.isBinaryJSON = true;
if (data.Length > (int)Global.CompressDocumentOverKiloBytes * _KILOBYTE)
{
ab.isCompressed = true;
data = MiniLZO.Compress(data);
}
ab.datalength = data.Length;
int firstblock = internalSave(keybytes, data, ab);
// save keys
_keys.Set(key, firstblock);
}
private int internalSave(byte[] keybytes, byte[] data, AllocationBlock ab)
{
int firstblock = _datastore.GetFreeBlockNumber();
int blocknum = firstblock;
byte[] header = CreateAllocHeader(ab, keybytes);
int dblocksize = _BlockSize - header.Length;
int offset = 0;
// compute data block count
int datablockcount = (data.Length / dblocksize) + 1;
// save data blocks
int counter = 0;
int len = data.Length;
while (datablockcount > 0)
{
datablockcount--;
int next = 0;
if (datablockcount > 0)
next = _datastore.GetFreeBlockNumber();
Buffer.BlockCopy(Helper.GetBytes(counter, false), 0, header, 0, 4); // set block number
Buffer.BlockCopy(Helper.GetBytes(next, false), 0, header, 4, 4); // set next pointer
_datastore.SeekBlock(blocknum);
_datastore.WriteBlockBytes(header, 0, header.Length);
int c = len;
if (c > dblocksize)
c = dblocksize;
_datastore.WriteBlockBytes(data, offset, c);
if (next > 0)
blocknum = next;
offset += c;
len -= c;
counter++;
}
return firstblock;
}
private byte[] CreateAllocHeader(AllocationBlock ab, byte[] keybytes)
{
byte[] alloc = new byte[_blockheader.Length + keybytes.Length];
if (ab.isCompressed)
alloc[8] = 1;
if (ab.isBinaryJSON)
alloc[8] += 2;
if (ab.deleteKey)
alloc[8] += 4;
Buffer.BlockCopy(Helper.GetBytes(ab.datalength, false), 0, alloc, 9, 4);
alloc[13] = ab.keylen;
alloc[14] = 1; // string keys for now
Buffer.BlockCopy(keybytes, 0, alloc, _blockheader.Length, ab.keylen);
return alloc;
}
private AllocationBlock FillAllocationBlock(int blocknumber)
{
AllocationBlock ab = new AllocationBlock();
ab.blocknumber = blocknumber;
ab.Blocks.Add(blocknumber);
byte[] b = _datastore.ReadBlockBytes(blocknumber, _blockheader.Length + 255);
int blocknumexpected = 0;
int next = ParseBlockHeader(ab, b, blocknumexpected);
blocknumexpected++;
while (next > 0)
{
ab.Blocks.Add(next);
b = _datastore.ReadBlockBytes(next, _blockheader.Length + ab.keylen);
next = ParseBlockHeader(ab, b, blocknumexpected);
blocknumexpected++;
}
return ab;
}
private int ParseBlockHeader(AllocationBlock ab, byte[] b, int blocknumberexpected)
{
int bnum = Helper.ToInt32(b, 0);
if (bnum != blocknumberexpected)
{
_log.Error("Block numbers does not match, looking for : " + blocknumberexpected);
//throw new Exception("Block numbers does not match, looking for : " + blocknumberexpected);
return -1;
}
if (b[14] != 1)
{
_log.Error("Expecting string keys only, got : " + b[14]);
//throw new Exception("Expecting string keys only, got : " + b[11]);
return -1;
}
int next = Helper.ToInt32(b, 4);
if (ab.keylen == 0)
{
byte flags = b[8];
if ((flags & 0x01) > 0)
ab.isCompressed = true;
if ((flags & 0x02) > 0)
ab.isBinaryJSON = true;
if ((flags & 0x04) > 0)
ab.deleteKey = true;
ab.datalength = Helper.ToInt32(b, 9);
byte keylen = b[13];
ab.keylen = keylen;
ab.key = Helper.GetString(b, _blockheader.Length, keylen);
}
return next;
}
private void RebuildDataFiles()
{
MGIndex<string> keys = null;
try
{
// remove old free list
if (File.Exists(_Path + "data.bmp"))
File.Delete(_Path + "data.bmp");
_datastore = new StorageFileHF(_Path + "data.mghf", Global.HighFrequencyKVDiskBlockSize);
_BlockSize = _datastore.GetBlockSize();
if (File.Exists(_Path + "keys.idx"))
{
_log.Debug("removing old keys index");
foreach (var f in Directory.GetFiles(_Path, "keys.*"))
File.Delete(f);
}
keys = new MGIndex<string>(_Path, "keys.idx", 255, /*Global.PageItemCount,*/ false);
MGRB visited = new MGRB();
int c = _datastore.NumberofBlocks();
for (int i = 1; i < c; i++) // go through blocks skip first
{
if (visited.Get(i))
continue;
byte[] b = _datastore.ReadBlockBytes(i, _blockheader.Length + 255);
int bnum = Helper.ToInt32(b, 0);
if (bnum > 0) // check if a start block
{
visited.Set(i, true);
_datastore.FreeBlock(i); // mark as free
continue;
}
AllocationBlock ab = new AllocationBlock();
// start block found
int blocknumexpected = 0;
int next = ParseBlockHeader(ab, b, blocknumexpected);
int last = 0;
bool freelast = false;
AllocationBlock old = null;
if (ab.key == null)
continue;
if (keys.Get(ab.key, out last))
{
old = this.FillAllocationBlock(last);
freelast = true;
}
blocknumexpected++;
bool failed = false;
if (ab.deleteKey == false)
{
while (next > 0) // read the blocks
{
ab.Blocks.Add(next);
b = _datastore.ReadBlockBytes(next, _blockheader.Length + ab.keylen);
next = ParseBlockHeader(ab, b, blocknumexpected);
if (next == -1) // non matching block
{
failed = true;
break;
}
blocknumexpected++;
}
}
else
{
failed = true;
keys.RemoveKey(ab.key);
}
// new data ok
if (failed == false)
{
keys.Set(ab.key, i);// valid block found
if (freelast && old != null)// free the old blocks
_datastore.FreeBlocks(old.Blocks);
}
visited.Set(i, true);
}
// all ok delete temp.$ file
if (File.Exists(_Path + _dirtyFilename))
File.Delete(_Path + _dirtyFilename);
}
catch (Exception ex)
{
_log.Error(ex);
}
finally
{
_log.Debug("Shutting down files and index");
_datastore.Shutdown();
keys.SaveIndex();
keys.Shutdown();
}
}
#endregion
internal void FreeBlocks(List<int> list)
{
lock (_lock)
_datastore.FreeBlocks(list);
}
// for .string files
internal int SaveData(string key, byte[] data)
{
lock (_lock)
{
byte[] kb = Helper.GetBytes(key);
AllocationBlock ab = new AllocationBlock();
ab.key = key;
ab.keylen = (byte)kb.Length;
ab.isCompressed = false;
ab.isBinaryJSON = true;
ab.datalength = data.Length;
return internalSave(kb, data, ab);
}
}
// for .string files
internal byte[] GetData(int blocknumber, out List<int> usedblocks)
{
lock (_lock)
{
AllocationBlock ab = FillAllocationBlock(blocknumber);
usedblocks = ab.Blocks;
byte[] data = readblockdata(ab);
return data;
}
}
public int Increment(string key, int amount)
{
byte[] k = Helper.GetBytes(key);
if (k.Length > 255)
{
_log.Error("Key length > 255 : " + key);
throw new Exception("Key must be less than 255 characters");
//return false;
}
lock (_lock)
{
if (_isDirty == false)
WriteDirtyFile();
AllocationBlock ab = null;
int firstblock = 0;
if (_keys.Get(key, out firstblock))// key exists already
ab = FillAllocationBlock(firstblock);
object obj = amount;
if (ab.deleteKey == false)
{
byte[] data = readblockdata(ab);
obj = fastBinaryJSON.BJSON.ToObject(data);
// add here
if (obj is int)
obj = ((int)obj) + amount;
else if (obj is long)
obj = ((long)obj) + amount;
else if (obj is decimal)
obj = ((decimal)obj) + amount;
else
return (int)obj;
}
SaveNew(key, k, obj);
if (ab != null)
{
// free old blocks
ab.Blocks.Add(ab.blocknumber);
_datastore.FreeBlocks(ab.Blocks);
}
return (int)obj;
}
}
public int Decrement(string key, int amount)
{
return (int)Increment(key, -amount);
}
public decimal Increment(string key, decimal amount)
{
byte[] k = Helper.GetBytes(key);
if (k.Length > 255)
{
_log.Error("Key length > 255 : " + key);
throw new Exception("Key must be less than 255 characters");
//return false;
}
lock (_lock)
{
if (_isDirty == false)
WriteDirtyFile();
AllocationBlock ab = null;
int firstblock = 0;
if (_keys.Get(key, out firstblock))// key exists already
ab = FillAllocationBlock(firstblock);
object obj = amount;
if (ab.deleteKey == false)
{
byte[] data = readblockdata(ab);
obj = fastBinaryJSON.BJSON.ToObject(data);
// add here
if (obj is decimal)
obj = ((decimal)obj) + amount;
else
return (decimal)obj;
}
SaveNew(key, k, obj);
if (ab != null)
{
// free old blocks
ab.Blocks.Add(ab.blocknumber);
_datastore.FreeBlocks(ab.Blocks);
}
return (decimal)obj;
}
}
public decimal Decrement(string key, decimal amount)
{
return Increment(key, -amount);
}
}
}
|
||||
TheStack | e09629fee69644e6afb0f526106eeb9e3ff963f1 | C#code:C# | {"size": 1034, "ext": "cs", "max_stars_repo_path": "WebApi/BusinessServices/Concrete/ProductServices.cs", "max_stars_repo_name": "zandrei007/WebApi", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "WebApi/BusinessServices/Concrete/ProductServices.cs", "max_issues_repo_name": "zandrei007/WebApi", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "WebApi/BusinessServices/Concrete/ProductServices.cs", "max_forks_repo_name": "zandrei007/WebApi", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.619047619, "max_line_length": 77, "alphanum_fraction": 0.6470019342} | using BusinessServices.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BusinessEntities;
namespace BusinessServices.Concrete
{
/// <summary>
/// Offers services for product specific CRUD operations
/// </summary>
public class ProductServices : IProductServices
{
public int CreateProduct(ProductEntity productEntity)
{
throw new NotImplementedException();
}
public bool DeleteProduct(int productId)
{
throw new NotImplementedException();
}
public IEnumerable<ProductEntity> GetAllProducts()
{
throw new NotImplementedException();
}
public ProductEntity GetProductById(int productId)
{
throw new NotImplementedException();
}
public bool UpdateProduct(int productId, ProductEntity productEntity)
{
throw new NotImplementedException();
}
}
}
|
||||
TheStack | e0978a59842d66e297fcc51cd28b11c0b3f28d3e | C#code:C# | {"size": 2252, "ext": "cs", "max_stars_repo_path": "ToMigrate/Raven.Database/Util/DatabaseHelper.cs", "max_stars_repo_name": "ryanheath/ravendb", "max_stars_repo_stars_event_min_datetime": "2017-03-02T13:05:14.000Z", "max_stars_repo_stars_event_max_datetime": "2017-03-02T13:05:14.000Z", "max_issues_repo_path": "ToMigrate/Raven.Database/Util/DatabaseHelper.cs", "max_issues_repo_name": "ryanheath/ravendb", "max_issues_repo_issues_event_min_datetime": "2019-03-12T12:10:52.000Z", "max_issues_repo_issues_event_max_datetime": "2019-03-12T12:10:52.000Z", "max_forks_repo_path": "ToMigrate/Raven.Database/Util/DatabaseHelper.cs", "max_forks_repo_name": "aviv86/ravendb", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 35.1875, "max_line_length": 95, "alphanum_fraction": 0.5861456483} | // -----------------------------------------------------------------------
// <copyright file="DatabaseHelper.cs" company="Hibernating Rhinos LTD">
// Copyright (c) Hibernating Rhinos LTD. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
using System;
using Raven.Abstractions.Data;
using Raven.Database.Config;
using Raven.Database.Extensions;
namespace Raven.Database.Util
{
public static class DatabaseHelper
{
public static bool IsSystemDatabase(this DocumentDatabase database)
{
return database.Name == null || database.Name == Constants.SystemDatabase;
}
public static void AssertSystemDatabase(DocumentDatabase database)
{
if (database.IsSystemDatabase() == false)
throw new InvalidOperationException("Not a system database");
}
public static string GetDatabaseKey(string key)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
if (key.StartsWith(Constants.Database.Prefix, StringComparison.OrdinalIgnoreCase))
return key;
return Constants.Database.Prefix + key;
}
public static string GetDatabaseName(string key)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
if (key.StartsWith(Constants.Database.Prefix, StringComparison.OrdinalIgnoreCase))
return key.Substring(Constants.Database.Prefix.Length);
return key;
}
public static void DeleteDatabaseFiles(RavenConfiguration configuration)
{
if (configuration.Core.RunInMemory)
return;
IOExtensions.DeleteDirectory(configuration.Core.DataDirectory);
if (configuration.Core.IndexStoragePath != null)
IOExtensions.DeleteDirectory(configuration.Core.IndexStoragePath);
if (configuration.Storage.JournalsStoragePath != null)
IOExtensions.DeleteDirectory(configuration.Storage.JournalsStoragePath);
}
}
}
|
||||
TheStack | e09b0d65005e9ad645e5364a159b2d1ddf31c441 | C#code:C# | {"size": 1097, "ext": "cs", "max_stars_repo_path": "MatterControl.MeshOperations/MeshExtensions.cs", "max_stars_repo_name": "klovaaxel/MatterControl", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MatterControl.MeshOperations/MeshExtensions.cs", "max_issues_repo_name": "klovaaxel/MatterControl", "max_issues_repo_issues_event_min_datetime": "2016-05-25T22:10:11.000Z", "max_issues_repo_issues_event_max_datetime": "2016-07-14T18:39:11.000Z", "max_forks_repo_path": "MatterControl.MeshOperations/MeshExtensions.cs", "max_forks_repo_name": "klovaaxel/MatterControl", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 21.5098039216, "max_line_length": 69, "alphanum_fraction": 0.645396536} | using System;
using g3;
using MatterHackers.PolygonMesh;
using MatterHackers.VectorMath;
namespace MatterHackers.MatterControl.DesignTools
{
public static class MeshExtensions
{
public static DMesh3 ToDMesh3(this Mesh inMesh)
{
var outMesh = new DMesh3();
foreach (var vertex in inMesh.Vertices)
{
outMesh.AppendVertex(new Vector3d(vertex.X, vertex.Y, vertex.Z));
}
foreach (var face in inMesh.Faces)
{
outMesh.AppendTriangle(face.v0, face.v1, face.v2);
}
return outMesh;
}
public static Mesh ToMesh(this DMesh3 mesh)
{
var outMesh = new Mesh();
int[] mapV = new int[mesh.MaxVertexID];
int nAccumCountV = 0;
foreach (int vi in mesh.VertexIndices())
{
mapV[vi] = nAccumCountV++;
Vector3d v = mesh.GetVertex(vi);
outMesh.Vertices.Add(new Vector3(v[0], v[1], v[2]));
}
foreach (int ti in mesh.TriangleIndices())
{
Index3i t = mesh.GetTriangle(ti);
t[0] = mapV[t[0]];
t[1] = mapV[t[1]];
t[2] = mapV[t[2]];
outMesh.Faces.Add(t[0], t[1], t[2], outMesh.Vertices);
}
return outMesh;
}
}
}
|
||||
TheStack | e09b1ff1515bcdcc6d3af26bb8f6593ca7ce3288 | C#code:C# | {"size": 10081, "ext": "cs", "max_stars_repo_path": "com/netfx/src/clr/bcl/system/security/cryptography/mactripledes.cs", "max_stars_repo_name": "npocmaka/Windows-Server-2003", "max_stars_repo_stars_event_min_datetime": "2020-11-13T13:42:52.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-16T09:13:13.000Z", "max_issues_repo_path": "com/netfx/src/clr/bcl/system/security/cryptography/mactripledes.cs", "max_issues_repo_name": "sancho1952007/Windows-Server-2003", "max_issues_repo_issues_event_min_datetime": "2020-10-19T08:02:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-19T08:23:18.000Z", "max_forks_repo_path": "com/netfx/src/clr/bcl/system/security/cryptography/mactripledes.cs", "max_forks_repo_name": "sancho1952007/Windows-Server-2003", "max_forks_repo_forks_event_min_datetime": "2020-11-14T09:43:20.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-28T08:59:57.000Z"} | {"max_stars_count": 17.0, "max_issues_count": 2.0, "max_forks_count": 14.0, "avg_line_length": 37.0625, "max_line_length": 127, "alphanum_fraction": 0.5283206031} | // ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*
*
* MACTripleDES.cs -- Implementation of the MAC-CBC keyed hash w/ 3DES
*
* @author t-ccaron
*
*/
// See: http://www.itl.nist.gov/fipspubs/fip81.htm for a spec
namespace System.Security.Cryptography {
using System.IO;
using System.Runtime.InteropServices;
/// <include file='doc\mactripleDES.uex' path='docs/doc[@for="MACTripleDES"]/*' />
public class MACTripleDES : KeyedHashAlgorithm
{
// Output goes to HashMemorySink since we don't care about the actual data
private ICryptoTransform m_encryptor;
private CryptoStream _cs;
private TailStream _ts;
private const int m_bitsPerByte = 8;
private int m_bytesPerBlock;
private TripleDES des;
// ---------------------------- Constructors ----------------------------
/// <include file='doc\mactripleDES.uex' path='docs/doc[@for="MACTripleDES.MACTripleDES"]/*' />
public MACTripleDES()
{
RandomNumberGenerator _rng;
KeyValue = new byte[24];
_rng = RandomNumberGenerator.Create();
_rng.GetBytes(KeyValue);
// Create a TripleDES encryptor
des = TripleDES.Create();
HashSizeValue = des.BlockSize;
m_bytesPerBlock = des.BlockSize/m_bitsPerByte;
// By definition, MAC-CBC-3DES takes an IV=0. C# zero-inits arrays,
// so all we have to do here is define it.
des.IV = new byte[m_bytesPerBlock];
des.Padding = PaddingMode.Zeros;
m_encryptor = null;
}
/// <include file='doc\mactripleDES.uex' path='docs/doc[@for="MACTripleDES.MACTripleDES1"]/*' />
public MACTripleDES(byte[] rgbKey)
: this("System.Security.Cryptography.TripleDES",rgbKey) { }
/// <include file='doc\mactripleDES.uex' path='docs/doc[@for="MACTripleDES.MACTripleDES2"]/*' />
public MACTripleDES(String strTripleDES, byte[] rgbKey)
{
// Make sure we know which algorithm to use
if (rgbKey == null)
throw new ArgumentNullException("rgbKey");
// Create a TripleDES encryptor
if (strTripleDES == null) {
des = TripleDES.Create();
} else {
des = TripleDES.Create(strTripleDES);
}
HashSizeValue = des.BlockSize;
// Stash the key away
KeyValue = (byte[]) rgbKey.Clone();
m_bytesPerBlock = des.BlockSize/m_bitsPerByte;
// By definition, MAC-CBC-3DES takes an IV=0. C# zero-inits arrays,
// so all we have to do here is define it.
des.IV = new byte[m_bytesPerBlock];
des.Padding = PaddingMode.Zeros;
m_encryptor = null;
}
/// <include file='doc\mactripleDES.uex' path='docs/doc[@for="MACTripleDES.Finalize"]/*' />
~MACTripleDES() {
Dispose(false);
}
// ------------------------- Protected Methods --------------------------
/// <include file='doc\mactripleDES.uex' path='docs/doc[@for="MACTripleDES.Initialize"]/*' />
public override void Initialize() {
m_encryptor = null;
}
/// <include file='doc\mactripleDES.uex' path='docs/doc[@for="MACTripleDES.HashCore"]/*' />
protected override void HashCore(byte[] rgbData, int ibStart, int cbSize)
{
// regenerate the TripleDES object before each call to ComputeHash
if (m_encryptor == null) {
des.Key = this.Key;
m_encryptor = des.CreateEncryptor();
_ts = new TailStream(des.BlockSize / 8); // 8 bytes
_cs = new CryptoStream(_ts, m_encryptor, CryptoStreamMode.Write);
}
// Encrypt using 3DES
_cs.Write(rgbData, ibStart, cbSize);
}
/// <include file='doc\mactripleDES.uex' path='docs/doc[@for="MACTripleDES.HashFinal"]/*' />
protected override byte[] HashFinal()
{
// If Hash has been called on a zero buffer
if (m_encryptor == null) {
des.Key = this.Key;
m_encryptor = des.CreateEncryptor();
_ts = new TailStream(des.BlockSize / 8); // 8 bytes
_cs = new CryptoStream(_ts, m_encryptor, CryptoStreamMode.Write);
}
// Finalize the hashing and return the result
_cs.Close();
return(_ts.Buffer);
}
// IDisposable methods
/// <include file='doc\mactripleDES.uex' path='docs/doc[@for="MACTripleDES.Dispose"]/*' />
protected override void Dispose(bool disposing) {
if (disposing) {
// dispose of our internal state
if (des != null) {
des.Clear();
}
if (m_encryptor != null) {
m_encryptor.Dispose();
}
if (_cs != null) {
_cs.Clear();
}
if (_ts != null) {
_ts.Clear();
}
}
base.Dispose(disposing);
}
}
//
// TailStream is another utility class -- it remembers the last n bytes written to it
// This is useful for MAC-3DES since we need to capture only the result of the last block
internal class TailStream : Stream, IDisposable {
private byte[] _Buffer;
private int _BufferSize;
private int _BufferIndex = 0;
private bool _BufferFull = false;
public TailStream(int bufferSize) {
_Buffer = new byte[bufferSize];
_BufferSize = bufferSize;
}
~TailStream() {
Dispose(false);
}
// IDisposable methods
void IDisposable.Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
public void Clear() {
((IDisposable) this).Dispose();
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
if (_Buffer != null) {
Array.Clear(_Buffer, 0, _Buffer.Length);
}
_Buffer = null;
}
}
public byte[] Buffer {
get { return (byte[]) _Buffer.Clone(); }
}
public override bool CanRead {
get { return false; }
}
public override bool CanSeek {
get { return false; }
}
public override bool CanWrite {
get { return true; }
}
public override long Length {
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); }
}
public override long Position {
get { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); }
set { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream")); }
}
public override void Close() {
return;
}
public override void Flush() {
return;
}
public override long Seek(long offset, SeekOrigin origin) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream"));
}
public override void SetLength(long value) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream"));
}
public override int Read([In, Out] byte[] buffer, int offset, int count) {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
}
public override void Write(byte[] buffer, int offset, int count) {
// If no bytes to write, then return
if (count == 0) return;
// The most common case will be when we have a full buffer
if (_BufferFull) {
// if more bytes are written in this call than the size of the buffer,
// just remember the last _BufferSize bytes
if (count > _BufferSize) {
System.Buffer.InternalBlockCopy(buffer, offset+count-_BufferSize, _Buffer, 0, _BufferSize);
return;
} else {
// move _BufferSize - count bytes left, then copy the new bytes
System.Buffer.InternalBlockCopy(_Buffer, _BufferSize - count, _Buffer, 0, _BufferSize - count);
System.Buffer.InternalBlockCopy(buffer, offset, _Buffer, _BufferSize - count, count);
return;
}
} else {
// buffer isn't full yet, so more cases
if (count > _BufferSize) {
System.Buffer.InternalBlockCopy(buffer, offset+count-_BufferSize, _Buffer, 0, _BufferSize);
_BufferFull = true;
return;
} else if (count + _BufferIndex >= _BufferSize) {
System.Buffer.InternalBlockCopy(_Buffer, _BufferIndex+count-_BufferSize, _Buffer, 0, _BufferSize - count);
System.Buffer.InternalBlockCopy(buffer, offset, _Buffer, _BufferIndex, count);
_BufferFull = true;
return;
} else {
System.Buffer.InternalBlockCopy(buffer, offset, _Buffer, _BufferIndex, count);
_BufferIndex += count;
return;
}
}
}
}
}
|
||||
TheStack | e09b5ffdad221e9fb24df4037cc6b1a8b7eac96c | C#code:C# | {"size": 2699, "ext": "cs", "max_stars_repo_path": "ViewModels/PropertiesMustMatchAttribute.cs", "max_stars_repo_name": "ozguryilmaz07/HUKUKOFIS", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ViewModels/PropertiesMustMatchAttribute.cs", "max_issues_repo_name": "ozguryilmaz07/HUKUKOFIS", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ViewModels/PropertiesMustMatchAttribute.cs", "max_forks_repo_name": "ozguryilmaz07/HUKUKOFIS", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 39.6911764706, "max_line_length": 108, "alphanum_fraction": 0.6494998147} | // -----------------------------------------------------------------------
// <copyright file="PropertiesMustMatchAttribute.cs" company="Nodine Legal, LLC">
// Licensed to Nodine Legal, LLC under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. Nodine Legal, LLC 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.
// </copyright>
// -----------------------------------------------------------------------
namespace OpenLawOffice.Web.ViewModels
{
using System;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.ComponentModel;
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public sealed class PropertiesMustMatchAttribute : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' and '{1}' do not match.";
private readonly object _typeId = new object();
public PropertiesMustMatchAttribute(string originalProperty, string confirmProperty)
: base(_defaultErrorMessage)
{
OriginalProperty = originalProperty;
ConfirmProperty = confirmProperty;
}
public string ConfirmProperty { get; private set; }
public string OriginalProperty { get; private set; }
public override object TypeId
{
get
{
return _typeId;
}
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
OriginalProperty, ConfirmProperty);
}
public override bool IsValid(object value)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
object originalValue = properties.Find(OriginalProperty, true /* ignoreCase */).GetValue(value);
object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
return Object.Equals(originalValue, confirmValue);
}
}
} |
||||
TheStack | e09c1196f0fc1f6294396beb88ee41e87e5d6c54 | C#code:C# | {"size": 1160, "ext": "cs", "max_stars_repo_path": "src/Microsoft.FeatureManagement/IFeatureFilter.cs", "max_stars_repo_name": "Tjayojo/FeatureManagement", "max_stars_repo_stars_event_min_datetime": "2021-11-28T16:47:53.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-28T16:47:53.000Z", "max_issues_repo_path": "src/Microsoft.FeatureManagement/IFeatureFilter.cs", "max_issues_repo_name": "Tjayojo/FeatureManagement", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Microsoft.FeatureManagement/IFeatureFilter.cs", "max_forks_repo_name": "Tjayojo/FeatureManagement", "max_forks_repo_forks_event_min_datetime": "2020-07-30T13:16:03.000Z", "max_forks_repo_forks_event_max_datetime": "2020-07-30T13:16:03.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 55.2380952381, "max_line_length": 334, "alphanum_fraction": 0.7301724138} | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
//
using System.Threading.Tasks;
namespace Microsoft.FeatureManagement
{
/// <summary>
/// A filter that can be used to determine whether some criteria is met to enable a feature. A feature filter is free to use any criteria available, such as process state or request content. Feature filters can be registered for a given feature and if any feature filter evaluates to true, that feature will be considered enabled.
/// </summary>
public interface IFeatureFilter : IFeatureFilterMetadata
{
/// <summary>
/// Evalutates the feature filter to see if the filter's criteria for being enabled has been satisfied.
/// </summary>
/// <param name="context">A feature filter evaluation context that contains information that may be needed to evalute the filter. This context includes configuration, if any, for this filter for the feature being evaluated.</param>
/// <returns>True if the filter's criteria has been met, false otherwise.</returns>
Task<bool> EvaluateAsync(FeatureFilterEvaluationContext context);
}
}
|
||||
TheStack | e09d8d6e5072a02573848cdff9814a8c033e733e | C#code:C# | {"size": 210, "ext": "cs", "max_stars_repo_path": "MonteCarloDXApp/MonteCarloDXApp/MonteCarloDXApp.Main/MainWindow.xaml.cs", "max_stars_repo_name": "isachpaz/MonteCarloApp", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MonteCarloDXApp/MonteCarloDXApp/MonteCarloDXApp.Main/MainWindow.xaml.cs", "max_issues_repo_name": "isachpaz/MonteCarloApp", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MonteCarloDXApp/MonteCarloDXApp/MonteCarloDXApp.Main/MainWindow.xaml.cs", "max_forks_repo_name": "isachpaz/MonteCarloApp", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 16.1538461538, "max_line_length": 50, "alphanum_fraction": 0.5952380952} | using DevExpress.Xpf.Core;
namespace MonteCarloDXApp.Main
{
public partial class MainWindow : ThemedWindow
{
public MainWindow()
{
InitializeComponent();
}
}
}
|
||||
TheStack | e09da2fb729341ee1df57b5212b7fbb45523d1bd | C#code:C# | {"size": 1579, "ext": "cs", "max_stars_repo_path": "osu.Game/Beatmaps/Drawables/BeatmapSetCover.cs", "max_stars_repo_name": "Vidalee/osu", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "osu.Game/Beatmaps/Drawables/BeatmapSetCover.cs", "max_issues_repo_name": "Vidalee/osu", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "osu.Game/Beatmaps/Drawables/BeatmapSetCover.cs", "max_forks_repo_name": "Vidalee/osu", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.7090909091, "max_line_length": 105, "alphanum_fraction": 0.5516149462} | // Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
namespace osu.Game.Beatmaps.Drawables
{
public class BeatmapSetCover : Sprite
{
private readonly BeatmapSetInfo set;
private readonly BeatmapSetCoverType type;
public BeatmapSetCover(BeatmapSetInfo set, BeatmapSetCoverType type = BeatmapSetCoverType.Cover)
{
if (set == null)
throw new ArgumentNullException(nameof(set));
this.set = set;
this.type = type;
}
[BackgroundDependencyLoader]
private void load(LargeTextureStore textures)
{
string resource = null;
switch (type)
{
case BeatmapSetCoverType.Cover:
resource = set.OnlineInfo.Covers.Cover;
break;
case BeatmapSetCoverType.Card:
resource = set.OnlineInfo.Covers.Card;
break;
case BeatmapSetCoverType.List:
resource = set.OnlineInfo.Covers.List;
break;
}
if (resource != null)
Texture = textures.Get(resource);
}
}
public enum BeatmapSetCoverType
{
Cover,
Card,
List,
}
}
|
||||
TheStack | e09dd9e6164f7720ca7b00e464d81af6c8605057 | C#code:C# | {"size": 3405, "ext": "cs", "max_stars_repo_path": "Assets/Framework/Components/Containers/EntityContainer.cs", "max_stars_repo_name": "PixelComrades/Framework", "max_stars_repo_stars_event_min_datetime": "2018-09-15T08:29:03.000Z", "max_stars_repo_stars_event_max_datetime": "2020-07-28T04:16:32.000Z", "max_issues_repo_path": "Assets/Framework/Components/Containers/EntityContainer.cs", "max_issues_repo_name": "FuzzySlipper/Framework", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Framework/Components/Containers/EntityContainer.cs", "max_forks_repo_name": "FuzzySlipper/Framework", "max_forks_repo_forks_event_min_datetime": "2019-11-06T15:57:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-04-29T15:14:06.000Z"} | {"max_stars_count": 10.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 29.3534482759, "max_line_length": 88, "alphanum_fraction": 0.5377386197} | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
namespace PixelComrades {
public sealed class EntityContainer : ISerializable {
private int _limit = -1;
private List<int> _list = new List<int>();
public EntityContainer(int limit = -1) {
_limit = limit;
}
public EntityContainer(SerializationInfo info, StreamingContext context) {
_limit = info.GetValue(nameof(_limit), _limit);
_list = info.GetValue(nameof(_list), _list);
}
public void GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue(nameof(_limit), _limit);
info.AddValue(nameof(_list), _list);
}
public bool IsFull { get { return _limit >= 0 && _list.Count >= _limit; } }
public int Count { get { return _list.Count; } }
public Entity this[int index] {
get {
if (!_list.HasIndex(index)) {
return null;
}
return EntityController.GetEntity(_list[index]);
}
}
public bool Contains(Entity item) {
return _list.Contains(item);
}
public int Add(Entity entity) {
_list.Add(entity);
return _list.Count-1;
}
public bool Remove(Entity entity) {
if (!_list.Contains(entity)) {
return false;
}
_list.Remove(entity);
return true;
}
public void Clear() {
_list.Clear();
}
public void Destroy() {
for (int i = 0; i < Count; i++) {
this[i].Destroy();
}
_list.Clear();
}
public bool ContainsType(string type) {
for (int i = 0; i < Count; i++) {
if (this[i].Get<TypeId>().Id == type) {
return true;
}
}
return false;
}
}
public interface IEntityContainer {
bool IsFull { get; }
Entity this[int index] { get; }
Entity Owner { get; }
int Count { get; }
bool Contains(Entity item);
/// <summary>
/// Should only be used by ContainerSystem
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
int ContainerSystemAdd(Entity item);
/// <summary>
/// Should only be used by ContainerSystem
/// </summary>
/// <param name="item"></param>
/// <param name="index"></param>
void ContainerSystemSet(Entity item, int index);
bool Remove(Entity entity);
void Clear();
}
public struct ContainerChanged : IEntityMessage {
public IEntityContainer EntityContainer { get; }
public ContainerChanged(IEntityContainer entityContainer) {
EntityContainer = entityContainer;
}
}
public struct ContainerStatusChanged : IEntityMessage {
public IEntityContainer EntityContainer { get; }
public Entity Entity { get; }
public ContainerStatusChanged(IEntityContainer entityContainer, Entity entity) {
EntityContainer = entityContainer;
Entity = entity;
}
}
}
|
||||
TheStack | e09e27255dbbf65b64c937b9c169c29ab7b8a6cb | C#code:C# | {"size": 21098, "ext": "cs", "max_stars_repo_path": "src/Owin.Loader/DefaultLoader.cs", "max_stars_repo_name": "gregwoodio/AspNetKatana", "max_stars_repo_stars_event_min_datetime": "2017-02-17T19:43:51.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T14:11:36.000Z", "max_issues_repo_path": "src/Owin.Loader/DefaultLoader.cs", "max_issues_repo_name": "gregwoodio/AspNetKatana", "max_issues_repo_issues_event_min_datetime": "2017-02-17T18:02:03.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:49:30.000Z", "max_forks_repo_path": "src/Owin.Loader/DefaultLoader.cs", "max_forks_repo_name": "gregwoodio/AspNetKatana", "max_forks_repo_forks_event_min_datetime": "2017-02-18T06:43:50.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-18T13:31:12.000Z"} | {"max_stars_count": 950.0, "max_issues_count": 408.0, "max_forks_count": 376.0, "avg_line_length": 39.4355140187, "max_line_length": 149, "alphanum_fraction": 0.5343160489} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using SharedResourceNamespace;
namespace Owin.Loader
{
using AppLoader = Func<string, IList<string>, Action<IAppBuilder>>;
/// <summary>
/// Locates the startup class based on the following convention:
/// AssemblyName.Startup, with a method named Configuration
/// </summary>
internal class DefaultLoader
{
private readonly AppLoader _next;
private readonly Func<Type, object> _activator;
private readonly IEnumerable<Assembly> _referencedAssemblies;
/// <summary>
///
/// </summary>
public DefaultLoader()
: this(null, null, null)
{
}
public DefaultLoader(IEnumerable<Assembly> referencedAssemblies)
: this(null, null, referencedAssemblies)
{
}
/// <summary>
/// Allows for a fallback loader to be specified.
/// </summary>
/// <param name="next"></param>
public DefaultLoader(AppLoader next)
: this(next, null, null)
{
}
/// <summary>
/// Allows for a fallback loader and a Dependency Injection activator to be specified.
/// </summary>
/// <param name="next"></param>
/// <param name="activator"></param>
public DefaultLoader(AppLoader next, Func<Type, object> activator)
: this(next, activator, null)
{
}
/// <summary>
///
/// </summary>
/// <param name="next"></param>
/// <param name="activator"></param>
/// <param name="referencedAssemblies"></param>
public DefaultLoader(AppLoader next, Func<Type, object> activator,
IEnumerable<Assembly> referencedAssemblies)
{
_next = next ?? NullLoader.Instance;
_activator = activator ?? Activator.CreateInstance;
_referencedAssemblies = referencedAssemblies ?? new AssemblyDirScanner();
}
/// <summary>
/// Executes the loader, searching for the entry point by name.
/// </summary>
/// <param name="startupName">The name of the assembly and type entry point</param>
/// <param name="errorDetails"></param>
/// <returns></returns>
public Action<IAppBuilder> Load(string startupName, IList<string> errorDetails)
{
return LoadImplementation(startupName, errorDetails) ?? _next(startupName, errorDetails);
}
private Action<IAppBuilder> LoadImplementation(string startupName, IList<string> errorDetails)
{
Tuple<Type, string> typeAndMethod = null;
startupName = startupName ?? string.Empty;
// Auto-discovery or Friendly name?
if (!startupName.Contains(','))
{
typeAndMethod = GetDefaultConfiguration(startupName, errorDetails);
}
if (typeAndMethod == null && !string.IsNullOrWhiteSpace(startupName))
{
typeAndMethod = GetTypeAndMethodNameForConfigurationString(startupName, errorDetails);
}
if (typeAndMethod == null)
{
return null;
}
Type type = typeAndMethod.Item1;
// default to the "Configuration" method if only the type name was provided
string methodName = !string.IsNullOrWhiteSpace(typeAndMethod.Item2) ? typeAndMethod.Item2 : Constants.Configuration;
Action<IAppBuilder> startup = MakeDelegate(type, methodName, errorDetails);
if (startup == null)
{
return null;
}
return builder =>
{
if (builder == null)
{
throw new ArgumentNullException("builder");
}
object value;
if (!builder.Properties.TryGetValue(Constants.HostAppName, out value) ||
String.IsNullOrWhiteSpace(Convert.ToString(value, CultureInfo.InvariantCulture)))
{
builder.Properties[Constants.HostAppName] = type.FullName;
}
startup(builder);
};
}
private Tuple<Type, string> GetTypeAndMethodNameForConfigurationString(string configuration, IList<string> errors)
{
Tuple<string, Assembly> typePair = HuntForAssembly(configuration, errors);
if (typePair == null)
{
return null;
}
string longestPossibleName = typePair.Item1; // method or type name
Assembly assembly = typePair.Item2;
// try the longest 2 possibilities at most (because you can't have a dot in the method name)
// so, typeName could specify a method or a type. we're looking for a type.
foreach (var typeName in DotByDot(longestPossibleName).Take(2))
{
Type type = assembly.GetType(typeName, false);
if (type == null)
{
errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.ClassNotFoundInAssembly,
configuration, typeName, assembly.FullName));
// must have been a method name (or doesn't exist), next!
continue;
}
string methodName = typeName == longestPossibleName
? null
: longestPossibleName.Substring(typeName.Length + 1);
return new Tuple<Type, string>(type, methodName);
}
return null;
}
private Tuple<Type, string> GetDefaultConfiguration(string friendlyName, IList<string> errors)
{
friendlyName = friendlyName ?? string.Empty;
bool conflict = false;
Tuple<Type, string> result = SearchForStartupAttribute(friendlyName, errors, ref conflict);
if (result == null && !conflict && string.IsNullOrEmpty(friendlyName))
{
result = SearchForStartupConvention(errors);
}
return result;
}
// Search for any assemblies with an OwinStartupAttribute. If a friendly name is provided, only accept an
// attribute with the matching value.
private Tuple<Type, string> SearchForStartupAttribute(string friendlyName, IList<string> errors, ref bool conflict)
{
friendlyName = friendlyName ?? string.Empty;
bool foundAnyInstances = false;
Tuple<Type, string> fullMatch = null;
Assembly matchedAssembly = null;
foreach (var assembly in _referencedAssemblies)
{
Attribute[] attributes;
try
{
// checking attribute's name first and only then instantiating it
// then we are filtering attributes by name second time as inheritors could be added by calling to GetCustomAttributes(type)
attributes = assembly.GetCustomAttributesData()
.Where(data => MatchesStartupAttribute(data.AttributeType))
.Select(data => data.AttributeType)
.SelectMany(type => assembly.GetCustomAttributes(type))
.Distinct()
.ToArray();
}
catch (CustomAttributeFormatException)
{
continue;
}
foreach (var owinStartupAttribute in attributes.Where(attribute => MatchesStartupAttribute(attribute.GetType())))
{
Type attributeType = owinStartupAttribute.GetType();
foundAnyInstances = true;
// Find the StartupType property.
PropertyInfo startupTypeProperty = attributeType.GetProperty(Constants.StartupType, typeof(Type));
if (startupTypeProperty == null)
{
errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.StartupTypePropertyMissing,
attributeType.AssemblyQualifiedName, assembly.FullName));
continue;
}
var startupType = startupTypeProperty.GetValue(owinStartupAttribute, null) as Type;
if (startupType == null)
{
errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.StartupTypePropertyEmpty, assembly.FullName));
continue;
}
// FriendlyName is an optional property.
string friendlyNameValue = string.Empty;
PropertyInfo friendlyNameProperty = attributeType.GetProperty(Constants.FriendlyName, typeof(string));
if (friendlyNameProperty != null)
{
friendlyNameValue = friendlyNameProperty.GetValue(owinStartupAttribute, null) as string ?? string.Empty;
}
if (!string.Equals(friendlyName, friendlyNameValue, StringComparison.OrdinalIgnoreCase))
{
errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.FriendlyNameMismatch,
friendlyNameValue, friendlyName, assembly.FullName));
continue;
}
// MethodName is an optional property.
string methodName = string.Empty;
PropertyInfo methodNameProperty = attributeType.GetProperty(Constants.MethodName, typeof(string));
if (methodNameProperty != null)
{
methodName = methodNameProperty.GetValue(owinStartupAttribute, null) as string ?? string.Empty;
}
if (fullMatch != null)
{
conflict = true;
errors.Add(string.Format(CultureInfo.CurrentCulture,
LoaderResources.Exception_AttributeNameConflict,
matchedAssembly.GetName().Name, fullMatch.Item1, assembly.GetName().Name, startupType, friendlyName));
}
else
{
fullMatch = new Tuple<Type, string>(startupType, methodName);
matchedAssembly = assembly;
}
}
}
if (!foundAnyInstances)
{
errors.Add(LoaderResources.NoOwinStartupAttribute);
}
if (conflict)
{
return null;
}
return fullMatch;
}
private static bool MatchesStartupAttribute(Type type)
{
return type.Name.Equals(Constants.OwinStartupAttribute, StringComparison.Ordinal);
}
// Search for any assemblies with a Startup or [AssemblyName].Startup class.
private Tuple<Type, string> SearchForStartupConvention(IList<string> errors)
{
Type matchedType = null;
bool conflict = false;
foreach (var assembly in _referencedAssemblies)
{
// Startup
CheckForStartupType(Constants.Startup, assembly, ref matchedType, ref conflict, errors);
// [AssemblyName].Startup
CheckForStartupType(assembly.GetName().Name + "." + Constants.Startup, assembly, ref matchedType, ref conflict, errors);
}
if (matchedType == null)
{
errors.Add(LoaderResources.NoAssemblyWithStartupClass);
return null;
}
if (conflict)
{
return null;
}
// Verify this class has a public method Configuration, helps limit false positives.
if (!matchedType.GetMethods().Any(methodInfo => methodInfo.Name.Equals(Constants.Configuration)))
{
errors.Add(string.Format(CultureInfo.CurrentCulture,
LoaderResources.MethodNotFoundInClass, Constants.Configuration, matchedType.AssemblyQualifiedName));
return null;
}
return new Tuple<Type, string>(matchedType, Constants.Configuration);
}
private static void CheckForStartupType(string startupName, Assembly assembly, ref Type matchedType, ref bool conflict, IList<string> errors)
{
Type startupType = assembly.GetType(startupName, throwOnError: false);
if (startupType != null)
{
// Conflict?
if (matchedType != null)
{
conflict = true;
errors.Add(string.Format(CultureInfo.CurrentCulture,
LoaderResources.Exception_StartupTypeConflict,
matchedType.AssemblyQualifiedName, startupType.AssemblyQualifiedName));
}
else
{
matchedType = startupType;
}
}
}
private Tuple<string, Assembly> HuntForAssembly(string configuration, IList<string> errors)
{
if (configuration == null)
{
throw new ArgumentNullException("configuration");
}
int commaIndex = configuration.IndexOf(',');
if (commaIndex >= 0)
{
// assembly is given, break the type and assembly apart
string methodOrTypeName = DotByDot(configuration.Substring(0, commaIndex)).FirstOrDefault();
string assemblyName = configuration.Substring(commaIndex + 1).Trim();
Assembly assembly = TryAssemblyLoad(assemblyName);
if (assembly == null)
{
errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.AssemblyNotFound,
configuration, assemblyName));
return null;
}
return Tuple.Create(methodOrTypeName, assembly);
}
// See if any referenced assemblies contain this type
foreach (var assembly in _referencedAssemblies)
{
// NameSpace.Type or NameSpace.Type.Method
foreach (var typeName in DotByDot(configuration).Take(2))
{
if (assembly.GetType(typeName, throwOnError: false) != null)
{
return Tuple.Create(configuration, assembly);
}
}
}
errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.TypeOrMethodNotFound, configuration));
return null;
}
private static Assembly TryAssemblyLoad(string assemblyName)
{
try
{
return Assembly.Load(assemblyName);
}
catch (FileNotFoundException)
{
return null;
}
catch (FileLoadException)
{
return null;
}
}
/// <summary>
///
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static IEnumerable<string> DotByDot(string text)
{
if (text == null)
{
yield break;
}
text = text.Trim('.');
for (int length = text.Length;
length > 0;
length = text.LastIndexOf('.', length - 1, length - 1))
{
yield return text.Substring(0, length);
}
}
private Action<IAppBuilder> MakeDelegate(Type type, string methodName, IList<string> errors)
{
MethodInfo partialMatch = null;
foreach (var methodInfo in type.GetMethods())
{
if (!methodInfo.Name.Equals(methodName))
{
continue;
}
// void Configuration(IAppBuilder app)
if (Matches(methodInfo, false, typeof(IAppBuilder)))
{
object instance = methodInfo.IsStatic ? null : _activator(type);
return builder => methodInfo.Invoke(instance, new[] { builder });
}
// object Configuration(IDictionary<string, object> appProperties)
if (Matches(methodInfo, true, typeof(IDictionary<string, object>)))
{
object instance = methodInfo.IsStatic ? null : _activator(type);
return builder => builder.Use(new Func<object, object>(_ => methodInfo.Invoke(instance, new object[] { builder.Properties })));
}
// object Configuration()
if (Matches(methodInfo, true))
{
object instance = methodInfo.IsStatic ? null : _activator(type);
return builder => builder.Use(new Func<object, object>(_ => methodInfo.Invoke(instance, new object[0])));
}
partialMatch = partialMatch ?? methodInfo;
}
if (partialMatch == null)
{
errors.Add(string.Format(CultureInfo.CurrentCulture,
LoaderResources.MethodNotFoundInClass, methodName, type.AssemblyQualifiedName));
}
else
{
errors.Add(string.Format(CultureInfo.CurrentCulture, LoaderResources.UnexpectedMethodSignature,
methodName, type.AssemblyQualifiedName));
}
return null;
}
private static bool Matches(MethodInfo methodInfo, bool hasReturnValue, params Type[] parameterTypes)
{
bool methodHadReturnValue = methodInfo.ReturnType != typeof(void);
if (hasReturnValue != methodHadReturnValue)
{
return false;
}
ParameterInfo[] parameters = methodInfo.GetParameters();
if (parameters.Length != parameterTypes.Length)
{
return false;
}
return parameters.Zip(parameterTypes, (pi, t) => pi.ParameterType == t).All(b => b);
}
private class AssemblyDirScanner : IEnumerable<Assembly>
{
public IEnumerator<Assembly> GetEnumerator()
{
AppDomainSetup info = AppDomain.CurrentDomain.SetupInformation;
IEnumerable<string> searchPaths = new string[0];
if (info.PrivateBinPathProbe == null || string.IsNullOrWhiteSpace(info.PrivateBinPath))
{
// Check the current directory
searchPaths = searchPaths.Concat(new string[] { string.Empty });
}
if (!string.IsNullOrWhiteSpace(info.PrivateBinPath))
{
// PrivateBinPath may be a semicolon separated list of subdirectories.
searchPaths = searchPaths.Concat(info.PrivateBinPath.Split(';'));
}
foreach (var searchPath in searchPaths)
{
string assembliesPath = Path.Combine(info.ApplicationBase, searchPath);
if (!Directory.Exists(assembliesPath))
{
continue;
}
IEnumerable<string> files = Directory.GetFiles(assembliesPath, "*.dll")
.Concat(Directory.GetFiles(assembliesPath, "*.exe"));
foreach (var file in files)
{
Assembly assembly = null;
try
{
assembly = Assembly.Load(AssemblyName.GetAssemblyName(file));
}
catch (BadImageFormatException)
{
// Not a managed dll/exe
continue;
}
yield return assembly;
}
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
}
|
||||
TheStack | e09ede5c337da4703453ca806a94a4a1389204db | C#code:C# | {"size": 1467, "ext": "cs", "max_stars_repo_path": "LauncherZ/Configuration/LauncherZConfig.cs", "max_stars_repo_name": "morriswmz/LauncherZ", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "LauncherZ/Configuration/LauncherZConfig.cs", "max_issues_repo_name": "morriswmz/LauncherZ", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LauncherZ/Configuration/LauncherZConfig.cs", "max_forks_repo_name": "morriswmz/LauncherZ", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.2272727273, "max_line_length": 74, "alphanum_fraction": 0.5637355147} | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace LauncherZ.Configuration
{
[JsonObject(MemberSerialization.OptIn)]
public class LauncherZConfig
{
#region Private Fields
private string _theme;
private int _maxResultCount;
#endregion
#region Defaults
public static string DefaultActivationKeyCombo
{
get { return "Win+OemQuestion"; }
}
public static string DefaultTheme
{
get { return "Default"; }
}
public static int DefaultMaxResultCount
{
get { return 100; }
}
#endregion
public LauncherZConfig()
{
MaxResultCount = DefaultMaxResultCount;
Priorities = new Dictionary<string, double>();
ActivationKeyCombo = DefaultActivationKeyCombo;
Theme = DefaultTheme;
}
[JsonProperty]
public int MaxResultCount
{
get { return _maxResultCount; }
set { _maxResultCount = Math.Max(1, value); }
}
[JsonProperty]
public string ActivationKeyCombo { get; set; }
[JsonProperty]
public Dictionary<string, double> Priorities { get; private set; }
[JsonProperty]
public string Theme
{
get { return _theme; }
set { _theme = value ?? DefaultTheme; }
}
}
}
|
||||
TheStack | e09f6b1e07715933cdf30c9edd5b4343096e07f5 | C#code:C# | {"size": 35971, "ext": "cs", "max_stars_repo_path": "activemq-dotnet/Apache.NMS.ActiveMQ/src/main/csharp/Session.cs", "max_stars_repo_name": "USC-ICT/stanfordparserwrapper", "max_stars_repo_stars_event_min_datetime": "2017-09-04T00:33:33.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-08T12:35:22.000Z", "max_issues_repo_path": "activemq-dotnet/Apache.NMS.ActiveMQ/src/main/csharp/Session.cs", "max_issues_repo_name": "USC-ICT/stanfordparserwrapper", "max_issues_repo_issues_event_min_datetime": "2018-07-17T22:10:09.000Z", "max_issues_repo_issues_event_max_datetime": "2021-01-20T20:36:10.000Z", "max_forks_repo_path": "activemq-dotnet/Apache.NMS.ActiveMQ/src/main/csharp/Session.cs", "max_forks_repo_name": "USC-ICT/stanfordparserwrapper", "max_forks_repo_forks_event_min_datetime": "2017-09-27T20:50:55.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T14:17:49.000Z"} | {"max_stars_count": 16.0, "max_issues_count": 11.0, "max_forks_count": 23.0, "avg_line_length": 32.2032229185, "max_line_length": 118, "alphanum_fraction": 0.543382169} | /*
* 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;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading;
using Apache.NMS.Util;
using Apache.NMS.ActiveMQ.Commands;
using Apache.NMS.ActiveMQ.Util;
using Apache.NMS.ActiveMQ.Threads;
namespace Apache.NMS.ActiveMQ
{
/// <summary>
/// Default provider of ISession
/// </summary>
public class Session : ISession, IDispatcher
{
/// <summary>
/// Private object used for synchronization, instead of public "this"
/// </summary>
private readonly object myLock = new object();
private readonly IDictionary consumers = Hashtable.Synchronized(new Hashtable());
private readonly IDictionary producers = Hashtable.Synchronized(new Hashtable());
private readonly SessionExecutor executor;
private readonly TransactionContext transactionContext;
private readonly Connection connection;
private bool dispatchAsync;
private bool exclusive;
private bool retroactive;
private byte priority = 0;
private readonly SessionInfo info;
private int consumerCounter;
private int producerCounter;
private long nextDeliveryId;
private long lastDeliveredSequenceId;
protected bool disposed = false;
protected bool closed = false;
protected bool closing = false;
protected Atomic<bool> clearInProgress = new Atomic<bool>();
private TimeSpan disposeStopTimeout = TimeSpan.FromMilliseconds(30000);
private TimeSpan closeStopTimeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
private TimeSpan requestTimeout;
private readonly AcknowledgementMode acknowledgementMode;
public Session(Connection connection, SessionId sessionId, AcknowledgementMode acknowledgementMode)
{
this.info = new SessionInfo();
this.info.SessionId = sessionId;
this.connection = connection;
this.connection.Oneway(this.info);
this.acknowledgementMode = acknowledgementMode;
this.requestTimeout = connection.RequestTimeout;
this.dispatchAsync = connection.DispatchAsync;
this.transactionContext = CreateTransactionContext();
this.exclusive = connection.ExclusiveConsumer;
this.retroactive = connection.UseRetroactiveConsumer;
Uri brokerUri = connection.BrokerUri;
// Set propertieDs on session using parameters prefixed with "session."
if(!String.IsNullOrEmpty(brokerUri.Query) && !brokerUri.OriginalString.EndsWith(")"))
{
string query = brokerUri.Query.Substring(brokerUri.Query.LastIndexOf(")") + 1);
StringDictionary options = URISupport.ParseQuery(query);
options = URISupport.GetProperties(options, "session.");
URISupport.SetProperties(this, options);
}
this.ConsumerTransformer = connection.ConsumerTransformer;
this.ProducerTransformer = connection.ProducerTransformer;
this.executor = new SessionExecutor(this, this.consumers);
if(connection.IsStarted)
{
this.Start();
}
connection.AddSession(this);
}
~Session()
{
Dispose(false);
}
#region Property Accessors
#region Session Transaction Events
// We delegate the events to the TransactionContext since it knows
// what the state is for both Local and DTC transactions.
public event SessionTxEventDelegate TransactionStartedListener
{
add { this.transactionContext.TransactionStartedListener += value; }
remove { this.transactionContext.TransactionStartedListener += value; }
}
public event SessionTxEventDelegate TransactionCommittedListener
{
add { this.transactionContext.TransactionCommittedListener += value; }
remove { this.transactionContext.TransactionCommittedListener += value; }
}
public event SessionTxEventDelegate TransactionRolledBackListener
{
add { this.transactionContext.TransactionRolledBackListener += value; }
remove { this.transactionContext.TransactionRolledBackListener += value; }
}
#endregion
/// <summary>
/// Sets the maximum number of messages to keep around per consumer
/// in addition to the prefetch window for non-durable topics until messages
/// will start to be evicted for slow consumers.
/// Must be > 0 to enable this feature
/// </summary>
public int MaximumPendingMessageLimit
{
set{ this.connection.PrefetchPolicy.MaximumPendingMessageLimit = value; }
}
/// <summary>
/// Enables or disables whether asynchronous dispatch should be used by the broker
/// </summary>
public bool DispatchAsync
{
get{ return this.dispatchAsync; }
set{ this.dispatchAsync = value; }
}
/// <summary>
/// Enables or disables exclusive consumers when using queues. An exclusive consumer means
/// only one instance of a consumer is allowed to process messages on a queue to preserve order
/// </summary>
public bool Exclusive
{
get{ return this.exclusive; }
set{ this.exclusive = value; }
}
/// <summary>
/// Enables or disables retroactive mode for consumers; i.e. do they go back in time or not?
/// </summary>
public bool Retroactive
{
get{ return this.retroactive; }
set{ this.retroactive = value; }
}
/// <summary>
/// Sets the default consumer priority for consumers
/// </summary>
public byte Priority
{
get{ return this.priority; }
set{ this.priority = value; }
}
public Connection Connection
{
get { return this.connection; }
}
public SessionId SessionId
{
get { return info.SessionId; }
}
public TransactionContext TransactionContext
{
get { return this.transactionContext; }
}
public TimeSpan RequestTimeout
{
get { return this.requestTimeout; }
set { this.requestTimeout = value; }
}
public bool Transacted
{
get { return this.IsTransacted; }
}
public virtual AcknowledgementMode AcknowledgementMode
{
get { return this.acknowledgementMode; }
}
public virtual bool IsClientAcknowledge
{
get { return this.acknowledgementMode == AcknowledgementMode.ClientAcknowledge; }
}
public virtual bool IsAutoAcknowledge
{
get { return this.acknowledgementMode == AcknowledgementMode.AutoAcknowledge; }
}
public virtual bool IsDupsOkAcknowledge
{
get { return this.acknowledgementMode == AcknowledgementMode.DupsOkAcknowledge; }
}
public virtual bool IsIndividualAcknowledge
{
get { return this.acknowledgementMode == AcknowledgementMode.IndividualAcknowledge; }
}
public virtual bool IsTransacted
{
get{ return this.acknowledgementMode == AcknowledgementMode.Transactional; }
}
public SessionExecutor Executor
{
get { return this.executor; }
}
public long NextDeliveryId
{
get { return Interlocked.Increment(ref this.nextDeliveryId); }
}
public long DisposeStopTimeout
{
get { return (long) this.disposeStopTimeout.TotalMilliseconds; }
set { this.disposeStopTimeout = TimeSpan.FromMilliseconds(value); }
}
public long CloseStopTimeout
{
get { return (long) this.closeStopTimeout.TotalMilliseconds; }
set { this.closeStopTimeout = TimeSpan.FromMilliseconds(value); }
}
private ConsumerTransformerDelegate consumerTransformer;
/// <summary>
/// A Delegate that is called each time a Message is dispatched to allow the client to do
/// any necessary transformations on the received message before it is delivered.
/// The Session instance sets the delegate on each Consumer it creates.
/// </summary>
public ConsumerTransformerDelegate ConsumerTransformer
{
get { return this.consumerTransformer; }
set { this.consumerTransformer = value; }
}
private ProducerTransformerDelegate producerTransformer;
/// <summary>
/// A delegate that is called each time a Message is sent from this Producer which allows
/// the application to perform any needed transformations on the Message before it is sent.
/// The Session instance sets the delegate on each Producer it creates.
/// </summary>
public ProducerTransformerDelegate ProducerTransformer
{
get { return this.producerTransformer; }
set { this.producerTransformer = value; }
}
internal Scheduler Scheduler
{
get { return this.connection.Scheduler; }
}
internal List<MessageConsumer> Consumers
{
get
{
List<MessageConsumer> copy = new List<MessageConsumer>();
lock(consumers.SyncRoot)
{
foreach(MessageConsumer consumer in consumers.Values)
{
copy.Add(consumer);
}
}
return copy;
}
}
internal long LastDeliveredSequenceId
{
get { return this.lastDeliveredSequenceId; }
}
#endregion
#region ISession Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if(this.disposed)
{
return;
}
try
{
// Force a Stop when we are Disposing vs a Normal Close.
this.executor.Stop(this.disposeStopTimeout);
Close();
}
catch
{
// Ignore network errors.
}
this.disposed = true;
}
public virtual void Close()
{
if (!this.closed)
{
try
{
Tracer.InfoFormat("Closing The Session with Id {0}", this.info.SessionId);
DoClose();
Tracer.InfoFormat("Closed The Session with Id {0}", this.info.SessionId);
}
catch (Exception ex)
{
Tracer.ErrorFormat("Error during session close: {0}", ex);
}
}
}
internal void DoClose()
{
Shutdown();
RemoveInfo removeInfo = new RemoveInfo();
removeInfo.ObjectId = this.info.SessionId;
removeInfo.LastDeliveredSequenceId = this.lastDeliveredSequenceId;
this.connection.Oneway(removeInfo);
}
internal void Shutdown()
{
Tracer.InfoFormat("Executing Shutdown on Session with Id {0}", this.info.SessionId);
if(this.closed)
{
return;
}
lock(myLock)
{
if(this.closed || this.closing)
{
return;
}
try
{
this.closing = true;
// Stop all message deliveries from this Session
this.executor.Stop(this.closeStopTimeout);
lock(consumers.SyncRoot)
{
foreach(MessageConsumer consumer in consumers.Values)
{
consumer.FailureError = this.connection.FirstFailureError;
consumer.Shutdown();
this.lastDeliveredSequenceId =
Math.Max(this.lastDeliveredSequenceId, consumer.LastDeliveredSequenceId);
}
}
consumers.Clear();
lock(producers.SyncRoot)
{
foreach(MessageProducer producer in producers.Values)
{
producer.Shutdown();
}
}
producers.Clear();
// If in a local transaction we just roll back at this point.
if (this.IsTransacted && this.transactionContext.InLocalTransaction)
{
try
{
this.transactionContext.Rollback();
}
catch
{
}
}
Connection.RemoveSession(this);
}
catch(Exception ex)
{
Tracer.ErrorFormat("Error during session close: {0}", ex);
}
finally
{
this.closed = true;
this.closing = false;
}
}
}
public IMessageProducer CreateProducer()
{
return CreateProducer(null);
}
public IMessageProducer CreateProducer(IDestination destination)
{
MessageProducer producer = null;
try
{
ActiveMQDestination dest = null;
if(destination != null)
{
dest = ActiveMQDestination.Transform(destination);
}
producer = DoCreateMessageProducer(GetNextProducerId(), dest);
producer.ProducerTransformer = this.ProducerTransformer;
this.AddProducer(producer);
this.Connection.SyncRequest(producer.ProducerInfo);
}
catch(Exception)
{
if(producer != null)
{
this.RemoveProducer(producer.ProducerId);
}
throw;
}
return producer;
}
internal virtual MessageProducer DoCreateMessageProducer(ProducerId id, ActiveMQDestination destination)
{
return new MessageProducer(this, id, destination, this.RequestTimeout);
}
public IMessageConsumer CreateConsumer(IDestination destination)
{
return CreateConsumer(destination, null, false);
}
public IMessageConsumer CreateConsumer(IDestination destination, string selector)
{
return CreateConsumer(destination, selector, false);
}
public IMessageConsumer CreateConsumer(IDestination destination, string selector, bool noLocal)
{
if(destination == null)
{
throw new InvalidDestinationException("Cannot create a Consumer with a Null destination");
}
ActiveMQDestination dest = ActiveMQDestination.Transform(destination);
int prefetchSize = this.Connection.PrefetchPolicy.DurableTopicPrefetch;
if(dest.IsTopic)
{
prefetchSize = this.connection.PrefetchPolicy.TopicPrefetch;
}
else if(dest.IsQueue)
{
prefetchSize = this.connection.PrefetchPolicy.QueuePrefetch;
}
MessageConsumer consumer = null;
try
{
consumer = DoCreateMessageConsumer(GetNextConsumerId(), dest, null, selector, prefetchSize,
this.connection.PrefetchPolicy.MaximumPendingMessageLimit,
noLocal);
consumer.ConsumerTransformer = this.ConsumerTransformer;
this.AddConsumer(consumer);
this.Connection.SyncRequest(consumer.ConsumerInfo);
if(this.Connection.IsStarted)
{
consumer.Start();
}
}
catch(Exception)
{
if(consumer != null)
{
this.RemoveConsumer(consumer);
}
throw;
}
return consumer;
}
public IMessageConsumer CreateDurableConsumer(ITopic destination, string name, string selector, bool noLocal)
{
if(destination == null)
{
throw new InvalidDestinationException("Cannot create a Consumer with a Null destination");
}
if (IsIndividualAcknowledge)
{
throw new NMSException("Cannot create a durable consumer for a session that is using " +
"Individual Acknowledgement mode.");
}
ActiveMQDestination dest = ActiveMQDestination.Transform(destination);
MessageConsumer consumer = null;
try
{
consumer = DoCreateMessageConsumer(GetNextConsumerId(), dest, name, selector,
this.connection.PrefetchPolicy.DurableTopicPrefetch,
this.connection.PrefetchPolicy.MaximumPendingMessageLimit,
noLocal);
consumer.ConsumerTransformer = this.ConsumerTransformer;
this.AddConsumer(consumer);
this.Connection.SyncRequest(consumer.ConsumerInfo);
if(this.Connection.IsStarted)
{
consumer.Start();
}
}
catch(Exception)
{
if(consumer != null)
{
this.RemoveConsumer(consumer);
}
throw;
}
return consumer;
}
internal virtual MessageConsumer DoCreateMessageConsumer(
ConsumerId id, ActiveMQDestination destination, string name, string selector,
int prefetch, int maxPending, bool noLocal)
{
return new MessageConsumer(this, id, destination, name, selector, prefetch,
maxPending, noLocal, false, this.DispatchAsync);
}
public void DeleteDurableConsumer(string name)
{
RemoveSubscriptionInfo command = new RemoveSubscriptionInfo();
command.ConnectionId = Connection.ConnectionId;
command.ClientId = Connection.ClientId;
command.SubcriptionName = name;
this.connection.SyncRequest(command);
}
public IQueueBrowser CreateBrowser(IQueue queue)
{
return this.CreateBrowser(queue, null);
}
public IQueueBrowser CreateBrowser(IQueue queue, string selector)
{
if(queue == null)
{
throw new InvalidDestinationException("Cannot create a Consumer with a Null destination");
}
ActiveMQDestination dest = ActiveMQDestination.Transform(queue);
QueueBrowser browser = null;
try
{
browser = new QueueBrowser(this, GetNextConsumerId(), dest, selector, this.DispatchAsync);
}
catch(Exception)
{
if(browser != null)
{
browser.Close();
}
throw;
}
return browser;
}
public IQueue GetQueue(string name)
{
return new ActiveMQQueue(name);
}
public ITopic GetTopic(string name)
{
return new ActiveMQTopic(name);
}
public ITemporaryQueue CreateTemporaryQueue()
{
return (ITemporaryQueue)this.connection.CreateTemporaryDestination(false);
}
public ITemporaryTopic CreateTemporaryTopic()
{
return (ITemporaryTopic)this.connection.CreateTemporaryDestination(true);
}
/// <summary>
/// Delete a destination (Queue, Topic, Temp Queue, Temp Topic).
/// </summary>
public void DeleteDestination(IDestination destination)
{
this.connection.DeleteDestination(destination);
}
public IMessage CreateMessage()
{
ActiveMQMessage answer = new ActiveMQMessage();
return ConfigureMessage(answer) as IMessage;
}
public ITextMessage CreateTextMessage()
{
ActiveMQTextMessage answer = new ActiveMQTextMessage();
return ConfigureMessage(answer) as ITextMessage;
}
public ITextMessage CreateTextMessage(string text)
{
ActiveMQTextMessage answer = new ActiveMQTextMessage(text);
return ConfigureMessage(answer) as ITextMessage;
}
public IMapMessage CreateMapMessage()
{
return ConfigureMessage(new ActiveMQMapMessage()) as IMapMessage;
}
public IBytesMessage CreateBytesMessage()
{
return ConfigureMessage(new ActiveMQBytesMessage()) as IBytesMessage;
}
public IBytesMessage CreateBytesMessage(byte[] body)
{
ActiveMQBytesMessage answer = new ActiveMQBytesMessage();
answer.Content = body;
return ConfigureMessage(answer) as IBytesMessage;
}
public IStreamMessage CreateStreamMessage()
{
return ConfigureMessage(new ActiveMQStreamMessage()) as IStreamMessage;
}
public IObjectMessage CreateObjectMessage(object body)
{
ActiveMQObjectMessage answer = new ActiveMQObjectMessage();
answer.Body = body;
return ConfigureMessage(answer) as IObjectMessage;
}
public void Commit()
{
this.DoCommit();
}
public void Rollback()
{
this.DoRollback();
}
public void Recover()
{
CheckClosed();
if (IsTransacted)
{
throw new IllegalStateException("Cannot Recover a Transacted Session");
}
lock(this.consumers.SyncRoot)
{
foreach(MessageConsumer consumer in this.consumers.Values)
{
consumer.Rollback();
}
}
}
#endregion
internal void DoSend(ActiveMQDestination destination, ActiveMQMessage message,
MessageProducer producer, MemoryUsage producerWindow, TimeSpan sendTimeout)
{
ActiveMQMessage msg = message;
if(destination.IsTemporary && !connection.IsTempDestinationActive(destination as ActiveMQTempDestination))
{
throw new InvalidDestinationException("Cannot publish to a deleted Destination: " + destination);
}
if(IsTransacted)
{
DoStartTransaction();
msg.TransactionId = TransactionContext.TransactionId;
}
msg.RedeliveryCounter = 0;
msg.BrokerPath = null;
if(this.connection.CopyMessageOnSend)
{
msg = (ActiveMQMessage)msg.Clone();
}
msg.OnSend();
msg.ProducerId = msg.MessageId.ProducerId;
if(sendTimeout.TotalMilliseconds <= 0 && !msg.ResponseRequired && !connection.AlwaysSyncSend &&
(!msg.Persistent || connection.AsyncSend || msg.TransactionId != null))
{
this.connection.Oneway(msg);
if(producerWindow != null)
{
// Since we defer lots of the marshaling till we hit the wire, this
// might not provide and accurate size. We may change over to doing
// more aggressive marshaling, to get more accurate sizes.. this is more
// important once users start using producer window flow control.
producerWindow.IncreaseUsage(msg.Size());
}
}
else
{
if(sendTimeout.TotalMilliseconds > 0)
{
this.connection.SyncRequest(msg, sendTimeout);
}
else
{
this.connection.SyncRequest(msg);
}
}
}
internal virtual void DoCommit()
{
if(!IsTransacted)
{
throw new InvalidOperationException(
"You cannot perform a Commit() on a non-transacted session. Acknowlegement mode is: "
+ this.AcknowledgementMode);
}
this.TransactionContext.Commit();
}
internal virtual void DoRollback()
{
if(!IsTransacted)
{
throw new InvalidOperationException(
"You cannot perform a Commit() on a non-transacted session. Acknowlegement mode is: "
+ this.AcknowledgementMode);
}
this.TransactionContext.Rollback();
}
/// <summary>
/// Ensures that a transaction is started
/// </summary>
internal virtual void DoStartTransaction()
{
if(IsTransacted && !TransactionContext.InTransaction)
{
this.TransactionContext.Begin();
}
}
public void AddConsumer(MessageConsumer consumer)
{
if(!this.closing)
{
ConsumerId id = consumer.ConsumerId;
// Registered with Connection before we register at the broker.
consumers[id] = consumer;
connection.AddDispatcher(id, this);
}
}
public void RemoveConsumer(MessageConsumer consumer)
{
connection.RemoveDispatcher(consumer.ConsumerId);
if(!this.closing)
{
consumers.Remove(consumer.ConsumerId);
}
connection.RemoveDispatcher(consumer);
}
public void AddProducer(MessageProducer producer)
{
if(!this.closing)
{
ProducerId id = producer.ProducerId;
this.producers[id] = producer;
this.connection.AddProducer(id, producer);
}
}
public void RemoveProducer(ProducerId objectId)
{
connection.RemoveProducer(objectId);
if(!this.closing)
{
producers.Remove(objectId);
}
}
public ConsumerId GetNextConsumerId()
{
ConsumerId id = new ConsumerId();
id.ConnectionId = info.SessionId.ConnectionId;
id.SessionId = info.SessionId.Value;
id.Value = Interlocked.Increment(ref consumerCounter);
return id;
}
public ProducerId GetNextProducerId()
{
ProducerId id = new ProducerId();
id.ConnectionId = info.SessionId.ConnectionId;
id.SessionId = info.SessionId.Value;
id.Value = Interlocked.Increment(ref producerCounter);
return id;
}
public void Stop()
{
if(this.executor != null)
{
this.executor.Stop();
}
}
public void Start()
{
lock(this.consumers.SyncRoot)
{
foreach(MessageConsumer consumer in this.consumers.Values)
{
consumer.Start();
}
}
if(this.executor != null)
{
this.executor.Start();
}
}
public bool Started
{
get
{
return this.executor != null ? this.executor.Running : false;
}
}
internal void Redispatch(IDispatcher dispatcher, MessageDispatchChannel channel)
{
MessageDispatch[] messages = channel.RemoveAll();
foreach (MessageDispatch dispatch in messages)
{
this.connection.RollbackDuplicate(dispatcher, dispatch.Message);
}
System.Array.Reverse(messages);
foreach(MessageDispatch message in messages)
{
this.executor.ExecuteFirst(message);
}
}
public void Dispatch(MessageDispatch dispatch)
{
if(this.executor != null)
{
this.executor.Execute(dispatch);
}
}
internal void ClearMessagesInProgress(ref long transportInterruptionProcessingComplete)
{
if(this.executor != null)
{
this.executor.ClearMessagesInProgress();
}
if (this.consumers.Count == 0)
{
return;
}
// Because we are called from inside the Transport Reconnection logic
// we spawn the Consumer clear to another Thread so that we can avoid
// any lock contention that might exist between the consumer and the
// connection that is reconnecting. Use the Connection Scheduler so
// that the clear calls are done one at a time to avoid further
// contention on the Connection and Session resources.
if (clearInProgress.CompareAndSet(false, true))
{
lock(this.consumers.SyncRoot)
{
foreach(MessageConsumer consumer in this.consumers.Values)
{
consumer.InProgressClearRequired();
Interlocked.Increment(ref transportInterruptionProcessingComplete);
Scheduler.ExecuteAfterDelay(ClearMessages, consumer, 0);
}
}
// Clear after all consumer have had their ClearMessagesInProgress method called.
Scheduler.ExecuteAfterDelay(ResetClearInProgressFlag, clearInProgress, 0);
}
}
private static void ClearMessages(object value)
{
MessageConsumer consumer = value as MessageConsumer;
if(Tracer.IsDebugEnabled)
{
Tracer.Debug("Performing Async Clear of In Progress Messages on Consumer: " + consumer.ConsumerId);
}
consumer.ClearMessagesInProgress();
}
private static void ResetClearInProgressFlag(object value)
{
Atomic<bool> clearInProgress = value as Atomic<bool>;
clearInProgress.Value = false;
}
internal void Acknowledge()
{
lock(this.consumers.SyncRoot)
{
foreach(MessageConsumer consumer in this.consumers.Values)
{
consumer.Acknowledge();
}
}
}
private ActiveMQMessage ConfigureMessage(ActiveMQMessage message)
{
message.Connection = this.connection;
if(this.IsTransacted)
{
// Allows Acknowledge to be called in a transaction with no effect per JMS Spec.
message.Acknowledger += new AcknowledgeHandler(DoNothingAcknowledge);
}
return message;
}
internal void SendAck(MessageAck ack)
{
this.SendAck(ack, false);
}
internal void SendAck(MessageAck ack, bool lazy)
{
if(Tracer.IsDebugEnabled)
{
Tracer.Debug("Session sending Ack: " + ack);
}
if(lazy || connection.SendAcksAsync || this.IsTransacted )
{
this.connection.Oneway(ack);
}
else
{
this.connection.SyncRequest(ack);
}
}
protected virtual TransactionContext CreateTransactionContext()
{
return new TransactionContext(this);
}
private void CheckClosed()
{
if (closed)
{
throw new IllegalStateException("Session is Closed");
}
}
/// <summary>
/// Prevents message from throwing an exception if a client calls Acknoweldge on
/// a message that is part of a transaction either being produced or consumed. The
/// JMS Spec indicates that users should be able to call Acknowledge with no effect
/// if the message is in a transaction.
/// </summary>
/// <param name="message">
/// A <see cref="ActiveMQMessage"/>
/// </param>
private static void DoNothingAcknowledge(ActiveMQMessage message)
{
}
class SessionCloseSynchronization : ISynchronization
{
private readonly Session session;
public SessionCloseSynchronization(Session session)
{
this.session = session;
}
public void BeforeEnd()
{
}
public void AfterCommit()
{
Tracer.Debug("SessionCloseSynchronization AfterCommit called for Session: " + session.SessionId);
session.DoClose();
}
public void AfterRollback()
{
Tracer.Debug("SessionCloseSynchronization AfterRollback called for Session: " + session.SessionId);
session.DoClose();
}
}
internal bool IsInUse(ActiveMQTempDestination dest)
{
lock(this.consumers.SyncRoot)
{
foreach(MessageConsumer consumer in this.consumers.Values)
{
if(consumer.IsInUse(dest))
{
return true;
}
}
}
return false;
}
}
}
|
||||
TheStack | e0a0245a10fcb42a892bf3cc9d5b02456b50213c | C#code:C# | {"size": 970, "ext": "cs", "max_stars_repo_path": "Bill.Management.Core.Implementations/ServiceExtensions.cs", "max_stars_repo_name": "Marina1824/levelup_160321", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Bill.Management.Core.Implementations/ServiceExtensions.cs", "max_issues_repo_name": "Marina1824/levelup_160321", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Bill.Management.Core.Implementations/ServiceExtensions.cs", "max_forks_repo_name": "Marina1824/levelup_160321", "max_forks_repo_forks_event_min_datetime": "2021-05-03T18:06:12.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-03T18:06:12.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 32.3333333333, "max_line_length": 96, "alphanum_fraction": 0.7525773196} | using Bill.Management.Core.Abstractions.Container;
using Bill.Management.Core.Abstractions.Services.JsonPersistence;
using Bill.Management.Core.Abstractions.Services.Logging;
using Bill.Management.Core.Abstractions.Services.Validation;
using Bill.Management.Core.Implementations.Services.JsonPersistence;
using Bill.Management.Core.Implementations.Services.Logging;
using Microsoft.Extensions.DependencyInjection;
namespace Bill.Management.Core.Implementations
{
public static class ServiceExtensions
{
public static IServiceCollection AddLogger(this IServiceCollection container)
{
container.AddSingleton<ILoggerService, LoggerService>();
return container;
}
public static IServiceCollection AddJson(this IServiceCollection container)
{
container.AddSingleton<IJsonPersistenceService, NewtonsoftJsonPersistenceService>();
return container;
}
}
}
|
||||
TheStack | e0a1c58e8e3864286586666e66b99c444e8d8b2f | C#code:C# | {"size": 3668, "ext": "cs", "max_stars_repo_path": "src/Marten.Testing/Linq/invoking_queryable_count_async_Tests.cs", "max_stars_repo_name": "gregfiske/marten", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Marten.Testing/Linq/invoking_queryable_count_async_Tests.cs", "max_issues_repo_name": "gregfiske/marten", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Marten.Testing/Linq/invoking_queryable_count_async_Tests.cs", "max_forks_repo_name": "gregfiske/marten", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 39.4408602151, "max_line_length": 114, "alphanum_fraction": 0.5924209378} | using System.Threading.Tasks;
using Marten.Services;
using Marten.Util;
using Shouldly;
using Xunit;
namespace Marten.Testing.Linq
{
public class invoking_queryable_count_async_Tests : DocumentSessionFixture<NulloIdentityMap>
{
[Fact]
public async Task count_without_any_where()
{
theSession.Store(new Target { Number = 1 });
theSession.Store(new Target { Number = 2 });
theSession.Store(new Target { Number = 3 });
theSession.Store(new Target { Number = 4 });
await theSession.SaveChangesAsync().ConfigureAwait(false);
var result = await theSession.Query<Target>().CountAsync().ConfigureAwait(false);
result.ShouldBe(4);
}
[Fact]
public async Task long_count_without_any_where()
{
theSession.Store(new Target { Number = 1 });
theSession.Store(new Target { Number = 2 });
theSession.Store(new Target { Number = 3 });
theSession.Store(new Target { Number = 4 });
await theSession.SaveChangesAsync().ConfigureAwait(false);
var result = await theSession.Query<Target>().LongCountAsync().ConfigureAwait(false);
result.ShouldBe(4);
}
[Fact]
public async Task count_with_a_where_clause()
{
theSession.Store(new Target { Number = 1 });
theSession.Store(new Target { Number = 2 });
theSession.Store(new Target { Number = 3 });
theSession.Store(new Target { Number = 4 });
theSession.Store(new Target { Number = 5 });
theSession.Store(new Target { Number = 6 });
await theSession.SaveChangesAsync().ConfigureAwait(false);
var result = await theSession.Query<Target>().CountAsync(x => x.Number > 3).ConfigureAwait(false);
result.ShouldBe(3);
}
[Fact]
public async Task long_count_with_a_where_clause()
{
theSession.Store(new Target { Number = 1 });
theSession.Store(new Target { Number = 2 });
theSession.Store(new Target { Number = 3 });
theSession.Store(new Target { Number = 4 });
theSession.Store(new Target { Number = 5 });
theSession.Store(new Target { Number = 6 });
await theSession.SaveChangesAsync().ConfigureAwait(false);
var result = await theSession.Query<Target>().LongCountAsync(x => x.Number > 3).ConfigureAwait(false);
result.ShouldBe(3);
}
[Fact]
public async Task sum_without_any_where()
{
theSession.Store(new Target { Number = 1 });
theSession.Store(new Target { Number = 2 });
theSession.Store(new Target { Number = 3 });
theSession.Store(new Target { Number = 4 });
await theSession.SaveChangesAsync().ConfigureAwait(false);
var result = await theSession.Query<Target>().SumAsync(x => x.Number).ConfigureAwait(false);
result.ShouldBe(10);
}
[Fact]
public async Task sum_with_nullable()
{
theSession.Store(new Target { NullableNumber = 1 });
theSession.Store(new Target { NullableNumber = 2 });
theSession.Store(new Target { NullableNumber = 3 });
theSession.Store(new Target { NullableNumber = 4 });
await theSession.SaveChangesAsync().ConfigureAwait(false);
var result = await theSession.Query<Target>().SumAsync(x => x.NullableNumber).ConfigureAwait(false);
result.ShouldBe(10);
}
}
} |
||||
TheStack | e0a22e9671d152bf1d02721e2a6a12b21f0196e9 | C#code:C# | {"size": 1004, "ext": "cs", "max_stars_repo_path": "VSDocumentReopen/VSDocumentReopen/Infrastructure/JsonHistoryRepositoryFactory.cs", "max_stars_repo_name": "brucejing/vs-reopen", "max_stars_repo_stars_event_min_datetime": "2018-08-25T15:50:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-22T05:04:08.000Z", "max_issues_repo_path": "VSDocumentReopen/VSDocumentReopen/Infrastructure/JsonHistoryRepositoryFactory.cs", "max_issues_repo_name": "AzureMentor/vs-reopen", "max_issues_repo_issues_event_min_datetime": "2018-09-20T11:51:18.000Z", "max_issues_repo_issues_event_max_datetime": "2021-11-17T11:22:16.000Z", "max_forks_repo_path": "VSDocumentReopen/VSDocumentReopen/Infrastructure/JsonHistoryRepositoryFactory.cs", "max_forks_repo_name": "AzureMentor/vs-reopen", "max_forks_repo_forks_event_min_datetime": "2019-06-18T07:39:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-28T06:55:39.000Z"} | {"max_stars_count": 20.0, "max_issues_count": 4.0, "max_forks_count": 5.0, "avg_line_length": 30.4242424242, "max_line_length": 96, "alphanum_fraction": 0.8147410359} | using System.ComponentModel;
using System.IO;
using VSDocumentReopen.Domain;
using VSDocumentReopen.Infrastructure.Helpers;
using VSDocumentReopen.Infrastructure.Repositories;
namespace VSDocumentReopen.Infrastructure
{
public sealed class JsonHistoryRepositoryFactory : IHistoryRepositoryFactory
{
private readonly IJsonSerializer _jsonSerializer;
public JsonHistoryRepositoryFactory(IJsonSerializer jsonSerializer)
{
_jsonSerializer = jsonSerializer;
}
public IHistoryRepository CreateHistoryRepository(SolutionInfo solutionInfo)
{
if (solutionInfo is null)
{
throw new InvalidEnumArgumentException($"Parameter: {nameof(solutionInfo)} cannot be null");
}
var historyFile = Path.Combine(solutionInfo.FullPath,
ConfigurationManager.Current.Config.VSTempFolderName,
ConfigurationManager.Current.Config.PackageWorkingDirName,
ConfigurationManager.Current.Config.HistoryFileName);
return new JsonHistoryRepository(_jsonSerializer, historyFile);
}
}
} |
||||
TheStack | e0a4785fcd07c267108d3afbebc1baa5a8c09277 | C#code:C# | {"size": 1984, "ext": "cs", "max_stars_repo_path": "CSharpGL/GLObjects/GLSwitches/FrontFaceSwitch.cs", "max_stars_repo_name": "baho-s/CSharpGL", "max_stars_repo_stars_event_min_datetime": "2015-08-30T03:35:18.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-21T13:23:17.000Z", "max_issues_repo_path": "CSharpGL/GLObjects/GLSwitches/FrontFaceSwitch.cs", "max_issues_repo_name": "TaiLongFei/CSharpGL", "max_issues_repo_issues_event_min_datetime": "2015-08-15T16:19:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-29T14:38:05.000Z", "max_forks_repo_path": "CSharpGL/GLObjects/GLSwitches/FrontFaceSwitch.cs", "max_forks_repo_name": "TaiLongFei/CSharpGL", "max_forks_repo_forks_event_min_datetime": "2015-08-29T08:42:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-15T09:51:07.000Z"} | {"max_stars_count": 565.0, "max_issues_count": 27.0, "max_forks_count": 246.0, "avg_line_length": 28.7536231884, "max_line_length": 87, "alphanum_fraction": 0.5307459677} | namespace CSharpGL
{
/// <summary>
/// This function sets what defines a front face. Counter ClockWise by default.
/// <para>作用是控制多边形的正面是如何决定的。在默认情况下,mode是GL_CCW。</para>
/// </summary>
public class FrontFaceSwitch : GLSwitch
{
private int[] originalPolygonMode = new int[1];
// Activator needs a non-parameter constructor.
/// <summary>
/// This function sets what defines a front face. Counter ClockWise by default.
/// <para>作用是控制多边形的正面是如何决定的。在默认情况下,mode是GL_CCW。</para>
/// </summary>
public FrontFaceSwitch() : this(FrontFaceMode.CCW) { }
/// <summary>
/// This function sets what defines a front face. Counter ClockWise by default.
/// <para>作用是控制多边形的正面是如何决定的。在默认情况下,mode是GL_CCW。</para>
/// </summary>
/// <param name="mode"></param>
public FrontFaceSwitch(FrontFaceMode mode)
{
this.Mode = mode;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format("glFrontFace({0})", Mode);
}
private uint lastMode;
/// <summary>
///
/// </summary>
protected override void StateOn()
{
GL.Instance.GetIntegerv((uint)GetTarget.FrontFace, originalPolygonMode);
this.lastMode = (uint)this.Mode;
if (this.lastMode != originalPolygonMode[0])
{
GL.Instance.FrontFace(this.lastMode);
}
}
/// <summary>
///
/// </summary>
protected override void StateOff()
{
if (this.lastMode != originalPolygonMode[0])
{
GL.Instance.FrontFace((uint)originalPolygonMode[0]);
}
}
/// <summary>
///
/// </summary>
public FrontFaceMode Mode { get; set; }
}
} |
||||
TheStack | e0a514e3160f40c61057e9ff70545ff2cb60fac3 | C#code:C# | {"size": 285, "ext": "cs", "max_stars_repo_path": "QuizDuellApi/Json/Opponent.cs", "max_stars_repo_name": "joshimoo/QuizDuell", "max_stars_repo_stars_event_min_datetime": "2015-10-12T10:22:14.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-20T08:01:01.000Z", "max_issues_repo_path": "QuizDuellApi/Json/Opponent.cs", "max_issues_repo_name": "joshimoo/QuizDuell", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "QuizDuellApi/Json/Opponent.cs", "max_forks_repo_name": "joshimoo/QuizDuell", "max_forks_repo_forks_event_min_datetime": "2015-02-14T10:48:21.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-04T18:19:35.000Z"} | {"max_stars_count": 5.0, "max_issues_count": null, "max_forks_count": 5.0, "avg_line_length": 28.5, "max_line_length": 85, "alphanum_fraction": 0.6070175439} | namespace QuizDuell.Json
{
public class Opponent
{
public string facebook_id { get; set; } // TODO: Not sure if this is included
public string avatar_code { get; set; }
public string name { get; set; }
public string user_id { get; set; }
}
} |
||||
TheStack | e0a60f02f770c1a70ba6ecf0cdc8af6680f19cb7 | C#code:C# | {"size": 1888, "ext": "cs", "max_stars_repo_path": "Src/Tests/UnitTests/Tests/LogAdapterTests/RemoveInvalidatesLogAdapterTest.cs", "max_stars_repo_name": "tagolog/logging", "max_stars_repo_stars_event_min_datetime": "2016-11-14T22:00:51.000Z", "max_stars_repo_stars_event_max_datetime": "2016-11-14T22:00:51.000Z", "max_issues_repo_path": "Src/Tests/UnitTests/Tests/LogAdapterTests/RemoveInvalidatesLogAdapterTest.cs", "max_issues_repo_name": "tagolog/logging", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Src/Tests/UnitTests/Tests/LogAdapterTests/RemoveInvalidatesLogAdapterTest.cs", "max_forks_repo_name": "tagolog/logging", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.1228070175, "max_line_length": 71, "alphanum_fraction": 0.5376059322} | using NUnit.Framework;
namespace Tagolog.UnitTest.Tests.LogAdapterTests
{
[TestFixture]
class RemoveInvalidatesLogAdapterTest : LogAdapterTest
{
[Test]
public void LogAdapter_RemoveInvalidatesLogAdapter()
{
Assert.AreEqual( 0, LogAdapter.Tags.Count );
using ( var scope = TagScopeManager.CreateScope() )
{
scope.Tags[ "tag1" ] = "value1";
scope.Tags[ "tag2" ] = "value2";
Assert.AreEqual( 2, LogAdapter.Tags.Count );
scope.Tags.Remove( "tag1" );
Assert.AreEqual( 1, LogAdapter.Tags.Count );
Assert.AreEqual( "value2", LogAdapter.Tags[ "tag2" ] );
TestWithNestedScope();
Assert.AreEqual( 1, LogAdapter.Tags.Count );
Assert.AreEqual( "value2", LogAdapter.Tags[ "tag2" ] );
}
Assert.AreEqual( 0, LogAdapter.Tags.Count );
}
/// <summary>
/// This fragment implemented as a separate method
/// to isolate nested scope from parent scope
/// and prevent some really annoying problems with
/// mess with acident "scope" and "nestedScope" calls
/// while they are in one method.
/// </summary>
void TestWithNestedScope()
{
using ( var nestedScope = TagScopeManager.CreateScope() )
{
nestedScope.Tags[ "tag3" ] = "value3";
nestedScope.Tags[ "tag4" ] = "value4";
Assert.AreEqual( 3, LogAdapter.Tags.Count );
nestedScope.Tags.Remove( "tag3" );
Assert.AreEqual( 2, LogAdapter.Tags.Count );
Assert.AreEqual( "value2", LogAdapter.Tags[ "tag2" ] );
Assert.AreEqual( "value4", LogAdapter.Tags[ "tag4" ] );
}
}
}
}
|
||||
TheStack | e0a83d88e6c91654ddfc1e19e8378bad08314c03 | C#code:C# | {"size": 866, "ext": "cs", "max_stars_repo_path": "src/Nut.Results/Extensions/Unsafe/T_GetError.cs", "max_stars_repo_name": "Archway-SharedLib/Nut.Results", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Nut.Results/Extensions/Unsafe/T_GetError.cs", "max_issues_repo_name": "Archway-SharedLib/Nut.Results", "max_issues_repo_issues_event_min_datetime": "2020-10-30T09:29:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-12-29T15:42:27.000Z", "max_forks_repo_path": "src/Nut.Results/Extensions/Unsafe/T_GetError.cs", "max_forks_repo_name": "Archway-SharedLib/Nut.Results", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 17.0, "max_forks_count": null, "avg_line_length": 33.3076923077, "max_line_length": 108, "alphanum_fraction": 0.6616628176} | using System;
using System.Threading.Tasks;
using SR = Nut.Results.Resources.Strings;
// ReSharper disable CheckNamespace
namespace Nut.Results
{
public static partial class ResultUnsafeExtensions
{
public static IError GetError<T>(this in Result<T> source)
{
if (source.IsOk) throw new InvalidOperationException(SR.Exception_ResultIsNotErrorBeforeCheck);
return source.errorValue;
}
public static async Task<IError> GetError<T>(this Task<Result<T>> source)
{
if (source is null) throw new ArgumentNullException(nameof(source));
var result = await source.ConfigureAwait(false);
if (result.IsOk) throw new InvalidOperationException(SR.Exception_ResultIsNotErrorBeforeCheck);
return result.errorValue;
}
}
} |
||||
TheStack | e0a8bbccf03c12493ac5bc178f4d1d2d07a2f5b1 | C#code:C# | {"size": 15041, "ext": "cs", "max_stars_repo_path": "RePair/Assets/Foliage2D/Scripts/Foliage2D_Animation.cs", "max_stars_repo_name": "Dividebyzer0Team/RePair", "max_stars_repo_stars_event_min_datetime": "2020-05-20T19:56:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-03T21:46:12.000Z", "max_issues_repo_path": "RePair/Assets/Foliage2D/Scripts/Foliage2D_Animation.cs", "max_issues_repo_name": "Dividebyzer0Team/RePair", "max_issues_repo_issues_event_min_datetime": "2020-05-28T09:36:06.000Z", "max_issues_repo_issues_event_max_datetime": "2020-05-28T09:36:06.000Z", "max_forks_repo_path": "RePair/Assets/Foliage2D/Scripts/Foliage2D_Animation.cs", "max_forks_repo_name": "Dividebyzer0Team/RePair", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 3.0, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 42.1316526611, "max_line_length": 190, "alphanum_fraction": 0.559271325} | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Foliage
{
#region Enums
/// <summary>
/// Describes the type of bending that should be applied to the foliage mesh.
/// </summary>
public enum Foliage2D_MeshBending
{
/// <summary>
/// Applies a simple bending to the foliage mesh by offsetting
/// the position of the mesh vertices.
/// </summary>
Simple,
/// <summary>
/// Applies a smart bending to the foliage mesh by rotating the vertices around a point.
/// </summary>
Smart
}
#endregion
public class Foliage2D_Animation : MonoBehaviour
{
#region Private fields
// List of objects that have a 2D collider and are staying in the current trigger collider.
private List<Collider2D> collider2DObject;
// List of objects that have a 3D collider and are staying in the current trigger collider.
private List<Collider> collider3DObject;
// The distance between the foliage object and an object that entered its
// trigger collider.
private List<float> enterOffset;
/// <summary>
/// The initial local position of the mesh vertices.
/// </summary>
private Vector3[] initialVertexPos;
/// <summary>
/// The final local position of the mesh vertices.
/// </summary>
private Vector3[] finalVertexPos;
/// <summary>
/// The amount by which to change the initial position of a vertex.
/// The change in position for the vertices on the same row is the same.
/// </summary>
private Vector3[] posOffset;
/// <summary>
/// A series of points around which to rotate the mesh vertices.
/// </summary>
private Vector2[] centerLinePoints;
/// <summary>
/// Reference to the Foliage2D component of this object.
/// </summary>
private Foliage2D foliage2D;
/// <summary>
/// Reference to the Animator component of this object.
/// </summary>
private Animator animator;
/// <summary>
/// Reference to the Mesh component of this object.
/// </summary>
private Mesh meshFilter;
/// <summary>
/// Did an object bend this foliage object?.
/// </summary>
private bool isBending = false;
/// <summary>
/// The number of verices a horizontal row has.
/// </summary>
private int horizontalVerts;
/// <summary>
/// The amount in degrees by which to rotate a vertex around a point.
/// </summary>
private float[] anglesInDeg;
#endregion
#region Public fields
public Foliage2D_MeshBending foliageBending = Foliage2D_MeshBending.Simple;
/// <summary>
/// A list of values that define which part of the "offset" value
/// should be used to calculate the new vertex position.
/// </summary>
public List<float> offsetFactor = new List<float>();
/// <summary>
/// This is the value that should be changed to animate the mesh.
/// </summary>
public Vector3 offset;
/// <summary>
/// Should we change the animation speed at the start?.
/// </summary>
public bool changeAnimationSpeed = false;
/// <summary>
/// The min value for a random animation speed.
/// </summary>
public float minSpeed = 0.5f;
/// <summary>
/// The max value for a random animation speed.
/// </summary>
public float maxSpeed = 2.0f;
/// <summary>
/// The min value for a random number.
/// </summary>
public float minSeconds = 0;
/// <summary>
/// The max value for a random number.
/// </summary>
public float maxSeconds = 1.5f;
#endregion
#region Class methods
void Start()
{
animator = GetComponent<Animator>();
foliage2D = GetComponent<Foliage2D>();
meshFilter = GetComponent<MeshFilter>().sharedMesh;
initialVertexPos = meshFilter.vertices;
horizontalVerts = foliage2D.widthSegments + 1;
finalVertexPos = meshFilter.vertices;
collider2DObject = new List<Collider2D>();
collider3DObject = new List<Collider>();
enterOffset = new List<float>();
anglesInDeg = new float[foliage2D.heightSegments + 1];
posOffset = new Vector3[foliage2D.heightSegments + 1];
centerLinePoints = new Vector2[foliage2D.heightSegments + 1];
// We change the default speed of the animation and then reset it
// back so that the motion of different foliage objects isn't synchronized.
// This will produce a more realistic behaviour.
if (animator != null && changeAnimationSpeed)
{
StartCoroutine(SetAnimationSpeed());
}
// This is a safeguard to eliminate the "Index out of Range Exception" errors
// that may be generated when the object in the scene is a prefab instance
// and the user forgot to save the changes he made to it.
if (offsetFactor.Count != foliage2D.heightSegments + 1)
{
offsetFactor.Clear();
int len = foliage2D.heightSegments + 1;
float offset = 1f / foliage2D.heightSegments;
for (int i = 0; i < len; i++)
{
offsetFactor.Add(offset * i);
}
}
}
/// <summary>
/// Changes the default speed of the animation.
/// </summary>
IEnumerator SetAnimationSpeed()
{
animator.speed = Random.Range(minSpeed, maxSpeed);
// This suspends the coroutine execution for a random amount of seconds.
// As a result the animation speed will be set to its default value after a small delay.
yield return new WaitForSeconds(Random.Range(minSeconds, maxSeconds));
animator.speed = 1f;
}
void Update()
{
UpdateVertsPos();
int len = collider2DObject.Count;
// The loop checks all the objects that are are currently staying in
// this collider and determines if a bending animations must be triggered.
for (int i = 0; i < len; i++)
{
float offset = collider2DObject[i].transform.position.x - transform.position.x;
// We want an object to trigger a foliage animation only when this object is past
// the middle point of the foliage object. For this purpose we compare the sign of
// the difference between the current position of the moving object and the foliage
// object, with the value of "enterOffset", of the current moving object.
if ((Mathf.Sign(enterOffset[i]) != Mathf.Sign(offset)) && !isBending && animator != null)
{
// Which animation to trigger is determined by comparing the position on the X
// axis of the moving object with that of the foliage object.
if (collider2DObject[i].transform.position.x > transform.position.x)
animator.SetTrigger("tRight");
else
animator.SetTrigger("tLeft");
// We set "isBending" to true so that on the next frame the animators trigger is not set again.
isBending = true;
}
}
// This updates the mesh vertices local position.
meshFilter.vertices = finalVertexPos;
}
/// <summary>
/// Updates the local position of the mesh vertices.
/// </summary>
private void UpdateVertsPos()
{
if (foliageBending == Foliage2D_MeshBending.Simple)
SimpleMeshBending();
else
SmartMeshBending();
}
/// <summary>
/// Applies a simple bending to the mesh.
/// </summary>
private void SimpleMeshBending()
{
int hLen = foliage2D.heightSegments + 1;
int wLen = foliage2D.widthSegments + 1;
// This for loop is responsible for the mesh animation.
// The final position of the mesh vertices is calculated based on
// their initial position plus the offset for a given horizontal row.
for (int i = 0; i < hLen; i++)
{
posOffset[i] = new Vector3(offset.x * offsetFactor[i], offset.y * offsetFactor[i], offset.z * offsetFactor[i]);
for (int j = 0; j < wLen; j++)
{
// The index of the vertex whose final local position must be calculated.
int vertIndex = horizontalVerts * i + j;
finalVertexPos[vertIndex] = new Vector3(
initialVertexPos[vertIndex].x + posOffset[i].x,
initialVertexPos[vertIndex].y + posOffset[i].y,
initialVertexPos[vertIndex].z + posOffset[i].z);
}
}
}
/// <summary>
/// Applies a more realistic bending to the mesh.
/// </summary>
private void SmartMeshBending()
{
// The value of -1 means the vertex will be moved to the left of it's
// initial position on the X axis while 1 to the right.
int dir = offset.x < 0 ? -1 : 1;
// The height of a horizontal mesh segment.
float heightOfSegment = foliage2D.height / foliage2D.heightSegments;
centerLinePoints[0] = new Vector2(offset.x * offsetFactor[0], initialVertexPos[0].y);
int hLen = foliage2D.heightSegments + 1;
int wLen = foliage2D.widthSegments + 1;
// You could say this is the backbone of the mesh. Uncomment the segment below this loop to see it in the scene view.
// Calculates the points around which to rotate the mesh vertices.
for (int i = 1; i < hLen; i++)
{
float xOffset = offset.x * offsetFactor[i];
if (Mathf.Abs(xOffset) < heightOfSegment)
centerLinePoints[i] = new Vector2(centerLinePoints[i - 1].x + xOffset, centerLinePoints[i - 1].y + Mathf.Sqrt((heightOfSegment * heightOfSegment) - (xOffset * xOffset)));
else
{
float y = Mathf.Abs(xOffset) - heightOfSegment;
centerLinePoints[i] = new Vector2(centerLinePoints[i - 1].x + dir * Mathf.Sqrt((heightOfSegment * heightOfSegment) - (y * y)), centerLinePoints[i - 1].y - y);
}
}
//// Uncomment this segment to see the mesh center line in the scene view.
//for (int i = 0; i < hLen - 1; i++)
//{
// Debug.DrawLine(transform.TransformPoint(centerLinePoints[i]), transform.TransformPoint(centerLinePoints[i + 1]), Color.blue);
//}
for (int i = 1; i < hLen; i++)
{
Vector2 line = centerLinePoints[i] - centerLinePoints[i - 1];
anglesInDeg[i] = Mathf.Atan2(line.y, line.x) * Mathf.Rad2Deg - 90f;
// The amount in radians by which to rotate a vertex around a point.
float angleInRadians = anglesInDeg[i] * Mathf.Deg2Rad;
for (int j = 0; j < wLen; j++)
{
// The index of the vertex whose final local position must be calculated.
int vertIndex = horizontalVerts * i + j;
// The initial position of a vertex is offset based on the values of "centerLinePoints".
finalVertexPos[vertIndex] = new Vector3(
initialVertexPos[vertIndex].x + centerLinePoints[i].x,
centerLinePoints[i].y,
initialVertexPos[vertIndex].z);
// The Current position of the vertex.
Vector3 vertCurPos = finalVertexPos[vertIndex];
// Calculates the final position of the vertex after it is rotated.
finalVertexPos[vertIndex] = new Vector3(
(vertCurPos.x - centerLinePoints[i].x) * Mathf.Cos(angleInRadians) - (vertCurPos.y - centerLinePoints[i].y) * Mathf.Sin(angleInRadians) + centerLinePoints[i].x,
(vertCurPos.x - centerLinePoints[i].x) * Mathf.Sin(angleInRadians) + (vertCurPos.y - centerLinePoints[i].y) * Mathf.Cos(angleInRadians) + centerLinePoints[i].y,
0.0f);
}
}
}
void OnTriggerEnter(Collider other)
{
if (!collider3DObject.Contains(other))
{
collider3DObject.Add(other);
// We save the difference between the moving object when it entered the trigger
// and the foliage object to a list so that we ca use it to determine when the
// moving object has passed the middle point of the foliage object.
enterOffset.Add(other.transform.position.x - transform.position.x);
}
}
void OnTriggerExit(Collider other)
{
// If a collider exited the foliage trigger, we don't need a reference to it anymore.
if (collider3DObject.Contains(other))
{
int index = collider3DObject.IndexOf(other);
collider3DObject.Remove(other);
enterOffset.RemoveAt(index);
}
isBending = false;
}
void OnTriggerEnter2D(Collider2D other)
{
if (!collider2DObject.Contains(other))
{
collider2DObject.Add(other);
// We save the difference between the moving object when it entered the trigger
// and the foliage object to a list so that we ca use it to determine when the
// moving object has passed the middle point of the foliage object.
enterOffset.Add(other.transform.position.x - transform.position.x);
}
}
void OnTriggerExit2D(Collider2D other)
{
// If a collider exited the foliage trigger, we don't need a reference to it anymore.
if (collider2DObject.Contains(other))
{
int index = collider2DObject.IndexOf(other);
collider2DObject.Remove(other);
enterOffset.RemoveAt(index);
}
isBending = false;
}
#endregion
}
}
|
||||
TheStack | e0a97f5fddd9744920c342594c6f4aafdd641e45 | C#code:C# | {"size": 970, "ext": "cs", "max_stars_repo_path": "Ressi/ressi/Assets/Common/Mechanics/ConsumableObject.cs", "max_stars_repo_name": "Megapop/Norad-Eduapp4syria", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Ressi/ressi/Assets/Common/Mechanics/ConsumableObject.cs", "max_issues_repo_name": "Megapop/Norad-Eduapp4syria", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Ressi/ressi/Assets/Common/Mechanics/ConsumableObject.cs", "max_forks_repo_name": "Megapop/Norad-Eduapp4syria", "max_forks_repo_forks_event_min_datetime": "2018-09-10T08:29:13.000Z", "max_forks_repo_forks_event_max_datetime": "2018-09-10T08:29:13.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 26.2162162162, "max_line_length": 80, "alphanum_fraction": 0.6958762887} | using System;
using UnityEngine;
[RequireComponent(typeof(Collider2D))]
[RequireComponent(typeof(Rigidbody2D))]
[DisallowMultipleComponent]
public class ConsumableObject : MonoBehaviour {
[NonSerialized]
public Action<ConsumableObject> OnConsume;
[Header("Placement")]
public float MaxYPosition;
public float MinYPosition;
bool _consumeTriggered;
void OnCollisionEnter2D(Collision2D other)
{
if (!other.enabled) return;
if (other.gameObject.tag != Constants.Tags.Player) return;
if (_consumeTriggered) return;
_consumeTriggered = true;
var controller = other.gameObject.GetComponent<RessiController>();
OnConsume(this);
controller.Movement.ClearTarget();
}
void OnDrawGizmosSelected()
{
Gizmos.DrawSphere(new Vector2(transform.position.x, MinYPosition), .1f);
Gizmos.DrawSphere(new Vector2(transform.position.x, MaxYPosition), .1f);
}
}
|
||||
TheStack | e0aaced7b4050fe20334f73a66f624b9404f9278 | C#code:C# | {"size": 6720, "ext": "cs", "max_stars_repo_path": "Portfolio/C#/DrinkOrderSystem/DrinkOrderSystem/ServerSide/SystemAdmin/NowOrdering.aspx.cs", "max_stars_repo_name": "yuchi0731/Portfolio", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Portfolio/C#/DrinkOrderSystem/DrinkOrderSystem/ServerSide/SystemAdmin/NowOrdering.aspx.cs", "max_issues_repo_name": "yuchi0731/Portfolio", "max_issues_repo_issues_event_min_datetime": "2022-02-16T03:52:05.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-16T03:52:05.000Z", "max_forks_repo_path": "Portfolio/C#/DrinkOrderSystem/DrinkOrderSystem/ServerSide/SystemAdmin/NowOrdering.aspx.cs", "max_forks_repo_name": "yuchi0731/Portfolio", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 29.2173913043, "max_line_length": 84, "alphanum_fraction": 0.5104166667} | using DOS_Auth;
using DOS_DBSoure;
using DOS_ORM.DOSmodel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace DrinkOrderSystem.ServerSide.SystemAdmin
{
public partial class NowOrdering : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
if (!AuthManager.IsLogined())
{
Response.Redirect("/ClientSide/Login.aspx");
return;
}
// 清除Session
ClearCustomSession();
//更新訂單成立狀況
DrinkListManager.CheckEstablishedorFail();
var list = DrinkListManager.GetOrderByRtimeNowOrdering();
if (list.Count > 0) //check is empty data (大於0就做資料繫結)
{
var orderlist = this.GetPageDataTable(list);
this.ucPager.Totaluser = list.Count;
this.ucPager.BindUserList();
this.gvNoworderinglist.DataSource = orderlist;
this.gvNoworderinglist.DataBind();
}
else
{
this.gvNoworderinglist.Visible = false;
this.ucPager.Visible = false;
this.plcNoData.Visible = true;
this.lbMsg.Text = "目前沒有可跟團的清單";
}
}
}
/// <summary> 清除Session</summary>
private void ClearCustomSession()
{
Session.Remove("OrderNumber");
Session.Remove("OrderMidNumber");
Session.Remove("forDetailNumber");
Session.Remove("OrderNumber");
Session.Remove("OrderDetailsIDforModify");
Session.Remove("NumberID");
}
private List<OrderList> GetPageDataTable(List<OrderList> list)
{
int startIndex = (this.GetCurrentPage() - 1) * 10;
return list.Skip(startIndex).Take(10).ToList();
}
private int GetCurrentPage()
{
string pageText = Request.QueryString["Page"];
if (string.IsNullOrWhiteSpace(pageText))
return 1;
int intPage;
if (!int.TryParse(pageText, out intPage))
return 1;
if (intPage <= 0)
return 1;
return intPage;
}
protected void btnSelect_Click(object sender, EventArgs e)
{
var select = this.ddSelect.SelectedValue.ToString();
var selectInfo = this.txtSelect.Text;
if (select == "account")
{
var list = DrinkListManager.GetNowOrderingByAccount(selectInfo);
if (list.Count > 0) //check is empty data (大於0就做資料繫結)
{
var orderlist = this.GetPageDataTable(list);
this.ucPager.Totaluser = list.Count;
this.ucPager.BindUserList();
this.gvNoworderinglist.DataSource = orderlist;
this.gvNoworderinglist.DataBind();
}
else
{
this.lbMsg.Text = "找不到此篩選資料,請確認輸入是否正確";
this.gvNoworderinglist.Visible = false;
this.plcNoData.Visible = true;
}
}
if (select == "orderNumber")
{
var list = DrinkListManager.GetNowOrderingByOrderNumber(selectInfo);
if (list.Count > 0) //check is empty data (大於0就做資料繫結)
{
var orderlist = this.GetPageDataTable(list);
this.ucPager.Totaluser = list.Count;
this.ucPager.BindUserList();
this.gvNoworderinglist.DataSource = orderlist;
this.gvNoworderinglist.DataBind();
}
else
{
this.lbMsg.Text = "找不到此篩選資料,請確認輸入是否正確";
this.gvNoworderinglist.Visible = false;
this.plcNoData.Visible = true;
}
}
}
protected void btnSortingN_Click(object sender, EventArgs e)
{
var list = DrinkListManager.GetOrderByRtimeNowOrdering();
if (list.Count > 0)
{
var orderlist = this.GetPageDataTable(list);
this.ucPager.Totaluser = list.Count;
this.ucPager.BindUserList();
this.gvNoworderinglist.DataSource = orderlist;
this.gvNoworderinglist.DataBind();
}
else
{
this.gvNoworderinglist.Visible = false;
this.plcNoData.Visible = true;
}
}
protected void btnSortingF_Click(object sender, EventArgs e)
{
var list = DrinkListManager.GetOrderByOtimeNowOrdering();
if (list.Count > 0)
{
var orderlist = this.GetPageDataTable(list);
this.ucPager.Totaluser = list.Count;
this.ucPager.BindUserList();
this.gvNoworderinglist.DataSource = orderlist;
this.gvNoworderinglist.DataBind();
}
else
{
this.gvNoworderinglist.Visible = false;
this.plcNoData.Visible = true;
}
}
protected void btnClearSelect_Click(object sender, EventArgs e)
{
this.txtSelect.Visible = false;
this.btnSelect.Visible = false;
Response.Redirect("/ServerSide/SystemAdmin/NowOrdering.aspx");
var list = DrinkListManager.GetOrderListNoOrdering();
if (list.Count > 0) //check is empty data (大於0就做資料繫結)
{
var orderlist = this.GetPageDataTable(list);
this.ucPager.Totaluser = list.Count;
this.ucPager.BindUserList();
this.gvNoworderinglist.DataSource = orderlist;
this.gvNoworderinglist.DataBind();
}
else
{
this.gvNoworderinglist.Visible = false;
this.ucPager.Visible = false;
this.plcNoData.Visible = true;
this.lbMsg.Text = "目前沒有可跟團的清單";
}
}
protected void ddSelect_SelectedIndexChanged(object sender, EventArgs e)
{
this.txtSelect.Visible = true;
this.btnSelect.Visible = true;
}
}
}
|
||||
TheStack | e0ad0b04be0896f460f1a88a65ddfd01604d3ca2 | C#code:C# | {"size": 2068, "ext": "cs", "max_stars_repo_path": "testings/version-tests/release-3.0/src/DistParameters.cs", "max_stars_repo_name": "aruzicka555/Extension-Base-BDA", "max_stars_repo_stars_event_min_datetime": "2016-02-19T20:03:28.000Z", "max_stars_repo_stars_event_max_datetime": "2016-02-19T20:03:28.000Z", "max_issues_repo_path": "testings/version-tests/release-3.0/src/DistParameters.cs", "max_issues_repo_name": "aruzicka555/Extension-Base-BDA", "max_issues_repo_issues_event_min_datetime": "2017-03-01T01:36:24.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-10T06:03:22.000Z", "max_forks_repo_path": "testings/version-tests/release-3.0/src/DistParameters.cs", "max_forks_repo_name": "aruzicka555/Extension-Base-BDA", "max_forks_repo_forks_event_min_datetime": "2017-01-27T21:21:56.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-07T14:46:36.000Z"} | {"max_stars_count": 1.0, "max_issues_count": 4.0, "max_forks_count": 10.0, "avg_line_length": 27.2105263158, "max_line_length": 79, "alphanum_fraction": 0.4023210832} | // Copyright 2005-2010 Portland State University, University of Wisconsin
// Authors: Robert M. Scheller, James B. Domingo
using Edu.Wisc.Forest.Flel.Util;
namespace Landis.Extension.BaseBDA
{
public enum DisturbanceType {Wind, Fire, Harvest, Null};
/// <summary>
/// Extra Dist Paramaters
/// </summary>
public interface IDistParameters
{
int Duration{get;set;}
double DistModifier{get;set;}
}
}
namespace Landis.Extension.BaseBDA
{
public class DistParameters
: IDistParameters
{
private int duration;
private double distModifier;
//---------------------------------------------------------------------
public int Duration
{
get {
return duration;
}
set {
if (value < 0)
throw new InputValueException(value.ToString(),
"Value must be = or > 0.");
duration = value;
}
}
public double DistModifier
{
get {
return distModifier;
}
set {
if (value < -1.0 || value > 1.0)
throw new InputValueException(value.ToString(),
"Value must be > -1 and < 1.");
distModifier = value;
}
}
//---------------------------------------------------------------------
public DistParameters()
{
}
//---------------------------------------------------------------------
/*public DistParameters(int duration,
double distModifier
)
{
this.duration = duration;
this.distModifier = distModifier;
}
//---------------------------------------------------------------------
public DistParameters()
{
this.duration = 0;
this.distModifier = 0.0;
}*/
}
}
|
||||
TheStack | e0ad778f3fbe695f9f199afe81a3fd0b22e7def1 | C#code:C# | {"size": 5410, "ext": "cs", "max_stars_repo_path": "Source/Terminals/Data/FilePersisted/FavoritesXmlFile.cs", "max_stars_repo_name": "RisesunStudios/Terminals", "max_stars_repo_stars_event_min_datetime": "2017-04-07T03:38:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:48:59.000Z", "max_issues_repo_path": "Source/Terminals/Data/FilePersisted/FavoritesXmlFile.cs", "max_issues_repo_name": "RisesunStudios/Terminals", "max_issues_repo_issues_event_min_datetime": "2017-04-07T04:49:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-10T14:39:44.000Z", "max_forks_repo_path": "Source/Terminals/Data/FilePersisted/FavoritesXmlFile.cs", "max_forks_repo_name": "RisesunStudios/Terminals", "max_forks_repo_forks_event_min_datetime": "2017-04-07T01:25:11.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T19:05:32.000Z"} | {"max_stars_count": 1178.0, "max_issues_count": 242.0, "max_forks_count": 309.0, "avg_line_length": 41.2977099237, "max_line_length": 146, "alphanum_fraction": 0.6465804067} | using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
namespace Terminals.Data.FilePersisted
{
internal class FavoritesXmlFile
{
private const string FAVORITESINGROUP = "//t:FavoritesInGroup";
private readonly XmlNamespaceManager namespaceManager;
private readonly XDocument document;
private FavoritesXmlFile(XDocument document)
{
this.document = document;
this.namespaceManager = CreateNameSpaceManager();
}
private static XmlNamespaceManager CreateNameSpaceManager()
{
var nameSpaceManager = new XmlNamespaceManager(new NameTable());
nameSpaceManager.AddNamespace("t", "http://Terminals.codeplex.com");
nameSpaceManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
nameSpaceManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
return nameSpaceManager;
}
internal static FavoritesXmlFile LoadXmlDocument(string fileLocation)
{
var document = XDocument.Load(fileLocation);
return CreateDocument(document);
}
internal static FavoritesXmlFile CreateDocument(XDocument source)
{
return new FavoritesXmlFile(source);
}
internal UnknonwPluginElements RemoveUnknownFavorites(string[] availableProtocols)
{
IEnumerable<XElement> favorites = this.SelectElements("//t:Favorite");
List<XElement> unknownFavorites = favorites.Where(f => this.IsUnknownProtocol(f, availableProtocols)).ToList();
unknownFavorites.ForEach(f => f.Remove());
IEnumerable<XElement> groupMembership = this.SelectElements(FAVORITESINGROUP);
Dictionary<string, List<XElement>> unknownMemberships = this.FilterGroupMembeship(groupMembership, unknownFavorites);
return new UnknonwPluginElements(unknownFavorites, unknownMemberships);
}
private Dictionary<string, List<XElement>> FilterGroupMembeship(IEnumerable<XElement> favoritesInGroups, List<XElement> unknownFavorites)
{
string[] unknownFavoriteIds = unknownFavorites.Select(f => f.Attribute("id").Value).ToArray();
return favoritesInGroups.ToDictionary(FindGroupId, fg => this.FilterUnknownFavoritesForGroup(fg, unknownFavoriteIds));
}
private List<XElement> FilterUnknownFavoritesForGroup(XElement favoritesInGroup, string[] unknownFavoriteIds)
{
return favoritesInGroup.XPathSelectElements("//t:guid", this.namespaceManager)
.Where(guid => unknownFavoriteIds.Contains(guid.Value))
.Select(this.ExtractFavoriteGuid)
.ToList();
}
private XElement ExtractFavoriteGuid(XElement unknownFavorite)
{
unknownFavorite.Remove();
return unknownFavorite;
}
private bool IsUnknownProtocol(XElement favoriteElement, string[] availableProtocols)
{
var protocol = favoriteElement.XPathSelectElements("t:Protocol", this.namespaceManager).First();
return !availableProtocols.Contains(protocol.Value);
}
internal XmlReader CreateReader()
{
return this.document.CreateReader();
}
internal void AppenUnknownContent(UnknonwPluginElements unknownElements)
{
this.AppendUnknownFavorites(unknownElements.Favorites);
this.AppenUnknownGroupMembership(unknownElements.GroupMembership);
}
private void AppenUnknownGroupMembership(Dictionary<string, List<XElement>> unknownFavoritesInGroup)
{
foreach (XElement favoritesInGroup in this.SelectElements(FAVORITESINGROUP))
{
this.AddUnknownFavoritesToGroup(unknownFavoritesInGroup, favoritesInGroup);
}
}
private void AddUnknownFavoritesToGroup(Dictionary<string, List<XElement>> unknownFavoritesInGroup, XElement favoritesInGroup)
{
string groupId = FindGroupId(favoritesInGroup);
List<XElement> toAdd = null;
if (unknownFavoritesInGroup.TryGetValue(groupId, out toAdd))
{
// missing backslash is not a mistake: search inside the element.
XElement favorites = this.SelectElements(favoritesInGroup, "t:Favorites").First();
favorites.Add(toAdd);
}
}
private static string FindGroupId(XElement favoritesInGroup)
{
return favoritesInGroup.Attribute("groupId").Value;
}
private void AppendUnknownFavorites(List<XElement> unknownFavorites)
{
XElement favorites = this.SelectElements("//t:Favorites").First();
favorites.Add(unknownFavorites);
}
private IEnumerable<XElement> SelectElements(string filter)
{
return this.SelectElements(this.document, filter);
}
private IEnumerable<XElement> SelectElements(XNode target, string filter)
{
return target.XPathSelectElements(filter, this.namespaceManager);
}
}
} |
||||
TheStack | e0af86bf273d23b2890fb4a053dec3eebd6f6743 | C#code:C# | {"size": 942, "ext": "cs", "max_stars_repo_path": "Assets/Player/Scripts/BetterFall.cs", "max_stars_repo_name": "KevinBank/StickFightTheGameVerticalSlice", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Player/Scripts/BetterFall.cs", "max_issues_repo_name": "KevinBank/StickFightTheGameVerticalSlice", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Player/Scripts/BetterFall.cs", "max_forks_repo_name": "KevinBank/StickFightTheGameVerticalSlice", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 29.4375, "max_line_length": 129, "alphanum_fraction": 0.7006369427} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// this class makes the player fall faster so the falling feels a but more real
/// </summary>
[RequireComponent(typeof(ActiveRagdollLegContoller))]
public class BetterFall : MonoBehaviour
{
private ActiveRagdollLegContoller legController;
[Tooltip("The effected rigedbody")]
[SerializeField] private Rigidbody rigidbody;
[Range(0,2)]
[SerializeField] private float fallingVelocity;
// Start is called before the first frame update
void Awake()
{
legController = this.GetComponent<ActiveRagdollLegContoller>();
}
// Update is called once per frame
void FixedUpdate()
{
if (legController.InAir && rigidbody.velocity.y < 0)
{
rigidbody.velocity = new Vector3(rigidbody.velocity.x, rigidbody.velocity.y - fallingVelocity, rigidbody.velocity.z);
}
}
}
|
||||
TheStack | e0b1ce7ee7ff27ebe3c279ebcddeb734bb9a4afc | C#code:C# | {"size": 1504, "ext": "cs", "max_stars_repo_path": "4.OOPBasic/00_OOP-Basic-11.18/07_Polymorphism/Lab_02_Shapes/Circle.cs", "max_stars_repo_name": "Brankovanov/SoftUniCourses", "max_stars_repo_stars_event_min_datetime": "2018-07-17T07:43:49.000Z", "max_stars_repo_stars_event_max_datetime": "2018-07-17T07:43:49.000Z", "max_issues_repo_path": "4.OOPBasic/00_OOP-Basic-11.18/07_Polymorphism/Lab_02_Shapes/Circle.cs", "max_issues_repo_name": "Brankovanov/SoftUniCourses", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "4.OOPBasic/00_OOP-Basic-11.18/07_Polymorphism/Lab_02_Shapes/Circle.cs", "max_forks_repo_name": "Brankovanov/SoftUniCourses", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.0666666667, "max_line_length": 111, "alphanum_fraction": 0.4315159574} | using System;
namespace Lab_02_Shapes
{
public class Circle:Shape
{
private double radius;
public double Radius
{
get
{
return this.radius;
}
private set
{
this.radius = value;
}
}
public Circle(double radius)
{
this.Radius = radius;
}
public override double CalculateArea()
{
return Math.PI * Math.Pow(this.Radius, 2);
}
public override double CalculatePerimeter()
{
return 2 * Math.PI * this.Radius;
}
public override string Draw()
{
var drawing = string.Empty;
for(var diameter = 0; diameter<this.Radius*2;diameter++)
{
drawing += new string(' ', (int)this.Radius * 2 - diameter - 1) + '*'
+ new string(' ', diameter * 2) + '*'+new string(' ', (int)this.Radius * 2 - diameter - 1)
+ Environment.NewLine;
}
var counter = 0;
for(var diameter = this.Radius * 2; diameter>0; diameter--)
{
drawing += new string(' ', counter) + '*'
+ new string(' ', (int)diameter) + new string(' ', (int)diameter-1) +'*'
+ Environment.NewLine;
counter++;
}
return drawing;
}
}
}
|
||||
TheStack | e0b457e52a6c550f340ee5836776384bcdd96c81 | C#code:C# | {"size": 885, "ext": "cs", "max_stars_repo_path": "src/Shashlik.Sms/Options/SmsOptions.cs", "max_stars_repo_name": "dotnet-shashlik/shashlik", "max_stars_repo_stars_event_min_datetime": "2021-03-12T01:38:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-12T01:38:21.000Z", "max_issues_repo_path": "src/Shashlik.Sms/Options/SmsOptions.cs", "max_issues_repo_name": "dotnet-shashlik/shashlik", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Shashlik.Sms/Options/SmsOptions.cs", "max_forks_repo_name": "dotnet-shashlik/shashlik", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 23.9189189189, "max_line_length": 95, "alphanum_fraction": 0.5118644068} | using System.Collections.Generic;
using Shashlik.Kernel.Attributes;
namespace Shashlik.Sms.Options
{
/// <summary>
/// 短信配置
/// </summary>
[AutoOptions("Shashlik.Sms")]
public class SmsOptions
{
/// <summary>
/// 是否启用
/// </summary>
public bool Enable { get; set; } = true;
/// <summary>
/// 使用空短信,不真实发送
/// </summary>
public bool UseEmptySms { get; set; }
/// <summary>
/// 批量发送最大手机数量
/// </summary>
public int BatchMax { get; set; } = 1000;
/// <summary>
/// 短信发送限制
/// </summary>
public List<SmsLimitConfig> Limits { get; set; } = new List<SmsLimitConfig>();
/// <summary>
/// 短信配置
/// </summary>
public List<SmsDomainConfig> DomainConfigs { get; set; } = new List<SmsDomainConfig>();
}
} |
||||
TheStack | e0b45fa8f65cfcbb89488742b9fd76e24cc74f14 | C#code:C# | {"size": 800, "ext": "cs", "max_stars_repo_path": "MongoDBDriver/Binary.cs", "max_stars_repo_name": "sunnanking/mongodb-csharp", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "MongoDBDriver/Binary.cs", "max_issues_repo_name": "sunnanking/mongodb-csharp", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "MongoDBDriver/Binary.cs", "max_forks_repo_name": "sunnanking/mongodb-csharp", "max_forks_repo_forks_event_min_datetime": "2021-02-16T11:58:31.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-16T11:58:31.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 23.5294117647, "max_line_length": 80, "alphanum_fraction": 0.4975} | using System;
using System.Collections.Generic;
using System.Text;
namespace MongoDB.Driver
{
public class Binary{
public enum TypeCode:byte{
Unknown = 0,
General = 2,
// Uuid is now replaced by Guid
//Uuid = 3,
Md5 = 5,
UserDefined = 80
}
public byte[] Bytes{get;set;}
public Binary.TypeCode Subtype{get;set;}
public Binary() { }
public Binary(byte[] value){
this.Bytes = value;
this.Subtype = TypeCode.General;
}
public override string ToString (){
return String.Format(@"{{ ""$binary"": ""{0}"", ""$type"" : {1} }}",
Convert.ToBase64String(Bytes), (int)Subtype);
}
}
}
|
||||
TheStack | e0b460c80325f6fb27fb99999429db4e210ca816 | C#code:C# | {"size": 2057, "ext": "cs", "max_stars_repo_path": "src/Steam.Models/DOTA2/MatchDetailModel.cs", "max_stars_repo_name": "Jcw87/SteamWebAPI2", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Steam.Models/DOTA2/MatchDetailModel.cs", "max_issues_repo_name": "Jcw87/SteamWebAPI2", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Steam.Models/DOTA2/MatchDetailModel.cs", "max_forks_repo_name": "Jcw87/SteamWebAPI2", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 27.0657894737, "max_line_length": 111, "alphanum_fraction": 0.6368497812} | using System;
using System.Collections.Generic;
namespace Steam.Models.DOTA2
{
public class MatchDetailModel
{
public IReadOnlyCollection<MatchPlayerModel> Players { get; set; }
public bool RadiantWin { get; set; }
public uint Duration { get; set; }
public DateTime StartTime { get; set; }
public ulong MatchId { get; set; }
public ulong MatchSequenceNumber { get; set; }
public uint TowerStatusRadiant { get; set; }
public TowerState TowerStatesRadiant { get { return new TowerState(TowerStatusRadiant); } }
public uint TowerStatusDire { get; set; }
public TowerState TowerStatesDire { get { return new TowerState(TowerStatusDire); } }
public uint BarracksStatusRadiant { get; set; }
public BarracksState BarracksStatesRadiant { get { return new BarracksState(BarracksStatusRadiant); } }
public uint BarracksStatusDire { get; set; }
public BarracksState BarracksStatesDire { get { return new BarracksState(BarracksStatusDire); } }
public uint Cluster { get; set; }
public uint FirstBloodTime { get; set; }
public uint LobbyType { get; set; }
public uint HumanPlayers { get; set; }
public uint LeagueId { get; set; }
public uint PositiveVotes { get; set; }
public uint NegativeVotes { get; set; }
public uint GameMode { get; set; }
public uint Engine { get; set; }
public uint RadiantTeamId { get; set; }
public string RadiantName { get; set; }
public ulong RadiantLogo { get; set; }
public uint RadiantTeamComplete { get; set; }
public uint DireTeamId { get; set; }
public string DireName { get; set; }
public ulong DireLogo { get; set; }
public uint DireTeamComplete { get; set; }
public uint RadiantCaptain { get; set; }
public uint DireCaptain { get; set; }
public IReadOnlyCollection<MatchPickBanModel> PicksAndBans { get; set; }
}
} |
||||
TheStack | e0b5c73ad4e0132ed72696228fe6a70e02851639 | C#code:C# | {"size": 3704, "ext": "cs", "max_stars_repo_path": "test/Test.Utility/ExceptionAssert.cs", "max_stars_repo_name": "Zaretto/NuGet", "max_stars_repo_stars_event_min_datetime": "2015-08-15T10:15:39.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-28T22:01:42.000Z", "max_issues_repo_path": "test/Test.Utility/ExceptionAssert.cs", "max_issues_repo_name": "Zaretto/NuGet", "max_issues_repo_issues_event_min_datetime": "2015-08-16T05:54:33.000Z", "max_issues_repo_issues_event_max_datetime": "2018-03-04T15:34:26.000Z", "max_forks_repo_path": "test/Test.Utility/ExceptionAssert.cs", "max_forks_repo_name": "Zaretto/NuGet", "max_forks_repo_forks_event_min_datetime": "2015-08-16T05:37:00.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T11:38:49.000Z"} | {"max_stars_count": 96.0, "max_issues_count": 59.0, "max_forks_count": 92.0, "avg_line_length": 43.0697674419, "max_line_length": 167, "alphanum_fraction": 0.6368790497} | using System;
using System.IO;
using Xunit;
namespace NuGet.Test
{
public static class ExceptionAssert
{
public static void Throws<TException>(Assert.ThrowsDelegate act) where TException : Exception
{
Throws<TException>(act, ex => { });
}
public static void Throws<TException>(Assert.ThrowsDelegate act, Action<TException> condition) where TException : Exception
{
Exception ex = Record.Exception(act);
Assert.NotNull(ex);
TException tex = Assert.IsAssignableFrom<TException>(ex);
condition(tex);
}
public static void Throws<TException>(Assert.ThrowsDelegate action, string expectedMessage) where TException : Exception
{
Throws<TException>(action, ex => Assert.Equal(expectedMessage, ex.Message));
}
public static void ThrowsArgNull(Assert.ThrowsDelegate act, string paramName)
{
Throws<ArgumentNullException>(act, ex => Assert.Equal(paramName, ex.ParamName));
}
public static void ThrowsArgNullOrEmpty(Assert.ThrowsDelegate act, string paramName)
{
ThrowsArgumentException<ArgumentException>(act, paramName, CommonResources.Argument_Cannot_Be_Null_Or_Empty);
}
public static void ThrowsArgOutOfRange(Assert.ThrowsDelegate act, string paramName, object minimum, object maximum, bool equalAllowed)
{
ThrowsArgumentException<ArgumentOutOfRangeException>(act, paramName, BuildOutOfRangeMessage(paramName, minimum, maximum, equalAllowed));
}
private static string BuildOutOfRangeMessage(string paramName, object minimum, object maximum, bool equalAllowed)
{
if (minimum == null)
{
return String.Format(equalAllowed ? CommonResources.Argument_Must_Be_LessThanOrEqualTo : CommonResources.Argument_Must_Be_LessThan, maximum);
}
else if (maximum == null)
{
return String.Format(equalAllowed ? CommonResources.Argument_Must_Be_GreaterThanOrEqualTo : CommonResources.Argument_Must_Be_GreaterThan, minimum);
}
else
{
return String.Format(CommonResources.Argument_Must_Be_Between, minimum, maximum);
}
}
public static void ThrowsArgumentException(Assert.ThrowsDelegate act, string message)
{
ThrowsArgumentException<ArgumentException>(act, message);
}
public static void ThrowsArgumentException<TArgException>(Assert.ThrowsDelegate act, string message) where TArgException : ArgumentException
{
Throws<TArgException>(act, ex => Assert.Equal(message, ex.Message));
}
public static void ThrowsArgumentException(Assert.ThrowsDelegate act, string paramName, string message)
{
ThrowsArgumentException<ArgumentException>(act, paramName, message);
}
public static void ThrowsArgumentException<TArgException>(Assert.ThrowsDelegate act, string paramName, string message) where TArgException : ArgumentException
{
Throws<TArgException>(act, ex =>
{
Assert.Equal(paramName, ex.ParamName);
var lines = ex.Message.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
Assert.Equal(2, lines.Length);
Assert.Equal(message, lines[0]);
Assert.True(lines[1].EndsWith(paramName));
});
}
}
}
|
||||
TheStack | e0b5e0d581ec7a6dc838f94ff28f81964beaf990 | C#code:C# | {"size": 3520, "ext": "cs", "max_stars_repo_path": "src/Extensions/Editors/GeneratorError.cs", "max_stars_repo_name": "pashcovich/More", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Extensions/Editors/GeneratorError.cs", "max_issues_repo_name": "pashcovich/More", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Extensions/Editors/GeneratorError.cs", "max_forks_repo_name": "pashcovich/More", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 33.5238095238, "max_line_length": 117, "alphanum_fraction": 0.53125} | namespace More.VisualStudio.Editors
{
using System;
using System.Diagnostics.Contracts;
/// <summary>
/// Represents a warning and error provided to the project system.
/// </summary>
public sealed class GeneratorError
{
private readonly string message;
private readonly int? line;
private readonly int? column;
private GeneratorError( string message, int? line, int? column )
{
this.message = message;
this.line = line;
this.column = column;
}
/// <summary>
/// Initializes a new instance of the <see cref="GeneratorError"/> class.
/// </summary>
/// <param name="message">The error message.</param>
public GeneratorError( string message )
: this( message, null, null )
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GeneratorError"/> class.
/// </summary>
/// <param name="message">The error message.</param>
/// <param name="line">The zero-based line number where the error occurred.</param>
public GeneratorError( string message, int line )
: this( message, new int?( line ), null )
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GeneratorError"/> class.
/// </summary>
/// <param name="message">The error message.</param>
/// <param name="line">The zero-based line number where the error occurred.</param>
/// <param name="column">The zero-based column number where the error occurred.</param>
public GeneratorError( string message, int line, int column )
: this( message, new int?( line ), new int?( column ) )
{
Arg.NotNullOrEmpty( message, nameof( message ) );
Arg.GreaterThanOrEqualTo( line, 0, nameof( line ) );
Arg.GreaterThanOrEqualTo( column, 0, nameof( column ) );
}
/// <summary>
/// Gets or sets whether the error is a warning.
/// </summary>
/// <value>True if the error is a warning; otherwise, false. The default value is <c>false</c>.</value>
public bool IsWarning
{
get;
set;
}
/// <summary>
/// Gets the warning or error message.
/// </summary>
/// <value>The warning or error message.</value>
public string Message
{
get
{
Contract.Ensures( !string.IsNullOrEmpty( message ) );
return message;
}
}
/// <summary>
/// Gets the zero-based line number where the error occurred, if any.
/// </summary>
/// <value>The line number where the error occurred or <c>null</c> if the line number is unknown.</value>
public int? Line
{
get
{
Contract.Ensures( line == null || line.Value >= 0 );
return line;
}
}
/// <summary>
/// Gets the zero-based column number where the error occurred, if any.
/// </summary>
/// <value>The column number where the error occurred or <c>null</c> if the column number is unknown.</value>
public int? Column
{
get
{
Contract.Ensures( column == null || column.Value >= 0 );
return column;
}
}
}
}
|
||||
TheStack | e0b62c19c65f7b84fecd1ab9ef2cab109c115990 | C#code:C# | {"size": 322, "ext": "cs", "max_stars_repo_path": "src/Migrator.Core/Issue/Containers/IssueOutput.cs", "max_stars_repo_name": "Kentico/newsletter-migrator", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/Migrator.Core/Issue/Containers/IssueOutput.cs", "max_issues_repo_name": "Kentico/newsletter-migrator", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Migrator.Core/Issue/Containers/IssueOutput.cs", "max_forks_repo_name": "Kentico/newsletter-migrator", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 20.125, "max_line_length": 46, "alphanum_fraction": 0.6708074534} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Migrator.Core
{
public class IssueOutput
{
public Guid IssueGuid { get; set; }
public Guid TemplateGuid { get; set; }
public string Widgets { get; set; }
}
}
|
||||
TheStack | e0b7506245958434820acd7b8c5a454525ce6dfc | C#code:C# | {"size": 2088, "ext": "cs", "max_stars_repo_path": "Semester2/Test2/2.2/2.2.Tests/ListIntBubbleSortTests.cs", "max_stars_repo_name": "yuniyakim/Homework", "max_stars_repo_stars_event_min_datetime": "2019-03-30T17:45:08.000Z", "max_stars_repo_stars_event_max_datetime": "2019-03-30T17:45:08.000Z", "max_issues_repo_path": "Semester2/Test2/2.2/2.2.Tests/ListIntBubbleSortTests.cs", "max_issues_repo_name": "yuniyakim/Homework", "max_issues_repo_issues_event_min_datetime": "2019-04-13T14:23:47.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-07T01:35:00.000Z", "max_forks_repo_path": "Semester2/Test2/2.2/2.2.Tests/ListIntBubbleSortTests.cs", "max_forks_repo_name": "yuniyakim/Homework", "max_forks_repo_forks_event_min_datetime": "2019-04-12T14:34:20.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-12T14:34:20.000Z"} | {"max_stars_count": 1.0, "max_issues_count": 2.0, "max_forks_count": 1.0, "avg_line_length": 25.4634146341, "max_line_length": 84, "alphanum_fraction": 0.4559386973} | using System;
using System.Collections.Generic;
using NUnit.Framework;
namespace _2._2
{
public class ListIntBubbleSortTests
{
private List<int> list;
private BubbleSort bubbleSort;
/// <summary>
/// Int comparer
/// </summary>
public class IntComparer : IComparer<int>
{
public int Compare(int element1, int element2)
{
return (element1 > element2) ? 1 : ((element1 < element2) ? -1 : 0);
}
}
[SetUp]
public void SetUp()
{
list = new List<int>();
bubbleSort = new BubbleSort();
}
[Test]
public void ListIntBubbleSortTest()
{
list.Add(4);
list.Add(8);
list.Add(-10);
list.Add(3);
list.Add(5);
list.Add(11);
list.Add(0);
list.Add(4);
var sortedList = new List<int>();
sortedList.Add(-10);
sortedList.Add(0);
sortedList.Add(3);
sortedList.Add(4);
sortedList.Add(4);
sortedList.Add(5);
sortedList.Add(8);
sortedList.Add(11);
var newlist = bubbleSort.Sort<int>(list, new IntComparer());
for (int i = 0; i < list.Count; ++i)
{
Assert.AreEqual(sortedList[i], newlist[i]);
}
}
[Test]
public void AnotherListIntBubbleSortTest()
{
list.Add(5);
list.Add(4);
list.Add(3);
list.Add(2);
list.Add(1);
var sortedList = new List<int>();
sortedList.Add(1);
sortedList.Add(2);
sortedList.Add(3);
sortedList.Add(4);
sortedList.Add(5);
var newlist = bubbleSort.Sort<int>(list, new IntComparer());
for (int i = 0; i < list.Count; ++i)
{
Assert.AreEqual(sortedList[i], newlist[i]);
}
}
}
} |
||||
TheStack | bd86c07b2f126a7fc904385f7537b04078ae5b34 | C#code:C# | {"size": 1894, "ext": "cs", "max_stars_repo_path": "src/EntityDb.Common.Tests/Implementations/Queries/EntityIdQuery.cs", "max_stars_repo_name": "entitydb-io/EntityDb", "max_stars_repo_stars_event_min_datetime": "2021-06-24T21:48:17.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-10T20:25:18.000Z", "max_issues_repo_path": "src/EntityDb.Common.Tests/Implementations/Queries/EntityIdQuery.cs", "max_issues_repo_name": "entitydb-io/EntityDb.NET", "max_issues_repo_issues_event_min_datetime": "2021-06-02T19:50:59.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T00:59:50.000Z", "max_forks_repo_path": "src/EntityDb.Common.Tests/Implementations/Queries/EntityIdQuery.cs", "max_forks_repo_name": "entitydb-io/EntityDb", "max_forks_repo_forks_event_min_datetime": "2021-10-03T05:51:07.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-03T05:51:07.000Z"} | {"max_stars_count": 3.0, "max_issues_count": 16.0, "max_forks_count": 1.0, "avg_line_length": 28.2686567164, "max_line_length": 108, "alphanum_fraction": 0.6013727561} | using EntityDb.Abstractions.Queries;
using EntityDb.Abstractions.Queries.FilterBuilders;
using EntityDb.Abstractions.Queries.SortBuilders;
using System;
namespace EntityDb.Common.Tests.Implementations.Queries
{
public record EntityIdQuery(Guid EntityId) : IAgentSignatureQuery, ICommandQuery, ILeaseQuery, ITagQuery
{
public TFilter GetFilter<TFilter>(ICommandFilterBuilder<TFilter> builder)
{
return builder.EntityIdIn(EntityId);
}
public TSort GetSort<TSort>(ICommandSortBuilder<TSort> builder)
{
return builder.Combine
(
builder.EntityId(true),
builder.EntityVersionNumber(true)
);
}
public TFilter GetFilter<TFilter>(ILeaseFilterBuilder<TFilter> builder)
{
return builder.EntityIdIn(EntityId);
}
public TSort GetSort<TSort>(ILeaseSortBuilder<TSort> builder)
{
return builder.Combine
(
builder.EntityId(true),
builder.EntityVersionNumber(true)
);
}
public TFilter GetFilter<TFilter>(IAgentSignatureFilterBuilder<TFilter> builder)
{
return builder.EntityIdsIn(EntityId);
}
public TSort GetSort<TSort>(IAgentSignatureSortBuilder<TSort> builder)
{
return builder.EntityIds(true);
}
public int? Skip => null;
public int? Take => null;
public TFilter GetFilter<TFilter>(ITagFilterBuilder<TFilter> builder)
{
return builder.EntityIdIn(EntityId);
}
public TSort GetSort<TSort>(ITagSortBuilder<TSort> builder)
{
return builder.Combine
(
builder.EntityId(true),
builder.EntityVersionNumber(true)
);
}
}
}
|
||||
TheStack | bd873dfdb4f89dfc14ee84c5a78f72d62cc67f5c | C#code:C# | {"size": 870, "ext": "cs", "max_stars_repo_path": "src/PlatformFramework/Localization/LocalizationExtensions.cs", "max_stars_repo_name": "vermilion/Dot", "max_stars_repo_stars_event_min_datetime": "2020-08-07T10:10:11.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-07T10:10:11.000Z", "max_issues_repo_path": "src/PlatformFramework/Localization/LocalizationExtensions.cs", "max_issues_repo_name": "vermilion/PlatformFramework", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/PlatformFramework/Localization/LocalizationExtensions.cs", "max_forks_repo_name": "vermilion/PlatformFramework", "max_forks_repo_forks_event_min_datetime": "2021-06-01T00:44:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-01T00:44:10.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 27.1875, "max_line_length": 89, "alphanum_fraction": 0.5977011494} | using System.Globalization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
namespace PlatformFramework.Localization
{
public static class LocalizationExtensions
{
public static void AddNullLocalization(this IServiceCollection services)
{
services.AddSingleton<IStringLocalizerFactory, NullStringLocalizerFactory>();
}
public static bool IsValidCultureName(this string cultureName)
{
if (string.IsNullOrWhiteSpace(cultureName))
{
return false;
}
try
{
var cultureInfo = CultureInfo.GetCultureInfo(cultureName);
return true;
}
catch (CultureNotFoundException)
{
return false;
}
}
}
} |
||||
TheStack | bd89d1b6a8d95cd08cfba9eda87ce84d10f81654 | C#code:C# | {"size": 2192, "ext": "cs", "max_stars_repo_path": "src/DurableTask.Core/Common/DateTimeUtils.cs", "max_stars_repo_name": "mnadeau2/durabletask", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/DurableTask.Core/Common/DateTimeUtils.cs", "max_issues_repo_name": "mnadeau2/durabletask", "max_issues_repo_issues_event_min_datetime": "2018-05-10T20:49:17.000Z", "max_issues_repo_issues_event_max_datetime": "2018-05-10T20:50:25.000Z", "max_forks_repo_path": "src/DurableTask.Core/Common/DateTimeUtils.cs", "max_forks_repo_name": "mnadeau2/durabletask", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": null, "avg_line_length": 39.8545454545, "max_line_length": 99, "alphanum_fraction": 0.5967153285} | // ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace DurableTask.Core.Common
{
using System;
using System.Reflection;
/// <summary>
/// Extension methods for DateTime
/// </summary>
public static class DateTimeUtils
{
/// <summary>
/// Returns bool indicating is the datetime has a value set
/// </summary>
public static bool IsSet(this DateTime dateTime)
{
if (dateTime == null)
{
return false;
}
return !(dateTime == DateTime.MinValue || dateTime == MinDateTime);
}
/// <summary>
/// Returns minimum allowable DateTime, allows overrdiing this for the storage emulator.
/// The Storage emulator supports a min datetime or DateTime.FromFileTimeUtc(0)
/// </summary>
public static readonly DateTime MinDateTime = DateTime.MinValue;
/// <summary>
/// Uses reflection to alter the static readonly MinDateTime value for tests
/// </summary>
public static void SetMinDateTimeForStorageEmulator()
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.Static;
Type settingsType = typeof(DateTimeUtils);
FieldInfo field = settingsType.GetField(nameof(DateTimeUtils.MinDateTime), flags);
field?.SetValue(settingsType, DateTime.FromFileTimeUtc(0));
}
}
}
|
||||
TheStack | bd8a4df08802921492719fe2cae04712f3900309 | C#code:C# | {"size": 3576, "ext": "cs", "max_stars_repo_path": "Acrux.Html/Specialized/Html401/OptionSelector.cs", "max_stars_repo_name": "AcruxSoftware/Acrux.Html", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Acrux.Html/Specialized/Html401/OptionSelector.cs", "max_issues_repo_name": "AcruxSoftware/Acrux.Html", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Acrux.Html/Specialized/Html401/OptionSelector.cs", "max_forks_repo_name": "AcruxSoftware/Acrux.Html", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 39.7333333333, "max_line_length": 305, "alphanum_fraction": 0.6238814318} | using System;
using System.Collections.Generic;
using System.Text;
namespace Acrux.Html.Specialized.Html401
{
/// <summary>
/// <!ELEMENT SELECT - - (OPTGROUP|OPTION)+ -- option selector -->
/// <!ATTLIST SELECT
/// %attrs; -- %coreattrs, %i18n, %events --
/// name CDATA #IMPLIED -- field name --
/// size NUMBER #IMPLIED -- rows visible --
/// multiple (multiple) #IMPLIED -- default is single selection --
/// disabled (disabled) #IMPLIED -- unavailable in this context --
/// tabindex NUMBER #IMPLIED -- position in tabbing order --
/// onfocus %Script; #IMPLIED -- the element got the focus --
/// onblur %Script; #IMPLIED -- the element lost the focus --
/// onchange %Script; #IMPLIED -- the element value was changed --
/// >
///
///
/// Attribute definitions
///
/// name = cdata [CI]
/// This attribute assigns the control name.
/// size = number [CN]
/// If a SELECT element is presented as a scrolled list box, this attribute specifies the number of rows in the list that should be visible at the same time. Visual user agents are not required to present a SELECT element as a list box; they may use any other mechanism, such as a drop-down menu.
/// multiple [CI]
/// If set, this boolean attribute allows multiple selections. If not set, the SELECT element only permits single selections.
///
/// Attributes defined elsewhere
///
/// id, class (document-wide identifiers)
/// lang (language information), dir (text direction)
/// title (element title)
/// style (inline style information)
/// disabled (disabled input controls)
/// tabindex (tabbing navigation)
/// onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup (intrinsic events)
///
/// </summary>
[HtmlTagAttributesMapper(TagName = "SELECT")]
public sealed class OptionSelector : HtmlElement
{
internal OptionSelector(string prefix, string localName, string namespaceURI, HtmlDocument doc, bool isEmptyTag, NodePosition parsedPosition)
: base(prefix, localName, namespaceURI, doc, isEmptyTag, parsedPosition)
{ }
#region Structure Definition
internal override ElementClosingTagRequirement ClosingTagRequirement
{ get { return ElementClosingTagRequirement.Required; } }
internal override bool AllowNestedElements
{ get { return false; } }
internal override bool IsHeadLevelElement
{ get { return false; } }
internal override bool IsInlineElement
{ get { return false; } }
internal override bool IsStructureModuleElement
{ get { return false; } }
internal override OptionalClosingTagType OptionalClosingTagMode
{ get { return OptionalClosingTagType.None; } }
internal override string[] OptionalClosingTagSpecifiedTags
{ get { return null; } }
private static List<string> s_ResetTags = new List<string>(new string[] {
});
private static List<string> s_IgnoreTags = new List<string>(new string[] {
});
internal override List<string> ResetTags
{ get { return s_ResetTags; } }
internal override List<string> IgnoreTags
{ get { return s_IgnoreTags; } }
#endregion
}
}
|
||||
TheStack | bd8b66ac026653b894a1d934fd25930dd201597c | C#code:C# | {"size": 65939, "ext": "cs", "max_stars_repo_path": "JilTests/DynamicSerializationTests.cs", "max_stars_repo_name": "TheXenocide/Jil", "max_stars_repo_stars_event_min_datetime": "2015-12-25T06:16:52.000Z", "max_stars_repo_stars_event_max_datetime": "2016-05-26T07:44:32.000Z", "max_issues_repo_path": "JilTests/DynamicSerializationTests.cs", "max_issues_repo_name": "sunxiaotianmg/Jil", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "JilTests/DynamicSerializationTests.cs", "max_forks_repo_name": "sunxiaotianmg/Jil", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 44.1063545151, "max_line_length": 3596, "alphanum_fraction": 0.4602132274} | using Jil;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Text;
using System.Globalization;
using Xunit;
namespace JilTests
{
public class DynamicSerializationTests
{
[Fact]
public void ToStringJSON()
{
{
var dyn = JSON.DeserializeDynamic("{\"Hello\":1}");
var res = dyn.ToString();
var shouldMatch = JSON.Serialize(new { Hello = 1 }, Options.ISO8601PrettyPrint);
Assert.Equal(shouldMatch, res);
}
{
var dyn1 = JSON.DeserializeDynamic(long.MaxValue.ToString(CultureInfo.InvariantCulture));
var dyn2 = JSON.DeserializeDynamic(ulong.MaxValue.ToString(CultureInfo.InvariantCulture));
var dyn3 = JSON.DeserializeDynamic(long.MinValue.ToString(CultureInfo.InvariantCulture));
var res1 = dyn1.ToString();
var res2 = dyn2.ToString();
var res3 = dyn3.ToString();
Assert.Equal(long.MaxValue.ToString(CultureInfo.InvariantCulture), res1);
Assert.Equal(ulong.MaxValue.ToString(CultureInfo.InvariantCulture), res2);
Assert.Equal(long.MinValue.ToString(CultureInfo.InvariantCulture), res3);
}
{
var dyn = JSON.DeserializeDynamic("1.23456");
var res = dyn.ToString();
Assert.Equal("1.23456", res);
}
{
var dyn1 = JSON.DeserializeDynamic("true");
var dyn2 = JSON.DeserializeDynamic("false");
var res1 = dyn1.ToString();
var res2 = dyn2.ToString();
Assert.Equal("true", res1);
Assert.Equal("false", res2);
}
{
var now = DateTime.UtcNow;
var str = JSON.Serialize(now, Options.ISO8601);
var dyn = JSON.DeserializeDynamic(str, Options.ISO8601);
var res = dyn.ToString();
Assert.Equal(str, res);
}
{
var g = Guid.NewGuid();
var str = JSON.Serialize(g);
var dyn = JSON.DeserializeDynamic(str);
var res = dyn.ToString();
Assert.Equal(str, res);
}
{
var dyn = JSON.DeserializeDynamic("\"how are you today?\"");
var str = dyn.ToString();
Assert.Equal("\"how are you today?\"", str);
}
{
var dyn1 = JSON.DeserializeDynamic("[1,2,3]");
var dyn2 = JSON.DeserializeDynamic("[]");
var dyn3 = JSON.DeserializeDynamic("[1, \"hello\", {}, 456]");
var res1 = dyn1.ToString();
var res2 = dyn2.ToString();
var res3 = dyn3.ToString();
var shouldMatch1 = JSON.Serialize(new[] { 1, 2, 3 }, Options.ISO8601PrettyPrint);
var shouldMatch2 = JSON.Serialize(new object[0], Options.ISO8601PrettyPrint);
var shouldMatch3 =
"[" +
JSON.Serialize(1, Options.ISO8601PrettyPrint) +
", " +
JSON.Serialize("hello", Options.ISO8601PrettyPrint) +
", " +
JSON.Serialize(new { }, Options.ISO8601PrettyPrint) +
", " +
JSON.Serialize(456, Options.ISO8601PrettyPrint) +
"]";
Assert.Equal(shouldMatch1, res1);
Assert.Equal(shouldMatch2, res2);
Assert.Equal(shouldMatch3, res3);
}
}
[Fact]
public void HeterogenousCollection()
{
using (var str = new StringWriter())
{
var dict = (dynamic)new ExpandoObject();
dict.Fizz = "Buzz";
var arr = new object[] { 123, "hello", new { Foo = "bar" }, dict };
JSON.SerializeDynamic(arr, str);
var res = str.ToString();
Assert.Equal("[123,\"hello\",{\"Foo\":\"bar\"},{\"Fizz\":\"Buzz\"}]", res);
}
}
[Fact]
public void Objects()
{
using (var str = new StringWriter())
{
var dict = (dynamic)new ExpandoObject();
dict.Foo = 123;
dict.Bar = "hello";
JSON.SerializeDynamic(dict, str);
var res = str.ToString();
Assert.Equal("{\"Foo\":123,\"Bar\":\"hello\"}", res);
}
}
[Fact]
public void Simple()
{
using (var str = new StringWriter())
{
JSON.SerializeDynamic(123, str);
var res = str.ToString();
Assert.Equal("123", res);
}
using (var str = new StringWriter())
{
JSON.SerializeDynamic("hello", str);
var res = str.ToString();
Assert.Equal("\"hello\"", res);
}
using (var str = new StringWriter())
{
JSON.SerializeDynamic(null, str);
var res = str.ToString();
Assert.Equal("null", res);
}
using (var str = new StringWriter())
{
var now = DateTime.UtcNow;
JSON.SerializeDynamic(now, str);
var res = str.ToString();
var dt = JSON.Deserialize<DateTime>(res);
Assert.True((now - dt).Duration() < TimeSpan.FromMilliseconds(1));
}
}
#region PersonElasticMigration methods and types
static dynamic Describe(Type t, string memberName)
{
if (Nullable.GetUnderlyingType(t) != null)
{
return Describe(Nullable.GetUnderlyingType(t), memberName);
}
if (t == typeof(string) || t == typeof(Guid))
{
return new
{
type = "string",
index = memberName == "Id" ? "not_analyzed" : "no"
};
}
if (t == typeof(int))
{
return new
{
type = "integer",
index = "no"
};
}
if (t == typeof(long))
{
return new
{
type = "long",
index = "no"
};
}
if (t == typeof(float))
{
return new
{
type = "float",
index = "no"
};
}
if (t == typeof(DateTime))
{
return new
{
type = "date",
format = "dateOptionalTime",
index = "no"
};
}
if (t.IsValueType()) throw new Exception("Unexpected valuetype: " + t.Name);
if (t.IsGenericType() && t.GetGenericTypeDefinition() == typeof(List<>))
{
return Describe(t.GetGenericArguments()[0], "--array--");
}
var ret = new Dictionary<string, dynamic>();
var properties = new Dictionary<string, dynamic>();
foreach (var prop in t.GetProperties())
{
var propName = prop.Name;
var propType = prop.PropertyType;
properties[propName] = Describe(propType, propName);
}
ret["properties"] = properties;
if (memberName == "--root--")
{
ret["dynamic"] = "strict";
ret["_all"] = new { enabled = false };
}
else
{
// can't specify type on the root; I guess object is implicit?
ret["type"] = "object";
}
return ret;
}
public class Person
{
public Guid Id { get; set; }
public MostRecentLocation MostRecentLocation { get; set; }
public List<Location> Locations { get; set; }
public List<InterestingTag> InterestingTags { get; set; }
public List<PersonIdentifier> Identifiers { get; set; }
public List<InterestingSite> InterestingSites { get; set; }
public List<TagView> TagViews { get; set; }
public List<DeveloperKind> DeveloperKinds { get; set; }
public List<Demographic> Demographics { get; set; }
public List<Education> Educations { get; set; }
public List<Industry> Industries { get; set; }
public List<Language> Languages { get; set; }
public List<WorkingHour> WorkingHours { get; set; }
public DateTime? LastSeen { get; set; }
public List<Merge> Merges { get; set; }
}
public class MostRecentLocation
{
public float Latitude { get; set; }
public float Longitude { get; set; }
public DateTime LastSeenDate { get; set; }
}
public class Location
{
public class LocationGeoPoint
{
public float Latitude { get; set; }
public float Longitude { get; set; }
}
public string CountryCode { get; set; }
public int LocType { get; set; }
public DateTime OnDate { get; set; }
public int SeenCount { get; set; }
public LocationGeoPoint GeoPoint { get; set; }
public string Name { get; set; }
}
public class InterestingTag
{
public int SiteId { get; set; }
public int TagId { get; set; }
public float Confidence { get; set; }
}
public class PersonIdentifier
{
public string Id { get; set; }
public int IdType { get; set; }
}
public class InterestingSite
{
public int SiteId { get; set; }
public float InterestLevel { get; set; }
}
public class TagView
{
public int SiteId { get; set; }
public int TagId { get; set; }
public long TimesViewed { get; set; }
}
public class DeveloperKind
{
public int DevType { get; set; }
public float RelativeScore { get; set; }
}
public class Demographic
{
[JilDirective(Ignore = true)]
public Guid PersonId { get; set; }
public int DeviceTypeId { get; set; }
public int BrowserId { get; set; }
public int OsId { get; set; }
public DateTime OnDate { get; set; }
public int SeenCount { get; set; }
}
public class Education
{
public string Tld { get; set; }
public string Name { get; set; }
public DateTime OnDate { get; set; }
public int SeenCount { get; set; }
public int SourceId { get; set; }
}
public class Industry
{
public Guid PersonId { get; set; }
public int IndustryId { get; set; }
public DateTime OnDate { get; set; }
public int SeenCount { get; set; }
}
public class Language
{
public string LanguageCode { get; set; }
public int LangSource { get; set; }
public DateTime OnDate { get; set; }
public int SeenCount { get; set; }
}
public class WorkingHour
{
public int Hour { get; set; }
public long Count { get; set; }
}
public class Merge
{
public Guid DestroyedPersonId { get; set; }
public DateTime CreationDate { get; set; }
}
#endregion
[Fact]
public void PersonElasticMigration()
{
var personDescribed = Describe(typeof(Person), "--root--");
var json = JSON.SerializeDynamic(personDescribed);
#if NETCOREAPP1_0
const string EXPECTED_VALUE = "{\"properties\":{\"Id\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"MostRecentLocation\":{\"properties\":{\"Latitude\":{\"type\":\"float\",\"index\":\"no\"},\"Longitude\":{\"type\":\"float\",\"index\":\"no\"},\"LastSeenDate\":{\"type\":\"date\",\"format\":\"dateOptionalTime\",\"index\":\"no\"}},\"type\":\"object\"},\"Locations\":{\"properties\":{\"CountryCode\":{\"type\":\"string\",\"index\":\"no\"},\"LocType\":{\"type\":\"integer\",\"index\":\"no\"},\"OnDate\":{\"type\":\"date\",\"format\":\"dateOptionalTime\",\"index\":\"no\"},\"SeenCount\":{\"type\":\"integer\",\"index\":\"no\"},\"GeoPoint\":{\"properties\":{\"Latitude\":{\"type\":\"float\",\"index\":\"no\"},\"Longitude\":{\"type\":\"float\",\"index\":\"no\"}},\"type\":\"object\"},\"Name\":{\"type\":\"string\",\"index\":\"no\"}},\"type\":\"object\"},\"InterestingTags\":{\"properties\":{\"SiteId\":{\"type\":\"integer\",\"index\":\"no\"},\"TagId\":{\"type\":\"integer\",\"index\":\"no\"},\"Confidence\":{\"type\":\"float\",\"index\":\"no\"}},\"type\":\"object\"},\"Identifiers\":{\"properties\":{\"Id\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"IdType\":{\"type\":\"integer\",\"index\":\"no\"}},\"type\":\"object\"},\"InterestingSites\":{\"properties\":{\"SiteId\":{\"type\":\"integer\",\"index\":\"no\"},\"InterestLevel\":{\"type\":\"float\",\"index\":\"no\"}},\"type\":\"object\"},\"TagViews\":{\"properties\":{\"SiteId\":{\"type\":\"integer\",\"index\":\"no\"},\"TagId\":{\"type\":\"integer\",\"index\":\"no\"},\"TimesViewed\":{\"type\":\"long\",\"index\":\"no\"}},\"type\":\"object\"},\"DeveloperKinds\":{\"properties\":{\"DevType\":{\"type\":\"integer\",\"index\":\"no\"},\"RelativeScore\":{\"type\":\"float\",\"index\":\"no\"}},\"type\":\"object\"},\"Demographics\":{\"properties\":{\"PersonId\":{\"type\":\"string\",\"index\":\"no\"},\"DeviceTypeId\":{\"type\":\"integer\",\"index\":\"no\"},\"BrowserId\":{\"type\":\"integer\",\"index\":\"no\"},\"OsId\":{\"type\":\"integer\",\"index\":\"no\"},\"OnDate\":{\"type\":\"date\",\"format\":\"dateOptionalTime\",\"index\":\"no\"},\"SeenCount\":{\"type\":\"integer\",\"index\":\"no\"}},\"type\":\"object\"},\"Educations\":{\"properties\":{\"Tld\":{\"type\":\"string\",\"index\":\"no\"},\"Name\":{\"type\":\"string\",\"index\":\"no\"},\"OnDate\":{\"type\":\"date\",\"format\":\"dateOptionalTime\",\"index\":\"no\"},\"SeenCount\":{\"type\":\"integer\",\"index\":\"no\"},\"SourceId\":{\"type\":\"integer\",\"index\":\"no\"}},\"type\":\"object\"},\"Industries\":{\"properties\":{\"PersonId\":{\"type\":\"string\",\"index\":\"no\"},\"IndustryId\":{\"type\":\"integer\",\"index\":\"no\"},\"OnDate\":{\"type\":\"date\",\"format\":\"dateOptionalTime\",\"index\":\"no\"},\"SeenCount\":{\"type\":\"integer\",\"index\":\"no\"}},\"type\":\"object\"},\"Languages\":{\"properties\":{\"LanguageCode\":{\"type\":\"string\",\"index\":\"no\"},\"LangSource\":{\"type\":\"integer\",\"index\":\"no\"},\"OnDate\":{\"type\":\"date\",\"format\":\"dateOptionalTime\",\"index\":\"no\"},\"SeenCount\":{\"type\":\"integer\",\"index\":\"no\"}},\"type\":\"object\"},\"WorkingHours\":{\"properties\":{\"Hour\":{\"type\":\"integer\",\"index\":\"no\"},\"Count\":{\"type\":\"long\",\"index\":\"no\"}},\"type\":\"object\"},\"LastSeen\":{\"type\":\"date\",\"format\":\"dateOptionalTime\",\"index\":\"no\"},\"Merges\":{\"properties\":{\"DestroyedPersonId\":{\"type\":\"string\",\"index\":\"no\"},\"CreationDate\":{\"type\":\"date\",\"format\":\"dateOptionalTime\",\"index\":\"no\"}},\"type\":\"object\"}},\"dynamic\":\"strict\",\"_all\":{\"enabled\":false}}";
#else
const string EXPECTED_VALUE = "{\"properties\":{\"Id\":{\"index\":\"not_analyzed\",\"type\":\"string\"},\"MostRecentLocation\":{\"properties\":{\"Latitude\":{\"index\":\"no\",\"type\":\"float\"},\"Longitude\":{\"index\":\"no\",\"type\":\"float\"},\"LastSeenDate\":{\"index\":\"no\",\"format\":\"dateOptionalTime\",\"type\":\"date\"}},\"type\":\"object\"},\"Locations\":{\"properties\":{\"CountryCode\":{\"index\":\"no\",\"type\":\"string\"},\"LocType\":{\"index\":\"no\",\"type\":\"integer\"},\"OnDate\":{\"index\":\"no\",\"format\":\"dateOptionalTime\",\"type\":\"date\"},\"SeenCount\":{\"index\":\"no\",\"type\":\"integer\"},\"GeoPoint\":{\"properties\":{\"Latitude\":{\"index\":\"no\",\"type\":\"float\"},\"Longitude\":{\"index\":\"no\",\"type\":\"float\"}},\"type\":\"object\"},\"Name\":{\"index\":\"no\",\"type\":\"string\"}},\"type\":\"object\"},\"InterestingTags\":{\"properties\":{\"SiteId\":{\"index\":\"no\",\"type\":\"integer\"},\"TagId\":{\"index\":\"no\",\"type\":\"integer\"},\"Confidence\":{\"index\":\"no\",\"type\":\"float\"}},\"type\":\"object\"},\"Identifiers\":{\"properties\":{\"Id\":{\"index\":\"not_analyzed\",\"type\":\"string\"},\"IdType\":{\"index\":\"no\",\"type\":\"integer\"}},\"type\":\"object\"},\"InterestingSites\":{\"properties\":{\"SiteId\":{\"index\":\"no\",\"type\":\"integer\"},\"InterestLevel\":{\"index\":\"no\",\"type\":\"float\"}},\"type\":\"object\"},\"TagViews\":{\"properties\":{\"SiteId\":{\"index\":\"no\",\"type\":\"integer\"},\"TagId\":{\"index\":\"no\",\"type\":\"integer\"},\"TimesViewed\":{\"index\":\"no\",\"type\":\"long\"}},\"type\":\"object\"},\"DeveloperKinds\":{\"properties\":{\"DevType\":{\"index\":\"no\",\"type\":\"integer\"},\"RelativeScore\":{\"index\":\"no\",\"type\":\"float\"}},\"type\":\"object\"},\"Demographics\":{\"properties\":{\"PersonId\":{\"index\":\"no\",\"type\":\"string\"},\"DeviceTypeId\":{\"index\":\"no\",\"type\":\"integer\"},\"BrowserId\":{\"index\":\"no\",\"type\":\"integer\"},\"OsId\":{\"index\":\"no\",\"type\":\"integer\"},\"OnDate\":{\"index\":\"no\",\"format\":\"dateOptionalTime\",\"type\":\"date\"},\"SeenCount\":{\"index\":\"no\",\"type\":\"integer\"}},\"type\":\"object\"},\"Educations\":{\"properties\":{\"Tld\":{\"index\":\"no\",\"type\":\"string\"},\"Name\":{\"index\":\"no\",\"type\":\"string\"},\"OnDate\":{\"index\":\"no\",\"format\":\"dateOptionalTime\",\"type\":\"date\"},\"SeenCount\":{\"index\":\"no\",\"type\":\"integer\"},\"SourceId\":{\"index\":\"no\",\"type\":\"integer\"}},\"type\":\"object\"},\"Industries\":{\"properties\":{\"PersonId\":{\"index\":\"no\",\"type\":\"string\"},\"IndustryId\":{\"index\":\"no\",\"type\":\"integer\"},\"OnDate\":{\"index\":\"no\",\"format\":\"dateOptionalTime\",\"type\":\"date\"},\"SeenCount\":{\"index\":\"no\",\"type\":\"integer\"}},\"type\":\"object\"},\"Languages\":{\"properties\":{\"LanguageCode\":{\"index\":\"no\",\"type\":\"string\"},\"LangSource\":{\"index\":\"no\",\"type\":\"integer\"},\"OnDate\":{\"index\":\"no\",\"format\":\"dateOptionalTime\",\"type\":\"date\"},\"SeenCount\":{\"index\":\"no\",\"type\":\"integer\"}},\"type\":\"object\"},\"WorkingHours\":{\"properties\":{\"Hour\":{\"index\":\"no\",\"type\":\"integer\"},\"Count\":{\"index\":\"no\",\"type\":\"long\"}},\"type\":\"object\"},\"LastSeen\":{\"index\":\"no\",\"format\":\"dateOptionalTime\",\"type\":\"date\"},\"Merges\":{\"properties\":{\"DestroyedPersonId\":{\"index\":\"no\",\"type\":\"string\"},\"CreationDate\":{\"index\":\"no\",\"format\":\"dateOptionalTime\",\"type\":\"date\"}},\"type\":\"object\"}},\"dynamic\":\"strict\",\"_all\":{\"enabled\":false}}";
#endif
Assert.Equal(EXPECTED_VALUE, json);
}
class _DynamicObject : DynamicObject
{
private object ConvertableTo;
public _DynamicObject(object convertableTo)
{
ConvertableTo = convertableTo;
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
if (binder.ReturnType.IsAssignableFrom(ConvertableTo.GetType()))
{
result = ConvertableTo;
return true;
}
result = null;
return false;
}
}
[Fact]
public void DynamicObject()
{
Assert.Equal("true", JSON.SerializeDynamic(new _DynamicObject(true)));
Assert.Equal("false", JSON.SerializeDynamic(new _DynamicObject(false)));
Assert.Equal("123", JSON.SerializeDynamic(new _DynamicObject(123UL)));
Assert.Equal("123", JSON.SerializeDynamic(new _DynamicObject(123L)));
Assert.Equal("-123", JSON.SerializeDynamic(new _DynamicObject(-123L)));
Assert.Equal("3.14159", JSON.SerializeDynamic(new _DynamicObject(3.14159)));
Assert.Equal("3.14159", JSON.SerializeDynamic(new _DynamicObject(3.14159f)).Substring(0, 7));
Assert.Equal("3.14159", JSON.SerializeDynamic(new _DynamicObject(3.14159m)));
Assert.Equal("\"hello world\"", JSON.SerializeDynamic(new _DynamicObject("hello world")));
Assert.Equal("\"c\"", JSON.SerializeDynamic(new _DynamicObject('c')));
var now = DateTime.UtcNow;
var nowStr = JSON.Serialize(now);
Assert.Equal(nowStr, JSON.SerializeDynamic(new _DynamicObject(now)));
var nowOffset = DateTimeOffset.UtcNow;
var nowOffsetStr = JSON.Serialize(nowOffset);
Assert.Equal(nowOffsetStr, JSON.SerializeDynamic(new _DynamicObject(nowOffset)));
var g = Guid.NewGuid();
Assert.Equal("\"" + g + "\"", JSON.SerializeDynamic(new _DynamicObject(g)));
Assert.Equal("[1,2,3]", JSON.SerializeDynamic(new _DynamicObject(new[] { 1, 2, 3 })));
}
[Fact]
public void ExpandoObject()
{
dynamic dyn = new ExpandoObject();
dyn.A = "B";
dyn.C = 123;
dyn.D = new { Foo = "Bar" };
dyn.E = new[] { 1, 2, 3, 4, 5, 6 };
dyn.F = new ExpandoObject();
dyn.F.A = "nope";
var res = JSON.SerializeDynamic(dyn);
Assert.Equal("{\"A\":\"B\",\"C\":123,\"D\":{\"Foo\":\"Bar\"},\"E\":[1,2,3,4,5,6],\"F\":{\"A\":\"nope\"}}", res);
}
[Fact]
public void RecursiveObjects()
{
{
var res = JSON.SerializeDynamic(new { foo = (object)new { baz1 = "1" }, bar = (object)new { baz2 = "2" } }, Options.ISO8601PrettyPrintExcludeNulls);
Assert.Equal("{\n \"foo\": {\n \"baz1\": \"1\"\n },\n \"bar\": {\n \"baz2\": \"2\"\n }\n}", res);
}
{
var res = JSON.SerializeDynamic(new { foo = new object[] { new { baz1 = "1" } }, bar = (object)new { baz2 = "2" } }, Options.ISO8601PrettyPrintExcludeNulls);
Assert.Equal("{\n \"foo\": [{\n \"baz1\": \"1\"\n }],\n \"bar\": {\n \"baz2\": \"2\"\n }\n}", res);
}
{
var res = JSON.SerializeDynamic(new { foo = new List<object> { new { barz = "1" } }, bar = (object)new { baz2 = "2" } }, Options.ISO8601PrettyPrintExcludeNulls);
Assert.Equal("{\n \"foo\": [{\n \"barz\": \"1\"\n }],\n \"bar\": {\n \"baz2\": \"2\"\n }\n}", res);
}
}
[Fact]
public void Issue87()
{
string json = "{\"datalist\":[{\"timestamp\":1413131613787,\"roomSchedule\":{\"roomName\":\"21\",\"timestamp\":1413131608000,\"schedule\":[{\"actualStart\":1413115680000,\"canceled\":false,\"duration\":35100000,\"precautions\":false,\"surgeon\":\"some, guy\",\"anonId\":\"666\",\"isFirst\":true,\"service\":\"svc\",\"hideName\":false,\"id\":\"1039666\",\"state\":\"intra\",\"location\":\"Or 21\",\"actualEnd\":1413150780000,\"plannedStart\":1413114300000,\"status\":\"surgStart\",\"started\":true,\"ssn\":\"123-45-6789\",\"isCurrent\":true,\"fullName\":\"WW, FF\",\"room\":\"21\",\"name\":\"WW\",\"dob\":\"01/01/1801\",\"plannedEnd\":1413149400000,\"scheduledStart\":1413114300000,\"mrn\":\"0000004\",\"procedure\":\"ZZ\",\"turnover\":1800000}]},\"unitId\":\"AA\"}]}";
dynamic obj = JSON.DeserializeDynamic(json);
var watch = new Stopwatch();
watch.Start();
string ser = JSON.SerializeDynamic(obj);
watch.Stop();
// 200ms is kind of arbitrary, but it was > 1000 before this Issue was fixed
Assert.True(watch.ElapsedMilliseconds < 200, "Took too long to SerializeDynamic, [" + watch.ElapsedMilliseconds + "ms]");
// technically this isn't guaranteed to be an exact match, but for a test case? Good enough
Assert.Equal(json, ser);
}
[Fact]
public void NullArrayElements()
{
using (var str = new StringWriter())
{
var obj =
new
{
ids = new string[] { null, "US", "HI" }
};
JSON.SerializeDynamic(obj, str, new Options(excludeNulls: true));
var res = str.ToString();
Assert.Equal("{\"ids\":[null,\"US\",\"HI\"]}", res);
}
}
[Fact]
public void ExcludingNulls()
{
// to stream tests
{
using (var str = new StringWriter())
{
JSON.SerializeDynamic(null, str, Options.Default);
var res = str.ToString();
Assert.Equal("null", res);
}
using (var str = new StringWriter())
{
JSON.SerializeDynamic(null, str, Options.ExcludeNulls);
var res = str.ToString();
// it's not a member, it should be written
Assert.Equal("null", res);
}
using (var str = new StringWriter())
{
JSON.SerializeDynamic(new[] { null, "hello", "world" }, str, Options.Default);
var res = str.ToString();
Assert.Equal("[null,\"hello\",\"world\"]", res);
}
using (var str = new StringWriter())
{
JSON.SerializeDynamic(new[] { null, "hello", "world" }, str, Options.ExcludeNulls);
var res = str.ToString();
// it's not a member, it should be written
Assert.Equal("[null,\"hello\",\"world\"]", res);
}
using (var str = new StringWriter())
{
var data = new Dictionary<string, int?>();
data["hello"] = 123;
data["world"] = null;
JSON.SerializeDynamic(data, str, Options.Default);
var res = str.ToString();
Assert.Equal("{\"hello\":123,\"world\":null}", res);
}
using (var str = new StringWriter())
{
var data = new Dictionary<string, int?>();
data["hello"] = 123;
data["world"] = null;
JSON.SerializeDynamic(data, str, Options.ExcludeNulls);
var res = str.ToString();
Assert.Equal("{\"hello\":123}", res);
}
using (var str = new StringWriter())
{
var data =
new
{
hello = 123,
world = default(object)
};
JSON.SerializeDynamic(data, str, Options.Default);
var res = str.ToString();
Assert.Equal("{\"hello\":123,\"world\":null}", res);
}
using (var str = new StringWriter())
{
var data =
new
{
hello = 123,
world = default(object)
};
JSON.SerializeDynamic(data, str, Options.ExcludeNulls);
var res = str.ToString();
Assert.Equal("{\"hello\":123}", res);
}
}
// to string tests
{
{
var res = JSON.SerializeDynamic(null, Options.Default);
Assert.Equal("null", res);
}
{
var res = JSON.SerializeDynamic(null, Options.ExcludeNulls);
// it's not a member, it should be written
Assert.Equal("null", res);
}
{
var res = JSON.SerializeDynamic(new[] { null, "hello", "world" }, Options.Default);
Assert.Equal("[null,\"hello\",\"world\"]", res);
}
{
var res = JSON.SerializeDynamic(new[] { null, "hello", "world" }, Options.ExcludeNulls);
// it's not a member, it should be written
Assert.Equal("[null,\"hello\",\"world\"]", res);
}
{
var data = new Dictionary<string, int?>();
data["hello"] = 123;
data["world"] = null;
var res = JSON.SerializeDynamic(data, Options.Default);
Assert.Equal("{\"hello\":123,\"world\":null}", res);
}
{
var data = new Dictionary<string, int?>();
data["hello"] = 123;
data["world"] = null;
var res = JSON.SerializeDynamic(data, Options.ExcludeNulls);
Assert.Equal("{\"hello\":123}", res);
}
{
var data =
new
{
hello = 123,
world = default(object)
};
var res = JSON.SerializeDynamic(data, Options.Default);
Assert.Equal("{\"hello\":123,\"world\":null}", res);
}
{
var data =
new
{
hello = 123,
world = default(object)
};
var res = JSON.SerializeDynamic(data, Options.ExcludeNulls);
Assert.Equal("{\"hello\":123}", res);
}
}
}
public class _ElasticExampleFailure
{
private List<object> _must = new List<object>();
private List<object> _must_not = new List<object>();
private List<object> _should = new List<object>();
public object[] must { get { return GetClean(_must); } }
public object[] must_not { get { return GetClean(_must_not); } }
public object[] should { get { return GetClean(_should); } }
public int? minimum_number_should_match { get; set; }
public float? boost { get; set; }
public bool? _cache { get; set; }
public void Append(_ElasticExampleFailure toAppend)
{
if (toAppend.must != null) this._must.AddRange(toAppend.must);
if (toAppend.must_not != null) this._must_not.AddRange(toAppend.must_not);
if (toAppend.should != null) this._should.AddRange(toAppend.should);
}
private object[] GetClean(List<object> list)
{
return list.Any() ? list.ToArray() : null;
}
public void AddMust(object query)
{
if (query != null)
{
_must.Add(query);
}
}
public void AddMustNot(object query)
{
if (query != null)
{
_must_not.Add(query);
}
}
public void AddShould(object query)
{
if (query != null)
{
_should.Add(query);
}
}
public bool HasTerms()
{
return _must.Any() || _must_not.Any() || _should.Any();
}
public static _ElasticExampleFailure BuildSkillsQuery(string queryString)
{
var skillsBoolQuery = new _ElasticExampleFailure
{
minimum_number_should_match = 1
};
// we determined that one query is a requirement here, and no more becuase
// otherwise it will try to run the entire boolean query on just the fields selected
// when we add advanced search so people can specify specific fields for specific text
// we will still need this inner bool query
var fieldsForQueryString = new List<string>
{
"personalStatement",
"yearsOfExperienceTags^1.5",
"stackExchangeAnswersTags^0.1",
"name",
"likeTags",
"stackOverflowUserName",
"projects.projectName",
"projects.projectTags",
"projects.projectDescription",
"experience.experienceJobTitle",
"experience.experienceEmployerName",
"experience.experienceTags",
"experience.experienceResponsibilities",
"education.educationInstitution",
"education.educationTags",
"education.educationDegreeName",
"education.educationAchievements",
};
skillsBoolQuery.AddShould(new
{
query_string = new
{
query = queryString,
default_operator = "AND",
fields = fieldsForQueryString.ToArray(),
use_dis_max = true,
}
});
return skillsBoolQuery;
}
}
[Fact]
public void ElasticExampleFailure()
{
var mainQuery = new _ElasticExampleFailure();
var filterQuery = new _ElasticExampleFailure() { _cache = true };
filterQuery.AddMustNot(new { term = new { blocking = 1234 }, });
mainQuery.AddMust(_ElasticExampleFailure.BuildSkillsQuery("Dean Ward"));
object filteredQuery =
new
{
query = new { @bool = mainQuery },
filter = new { @bool = filterQuery }
};
object queryObject =
new
{
from = 0,
size = 30,
query = new
{
filtered = filteredQuery
},
};
var options = new Options(prettyPrint: true);
var res = JSON.SerializeDynamic(queryObject, options);
#if NETCOREAPP1_0
const string EXPECTED_VALUE = "{\n \"from\": 0,\n \"size\": 30,\n \"query\": {\n \"filtered\": {\n \"query\": {\n \"bool\": {\n \"must\": [{\n \"must\": null,\n \"must_not\": null,\n \"should\": [{\n \"query_string\": {\n \"use_dis_max\": true,\n \"fields\": [\"personalStatement\", \"yearsOfExperienceTags^1.5\", \"stackExchangeAnswersTags^0.1\", \"name\", \"likeTags\", \"stackOverflowUserName\", \"projects.projectName\", \"projects.projectTags\", \"projects.projectDescription\", \"experience.experienceJobTitle\", \"experience.experienceEmployerName\", \"experience.experienceTags\", \"experience.experienceResponsibilities\", \"education.educationInstitution\", \"education.educationTags\", \"education.educationDegreeName\", \"education.educationAchievements\"],\n \"query\": \"Dean Ward\",\n \"default_operator\": \"AND\"\n }\n }],\n \"minimum_number_should_match\": 1,\n \"boost\": null,\n \"_cache\": null\n }],\n \"must_not\": null,\n \"should\": null,\n \"minimum_number_should_match\": null,\n \"boost\": null,\n \"_cache\": null\n }\n },\n \"filter\": {\n \"bool\": {\n \"must\": null,\n \"must_not\": [{\n \"term\": {\n \"blocking\": 1234\n }\n }],\n \"should\": null,\n \"minimum_number_should_match\": null,\n \"boost\": null,\n \"_cache\": true\n }\n }\n }\n }\n}";
#else
const string EXPECTED_VALUE = "{\n \"size\": 30,\n \"from\": 0,\n \"query\": {\n \"filtered\": {\n \"query\": {\n \"bool\": {\n \"must\": [{\n \"must\": null,\n \"must_not\": null,\n \"should\": [{\n \"query_string\": {\n \"use_dis_max\": true,\n \"fields\": [\"personalStatement\", \"yearsOfExperienceTags^1.5\", \"stackExchangeAnswersTags^0.1\", \"name\", \"likeTags\", \"stackOverflowUserName\", \"projects.projectName\", \"projects.projectTags\", \"projects.projectDescription\", \"experience.experienceJobTitle\", \"experience.experienceEmployerName\", \"experience.experienceTags\", \"experience.experienceResponsibilities\", \"education.educationInstitution\", \"education.educationTags\", \"education.educationDegreeName\", \"education.educationAchievements\"],\n \"default_operator\": \"AND\",\n \"query\": \"Dean Ward\"\n }\n }],\n \"_cache\": null,\n \"boost\": null,\n \"minimum_number_should_match\": 1\n }],\n \"must_not\": null,\n \"should\": null,\n \"_cache\": null,\n \"boost\": null,\n \"minimum_number_should_match\": null\n }\n },\n \"filter\": {\n \"bool\": {\n \"must\": null,\n \"must_not\": [{\n \"term\": {\n \"blocking\": 1234\n }\n }],\n \"should\": null,\n \"_cache\": true,\n \"boost\": null,\n \"minimum_number_should_match\": null\n }\n }\n }\n }\n}";
#endif
Assert.Equal(EXPECTED_VALUE, res);
}
abstract class _RecursiveDynamic_Abstract
{
public _RecursiveDynamic_Abstract[] SubMembers { get; set; }
public object[] SubMembersAsObjects { get { return SubMembers == null ? null : SubMembers.Cast<object>().ToArray(); } }
public int A { get; set; }
}
class _RecursiveDynamic : _RecursiveDynamic_Abstract
{
public double B { get; set; }
}
[Fact]
public void RecursiveDynamic()
{
object[] foo = new object[]
{
new
{
Item = (object)new _RecursiveDynamic
{
A = 999,
B = -999,
SubMembers = new[] { new _RecursiveDynamic { A = 1, B = 2.0, SubMembers = new[] { new _RecursiveDynamic { A = 5, B = 6.6 } } }, new _RecursiveDynamic { A = 3, B = 4 } }
}
},
new
{
Item = (object)new _RecursiveDynamic
{
A = 999,
B = -999,
SubMembers = new[] { new _RecursiveDynamic { A = 1, B = 2.0, SubMembers = new[] { new _RecursiveDynamic { A = 5, B = 6.6 } } }, new _RecursiveDynamic { A = 3, B = 4 } }
}
}
};
var res = JSON.SerializeDynamic(foo, Options.PrettyPrintExcludeNullsIncludeInherited);
#if NETCOREAPP1_0
const string EXPECTED_VALUE = "[{\n \"Item\": {\n \"B\": -999,\n \"A\": 999,\n \"SubMembers\": [{\n \"B\": 2,\n \"A\": 1,\n \"SubMembers\": [{\n \"B\": 6.6,\n \"A\": 5\n }],\n \"SubMembersAsObjects\": [{\n \"B\": 6.6,\n \"A\": 5\n }]\n }, {\n \"B\": 4,\n \"A\": 3\n }],\n \"SubMembersAsObjects\": [{\n \"B\": 2,\n \"A\": 1,\n \"SubMembers\": [{\n \"B\": 6.6,\n \"A\": 5\n }],\n \"SubMembersAsObjects\": [{\n \"B\": 6.6,\n \"A\": 5\n }]\n }, {\n \"B\": 4,\n \"A\": 3\n }]\n }\n}, {\n \"Item\": {\n \"B\": -999,\n \"A\": 999,\n \"SubMembers\": [{\n \"B\": 2,\n \"A\": 1,\n \"SubMembers\": [{\n \"B\": 6.6,\n \"A\": 5\n }],\n \"SubMembersAsObjects\": [{\n \"B\": 6.6,\n \"A\": 5\n }]\n }, {\n \"B\": 4,\n \"A\": 3\n }],\n \"SubMembersAsObjects\": [{\n \"B\": 2,\n \"A\": 1,\n \"SubMembers\": [{\n \"B\": 6.6,\n \"A\": 5\n }],\n \"SubMembersAsObjects\": [{\n \"B\": 6.6,\n \"A\": 5\n }]\n }, {\n \"B\": 4,\n \"A\": 3\n }]\n }\n}]";
#else
const string EXPECTED_VALUE = "[{\n \"Item\": {\n \"A\": 999,\n \"B\": -999,\n \"SubMembers\": [{\n \"A\": 1,\n \"B\": 2,\n \"SubMembers\": [{\n \"A\": 5,\n \"B\": 6.6\n }],\n \"SubMembersAsObjects\": [{\n \"A\": 5,\n \"B\": 6.6\n }]\n }, {\n \"A\": 3,\n \"B\": 4\n }],\n \"SubMembersAsObjects\": [{\n \"A\": 1,\n \"B\": 2,\n \"SubMembers\": [{\n \"A\": 5,\n \"B\": 6.6\n }],\n \"SubMembersAsObjects\": [{\n \"A\": 5,\n \"B\": 6.6\n }]\n }, {\n \"A\": 3,\n \"B\": 4\n }]\n }\n}, {\n \"Item\": {\n \"A\": 999,\n \"B\": -999,\n \"SubMembers\": [{\n \"A\": 1,\n \"B\": 2,\n \"SubMembers\": [{\n \"A\": 5,\n \"B\": 6.6\n }],\n \"SubMembersAsObjects\": [{\n \"A\": 5,\n \"B\": 6.6\n }]\n }, {\n \"A\": 3,\n \"B\": 4\n }],\n \"SubMembersAsObjects\": [{\n \"A\": 1,\n \"B\": 2,\n \"SubMembers\": [{\n \"A\": 5,\n \"B\": 6.6\n }],\n \"SubMembersAsObjects\": [{\n \"A\": 5,\n \"B\": 6.6\n }]\n }, {\n \"A\": 3,\n \"B\": 4\n }]\n }\n}]";
#endif
Assert.Equal(EXPECTED_VALUE, res);
}
[Fact]
public void MicrosoftTimeSpans()
{
var rand = new Random();
var timeSpans = new List<TimeSpan>();
for (var i = 0; i < 1000; i++)
{
var d = rand.Next(10675199 - 1);
var h = rand.Next(24);
var m = rand.Next(60);
var s = rand.Next(60);
var ms = rand.Next(1000);
var ts = new TimeSpan(d, h, m, s, ms);
if (rand.Next(2) == 0)
{
ts = ts.Negate();
}
timeSpans.Add(ts);
}
timeSpans.Add(TimeSpan.MaxValue);
timeSpans.Add(TimeSpan.MinValue);
timeSpans.Add(default(TimeSpan));
foreach (var ts in timeSpans)
{
string streamJson, stringJson;
using (var str = new StringWriter())
{
JSON.SerializeDynamic(ts, str, Options.Default);
streamJson = str.ToString();
}
{
stringJson = JSON.SerializeDynamic(ts, Options.Default);
}
Assert.StartsWith("\"", streamJson);
Assert.EndsWith("\"", streamJson);
Assert.StartsWith("\"", stringJson);
Assert.EndsWith("\"", stringJson);
var dotNetStr = ts.ToString();
streamJson = streamJson.Trim('"');
stringJson = stringJson.Trim('"');
if (dotNetStr.IndexOf('.') != -1) dotNetStr = dotNetStr.TrimEnd('0');
if (streamJson.IndexOf('.') != -1) streamJson = streamJson.TrimEnd('0');
if (stringJson.IndexOf('.') != -1) stringJson = stringJson.TrimEnd('0');
Assert.Equal(dotNetStr, streamJson);
Assert.Equal(dotNetStr, stringJson);
}
}
[Fact]
public void SecondsTimeSpans()
{
var rand = new Random();
var timeSpans = new List<TimeSpan>();
for (var i = 0; i < 1000; i++)
{
var d = rand.Next(10675199 - 1);
var h = rand.Next(24);
var m = rand.Next(60);
var s = rand.Next(60);
var ms = rand.Next(1000);
var ts = new TimeSpan(d, h, m, s, ms);
if (rand.Next(2) == 0)
{
ts = ts.Negate();
}
timeSpans.Add(ts);
}
timeSpans.Add(TimeSpan.MaxValue);
timeSpans.Add(TimeSpan.MinValue);
timeSpans.Add(default(TimeSpan));
foreach (var ts in timeSpans)
{
string streamJson, stringJson;
using (var str = new StringWriter())
{
JSON.SerializeDynamic(ts, str, Options.SecondsSinceUnixEpoch);
streamJson = str.ToString();
}
{
stringJson = JSON.SerializeDynamic(ts, Options.SecondsSinceUnixEpoch);
}
var dotNetStr = ts.TotalSeconds.ToString("R", CultureInfo.InvariantCulture);
if (dotNetStr.IndexOf('.') != -1) dotNetStr = dotNetStr.TrimEnd('0');
if (streamJson.IndexOf('.') != -1) streamJson = streamJson.TrimEnd('0');
if (stringJson.IndexOf('.') != -1) stringJson = stringJson.TrimEnd('0');
Assert.Equal(dotNetStr, streamJson);
Assert.Equal(dotNetStr, stringJson);
}
}
[Fact]
public void MillsecondsTimeSpans()
{
var rand = new Random();
var timeSpans = new List<TimeSpan>();
for (var i = 0; i < 1000; i++)
{
var d = rand.Next(10675199 - 1);
var h = rand.Next(24);
var m = rand.Next(60);
var s = rand.Next(60);
var ms = rand.Next(1000);
var ts = new TimeSpan(d, h, m, s, ms);
if (rand.Next(2) == 0)
{
ts = ts.Negate();
}
timeSpans.Add(ts);
}
timeSpans.Add(TimeSpan.MaxValue);
timeSpans.Add(TimeSpan.MinValue);
timeSpans.Add(default(TimeSpan));
foreach (var ts in timeSpans)
{
string streamJson, stringJson;
using (var str = new StringWriter())
{
JSON.SerializeDynamic(ts, str, Options.MillisecondsSinceUnixEpoch);
streamJson = str.ToString();
}
{
stringJson = JSON.SerializeDynamic(ts, Options.MillisecondsSinceUnixEpoch);
}
var dotNetStr = ts.TotalMilliseconds.ToString("R", CultureInfo.InvariantCulture);
if (dotNetStr.IndexOf('.') != -1) dotNetStr = dotNetStr.TrimEnd('0');
if (streamJson.IndexOf('.') != -1) streamJson = streamJson.TrimEnd('0');
if (stringJson.IndexOf('.') != -1) stringJson = stringJson.TrimEnd('0');
Assert.Equal(dotNetStr, streamJson);
Assert.Equal(dotNetStr, stringJson);
}
}
[Fact]
public void ISO8601TimeSpans()
{
var rand = new Random();
var timeSpans = new List<TimeSpan>();
for (var i = 0; i < 1000; i++)
{
var d = rand.Next(10675199 - 1);
var h = rand.Next(24);
var m = rand.Next(60);
var s = rand.Next(60);
var ms = rand.Next(1000);
var ts = new TimeSpan(d, h, m, s, ms);
if (rand.Next(2) == 0)
{
ts = ts.Negate();
}
timeSpans.Add(ts);
}
timeSpans.Add(TimeSpan.MaxValue);
timeSpans.Add(TimeSpan.MinValue);
timeSpans.Add(default(TimeSpan));
foreach (var ts in timeSpans)
{
string streamJson, stringJson;
using (var str = new StringWriter())
{
JSON.SerializeDynamic(ts, str, Options.ISO8601);
streamJson = str.ToString();
}
{
stringJson = JSON.SerializeDynamic(ts, Options.ISO8601);
}
Assert.True(streamJson == stringJson);
var dotNetStr = System.Xml.XmlConvert.ToString(ts);
streamJson = streamJson.Trim('"');
stringJson = stringJson.Trim('"');
if (streamJson.IndexOf('.') != -1)
{
var lastChar = streamJson[streamJson.Length - 1];
streamJson = streamJson.Substring(0, streamJson.Length - 1).TrimEnd('0') + lastChar;
}
if (stringJson.IndexOf('.') != -1)
{
var lastChar = stringJson[stringJson.Length - 1];
stringJson = stringJson.Substring(0, stringJson.Length - 1).TrimEnd('0') + lastChar;
}
Assert.Equal(dotNetStr, streamJson);
Assert.Equal(dotNetStr, stringJson);
}
}
[Fact]
public void RFC1123()
{
var now = DateTime.UtcNow;
var str = JSON.SerializeDynamic(now, Options.RFC1123);
var res = JSON.Deserialize<DateTime>(str, Options.RFC1123);
var diff = (now - res).Duration();
Assert.True(diff.TotalSeconds < 1);
}
[Fact]
public void MicrosoftDateTimeOffsetSelfRoundtrip()
{
var dtos =
new[]
{
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromHours(1)),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromHours(-1)),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromHours(2)),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromHours(-2)),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromHours(3)),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromHours(-3)),
new DateTimeOffset(1234, 5, 6, 7, 8, 9, new TimeSpan(4, 30, 00)),
new DateTimeOffset(1234, 5, 6, 7, 8, 9, new TimeSpan(-4, -30, 00)),
};
foreach (var dto in dtos)
{
var val = JSON.Serialize(dto);
var dyn = JSON.DeserializeDynamic(val);
var staticRes = (DateTimeOffset)dyn;
var diff = (dto - staticRes);
Assert.True(diff.TotalMilliseconds <= 0);
var res = JSON.SerializeDynamic(dyn);
Assert.Equal(val, res);
}
}
[Fact]
public void ISO8601DateTimeOffsetSelfRoundtrip()
{
var dtos =
new[]
{
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.Zero),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromHours(1)),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromHours(-1)),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromHours(2)),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromHours(-2)),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromHours(3)),
new DateTimeOffset(1970, 1, 1, 0, 0, 0, TimeSpan.FromHours(-3)),
new DateTimeOffset(1234, 5, 6, 7, 8, 9, new TimeSpan(4, 30, 00)),
new DateTimeOffset(1234, 5, 6, 7, 8, 9, new TimeSpan(-4, -30, 00)),
};
foreach (var dto in dtos)
{
var val = JSON.Serialize(dto, Options.ISO8601);
var dyn = JSON.DeserializeDynamic(val, Options.ISO8601);
var staticRes = (DateTimeOffset)dyn;
var diff = (dto - staticRes);
Assert.True(diff.TotalMilliseconds <= 0);
var res = JSON.SerializeDynamic(dyn, Options.ISO8601);
Assert.Equal(val, res);
}
}
public class _Issue139
{
public string Prop1;
public _Issue139 Prop2;
}
public class _Issue139_2
{
public _Issue139_3 Foo;
}
public class _Issue139_3
{
public _Issue139_2 Bar;
}
[Fact]
public void Issue139()
{
{
var a = new _Issue139 { Prop1 = "string", Prop2 = new _Issue139() { Prop1 = "string2" } };
var res = JSON.SerializeDynamic(a);
Assert.Equal("{\"Prop2\":{\"Prop2\":null,\"Prop1\":\"string2\"},\"Prop1\":\"string\"}", res);
}
{
var b = new _Issue139_2 { Foo = new _Issue139_3 { Bar = new _Issue139_2 { } } };
var res = JSON.SerializeDynamic(b);
Assert.Equal("{\"Foo\":{\"Bar\":{\"Foo\":null}}}", res);
}
}
// Also see DeserializeDynamicTests._Issue150
class _Issue150
{
public enum A { A, B, C }
public class _InArray<T>
{
[JilDirective(TreatEnumerationAs = typeof(int))]
public T[] ArrayOfEnum;
}
public class _InList<T>
{
[JilDirective(TreatEnumerationAs = typeof(int))]
public List<T> ListOfEnum;
}
public class _InListProp<T>
{
[JilDirective(TreatEnumerationAs = typeof(int))]
public List<T> ListOfEnum { get; set; }
}
public class _InEnumerable<T>
{
[JilDirective(TreatEnumerationAs = typeof(int))]
public IEnumerable<T> EnumerableOfEnum;
}
public class _AsDictionaryKey<T>
{
[JilDirective(TreatEnumerationAs = typeof(int))]
public Dictionary<T, int> DictionaryWithEnumKey;
}
public class _AsDictionaryValue<T>
{
[JilDirective(TreatEnumerationAs = typeof(int))]
public Dictionary<int, T> DictionaryWithEnumValue;
}
public class _MultipleLists<T> {
[JilDirective(TreatEnumerationAs = typeof(int))]
public List<T> List1;
public List<T> List2;
}
}
[Fact]
public void Issue150()
{
{
var obj = new _Issue150._InArray<_Issue150.A>();
obj.ArrayOfEnum = new[] { _Issue150.A.A, _Issue150.A.B };
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"ArrayOfEnum\":[0,1]}", str);
}
{
var obj = new _Issue150._InArray<_Issue150.A?>();
obj.ArrayOfEnum = new _Issue150.A?[] { _Issue150.A.A, null };
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"ArrayOfEnum\":[0,null]}", str);
}
{
var obj = new _Issue150._InList<_Issue150.A>();
obj.ListOfEnum = new List<_Issue150.A>(new[] { _Issue150.A.A, _Issue150.A.B });
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"ListOfEnum\":[0,1]}", str);
}
{
var obj = new _Issue150._InList<_Issue150.A?>();
obj.ListOfEnum = new List<_Issue150.A?>(new _Issue150.A?[] { _Issue150.A.A, null });
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"ListOfEnum\":[0,null]}", str);
}
{
var obj = new _Issue150._InListProp<_Issue150.A>();
obj.ListOfEnum = new List<_Issue150.A>(new[] { _Issue150.A.A, _Issue150.A.B });
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"ListOfEnum\":[0,1]}", str);
}
{
var obj = new _Issue150._InListProp<_Issue150.A?>();
obj.ListOfEnum = new List<_Issue150.A?>(new _Issue150.A?[] { _Issue150.A.A, null });
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"ListOfEnum\":[0,null]}", str);
}
{
var obj = new _Issue150._InEnumerable<_Issue150.A>();
obj.EnumerableOfEnum = new HashSet<_Issue150.A> { _Issue150.A.A, _Issue150.A.B };
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"EnumerableOfEnum\":[0,1]}", str);
}
{
var obj = new _Issue150._InEnumerable<_Issue150.A?>();
obj.EnumerableOfEnum = new HashSet<_Issue150.A?> { _Issue150.A.A, null };
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"EnumerableOfEnum\":[0,null]}", str);
}
{
var obj = new _Issue150._AsDictionaryKey<_Issue150.A>();
obj.DictionaryWithEnumKey = new Dictionary<_Issue150.A, int>
{
{ _Issue150.A.A, 10 },
{ _Issue150.A.B, 20 }
};
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"DictionaryWithEnumKey\":{\"0\":10,\"1\":20}}", str);
}
{
var obj = new _Issue150._AsDictionaryValue<_Issue150.A>();
obj.DictionaryWithEnumValue = new Dictionary<int, _Issue150.A>
{
{ 10, _Issue150.A.A },
{ 20, _Issue150.A.B }
};
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"DictionaryWithEnumValue\":{\"10\":0,\"20\":1}}", str);
}
{
var obj = new _Issue150._AsDictionaryValue<_Issue150.A?>();
obj.DictionaryWithEnumValue = new Dictionary<int, _Issue150.A?>
{
{ 10, _Issue150.A.A },
{ 20, null }
};
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"DictionaryWithEnumValue\":{\"10\":0,\"20\":null}}", str);
}
{
var obj = new _Issue150._MultipleLists<_Issue150.A>();
obj.List1 = new List<_Issue150.A>(new[] { _Issue150.A.A, _Issue150.A.B });
obj.List2 = new List<_Issue150.A>(new[] { _Issue150.A.A, _Issue150.A.B });
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"List1\":[0,1],\"List2\":[\"A\",\"B\"]}", str);
}
}
// Also see DeserializeDynamicTests._Issue151
class _Issue151
{
public enum A { A, B, C }
[JilDirective(TreatEnumerationAs = typeof(int))]
public A? NullableEnum;
}
[Fact]
public void Issue151()
{
{
var obj = new _Issue151();
obj.NullableEnum = _Issue151.A.B;
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"NullableEnum\":1}", str);
}
{
var obj = new _Issue151();
obj.NullableEnum = null;
var str = JSON.SerializeDynamic(obj);
Assert.Equal("{\"NullableEnum\":null}", str);
}
}
[Fact]
public void Issue158()
{
{
const string json = "4.3563456344358765e+10";
double res = JSON.DeserializeDynamic(json);
var shouldMatch = double.Parse(json);
var diff = Math.Abs(res - shouldMatch);
Assert.Equal(shouldMatch, res);
}
{
const string json = "4.356345634435876535634563443587653563456344358765356345634435876535634563443587653563456344358765e+10";
double res = JSON.DeserializeDynamic(json);
var shouldMatch = double.Parse(json);
var diff = Math.Abs(res - shouldMatch);
Assert.Equal(shouldMatch, res);
}
{
const string json = "4.444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444445e+10";
double res = JSON.DeserializeDynamic(json);
var shouldMatch = double.Parse(json);
var diff = Math.Abs(res - shouldMatch);
Assert.Equal(shouldMatch, res);
}
}
struct _TopLevelNulls
{
public string A { get; set; }
}
[Fact]
public void TopLevelNulls()
{
object obj = null;
Assert.Equal("null", JSON.SerializeDynamic(obj));
var arr = new[] { "test", null, null, null };
Assert.Equal("[\"test\",null,null,null]", JSON.SerializeDynamic(arr));
Assert.Equal("[\"test\",null,null,null]", JSON.SerializeDynamic(arr, Options.ExcludeNulls));
var propObj =
new
{
Fields = arr
};
var propObjArr = new[] { propObj, null, null, null };
var propObjArrJson = JSON.SerializeDynamic(propObjArr);
Assert.Equal("[{\"Fields\":[\"test\",null,null,null]},null,null,null]", propObjArrJson);
var propObjArrJsonExcludesNull = JSON.SerializeDynamic(propObjArr, Options.ExcludeNulls);
Assert.Equal("[{\"Fields\":[\"test\",null,null,null]},null,null,null]", propObjArrJsonExcludesNull);
_TopLevelNulls? nullable = new _TopLevelNulls { A = "test" };
var nullableArr = new[] { nullable, null, null, null };
var nullableArrJson = JSON.SerializeDynamic(nullableArr);
Assert.Equal("[{\"A\":\"test\"},null,null,null]", nullableArrJson);
var nullableArrJsonExcludesNull = JSON.SerializeDynamic(nullableArr, Options.ExcludeNulls);
Assert.Equal("[{\"A\":\"test\"},null,null,null]", nullableArrJsonExcludesNull);
}
[Fact]
public void Issue200()
{
dynamic dyn = new ExpandoObject();
dyn.FooBar = "blah";
var json = JSON.SerializeDynamic(dyn, Options.CamelCase);
Assert.Equal("{\"fooBar\":\"blah\"}", json);
}
[Fact]
public void Issue224()
{
var tokenResponse =
new Newtonsoft.Json.Linq.JObject(
new Newtonsoft.Json.Linq.JProperty("userName", "test@123"),
new Newtonsoft.Json.Linq.JProperty("access_token", "my access token"),
new Newtonsoft.Json.Linq.JProperty("token_type", "bearer")
);
var json = JSON.SerializeDynamic(tokenResponse);
Assert.Equal("{\"userName\":\"test@123\",\"access_token\":\"my access token\",\"token_type\":\"bearer\"}", json);
}
[Fact]
public void Issue230()
{
var dyn = JSON.DeserializeDynamic("\"2000\"", Options.ISO8601);
var json = JSON.SerializeDynamic(dyn, Options.ISO8601);
Assert.Equal("\"2000\"", json);
}
}
} |
||||
TheStack | bd8c0a9adab5dce1327006dfcac87dd910d79878 | C#code:C# | {"size": 4268, "ext": "cs", "max_stars_repo_path": "PasswordManagerWPF/ViewModels/WindowViewModel.cs", "max_stars_repo_name": "Xodvrvp/PasswordManager", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PasswordManagerWPF/ViewModels/WindowViewModel.cs", "max_issues_repo_name": "Xodvrvp/PasswordManager", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PasswordManagerWPF/ViewModels/WindowViewModel.cs", "max_forks_repo_name": "Xodvrvp/PasswordManager", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 28.644295302, "max_line_length": 111, "alphanum_fraction": 0.5199156514} | using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace PasswordManagerWPF
{
/// <summary>
/// View Model for custom window
/// </summary>
public class WindowViewModel : BaseViewModel
{
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
/// <param name="window"></param>
public WindowViewModel(Window window)
{
Window = window;
Page = new PasswordsPage()
{
DataContext = new PasswordEntryViewModel()
};
KeyboardHandler kh = new KeyboardHandler(Window, new Action(SelectPassword));
}
#endregion
#region Public properties
// page displayed by window
public Page Page
{
get => page;
set
{
if (page == value)
return;
page = value;
OnPropertyChanged();
}
}
// window that uses this viewmodel
public Window Window
{
get => window;
set
{
if (window == value)
return;
window = value;
OnPropertyChanged();
}
}
// Size of resize border
public int ResizeBorder { get; set; } = 6;
// Thickness of resize border
public Thickness ResizeBorderThickness { get { return new Thickness(ResizeBorder); } }
// Height of title bar
public int TitleHeight { get; set; } = 40;
#endregion
#region Private fields
private Window window;
private Page page;
// notify icon, allows working in system tray
private System.Windows.Forms.NotifyIcon notifyIcon = null;
#endregion
#region Commands
public ICommand MinimizeCommand => new RelayCommand(MinimizeToTray);
public ICommand MaximizeCommand => new RelayCommand(() => Window.WindowState ^= WindowState.Maximized);
public ICommand CloseCommand => new RelayCommand(CloseWindow);
#endregion
#region Methods
/// <summary>
/// Minimizes application to system tray.
/// </summary>
private void MinimizeToTray()
{
var datacontext = (PasswordEntryViewModel)Page.DataContext;
datacontext.LockDb();
window.Hide();
if (notifyIcon == null)
{
notifyIcon = new System.Windows.Forms.NotifyIcon();
notifyIcon.Icon = new System.Drawing.Icon(Properties.Resources.IconNotify);
}
notifyIcon.Visible = true;
notifyIcon.DoubleClick +=
delegate (object sender, EventArgs args)
{
window.Show();
datacontext.OpenDb();
notifyIcon.Visible = false;
};
}
/// <summary>
/// Method triggered by <see cref="KeyboardHandler"/> when user press selected hotkey.
/// Allows user to select password and use autofill functionality.
/// </summary>
private void SelectPassword()
{
var datacontext = (PasswordEntryViewModel)Page.DataContext;
datacontext.ActiveWindow = PasswordManagerCore.ForegroundWindowHandler.GetActiveWindow();
datacontext.SelectionMode = true;
datacontext.HideWindow = new Action(HideWindow);
window.Show();
datacontext.OpenDb();
}
/// <summary>
/// Minimizes application
/// </summary>
private void HideWindow()
{
window.Hide();
}
/// <summary>
/// Closes application and cleans up <see cref="notifyIcon"/>
/// </summary>
private void CloseWindow()
{
if(notifyIcon != null)
{
notifyIcon.Visible = false;
notifyIcon.Icon = null;
notifyIcon.Dispose();
}
Window.Close();
}
#endregion
}
}
|
||||
TheStack | bd8cfdf1aabc9c749dbc82a6dba5e751bbc71cdc | C#code:C# | {"size": 1374, "ext": "cs", "max_stars_repo_path": "src/TvDbSharper/Dto/SearchDtos.cs", "max_stars_repo_name": "MokuJinJin/TvDbSharper", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/TvDbSharper/Dto/SearchDtos.cs", "max_issues_repo_name": "MokuJinJin/TvDbSharper", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/TvDbSharper/Dto/SearchDtos.cs", "max_forks_repo_name": "MokuJinJin/TvDbSharper", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.1612903226, "max_line_length": 99, "alphanum_fraction": 0.6018922853} | using Newtonsoft.Json;
namespace TvDbSharper.Dto
{
/// <summary>
/// An enum used for searching for series with <see cref="T:ISearchClient.SearchSeriesAsync"/>,
/// each value represents a property by which the search is performed
/// </summary>
public enum SearchParameter
{
Name,
ImdbId,
// ReSharper disable once InconsistentNaming
Zap2itId,
Slug,
}
#if DEBUG
[JsonObject(ItemRequired = Required.AllowNull)]
#endif
public class SeriesSearchResult
{
public string[] Aliases { get; set; }
public string Banner { get; set; }
#if DEBUG
[JsonProperty(Required = Required.Default)]
#endif
public string FanArt { get; set; }
#if DEBUG
[JsonProperty(Required = Required.Default)]
#endif
public string Poster { get; set; }
public string FirstAired { get; set; }
public int Id { get; set; }
public string Network { get; set; }
#if DEBUG
[JsonProperty(Required = Required.Default)]
#endif
public string Image { get; set; }
#if DEBUG
[JsonProperty(Required = Required.Default)]
#endif
public string Overview { get; set; }
public string SeriesName { get; set; }
public string Slug { get; set; }
public string Status { get; set; }
}
} |
||||
TheStack | bd8d308eb0c30da20db785617df3c50ca73a3bb0 | C#code:C# | {"size": 1127, "ext": "cs", "max_stars_repo_path": "Automation-Project/mysite-tests/tests/GoogleTests.cs", "max_stars_repo_name": "jayadevp6/nunit-selenim-project", "max_stars_repo_stars_event_min_datetime": "2018-04-20T04:06:56.000Z", "max_stars_repo_stars_event_max_datetime": "2020-06-23T01:51:49.000Z", "max_issues_repo_path": "Automation-Project/mysite-tests/tests/GoogleTests.cs", "max_issues_repo_name": "jayadevp6/nunit-selenim-project", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Automation-Project/mysite-tests/tests/GoogleTests.cs", "max_forks_repo_name": "jayadevp6/nunit-selenim-project", "max_forks_repo_forks_event_min_datetime": "2018-08-06T19:42:59.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-10T14:33:19.000Z"} | {"max_stars_count": 5.0, "max_issues_count": null, "max_forks_count": 4.0, "avg_line_length": 30.4594594595, "max_line_length": 70, "alphanum_fraction": 0.6592724046} | using my_site_tests.Infra.PageObjects;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace my_site_tests.Tests
{
[TestFixture]
public class GoogleTests : AbstractGoogleTestCase
{
[Test]
public void TestGoogleSearchPageSuccess()
{
report.Step("About to enter check cheese search results");
Thread.Sleep(5000);
GoogleSearchPage googleSearchPage = web.GetSearchPage();
googleSearchPage.SendKeysToSearchTb("Cheeseasas");
googleSearchPage.ClickOnSearchBtn();
}
[Test]
public void TestGoogleSearchPageFailure()
{
report.Step("About to enter check cheese search results");
Thread.Sleep(10000);
GoogleSearchPage googleSearchPage = web.GetSearchPage();
googleSearchPage.SendKeysToSearchTb("Cheeseasas");
googleSearchPage.ClickOnSearchBtn();
Assert.NotNull(null, "Failing the test by purpose");
}
}
}
|
||||
TheStack | bd8d60bc7bceaaa7403b8d364c544d92c617a461 | C#code:C# | {"size": 153, "ext": "cs", "max_stars_repo_path": "csharp_bad/csharp_bad/NullConditional.cs", "max_stars_repo_name": "jirkapok/Presentations", "max_stars_repo_stars_event_min_datetime": "2019-06-23T07:07:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-01T13:23:55.000Z", "max_issues_repo_path": "csharp_bad/csharp_bad/NullConditional.cs", "max_issues_repo_name": "jirkapok/Presentations", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "csharp_bad/csharp_bad/NullConditional.cs", "max_forks_repo_name": "jirkapok/Presentations", "max_forks_repo_forks_event_min_datetime": "2022-03-22T18:02:30.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-22T18:02:30.000Z"} | {"max_stars_count": 3.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 17.0, "max_line_length": 47, "alphanum_fraction": 0.660130719} | using System.Collections.Generic;
namespace csharp_bad
{
public class NullConditional
{
public List<string> Dummy { get; set; }
}
} |
||||
TheStack | bd8dde2fea734c7b22224a118a8d6643e35ee6c2 | C#code:C# | {"size": 1495, "ext": "cs", "max_stars_repo_path": "test/Cool.Normalization.Permissions.RemoteProxies.Tests/NormalizationPermissionRemoteProxyTestModule.cs", "max_stars_repo_name": "MaiReo/cool-normalization", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "test/Cool.Normalization.Permissions.RemoteProxies.Tests/NormalizationPermissionRemoteProxyTestModule.cs", "max_issues_repo_name": "MaiReo/cool-normalization", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "test/Cool.Normalization.Permissions.RemoteProxies.Tests/NormalizationPermissionRemoteProxyTestModule.cs", "max_forks_repo_name": "MaiReo/cool-normalization", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.5102040816, "max_line_length": 147, "alphanum_fraction": 0.6381270903} | using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Reflection.Extensions;
using Abp.Runtime.Session;
using Castle.MicroKernel.Registration;
using Cool.Normalization.Permissions;
using System;
using cool.permission.client.Api;
using cool.permission.client.Model;
namespace Abp.Modules
{
[DependsOn(
typeof( NormalizationPermissionRemoteProxyModule ),
typeof( Abp.TestBase.AbpTestBaseModule )
)]
public class NormalizationPermissionRemoteProxyTestModule : AbpModule
{
public override void PreInitialize()
{
Configuration.ReplaceService<IPermissionApi, FakePermissionApi>();
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention( typeof( NormalizationPermissionRemoteProxyTestModule ).GetAssembly() );
}
private void RegisterIfNot<TService, TImpl>( DependencyLifeStyle lifeStyle = default ) where TService : class where TImpl : class, TService
{
if (IocManager.IsRegistered<TService>())
{
return;
}
IocManager.Register<TService, TImpl>( lifeStyle );
}
private void RegisterIfNot<T>( Abp.Dependency.DependencyLifeStyle lifeStyle = default ) where T : class
{
if (IocManager.IsRegistered<T>())
{
return;
}
IocManager.Register<T>( lifeStyle );
}
}
} |
||||
TheStack | bd8f49bdfbafe220c9777f81f9e0a9f62b361b76 | C#code:C# | {"size": 8395, "ext": "cs", "max_stars_repo_path": "nextdhoom.com - SourceCode/Models/replacebadword.cs", "max_stars_repo_name": "aminnagpure/nextdhoom1.0", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "nextdhoom.com - SourceCode/Models/replacebadword.cs", "max_issues_repo_name": "aminnagpure/nextdhoom1.0", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "nextdhoom.com - SourceCode/Models/replacebadword.cs", "max_forks_repo_name": "aminnagpure/nextdhoom1.0", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 149.9107142857, "max_line_length": 4258, "alphanum_fraction": 0.662179869} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text.RegularExpressions;
using System.Web;
namespace WebApplication13.Models
{
public class commonFun
{
public virtual string ReplaceBadWords(string str)
{
try
{
if (!string.IsNullOrEmpty(str))
{
//Dim pattern As String = "( *damn | *dyke | *fuck* | *shit* | @$$ | ahole | amcik | andskota | anus | arschloch | arse* | ash0le | ash0les | asholes | ass | Ass Monkey | Assface | assh0le | assh0lez | asshole | assholes | assholz | assrammer | asswipe | ayir | azzhole | b!+ch | b!tch | b00b* | b00bs | b17ch | b1tch | bassterds | bastard | bastards | bastardz | basterds | basterdz | bi+ch | bi7ch | Biatch | bitch | bitch* | bitches | Blow Job | blowjob | boffing | boiolas | bollock* | boobs | breasts | buceta | butt-pirate | butthole | buttwipe | c0ck | c0cks | c0k | cabron | Carpet Muncher | cawk | cawks | cazzo | chink | chraa | chuj | cipa | clit | clits | cnts | cntz | cock | Cock* | cock-head | cock-sucker | cockhead | cocks | CockSucker | crap | cum | cunt | cunt* | cunts | cuntz | d4mn | daygo | dego | dick | dick* | dike* | dild0 | dild0s | dildo | dildos | dilld0 | dilld0s | dirsa | dominatricks | dominatrics | dominatrix | dupa | dyke | dziwka | ejackulate | ejakulate | Ekrem* | Ekto | enculer | enema | f u c k | f u c k e r | faen | fag | fag* | fag1t | faget | fagg1t | faggit | faggot | fagit | fags | fagz | faig | faigs | fanculo | fanny | fart | fatass | fcuk | feces | feg | Felcher | ficken | fitt* | Flikker | flipping the bird | foreskin | Fotze | Fu(* | fuck | fucker | fuckin | fucking | fucks | Fudge Packer | fuk | fuk* | Fukah | Fuken | fuker | Fukin | Fukk | Fukkah | Fukken | Fukker | Fukkin | futkretzn | fux0r | g00k | gay | gayboy | gaygirl | gays | gayz | God-damned | gook | guiena | h00r | h0ar | h0r | h0re | h4x0r | hell | hells | helvete | hoar | hoer | hoer* | honkey | hoor | hoore | hore | Huevon | hui | injun | jackoff | jap | japs | jerk-off | jisim | jism | jiss | jizm | jizz | kanker* | kawk | kike | klootzak | knob | knobs | knobz | knulle | kraut | kuk | kuksuger | kunt | kunts | kuntz | Kurac | kurwa | kusi* | kyrpa* | l3i+ch | l3itch | Lesbian | lesbo | Lezzian | Lipshits | Lipshitz | mamhoon | masochist | masokist | massterbait | masstrbait | masstrbate | masterbaiter | masterbat* | masterbat3 | masterbate | masterbates | masturbat* | masturbate | merd* | mibun | mofo | monkleigh | Motha Fucker | Motha Fuker | Motha Fukkah | Motha Fukker | Mother Fucker | Mother Fukah | Mother Fuker | Mother Fukkah | Mother Fukker | mother-fucker | motherfucker | mouliewop | muie | mulkku | muschi | Mutha Fucker | Mutha Fukah | Mutha Fuker | Mutha Fukkah | Mutha Fukker | n1gr | nastt | nazi | nazis | nepesaurio | nigga | nigger | nigger* | nigger; | nigur; | niiger; | niigr; | nutsack | orafis | orgasim; | orgasm | orgasum | oriface | orifice | orifiss | orospu | p0rn | packi | packie | packy | paki | pakie | paky | paska* | pecker | peeenus | peeenusss | peenus | peinus | pen1s | penas | penis | penis-breath | penus | penuus | perse | Phuc | Phuck | Phuk | Phuker | Phukker | picka | pierdol* | pillu* | pimmel | pimpis | piss* | pizda | polac | polack | polak | Poonani | poontsee | poop | porn | pr0n | pr1c | pr1ck | pr1k | preteen | pula | pule | pusse | pussee | pussy | puta | puto | puuke | puuker | qahbeh | queef* | queer | queers | queerz | qweers | qweerz | qweir | rautenberg | recktum | rectum | retard | s.o.b. | sadist | scank | schaffer | scheiss* | schlampe | schlong | schmuck | screw | screwing | scrotum | semen | sex | sexy | sh!+ | Sh!t | sh!t* | sh1t | sh1ter | sh1ts | sh1tter | sh1tz | sharmuta | sharmute | shemale | shi+ | shipal | shit | shits | shitter | Shitty | Shity | shitz | shiz | Shyt | Shyte | Shytty | Shyty | skanck | skank | skankee | skankey | skanks | Skanky | skribz | skurwysyn | slut | sluts | Slutty | slutz | smut | son-of-a-bitch | sphencter | spic | spierdalaj | splooge | suka | teets | teez | testical | testicle | testicle* | tit | tits | titt | titt* | turd | twat | va1jina | vag1na | vagiina | vagina | vaj1na | vajina | vittu | vullva | vulva | w00se | w0p | wank | wank* | wetback* | wh00r | wh0re | whoar | whore | wichser | wop* | xrated | xxx | yed | zabourah )"
// string pattern = "(damn|dyke|fuck|shit|ahole|amcik|andskota|anus|arschloch|arse|ash0le|ash0les|asholes|ass|AssMonkey|Assface|assh0le|assh0lez|asshole|assholes|assholz|assrammer|asswipe|ayir|azzhole|bassterds|bastard|bastards|bastardz|basterds|basterdz|Biatch|bitch|bitch|bitches|BlowJob|blowjob|boffing|boiolas|bollock|boobs|breasts|buceta|butt-pirate|butthole|buttwipe|c0ck|c0cks|c0k|cabron|CarpetMuncher|cawk|cawks|cazzo|chink|chraa|chuj|cipa|clit|clits|cnts|cntz|cock|Cock|cock-head|cock-sucker|cockhead|cocks|CockSucker|crap|cum|cunt|cunt|cunts|cuntz|d4mn|daygo|dego|dick|dick|dike|fuck|fucker|fag|fart|fatass|fcuk|feces|feg|Felcher|ficken|fitt|Flikker|flippingthebird|foreskin|Fotze|fuck|fucker|fuckin|fucking|fucks|FudgePacker|fuk|Fukah|Fuken|fuker|Fukin|Fukk|Fukkah|Fukken|Fukker|Fukkin|guiena|hoor|lootzak|knob|knobs|knobz|knulle|kraut|kuk|kuksuger|kunt|kunts|kuntz|Kurac|kurwa|kusi|kyrpa|lesbo|Lezzian|Lipshits|Lipshitz|mamhoon|masochist|masokist|massterbait|masstrbait|masstrbate|masterbaiter|masterbat|masterbat3|masterbate|masterbates|masturbat|masturbate|merd|mibun|mofo|monkleigh|MothaFucker|MothaFuker|MothaFukkah|MothaFukker|MotherFucker|MotherFukah|MotherFuker|MotherFukkah|MotherFukker|mother-fucker|motherfucker|mouliewop|muie|mulkku|muschi|MuthaFucker|MuthaFukah|MuthaFuker|MuthaFukkah|MuthaFukker|n1gr|nastt|nazi|nazis|nepesaurio|nigga|nigger|nigger*|nigger;|nigur;|niiger;|niigr;|nutsack|orafis|orgasim;|orgasm|orgasum|oriface|orifice|orifiss|orospu|p0rn|packi|packie|packy|paki|pakie|paky|paska*|pecker|peeenus|peeenusss|peenus|peinus|pen1s|penas|penis|penis-breath|penus|penuus|perse|Phuc|Phuck|Phuk|Phuker|Phukker|picka|pierdol*|pillu*|pimmel|pimpis|piss*|pizda|polac|polack|polak|Poonani|poontsee|poop|porn|pr0n|pr1c|pr1ck|pr1k|preteen|pula|pule|pusse|pussee|pussy|puta|puto|puuke|puuker|qahbeh|queef*|queer|queers|queerz|qweers|qweerz|qweir|rautenberg|recktum|rectum|retard|s.o.b.|sadist|scank|schaffer|scheiss*|schlampe|schlong|schmuck|screw|screwing|scrotum|semen|sex|sexy|sh!+|Sh!t|sh!t*|sh1t|sh1ter|sh1ts|sh1tter|sh1tz|sharmuta|sharmute|shemale|shi+|shipal|shit|shits|shitter|Shitty|Shity|shitz|shiz|Shyt|Shyte|Shytty|Shyty|skanck|skank|skankee|skankey|skanks|Skanky|skribz|skurwysyn|slut|sluts|Slutty|slutz|smut|son-of-a-bitch|sphencter|spic|spierdalaj|splooge|suka|teets|teez|testical|testicle|testicle*|tit|tits|titt|titt*|turd|twat|va1jina|vag1na|vagiina|vagina|vaj1na|vajina|vittu|vullva|vulva|w00se|w0p|wank|wank*|wetback*|wh00r|wh0re|whoar|whore|wichser|wop*|xrated|xxx|yed|zabourah)";
string pattern = "(damn|dyke|fuck|shit|ahole|amcik|anal|Ass|Anal|Cock|penis|suck|)";
str = Regex.Replace(str, pattern, string.Empty, RegexOptions.IgnoreCase);
//
}
return str.Trim();
}
catch( Exception ex)
{
return ex.Message ;
}
}
public virtual string getip()
{
//get mac address
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// only return MAC Address from first card
{
IPInterfaceProperties properties = adapter.GetIPProperties();
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
}
// To Get IP Address
string IPHost = Dns.GetHostName();
string IP = Dns.GetHostEntry(IPHost).AddressList[0].ToString();
return IP;
}
}
} |
||||
TheStack | bd91668aee60d1c7931a8476741af83e0c9371c3 | C#code:C# | {"size": 1088, "ext": "cs", "max_stars_repo_path": "New Unity Project/Library/PackageCache/[email protected]/Editor/AndroidLogcatStatusBar.cs", "max_stars_repo_name": "HugoJBello/unity-2d-test", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "New Unity Project/Library/PackageCache/[email protected]/Editor/AndroidLogcatStatusBar.cs", "max_issues_repo_name": "HugoJBello/unity-2d-test", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "New Unity Project/Library/PackageCache/[email protected]/Editor/AndroidLogcatStatusBar.cs", "max_forks_repo_name": "HugoJBello/unity-2d-test", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 27.8974358974, "max_line_length": 128, "alphanum_fraction": 0.5358455882} | #if PLATFORM_ANDROID
using System;
using UnityEngine;
namespace Unity.Android.Logcat
{
internal class AndroidLogcatStatusBar
{
public string Message { set; get; }
public bool Connected { set; get; }
public AndroidLogcatStatusBar()
{
Message = String.Empty;
}
public void DoGUI()
{
var rc = GUILayoutUtility.GetRect(GUIContent.none, AndroidLogcatStyles.statusLabel, GUILayout.ExpandWidth(true));
if (Event.current.type == EventType.Repaint)
{
AndroidLogcatStyles.statusBarBackground.Draw(rc, false, true, false, false);
}
rc.x += 10.0f;
var msg = Connected ? "<color=#00FF00FF><b>Connected</b></color>" : "<color=#FF0000FF><b>Disconnected</b></color>";
if (!string.IsNullOrEmpty(Message))
{
msg += " : ";
msg += Message;
}
GUI.Label(rc, msg, AndroidLogcatStyles.statusLabel);
}
}
}
#endif
|
||||
TheStack | bd919921e2d728da88bd1debf9f4239ef4cdb339 | C#code:C# | {"size": 738, "ext": "cs", "max_stars_repo_path": "source.extension.cs", "max_stars_repo_name": "SirAeroWN/OpenInVim", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "source.extension.cs", "max_issues_repo_name": "SirAeroWN/OpenInVim", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "source.extension.cs", "max_forks_repo_name": "SirAeroWN/OpenInVim", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.8421052632, "max_line_length": 83, "alphanum_fraction": 0.4864498645} | // ------------------------------------------------------------------------------
// <auto-generated>
// This file was generated by the extension VSIX Synchronizer
// </auto-generated>
// ------------------------------------------------------------------------------
namespace OpenInVim
{
internal sealed partial class Vsix
{
public const string Id = "OpenIn.f9ec1140-9c52-4362-b8e1-2afdcd99a7ef";
public const string Name = "OpenIn";
public const string Description = @"Empty VSIX Project.";
public const string Language = "en-US";
public const string Version = "1.0";
public const string Author = "Alarm.com";
public const string Tags = "";
}
}
|
||||
TheStack | bd91f22e7bd82d10920a242348620983c7581104 | C#code:C# | {"size": 600, "ext": "cs", "max_stars_repo_path": "Assets/Plugins/VContainer/MVP.DOTween/Runtime/Animations/DOFadeAnimation.cs", "max_stars_repo_name": "chikinov/vcontainer-mvp", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Plugins/VContainer/MVP.DOTween/Runtime/Animations/DOFadeAnimation.cs", "max_issues_repo_name": "chikinov/vcontainer-mvp", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Plugins/VContainer/MVP.DOTween/Runtime/Animations/DOFadeAnimation.cs", "max_forks_repo_name": "chikinov/vcontainer-mvp", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.0, "max_line_length": 66, "alphanum_fraction": 0.5666666667} | using DG.Tweening;
using UnityEngine;
namespace VContainer.Unity.MVP.DOTween
{
public class DOFadeAnimation : DOTweenAnimation
{
[Range(0F, 1F)]
[SerializeField] private float to = 1F;
public override IAnimation Play()
{
if (TryGetComponent<CanvasGroup>(out var canvasGroup))
tween = canvasGroup.DOFade(to, duration)
.SetEase(ease)
.SetUpdate(ignoreTimeScale)
.OnComplete(OnTweenComplete);
else OnTweenComplete();
return this;
}
}
}
|
||||
TheStack | bd9256bcb7297fdd24401bb35d3d3dd0d1996709 | C#code:C# | {"size": 1062, "ext": "cs", "max_stars_repo_path": "Loops/OddOrEvenProduct/OddOrEvenProduct.cs", "max_stars_repo_name": "marianbochev/CSharpFundamentals", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Loops/OddOrEvenProduct/OddOrEvenProduct.cs", "max_issues_repo_name": "marianbochev/CSharpFundamentals", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Loops/OddOrEvenProduct/OddOrEvenProduct.cs", "max_forks_repo_name": "marianbochev/CSharpFundamentals", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.9024390244, "max_line_length": 84, "alphanum_fraction": 0.4237288136} | using System;
using System.Linq;
using System.Numerics;
class OddAndEvenProduct
{
static void Main()
{
{
//input
uint n = uint.Parse(Console.ReadLine());
string[] stringArray = Console.ReadLine().Split();
int[] numbers = new int[n];
long sumOfEvenProduct = 1;
long sumOfOddProduct = 1;
//logic
for (int i = 0; i <= numbers.Length - 1; i++)
{
numbers[i]=Convert.ToInt32(stringArray[i]);
if (i % 2 == 0)
{
sumOfEvenProduct *= numbers[i];
}
else
{
sumOfOddProduct *= numbers[i];
}
}
if (sumOfEvenProduct == sumOfOddProduct)
{
Console.WriteLine("yes " + sumOfEvenProduct);
}
else
{
Console.WriteLine("no " + sumOfEvenProduct + " " + sumOfOddProduct);
}
}
}
}
|
||||
TheStack | bd9477b31420fe8c72d840a71f59cf85577d9a56 | C#code:C# | {"size": 2252, "ext": "cs", "max_stars_repo_path": "src/Facilities/Merchant/MerchantItem.cs", "max_stars_repo_name": "leudaimon/Kerbal-Konstructs", "max_stars_repo_stars_event_min_datetime": "2016-11-13T22:26:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-14T10:09:07.000Z", "max_issues_repo_path": "src/Facilities/Merchant/MerchantItem.cs", "max_issues_repo_name": "leudaimon/Kerbal-Konstructs", "max_issues_repo_issues_event_min_datetime": "2016-11-10T13:30:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-15T21:05:52.000Z", "max_forks_repo_path": "src/Facilities/Merchant/MerchantItem.cs", "max_forks_repo_name": "leudaimon/Kerbal-Konstructs", "max_forks_repo_forks_event_min_datetime": "2016-11-11T02:28:57.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T04:28:58.000Z"} | {"max_stars_count": 31.0, "max_issues_count": 169.0, "max_forks_count": 29.0, "avg_line_length": 23.4583333333, "max_line_length": 103, "alphanum_fraction": 0.6953818828} | using System.IO;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using KSP.UI.Screens;
using KodeUI;
using KerbalKonstructs.Core;
using KerbalKonstructs.Modules;
using KerbalKonstructs.ResourceManager;
namespace KerbalKonstructs.UI {
public class MerchantItem
{
public Merchant merchant { get; private set; }
public TradedResource tradedResource { get; private set; }
public RMResourceInfo vesselResource { get; private set; }
public string name
{
get { return tradedResource.resource.name; }
}
public double basePrice
{
get { return tradedResource.resource.unitCost; }
}
public double buyPrice
{
get { return tradedResource.multiplierBuy * basePrice; }
}
public double sellPrice
{
get { return tradedResource.multiplierSell * basePrice; }
}
public bool canSell { get { return tradedResource.canBeSold; } }
public bool canBuy { get { return tradedResource.canBeBought; } }
public MerchantItem (Merchant merchant, TradedResource tradedResource, RMResourceInfo vesselResource)
{
this.merchant = merchant;
this.tradedResource = tradedResource;
this.vesselResource = vesselResource;
}
public class List : List<MerchantItem>, UIKit.IListObject
{
public UnityAction<MerchantItem> onFromVessel { get; set; }
public UnityAction<MerchantItem> onToVessel { get; set; }
public Layout Content { get; set; }
public Merchant Merchant { get; set; }
public Vessel Vessel { get; set; }
public RectTransform RectTransform
{
get { return Content.rectTransform; }
}
public void Create (int index)
{
Content
.Add<MerchantItemView> ("MerchantItem")
.OnFromVessel (onFromVessel)
.OnToVessel (onToVessel)
.Item (this[index])
.Finish ()
;
}
public void Update (GameObject obj, int index)
{
var view = obj.GetComponent<MerchantItemView> ();
view.Item (this[index]);
}
public void Update(MerchantItem item)
{
int index = IndexOf (item);
if (index >= 0) {
var child = Content.rectTransform.GetChild (index);
var view = child.GetComponent<MerchantItemView> ();
view.Item(item);
}
}
public List ()
{
}
}
}
}
|
||||
TheStack | bd954bbbc66aefc19c845d9c5f50418ccc99e676 | C#code:C# | {"size": 3477, "ext": "cs", "max_stars_repo_path": "FastSockets/Logger/ConsoleLogger.cs", "max_stars_repo_name": "bmjoy/FastSocketsAPI", "max_stars_repo_stars_event_min_datetime": "2021-12-10T09:11:59.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-10T09:11:59.000Z", "max_issues_repo_path": "FastSockets/Logger/ConsoleLogger.cs", "max_issues_repo_name": "bmjoy/FastSocketsAPI", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FastSockets/Logger/ConsoleLogger.cs", "max_forks_repo_name": "bmjoy/FastSocketsAPI", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 31.8990825688, "max_line_length": 171, "alphanum_fraction": 0.4900776531} | //-----------------------------------------------------------------------
// <copyright file="ConsoleLogger.cs" company="Tobias Lenz">
// Copyright Tobias Lenz. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace FastSockets
{
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
/// <summary>
/// Outputs messages to Console and log file.
/// </summary>
public static class ConsoleLogger
{
/// <summary>
/// The log file
/// </summary>
private static string _logfile = "log.txt";
/// <summary>
/// The is initialized
/// </summary>
private static bool _isInitialized = false;
/// <summary>
/// The file locked
/// </summary>
private static ManualResetEvent _fileLocked = new ManualResetEvent(true);
/// <summary>
/// Initializes the logger.
/// </summary>
/// <param name="logfile">The log file.</param>
public static void InitLogger(string logfile)
{
File.Delete(logfile);
ConsoleLogger._logfile = logfile;
_isInitialized = true;
}
/// <summary>
/// Writes to log.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="toConsole">if set to <c>true</c> [to console].</param>
public static void WriteToLog(string message, bool toConsole = false)
{
if (!_isInitialized)
{
Console.WriteLine(message);
return;
}
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
try
{
_fileLocked.WaitOne();
_fileLocked.Reset();
ostrm = new FileStream(_logfile, FileMode.Append, FileAccess.Write);
writer = new StreamWriter(ostrm);
}
catch (Exception)
{
////Console.WriteLine("Cannot open " + _logfile + " for writing");
////Console.WriteLine(e.Message);
return;
}
Console.SetOut(writer);
Console.WriteLine(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss.fff") + "|" + message);
Console.SetOut(oldOut);
writer.Close();
ostrm.Close();
if (toConsole)
{
Console.WriteLine(message);
}
_fileLocked.Set();
}
/// <summary>
/// Writes the error to log.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="toConsole">if set to <c>true</c> [to console].</param>
public static void WriteErrorToLog(string message, bool toConsole = false)
{
var stackTrace = new StackTrace(true);
StackFrame[] f = stackTrace.GetFrames();
WriteToLog("<STACKTRACE BEGIN>", toConsole);
foreach (StackFrame r in f)
{
string s = "[Filename: " + r.GetFileName() + " Method: " + r.GetMethod() + " Line: " + r.GetFileLineNumber() + " Column: " + r.GetFileColumnNumber() + "]";
WriteToLog(s, toConsole);
}
WriteToLog("<STACKTRACE END> " + message, toConsole);
}
}
}
|
||||
TheStack | bd980c2cf0ae7c2722f2e30af7acd027c73a65da | C#code:C# | {"size": 1005, "ext": "cs", "max_stars_repo_path": "Core/YJC.Toolkit.Core/Data/_Expression/ParamExpressionAttribute.cs", "max_stars_repo_name": "madiantech/tkcore", "max_stars_repo_stars_event_min_datetime": "2020-12-28T07:36:28.000Z", "max_stars_repo_stars_event_max_datetime": "2021-10-02T23:37:11.000Z", "max_issues_repo_path": "Core/YJC.Toolkit.Core/Data/_Expression/ParamExpressionAttribute.cs", "max_issues_repo_name": "madiantech/tkcore", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Core/YJC.Toolkit.Core/Data/_Expression/ParamExpressionAttribute.cs", "max_forks_repo_name": "madiantech/tkcore", "max_forks_repo_forks_event_min_datetime": "2021-10-02T23:37:34.000Z", "max_forks_repo_forks_event_max_datetime": "2021-10-02T23:37:34.000Z"} | {"max_stars_count": 4.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 29.5588235294, "max_line_length": 86, "alphanum_fraction": 0.6089552239} | using System;
using YJC.Toolkit.Sys;
namespace YJC.Toolkit.Data
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public sealed class ParamExpressionAttribute : BasePlugInAttribute
{
public ParamExpressionAttribute(string regName)
{
TkDebug.AssertArgumentNullOrEmpty(regName, "regName", null);
TkDebug.Assert(regName.Length == 1,
string.Format(ObjectUtil.SysCulture,
"ParamExpression的注册名只能是一个字符,现在的注册名{0}不是", regName), null);
TkDebug.Assert(!char.IsLetterOrDigit(regName[0]),
string.Format(ObjectUtil.SysCulture,
"ParamExpression的注册名要求不是字母或数字,现在的注册名{0}不是", regName), null);
RegName = regName;
}
public bool SqlInject { get; set; }
public override string FactoryName
{
get
{
return ParamExpressionPlugInFactory.REG_NAME;
}
}
}
}
|
||||
TheStack | bd99bd6cd9ecb99bae56fcb0e638b8899184817c | C#code:C# | {"size": 12175, "ext": "cshtml", "max_stars_repo_path": "adminlte/Views/TASRegistroNotas/TASRegistroNotasNuevo.cshtml", "max_stars_repo_name": "AMarvellous/CIAC-TAS-Web", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "adminlte/Views/TASRegistroNotas/TASRegistroNotasNuevo.cshtml", "max_issues_repo_name": "AMarvellous/CIAC-TAS-Web", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "adminlte/Views/TASRegistroNotas/TASRegistroNotasNuevo.cshtml", "max_forks_repo_name": "AMarvellous/CIAC-TAS-Web", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 47.373540856, "max_line_length": 243, "alphanum_fraction": 0.459137577} | @model adminlte.TASRegistroNotasService.TASRegistroNotasSet
@{
ViewBag.Title = "TASRegistroNotasNuevo";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
TAS
<small>Registro Notas</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li>
<li><a href="#">Registro Notas</a></li>
<li class="active">Configuracion</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<!-- Default box -->
<div class="box box-primary">
@using (Html.BeginForm())
{
<div class="box-header with-border">
<h3 class="box-title">CIAC TAS</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
@*<form role="form">*@
<div class="box-body">
@Html.AntiForgeryToken()
<div class="form-group">
@Html.Label("Programa")
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-users"></i>
</div>
@*@Html.EditorFor(model => model.ltTASRegistroNotas[0].Grupo, new { htmlAttributes = new { @class = "form-control" } })*@
@Html.DropDownListFor(model => model.ltTASRegistroNotas[0].Programa, new SelectList(@ViewBag.ltTASPrograma as System.Collections.IEnumerable, null, "Programa"), "Programa", new { @class = "form-control controlar" })
@Html.ValidationMessageFor(model => model.ltTASRegistroNotas[0].Programa, "", new { @class = "text-danger" })
@*<input type="number" class="form-control">*@
</div>
<!-- /.input group -->
</div>
<div class="form-group">
@Html.Label("Grupo")
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-users"></i>
</div>
@*@Html.EditorFor(model => model.ltTASRegistroNotas[0].Grupo, new { htmlAttributes = new { @class = "form-control" } })*@
@Html.DropDownListFor(model => model.ltTASRegistroNotas[0].Grupo, new SelectList(@ViewBag.ltTASGrupo as System.Collections.IEnumerable, null, "Grupo"), "Grupo", new { @class = "form-control controlar" })
@Html.ValidationMessageFor(model => model.ltTASRegistroNotas[0].Grupo, "", new { @class = "text-danger" })
@*<input type="number" class="form-control">*@
</div>
<!-- /.input group -->
</div>
<div class="form-group">
@Html.Label("Materia")
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-users"></i>
</div>
@*@Html.EditorFor(model => model.ltTASRegistroNotas[0].Grupo, new { htmlAttributes = new { @class = "form-control" } })*@
@Html.DropDownListFor(model => model.ltTASRegistroNotas[0].Materia, new SelectList(@ViewBag.ltTASMateria as System.Collections.IEnumerable, null, "Materia"), "Materia", new { @class = "form-control controlar" })
@Html.ValidationMessageFor(model => model.ltTASRegistroNotas[0].Materia, "", new { @class = "text-danger" })
@*<input type="number" class="form-control">*@
</div>
<!-- /.input group -->
</div>
<div class="form-group">
@Html.Label("Modulo")
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-users"></i>
</div>
@*@Html.EditorFor(model => model.ltTASRegistroNotas[0].Grupo, new { htmlAttributes = new { @class = "form-control" } })*@
@Html.DropDownListFor(model => model.ltTASRegistroNotas[0].ModuloMateria, new SelectList(@ViewBag.ltTASModulo as System.Collections.IEnumerable, null, "Modulo"), "Modulo", new { @class = "form-control controlar" })
@Html.ValidationMessageFor(model => model.ltTASRegistroNotas[0].ModuloMateria, "", new { @class = "text-danger" })
@*<input type="number" class="form-control">*@
</div>
<!-- /.input group -->
</div>
<div class="form-group">
@Html.Label("Gestion")
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-users"></i>
</div>
@*@Html.EditorFor(model => model.ltTASRegistroNotas[0].Grupo, new { htmlAttributes = new { @class = "form-control" } })*@
@Html.DropDownListFor(model => model.ltTASRegistroNotas[0].Gestion, new SelectList(@ViewBag.ltTASGestion as System.Collections.IEnumerable, null, "Gestion"), "Gestion", new { @class = "form-control controlar" })
@Html.ValidationMessageFor(model => model.ltTASRegistroNotas[0].Gestion, "", new { @class = "text-danger" })
@*<input type="number" class="form-control">*@
</div>
<!-- /.input group -->
</div>
<div class="form-group">
@Html.Label("Progregos Cantidad")
<div class="input-group">
<div class="input-group-addon">
<i class="fa fa-users"></i>
</div>
@*@Html.EditorFor(model => model.ltTASRegistroNotas[0].Grupo, new { htmlAttributes = new { @class = "form-control" } })*@
@Html.DropDownList("CantidadProgresos", new SelectList(@ViewBag.ltCantidadProgresos as System.Collections.IEnumerable), "Cantidad de Progresos", new { @class = "form-control controlar" })
@*<input type="number" class="form-control">*@
</div>
<!-- /.input group -->
</div>
@Html.HiddenFor(model => model.ltTASRegistroNotas[0].NumeroProgresos)
@Html.HiddenFor(model => model.ltTASRegistroNotas[0].NombreReferenciaProgreso)
@Html.HiddenFor(model => model.ltTASRegistroNotas[0].PorcentajeIndividualProgreso)
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary">Siguiente</button>
</div>
@*</form>*@
}
</div>
<!-- /.box -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
@*@Scripts.Render("~/bundles/jquery")*@
@section scripts{
<script type="text/javascript">
$(document).on('change', '#CantidadProgresos', function (e) {
$('#Container').html('');
$("div.divCreated").remove();
if ($('#CantidadProgresos').val() > 0) {
for (i = 0; i < $('#CantidadProgresos').val(); i++) {
//Agregar los progresos aca
var Row = '<div class="row divCreated">';
Row += '<div class="col-xs-5">'
Row += '<input type="text" class="form-control nombreEvaluacion" placeholder="Nombre Progreso">'
Row += '</div>'
Row += '<div class="col-xs-5">'
Row += '<input type="text" class="form-control allownumericwithdecimal porcentajeEvaluacion" placeholder="Porcentaje Progreso">'
Row += '</div>'
Row += '</div>'
$(".box-body").append(Row);
}
$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
//this.value = this.value.replace(/[^0-9\.]/g,'');
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
}
else {
}
})
$('form').submit(function () {
if ($('#ltTASRegistroNotas_0__Programa').val() == '') {
alert("No se selecciono ningun Programa");
return false;
}
if ($('#ltTASRegistroNotas_0__Grupo').val() == '') {
alert("No se selecciono ningun Grupo");
return false;
}
if ($('#ltTASRegistroNotas_0__Materia').val() == '') {
alert("No se selecciono ninguna Materia");
return false;
}
if ($('#ltTASRegistroNotas_0__ModuloMateria').val() == '') {
alert("No se selecciono ningun Modulo");
return false;
}
if ($('#ltTASRegistroNotas_0__Gestion').val() == '') {
alert("No se selecciono ninguna Gestion");
return false;
}
if ($('#CantidadProgresos').val() == '') {
alert("No se selecciono ninguna cantidad de evaluacion de progreso");
return false;
}
$("#ltTASRegistroNotas_0__NumeroProgresos").val($('#CantidadProgresos').val());
var strConcat = '';
$("input.nombreEvaluacion").each(function () {
strConcat += "*.-Split-.*" + $(this).val();
//alert($(this).val())
});
$("#ltTASRegistroNotas_0__NombreReferenciaProgreso").val(strConcat);
var SumPorcentaje = 0;
var strPorcentaje = '';
$("input.porcentajeEvaluacion").each(function () {
strPorcentaje += "*.-Split-.*" + Number($(this).val());
SumPorcentaje += Number($(this).val());
});
if (SumPorcentaje == 30) {
$("#ltTASRegistroNotas_0__PorcentajeIndividualProgreso").val(strPorcentaje);
} else {
alert('La suma de porcentajes no es 30, la suma actual es:' + SumPorcentaje);
return false;
}
//// Check if empty of not
//if (name === '') {
// alert('Text-field is empty.');
// return false;
//}
});
//$(document).on('click', 'form button[type=submit]', function (e) {
// var isValid = $(e.target).parents('form').isValid();
// if (!isValid) {
// e.preventDefault(); //prevent the default action
// }
// });
//$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
// alert("as")
// //this.value = this.value.replace(/[^0-9\.]/g,'');
// $(this).val($(this).val().replace(/[^0-9\.]/g, ''));
// if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
// event.preventDefault();
// }
//});
</script>
} |
||||
TheStack | bd9a2811a5fc4d1bdcf83e1786447e0c8e0734f2 | C#code:C# | {"size": 4479, "ext": "cs", "max_stars_repo_path": "AmeffSerializer/V31/Element/ElementType.cs", "max_stars_repo_name": "adrichem/AmeffSerializer", "max_stars_repo_stars_event_min_datetime": "2020-09-04T16:16:13.000Z", "max_stars_repo_stars_event_max_datetime": "2020-09-04T16:16:13.000Z", "max_issues_repo_path": "AmeffSerializer/V31/Element/ElementType.cs", "max_issues_repo_name": "adrichem/AmeffSerializer", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AmeffSerializer/V31/Element/ElementType.cs", "max_forks_repo_name": "adrichem/AmeffSerializer", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 60.527027027, "max_line_length": 97, "alphanum_fraction": 0.7807546327} | namespace Adrichem.Serialization.Ameff.V31.Element
{
[System.Xml.Serialization.XmlInclude(typeof(CompositeType))]
[System.Xml.Serialization.XmlInclude(typeof(Location))]
[System.Xml.Serialization.XmlInclude(typeof(Grouping))]
[System.Xml.Serialization.XmlInclude(typeof(RelationshipConnectorType))]
[System.Xml.Serialization.XmlInclude(typeof(OrJunction))]
[System.Xml.Serialization.XmlInclude(typeof(AndJunction))]
[System.Xml.Serialization.XmlInclude(typeof(RealElementType))]
[System.Xml.Serialization.XmlInclude(typeof(Gap))]
[System.Xml.Serialization.XmlInclude(typeof(Plateau))]
[System.Xml.Serialization.XmlInclude(typeof(ImplementationEvent))]
[System.Xml.Serialization.XmlInclude(typeof(Deliverable))]
[System.Xml.Serialization.XmlInclude(typeof(WorkPackage))]
[System.Xml.Serialization.XmlInclude(typeof(CourseOfAction))]
[System.Xml.Serialization.XmlInclude(typeof(ValueStream))]
[System.Xml.Serialization.XmlInclude(typeof(Capability))]
[System.Xml.Serialization.XmlInclude(typeof(Resource))]
[System.Xml.Serialization.XmlInclude(typeof(Value))]
[System.Xml.Serialization.XmlInclude(typeof(Meaning))]
[System.Xml.Serialization.XmlInclude(typeof(Constraint))]
[System.Xml.Serialization.XmlInclude(typeof(Requirement))]
[System.Xml.Serialization.XmlInclude(typeof(Principle))]
[System.Xml.Serialization.XmlInclude(typeof(Outcome))]
[System.Xml.Serialization.XmlInclude(typeof(Goal))]
[System.Xml.Serialization.XmlInclude(typeof(Assessment))]
[System.Xml.Serialization.XmlInclude(typeof(Driver))]
[System.Xml.Serialization.XmlInclude(typeof(Stakeholder))]
[System.Xml.Serialization.XmlInclude(typeof(Material))]
[System.Xml.Serialization.XmlInclude(typeof(DistributionNetwork))]
[System.Xml.Serialization.XmlInclude(typeof(Facility))]
[System.Xml.Serialization.XmlInclude(typeof(Equipment))]
[System.Xml.Serialization.XmlInclude(typeof(Artifact))]
[System.Xml.Serialization.XmlInclude(typeof(TechnologyService))]
[System.Xml.Serialization.XmlInclude(typeof(TechnologyEvent))]
[System.Xml.Serialization.XmlInclude(typeof(TechnologyInteraction))]
[System.Xml.Serialization.XmlInclude(typeof(TechnologyProcess))]
[System.Xml.Serialization.XmlInclude(typeof(TechnologyFunction))]
[System.Xml.Serialization.XmlInclude(typeof(CommunicationNetwork))]
[System.Xml.Serialization.XmlInclude(typeof(Path))]
[System.Xml.Serialization.XmlInclude(typeof(TechnologyInterface))]
[System.Xml.Serialization.XmlInclude(typeof(TechnologyCollaboration))]
[System.Xml.Serialization.XmlInclude(typeof(SystemSoftware))]
[System.Xml.Serialization.XmlInclude(typeof(Device))]
[System.Xml.Serialization.XmlInclude(typeof(Node))]
[System.Xml.Serialization.XmlInclude(typeof(DataObject))]
[System.Xml.Serialization.XmlInclude(typeof(ApplicationService))]
[System.Xml.Serialization.XmlInclude(typeof(ApplicationEvent))]
[System.Xml.Serialization.XmlInclude(typeof(ApplicationProcess))]
[System.Xml.Serialization.XmlInclude(typeof(ApplicationInteraction))]
[System.Xml.Serialization.XmlInclude(typeof(ApplicationFunction))]
[System.Xml.Serialization.XmlInclude(typeof(ApplicationInterface))]
[System.Xml.Serialization.XmlInclude(typeof(ApplicationCollaboration))]
[System.Xml.Serialization.XmlInclude(typeof(ApplicationComponent))]
[System.Xml.Serialization.XmlInclude(typeof(Product))]
[System.Xml.Serialization.XmlInclude(typeof(Representation))]
[System.Xml.Serialization.XmlInclude(typeof(Contract))]
[System.Xml.Serialization.XmlInclude(typeof(BusinessObject))]
[System.Xml.Serialization.XmlInclude(typeof(BusinessService))]
[System.Xml.Serialization.XmlInclude(typeof(BusinessEvent))]
[System.Xml.Serialization.XmlInclude(typeof(BusinessInteraction))]
[System.Xml.Serialization.XmlInclude(typeof(BusinessFunction))]
[System.Xml.Serialization.XmlInclude(typeof(BusinessProcess))]
[System.Xml.Serialization.XmlInclude(typeof(BusinessInterface))]
[System.Xml.Serialization.XmlInclude(typeof(BusinessCollaboration))]
[System.Xml.Serialization.XmlInclude(typeof(BusinessRole))]
[System.Xml.Serialization.XmlInclude(typeof(BusinessActor))]
[System.Serializable()]
[System.Xml.Serialization.XmlType(Namespace = "http://www.opengroup.org/xsd/archimate/3.0/")]
public abstract partial class ElementType : ConceptType
{
}
}
|
||||
TheStack | bd9bd24b2cb36334ca3334cf0e40b850bcf6de58 | C#code:C# | {"size": 4860, "ext": "cs", "max_stars_repo_path": "Source/EventFlow.Examples.Shipping.Tests/IntegrationTests/Scenarios.cs", "max_stars_repo_name": "FinalFortune/EventFlow", "max_stars_repo_stars_event_min_datetime": "2020-11-26T01:39:45.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-26T01:39:45.000Z", "max_issues_repo_path": "Source/EventFlow.Examples.Shipping.Tests/IntegrationTests/Scenarios.cs", "max_issues_repo_name": "FinalFortune/EventFlow", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Source/EventFlow.Examples.Shipping.Tests/IntegrationTests/Scenarios.cs", "max_forks_repo_name": "FinalFortune/EventFlow", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 37.6744186047, "max_line_length": 121, "alphanum_fraction": 0.666255144} | // The MIT License (MIT)
//
// Copyright (c) 2015-2020 Rasmus Mikkelsen
// Copyright (c) 2015-2020 eBay Software Foundation
// https://github.com/eventflow/EventFlow
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using EventFlow.Aggregates;
using EventFlow.Configuration;
using EventFlow.Core;
using EventFlow.Examples.Shipping.Application;
using EventFlow.Examples.Shipping.Domain.Model.CargoModel.ValueObjects;
using EventFlow.Examples.Shipping.Domain.Model.LocationModel;
using EventFlow.Examples.Shipping.Domain.Model.VoyageModel;
using EventFlow.Examples.Shipping.Domain.Model.VoyageModel.Commands;
using EventFlow.Examples.Shipping.Queries.InMemory;
using EventFlow.Extensions;
using EventFlow.Logs;
using EventFlow.TestHelpers;
using FluentAssertions.Extensions;
using NUnit.Framework;
namespace EventFlow.Examples.Shipping.Tests.IntegrationTests
{
[Category(Categories.Integration)]
public class Scenarios : Test
{
private IRootResolver _resolver;
private IAggregateStore _aggregateStore;
private ICommandBus _commandBus;
[SetUp]
public void SetUp()
{
_resolver = EventFlowOptions.New
.ConfigureShippingDomain()
.ConfigureShippingQueriesInMemory()
.CreateResolver();
_aggregateStore = _resolver.Resolve<IAggregateStore>();
_commandBus = _resolver.Resolve<ICommandBus>();
}
[TearDown]
public void TearDown()
{
_resolver.DisposeSafe(new ConsoleLog(), "");
}
[Test]
public async Task Simple()
{
await CreateLocationAggregatesAsync().ConfigureAwait(false);
await CreateVoyageAggregatesAsync().ConfigureAwait(false);
var route = new Route(
Locations.Tokyo,
Locations.Helsinki,
1.October(2008).At(11, 00),
6.November(2008).At(12, 00));
var booking = _resolver.Resolve<IBookingApplicationService>();
await booking.BookCargoAsync(route, CancellationToken.None).ConfigureAwait(false);
var voyage = _resolver.Resolve<IScheduleApplicationService>();
await voyage.DelayScheduleAsync(
Voyages.DallasToHelsinkiId,
TimeSpan.FromDays(7),
CancellationToken.None)
.ConfigureAwait(false);
}
public Task CreateVoyageAggregatesAsync()
{
return Task.WhenAll(Voyages.GetVoyages().Select(CreateVoyageAggregateAsync));
}
public Task CreateVoyageAggregateAsync(Voyage voyage)
{
return _commandBus.PublishAsync(new VoyageCreateCommand(voyage.Id, voyage.Schedule), CancellationToken.None);
}
public Task CreateLocationAggregatesAsync()
{
return Task.WhenAll(Locations.GetLocations().Select(CreateLocationAggregateAsync));
}
public Task CreateLocationAggregateAsync(Location location)
{
return UpdateAsync<LocationAggregate, LocationId>(location.Id, a => a.Create(location.Name));
}
private async Task UpdateAsync<TAggregate, TIdentity>(TIdentity id, Action<TAggregate> action)
where TAggregate : IAggregateRoot<TIdentity>
where TIdentity : IIdentity
{
await _aggregateStore.UpdateAsync<TAggregate, TIdentity>(
id,
SourceId.New,
(a, c) =>
{
action(a);
return Task.FromResult(0);
},
CancellationToken.None)
.ConfigureAwait(false);
}
}
} |
||||
TheStack | bd9e00e6b235c17d0d6a7a5747917c71f1dc6a71 | C#code:C# | {"size": 20771, "ext": "cs", "max_stars_repo_path": "xilium.cefglue/CefGlue/Interop/Classes.g/cef_browser_t.g.cs", "max_stars_repo_name": "git-thinh/Xilium.CefGlue-lvcef-39.0", "max_stars_repo_stars_event_min_datetime": "2018-07-02T02:52:20.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-10T00:41:21.000Z", "max_issues_repo_path": "xilium.cefglue/CefGlue/Interop/Classes.g/cef_browser_t.g.cs", "max_issues_repo_name": "git-thinh/Xilium.CefGlue-lvcef-39.0", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "xilium.cefglue/CefGlue/Interop/Classes.g/cef_browser_t.g.cs", "max_forks_repo_name": "git-thinh/Xilium.CefGlue-lvcef-39.0", "max_forks_repo_forks_event_min_datetime": "2018-09-23T02:07:15.000Z", "max_forks_repo_forks_event_max_datetime": "2020-03-15T19:21:40.000Z"} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 35.0861486486, "max_line_length": 141, "alphanum_fraction": 0.5659814164} | //
// DO NOT MODIFY! THIS IS AUTOGENERATED FILE!
//
namespace Xilium.CefGlue.Interop
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using System.Security;
[StructLayout(LayoutKind.Sequential, Pack = libcef.ALIGN)]
[SuppressMessage("Microsoft.Design", "CA1049:TypesThatOwnNativeResourcesShouldBeDisposable")]
internal unsafe struct cef_browser_t
{
internal cef_base_t _base;
internal IntPtr _get_host;
internal IntPtr _can_go_back;
internal IntPtr _go_back;
internal IntPtr _can_go_forward;
internal IntPtr _go_forward;
internal IntPtr _is_loading;
internal IntPtr _reload;
internal IntPtr _reload_ignore_cache;
internal IntPtr _stop_load;
internal IntPtr _get_identifier;
internal IntPtr _is_same;
internal IntPtr _is_popup;
internal IntPtr _has_document;
internal IntPtr _get_main_frame;
internal IntPtr _get_focused_frame;
internal IntPtr _get_frame_byident;
internal IntPtr _get_frame;
internal IntPtr _get_frame_count;
internal IntPtr _get_frame_identifiers;
internal IntPtr _get_frame_names;
internal IntPtr _send_process_message;
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate void add_ref_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate int release_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate int has_one_ref_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate cef_browser_host_t* get_host_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate int can_go_back_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate void go_back_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate int can_go_forward_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate void go_forward_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate int is_loading_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate void reload_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate void reload_ignore_cache_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate void stop_load_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate int get_identifier_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate int is_same_delegate(cef_browser_t* self, cef_browser_t* that);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate int is_popup_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate int has_document_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate cef_frame_t* get_main_frame_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate cef_frame_t* get_focused_frame_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate cef_frame_t* get_frame_byident_delegate(cef_browser_t* self, long identifier);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate cef_frame_t* get_frame_delegate(cef_browser_t* self, cef_string_t* name);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate UIntPtr get_frame_count_delegate(cef_browser_t* self);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate void get_frame_identifiers_delegate(cef_browser_t* self, UIntPtr* identifiersCount, long* identifiers);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate void get_frame_names_delegate(cef_browser_t* self, cef_string_list* names);
[UnmanagedFunctionPointer(libcef.CEF_CALLBACK)]
#if !DEBUG
[SuppressUnmanagedCodeSecurity]
#endif
private delegate int send_process_message_delegate(cef_browser_t* self, CefProcessId target_process, cef_process_message_t* message);
// AddRef
private static IntPtr _p0;
private static add_ref_delegate _d0;
public static void add_ref(cef_browser_t* self)
{
add_ref_delegate d;
var p = self->_base._add_ref;
if (p == _p0) { d = _d0; }
else
{
d = (add_ref_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(add_ref_delegate));
if (_p0 == IntPtr.Zero) { _d0 = d; _p0 = p; }
}
d(self);
}
// Release
private static IntPtr _p1;
private static release_delegate _d1;
public static int release(cef_browser_t* self)
{
release_delegate d;
var p = self->_base._release;
if (p == _p1) { d = _d1; }
else
{
d = (release_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(release_delegate));
if (_p1 == IntPtr.Zero) { _d1 = d; _p1 = p; }
}
return d(self);
}
// HasOneRef
private static IntPtr _p2;
private static has_one_ref_delegate _d2;
public static int has_one_ref(cef_browser_t* self)
{
has_one_ref_delegate d;
var p = self->_base._has_one_ref;
if (p == _p2) { d = _d2; }
else
{
d = (has_one_ref_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(has_one_ref_delegate));
if (_p2 == IntPtr.Zero) { _d2 = d; _p2 = p; }
}
return d(self);
}
// GetHost
private static IntPtr _p3;
private static get_host_delegate _d3;
public static cef_browser_host_t* get_host(cef_browser_t* self)
{
get_host_delegate d;
var p = self->_get_host;
if (p == _p3) { d = _d3; }
else
{
d = (get_host_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_host_delegate));
if (_p3 == IntPtr.Zero) { _d3 = d; _p3 = p; }
}
return d(self);
}
// CanGoBack
private static IntPtr _p4;
private static can_go_back_delegate _d4;
public static int can_go_back(cef_browser_t* self)
{
can_go_back_delegate d;
var p = self->_can_go_back;
if (p == _p4) { d = _d4; }
else
{
d = (can_go_back_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(can_go_back_delegate));
if (_p4 == IntPtr.Zero) { _d4 = d; _p4 = p; }
}
return d(self);
}
// GoBack
private static IntPtr _p5;
private static go_back_delegate _d5;
public static void go_back(cef_browser_t* self)
{
go_back_delegate d;
var p = self->_go_back;
if (p == _p5) { d = _d5; }
else
{
d = (go_back_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(go_back_delegate));
if (_p5 == IntPtr.Zero) { _d5 = d; _p5 = p; }
}
d(self);
}
// CanGoForward
private static IntPtr _p6;
private static can_go_forward_delegate _d6;
public static int can_go_forward(cef_browser_t* self)
{
can_go_forward_delegate d;
var p = self->_can_go_forward;
if (p == _p6) { d = _d6; }
else
{
d = (can_go_forward_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(can_go_forward_delegate));
if (_p6 == IntPtr.Zero) { _d6 = d; _p6 = p; }
}
return d(self);
}
// GoForward
private static IntPtr _p7;
private static go_forward_delegate _d7;
public static void go_forward(cef_browser_t* self)
{
go_forward_delegate d;
var p = self->_go_forward;
if (p == _p7) { d = _d7; }
else
{
d = (go_forward_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(go_forward_delegate));
if (_p7 == IntPtr.Zero) { _d7 = d; _p7 = p; }
}
d(self);
}
// IsLoading
private static IntPtr _p8;
private static is_loading_delegate _d8;
public static int is_loading(cef_browser_t* self)
{
is_loading_delegate d;
var p = self->_is_loading;
if (p == _p8) { d = _d8; }
else
{
d = (is_loading_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(is_loading_delegate));
if (_p8 == IntPtr.Zero) { _d8 = d; _p8 = p; }
}
return d(self);
}
// Reload
private static IntPtr _p9;
private static reload_delegate _d9;
public static void reload(cef_browser_t* self)
{
reload_delegate d;
var p = self->_reload;
if (p == _p9) { d = _d9; }
else
{
d = (reload_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(reload_delegate));
if (_p9 == IntPtr.Zero) { _d9 = d; _p9 = p; }
}
d(self);
}
// ReloadIgnoreCache
private static IntPtr _pa;
private static reload_ignore_cache_delegate _da;
public static void reload_ignore_cache(cef_browser_t* self)
{
reload_ignore_cache_delegate d;
var p = self->_reload_ignore_cache;
if (p == _pa) { d = _da; }
else
{
d = (reload_ignore_cache_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(reload_ignore_cache_delegate));
if (_pa == IntPtr.Zero) { _da = d; _pa = p; }
}
d(self);
}
// StopLoad
private static IntPtr _pb;
private static stop_load_delegate _db;
public static void stop_load(cef_browser_t* self)
{
stop_load_delegate d;
var p = self->_stop_load;
if (p == _pb) { d = _db; }
else
{
d = (stop_load_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(stop_load_delegate));
if (_pb == IntPtr.Zero) { _db = d; _pb = p; }
}
d(self);
}
// GetIdentifier
private static IntPtr _pc;
private static get_identifier_delegate _dc;
public static int get_identifier(cef_browser_t* self)
{
get_identifier_delegate d;
var p = self->_get_identifier;
if (p == _pc) { d = _dc; }
else
{
d = (get_identifier_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_identifier_delegate));
if (_pc == IntPtr.Zero) { _dc = d; _pc = p; }
}
return d(self);
}
// IsSame
private static IntPtr _pd;
private static is_same_delegate _dd;
public static int is_same(cef_browser_t* self, cef_browser_t* that)
{
is_same_delegate d;
var p = self->_is_same;
if (p == _pd) { d = _dd; }
else
{
d = (is_same_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(is_same_delegate));
if (_pd == IntPtr.Zero) { _dd = d; _pd = p; }
}
return d(self, that);
}
// IsPopup
private static IntPtr _pe;
private static is_popup_delegate _de;
public static int is_popup(cef_browser_t* self)
{
is_popup_delegate d;
var p = self->_is_popup;
if (p == _pe) { d = _de; }
else
{
d = (is_popup_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(is_popup_delegate));
if (_pe == IntPtr.Zero) { _de = d; _pe = p; }
}
return d(self);
}
// HasDocument
private static IntPtr _pf;
private static has_document_delegate _df;
public static int has_document(cef_browser_t* self)
{
has_document_delegate d;
var p = self->_has_document;
if (p == _pf) { d = _df; }
else
{
d = (has_document_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(has_document_delegate));
if (_pf == IntPtr.Zero) { _df = d; _pf = p; }
}
return d(self);
}
// GetMainFrame
private static IntPtr _p10;
private static get_main_frame_delegate _d10;
public static cef_frame_t* get_main_frame(cef_browser_t* self)
{
get_main_frame_delegate d;
var p = self->_get_main_frame;
if (p == _p10) { d = _d10; }
else
{
d = (get_main_frame_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_main_frame_delegate));
if (_p10 == IntPtr.Zero) { _d10 = d; _p10 = p; }
}
return d(self);
}
// GetFocusedFrame
private static IntPtr _p11;
private static get_focused_frame_delegate _d11;
public static cef_frame_t* get_focused_frame(cef_browser_t* self)
{
get_focused_frame_delegate d;
var p = self->_get_focused_frame;
if (p == _p11) { d = _d11; }
else
{
d = (get_focused_frame_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_focused_frame_delegate));
if (_p11 == IntPtr.Zero) { _d11 = d; _p11 = p; }
}
return d(self);
}
// GetFrame
private static IntPtr _p12;
private static get_frame_byident_delegate _d12;
public static cef_frame_t* get_frame_byident(cef_browser_t* self, long identifier)
{
get_frame_byident_delegate d;
var p = self->_get_frame_byident;
if (p == _p12) { d = _d12; }
else
{
d = (get_frame_byident_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_frame_byident_delegate));
if (_p12 == IntPtr.Zero) { _d12 = d; _p12 = p; }
}
return d(self, identifier);
}
// GetFrame
private static IntPtr _p13;
private static get_frame_delegate _d13;
public static cef_frame_t* get_frame(cef_browser_t* self, cef_string_t* name)
{
get_frame_delegate d;
var p = self->_get_frame;
if (p == _p13) { d = _d13; }
else
{
d = (get_frame_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_frame_delegate));
if (_p13 == IntPtr.Zero) { _d13 = d; _p13 = p; }
}
return d(self, name);
}
// GetFrameCount
private static IntPtr _p14;
private static get_frame_count_delegate _d14;
public static UIntPtr get_frame_count(cef_browser_t* self)
{
get_frame_count_delegate d;
var p = self->_get_frame_count;
if (p == _p14) { d = _d14; }
else
{
d = (get_frame_count_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_frame_count_delegate));
if (_p14 == IntPtr.Zero) { _d14 = d; _p14 = p; }
}
return d(self);
}
// GetFrameIdentifiers
private static IntPtr _p15;
private static get_frame_identifiers_delegate _d15;
public static void get_frame_identifiers(cef_browser_t* self, UIntPtr* identifiersCount, long* identifiers)
{
get_frame_identifiers_delegate d;
var p = self->_get_frame_identifiers;
if (p == _p15) { d = _d15; }
else
{
d = (get_frame_identifiers_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_frame_identifiers_delegate));
if (_p15 == IntPtr.Zero) { _d15 = d; _p15 = p; }
}
d(self, identifiersCount, identifiers);
}
// GetFrameNames
private static IntPtr _p16;
private static get_frame_names_delegate _d16;
public static void get_frame_names(cef_browser_t* self, cef_string_list* names)
{
get_frame_names_delegate d;
var p = self->_get_frame_names;
if (p == _p16) { d = _d16; }
else
{
d = (get_frame_names_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(get_frame_names_delegate));
if (_p16 == IntPtr.Zero) { _d16 = d; _p16 = p; }
}
d(self, names);
}
// SendProcessMessage
private static IntPtr _p17;
private static send_process_message_delegate _d17;
public static int send_process_message(cef_browser_t* self, CefProcessId target_process, cef_process_message_t* message)
{
send_process_message_delegate d;
var p = self->_send_process_message;
if (p == _p17) { d = _d17; }
else
{
d = (send_process_message_delegate)Marshal.GetDelegateForFunctionPointer(p, typeof(send_process_message_delegate));
if (_p17 == IntPtr.Zero) { _d17 = d; _p17 = p; }
}
return d(self, target_process, message);
}
}
}
|
||||
TheStack | bd9e2110b3624f5294d3484d8fdd656554e362f4 | C#code:C# | {"size": 857, "ext": "cs", "max_stars_repo_path": "src/RendleLabs.Redis.DivideAndConquer/DivideAndConquerPublisherEx.cs", "max_stars_repo_name": "RendleLabs/Redis.DivideAndConquer", "max_stars_repo_stars_event_min_datetime": "2017-01-30T21:17:08.000Z", "max_stars_repo_stars_event_max_datetime": "2017-01-30T21:17:08.000Z", "max_issues_repo_path": "src/RendleLabs.Redis.DivideAndConquer/DivideAndConquerPublisherEx.cs", "max_issues_repo_name": "RendleLabs/Redis.DivideAndConquer", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RendleLabs.Redis.DivideAndConquer/DivideAndConquerPublisherEx.cs", "max_forks_repo_name": "RendleLabs/Redis.DivideAndConquer", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 47.6111111111, "max_line_length": 145, "alphanum_fraction": 0.7747957993} | using System.Collections.Concurrent;
using System.Runtime.CompilerServices;
using StackExchange.Redis;
namespace RendleLabs.Redis.DivideAndConquer
{
public static class DivideAndConquerPublisherEx
{
private static readonly ConditionalWeakTable<ConnectionMultiplexer, ConcurrentDictionary<RedisChannel, IDivideAndConquerPublisher>> Cache
= new ConditionalWeakTable<ConnectionMultiplexer, ConcurrentDictionary<RedisChannel, IDivideAndConquerPublisher>>();
public static IDivideAndConquerPublisher GetDivideAndConquerPublisher(this ConnectionMultiplexer redis, RedisChannel channel)
{
var dict = Cache.GetValue(redis, _ => new ConcurrentDictionary<RedisChannel, IDivideAndConquerPublisher>());
return dict.GetOrAdd(channel, ch => new DivideAndConquerPublisher(redis, ch));
}
}
} |
||||
TheStack | bd9e6340f88c6d4b4628b767cfbdb78839307055 | C#code:C# | {"size": 10736, "ext": "cs", "max_stars_repo_path": "Spyglass/Commands/MailCommands.cs", "max_stars_repo_name": "Erlite/Spyglass", "max_stars_repo_stars_event_min_datetime": "2021-08-23T05:17:40.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T19:58:11.000Z", "max_issues_repo_path": "Spyglass/Commands/MailCommands.cs", "max_issues_repo_name": "QI-Software/Spyglass", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Spyglass/Commands/MailCommands.cs", "max_forks_repo_name": "QI-Software/Spyglass", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 5.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 49.4746543779, "max_line_length": 222, "alphanum_fraction": 0.6278874814} | using System;
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.Entities;
using DSharpPlus.Interactivity.Extensions;
using DSharpPlus.SlashCommands;
using Serilog.Core;
using Spyglass.Database.Moderation;
using Spyglass.Preconditions;
using Spyglass.Services;
using Spyglass.Utilities;
namespace Spyglass.Commands
{
[SlashCommandGroup("mail", "Contains commands pertaining to moderation mail.")]
[RequireBotPermissions(Permissions.ManageChannels | Permissions.SendMessages | Permissions.AddReactions)]
public class MailCommands : ApplicationCommandModule
{
private readonly BlacklistService _blacklist;
private readonly ConfigurationService _config;
private readonly EmbedService _embeds;
private readonly Logger _log;
private readonly MailService _mail;
public MailCommands(BlacklistService blacklist, ConfigurationService config, EmbedService embeds, MailService mail, Logger log)
{
_blacklist = blacklist;
_config = config;
_embeds = embeds;
_log = log;
_mail = mail;
}
[SlashCommand("setup", "Set up mod mail in the current server.")]
[RequirePermissions(Permissions.ManageGuild)]
public async Task SetupModmail(InteractionContext ctx)
{
var config = _config.GetConfig();
if (config.ModMailEnabled)
{
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
new DiscordInteractionResponseBuilder().AddEmbed(_embeds.Message("Mod mail is already enabled, please disable it first.", DiscordColor.Red)));
return;
}
var setupButton = new DiscordButtonComponent(ButtonStyle.Primary, "setupModMail", "Setup Mod Mail");
var cancelButton = new DiscordButtonComponent(ButtonStyle.Danger, "cancelModMail", "Cancel");
var warningEmbed = _embeds.Message("You are about to setup moderation mail on **this** server. Mod mail requires a **lot** of channels, so I recommend doing this on a secondary server to avoid issues.",
DiscordColor.Orange);
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
new DiscordInteractionResponseBuilder()
.AddComponents(setupButton, cancelButton)
.AddEmbed(warningEmbed));
var message = await ctx.GetOriginalResponseAsync();
var result = await message.WaitForButtonAsync(ctx.User, TimeSpan.FromMinutes(5));
if (result.TimedOut)
{
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().AddEmbed(_embeds.Message("Timed out.", DiscordColor.Red)));
return;
}
if (result.Result.Id == cancelButton.CustomId)
{
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().AddEmbed(_embeds.Message("Cancelled.", DiscordColor.Red)));
return;
}
config.ModMailServerId = ctx.Guild.Id;
var unansweredCategory = ctx.Guild.Channels.Values
.FirstOrDefault(c => c.IsCategory && c.Name.ToLower().Equals("unanswered"));
unansweredCategory ??= await ctx.Guild.CreateChannelCategoryAsync("Unanswered");
var answeredCategory = ctx.Guild.Channels.Values
.FirstOrDefault(c => c.IsCategory && c.Name.ToLower().Equals("answered"));
answeredCategory ??= await ctx.Guild.CreateChannelCategoryAsync("Answered");
config.ModMailUnansweredCategoryId = unansweredCategory.Id;
config.ModMailAnsweredCategoryId = answeredCategory.Id;
config.ModMailEnabled = true;
try
{
await _config.SaveConfigAsync();
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().AddEmbed(_embeds.Message("Successfully enabled mod mail and saved configuration.", DiscordColor.Green)));
_ = _mail.RecoverSessionsAsync();
_log.Information($"{ctx.User} enabled mod mail.");
}
catch (Exception e)
{
_log.Error(e, "An exception has occurred while modifying the configuration.");
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder()
.AddEmbed(_embeds.Message("Failed to save configuration, contact the maintainer.", DiscordColor.Red)));
}
}
[SlashCommand("disable", "Disables mod mail, completely stopping incoming and outgoing mail.")]
[RequirePermissions(Permissions.ManageGuild)]
public async Task DisableModMail(InteractionContext ctx)
{
var config = _config.GetConfig();
if (!config.ModMailEnabled)
{
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
new DiscordInteractionResponseBuilder().AddEmbed(_embeds.Message("Mod mail is already disabled, please enable it first.", DiscordColor.Red)));
return;
}
var modMailGuild = await DiscordUtils.TryGetGuildAsync(ctx.Client, config.ModMailServerId);
if (modMailGuild != null && ctx.Guild.Id != modMailGuild.Id)
{
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
new DiscordInteractionResponseBuilder().AddEmbed(_embeds.Message("This command can only be ran on the mail server for safety reasons, unless I do not have access to said server.", DiscordColor.Red)));
return;
}
await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);
config.ModMailEnabled = false;
config.ModMailServerId = 0;
config.ModMailAnsweredCategoryId = 0;
config.ModMailUnansweredCategoryId = 0;
try
{
await _config.SaveConfigAsync();
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().AddEmbed(_embeds.Message("Successfully disabled mod mail.", DiscordColor.Green)));
_log.Information($"{ctx.User} disabled mod mail.");
}
catch (Exception e)
{
_log.Error(e, "An exception has occurred while modifying the configuration.");
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder()
.AddEmbed(_embeds.Message("Failed to save configuration, contact the maintainer.", DiscordColor.Red)));
}
}
[SlashCommand("create", "Create a mod mail session to discuss with a user.")]
public async Task CreateModMailSession(InteractionContext ctx,
[Option("user", "The user to create a mod mail session for.")] DiscordUser user)
{
var config = _config.GetConfig();
if (!config.ModMailEnabled)
{
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
new DiscordInteractionResponseBuilder().AddEmbed(_embeds.Message("Mod mail is not enabled, please enable it first.", DiscordColor.Red)));
return;
}
if (_mail.HasSession(user.Id))
{
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource, new DiscordInteractionResponseBuilder()
.AddEmbed(_embeds.Message("The specified user already has a mail session opened.", DiscordColor.Red)));
return;
}
await ctx.CreateResponseAsync(InteractionResponseType.DeferredChannelMessageWithSource);
try
{
var session = await _mail.CreateSessionAsync(user.Id);
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().AddEmbed(_embeds.Message($"Created new session for user {user.Username}#{user.Discriminator}: <#{session.MailChannelId}>.", DiscordColor.Green)));
}
catch (Exception e)
{
_log.Error(e, $"ModMail: Failed to create session for user {user}: {e.Message}");
await ctx.FollowUpAsync(new DiscordFollowupMessageBuilder().AddEmbed(_embeds.Message($"Failed to create session for {user.Username}#{user.Discriminator}: {e.Message}", DiscordColor.Red)));
}
}
[SlashCommand("close", "Close a mod mail session.")]
public async Task CloseModMailSession(InteractionContext ctx,
[Option("channel", "The channel to close. Leave empty to pick the current one.")] DiscordChannel channel = null)
{
var config = _config.GetConfig();
if (!config.ModMailEnabled)
{
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
new DiscordInteractionResponseBuilder().AddEmbed(_embeds.Message("Mod mail is not enabled, please enable it first.", DiscordColor.Red)));
return;
}
channel ??= ctx.Channel;
if (!_mail.IsChannelLinkedToSession(channel.Id))
{
await ctx.CreateResponseAsync(InteractionResponseType.ChannelMessageWithSource,
new DiscordInteractionResponseBuilder().AddEmbed(_embeds.Message($"{channel.Mention} isn't linked to any mail session.", DiscordColor.Red)));
return;
}
var session = _mail.GetSessionFromChannel(ctx.Channel.Id);
var query = _blacklist.IsBlacklisted(BlacklistType.ModMail, session.MailUserId);
if (query.Successful && !query.Result && ctx.Channel.Parent != null
&& ctx.Channel.ParentId != config.ModMailUnansweredCategoryId)
{
var mainGuild = await DiscordUtils.TryGetGuildAsync(ctx.Client, config.MainGuildId);
if (mainGuild != null)
{
var sessionUser = await DiscordUtils.TryGetMemberAsync(mainGuild, session.MailUserId);
_ = DiscordUtils.TryMessageUserAsync(sessionUser, new DiscordMessageBuilder().WithEmbed(_embeds.Message(
"This moderation mail session is now closed, thank you!",
DiscordColor.Green)));
}
}
await _mail.CloseMailSessionAsync(session);
}
}
} |
||||
TheStack | bda0390a90d09006d5b81655be77a58c363b6fd5 | C#code:C# | {"size": 7379, "ext": "cs", "max_stars_repo_path": "Tools/DeviceValidator/SendLogFrom.cs", "max_stars_repo_name": "okertanov/Developer-Tools-for-UPnP-Technologies", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Tools/DeviceValidator/SendLogFrom.cs", "max_issues_repo_name": "okertanov/Developer-Tools-for-UPnP-Technologies", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Tools/DeviceValidator/SendLogFrom.cs", "max_forks_repo_name": "okertanov/Developer-Tools-for-UPnP-Technologies", "max_forks_repo_forks_event_min_datetime": "2019-02-22T19:57:30.000Z", "max_forks_repo_forks_event_max_datetime": "2019-02-22T19:57:30.000Z"} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 33.5409090909, "max_line_length": 107, "alphanum_fraction": 0.6767854723} | /*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
namespace UPnPValidator
{
/// <summary>
/// Summary description for SendLogFrom.
/// </summary>
public class SendLogFrom : System.Windows.Forms.Form
{
private System.Windows.Forms.Label CompanyLabel;
private System.Windows.Forms.TextBox CompanyNameTextBox;
private System.Windows.Forms.TextBox EmailAddressTextBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private new System.Windows.Forms.Button CancelButton;
private System.Windows.Forms.Button SendButton;
private System.Windows.Forms.TextBox DeviceDescriptionTextBox;
private System.Windows.Forms.TextBox SMTPServerTextBox;
private System.Windows.Forms.Label label3;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public SendLogFrom()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
public new string CompanyName
{
get {return CompanyNameTextBox.Text;}
}
public string EmailAddress
{
get {return EmailAddressTextBox.Text;}
}
public string DeviceDescription
{
get {return DeviceDescriptionTextBox.Text;}
}
public string SMTPServer
{
get {return SMTPServerTextBox.Text;}
set {SMTPServerTextBox.Text = value;}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(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()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(SendLogFrom));
this.CompanyLabel = new System.Windows.Forms.Label();
this.CompanyNameTextBox = new System.Windows.Forms.TextBox();
this.EmailAddressTextBox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.DeviceDescriptionTextBox = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label();
this.CancelButton = new System.Windows.Forms.Button();
this.SendButton = new System.Windows.Forms.Button();
this.SMTPServerTextBox = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// CompanyLabel
//
this.CompanyLabel.Location = new System.Drawing.Point(16, 18);
this.CompanyLabel.Name = "CompanyLabel";
this.CompanyLabel.Size = new System.Drawing.Size(120, 16);
this.CompanyLabel.TabIndex = 0;
this.CompanyLabel.Text = "Company";
//
// CompanyNameTextBox
//
this.CompanyNameTextBox.Location = new System.Drawing.Point(152, 16);
this.CompanyNameTextBox.Name = "CompanyNameTextBox";
this.CompanyNameTextBox.Size = new System.Drawing.Size(192, 20);
this.CompanyNameTextBox.TabIndex = 1;
this.CompanyNameTextBox.Text = "";
//
// EmailAddressTextBox
//
this.EmailAddressTextBox.Location = new System.Drawing.Point(152, 48);
this.EmailAddressTextBox.Name = "EmailAddressTextBox";
this.EmailAddressTextBox.Size = new System.Drawing.Size(192, 20);
this.EmailAddressTextBox.TabIndex = 3;
this.EmailAddressTextBox.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 48);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(112, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Email Address";
//
// DeviceDescriptionTextBox
//
this.DeviceDescriptionTextBox.Location = new System.Drawing.Point(152, 112);
this.DeviceDescriptionTextBox.Multiline = true;
this.DeviceDescriptionTextBox.Name = "DeviceDescriptionTextBox";
this.DeviceDescriptionTextBox.Size = new System.Drawing.Size(192, 64);
this.DeviceDescriptionTextBox.TabIndex = 5;
this.DeviceDescriptionTextBox.Text = "";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 112);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(120, 16);
this.label2.TabIndex = 4;
this.label2.Text = "Device Description";
//
// CancelButton
//
this.CancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.CancelButton.Location = new System.Drawing.Point(152, 192);
this.CancelButton.Name = "CancelButton";
this.CancelButton.Size = new System.Drawing.Size(96, 23);
this.CancelButton.TabIndex = 6;
this.CancelButton.Text = "Cancel";
//
// SendButton
//
this.SendButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.SendButton.Location = new System.Drawing.Point(248, 192);
this.SendButton.Name = "SendButton";
this.SendButton.Size = new System.Drawing.Size(96, 23);
this.SendButton.TabIndex = 7;
this.SendButton.Text = "Send";
//
// SMTPServerTextBox
//
this.SMTPServerTextBox.Location = new System.Drawing.Point(152, 80);
this.SMTPServerTextBox.Name = "SMTPServerTextBox";
this.SMTPServerTextBox.Size = new System.Drawing.Size(192, 20);
this.SMTPServerTextBox.TabIndex = 9;
this.SMTPServerTextBox.Text = "";
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 80);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(112, 16);
this.label3.TabIndex = 8;
this.label3.Text = "SMTP Server";
//
// SendLogFrom
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(376, 230);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.SMTPServerTextBox,
this.label3,
this.SendButton,
this.CancelButton,
this.DeviceDescriptionTextBox,
this.label2,
this.EmailAddressTextBox,
this.label1,
this.CompanyNameTextBox,
this.CompanyLabel});
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "SendLogFrom";
this.Text = "SendLogFrom";
this.ResumeLayout(false);
}
#endregion
}
}
|
||||
TheStack | bda0519703d745fe3f3bb85622e34ac2232eee1d | C#code:C# | {"size": 253, "ext": "cs", "max_stars_repo_path": "Topocat.Backend/Topocat.Domain/Entities/Map/Events/MapRemoved.cs", "max_stars_repo_name": "DarkFIxED/topocat", "max_stars_repo_stars_event_min_datetime": "2019-01-05T13:57:48.000Z", "max_stars_repo_stars_event_max_datetime": "2019-12-17T13:21:38.000Z", "max_issues_repo_path": "Topocat.Backend/Topocat.Domain/Entities/Map/Events/MapRemoved.cs", "max_issues_repo_name": "DarkFIxED/topocat", "max_issues_repo_issues_event_min_datetime": "2019-01-23T04:04:50.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-02T03:03:03.000Z", "max_forks_repo_path": "Topocat.Backend/Topocat.Domain/Entities/Map/Events/MapRemoved.cs", "max_forks_repo_name": "DarkFIxED/topocat", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 4.0, "max_issues_count": 28.0, "max_forks_count": null, "avg_line_length": 18.0714285714, "max_line_length": 44, "alphanum_fraction": 0.5731225296} | using Topocat.Common;
namespace Topocat.Domain.Entities.Map.Events
{
public class MapRemoved : IDomainEvent
{
public string MapId { get; set; }
public MapRemoved(Map map)
{
MapId = map.Id;
}
}
} |
||||
TheStack | bda0e343159c9ba315188b96b8fca7f317d9c5fc | C#code:C# | {"size": 2072, "ext": "cs", "max_stars_repo_path": "src/RW.Orchard.Conditions/Providers/TagCondition.cs", "max_stars_repo_name": "robertwray/RW.Orchard.Conditions", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/RW.Orchard.Conditions/Providers/TagCondition.cs", "max_issues_repo_name": "robertwray/RW.Orchard.Conditions", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/RW.Orchard.Conditions/Providers/TagCondition.cs", "max_forks_repo_name": "robertwray/RW.Orchard.Conditions", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 38.3703703704, "max_line_length": 162, "alphanum_fraction": 0.6732625483} | using Orchard;
using Orchard.Alias;
using Orchard.Conditions.Services;
using Orchard.ContentManagement;
using Orchard.Environment.Extensions;
using Orchard.Tags.Models;
using System;
using System.Linq;
namespace RW.Orchard.Conditions.Providers
{
[OrchardFeature("RW.Orchard.Conditions.Tag")]
public sealed class TagCondition : IConditionProvider
{
private readonly IAliasService _aliasService;
private readonly IWorkContextAccessor _workContextAccessor;
private readonly IContentManager _contentManager;
public TagCondition(IAliasService aliasService, IWorkContextAccessor workContextAccessor, IContentManager contentManager)
{
_aliasService = aliasService;
_workContextAccessor = workContextAccessor;
_contentManager = contentManager;
}
public void Evaluate(ConditionEvaluationContext evaluationContext)
{
if (!string.Equals(evaluationContext.FunctionName, "tag", StringComparison.OrdinalIgnoreCase))
{
return;
}
var tagName = Convert.ToString(evaluationContext.Arguments[0]);
var _currentContent = GetContentItemForCurrentRequest();
if (_currentContent.Has<TagsPart>())
{
var tagPart = _currentContent.Get<TagsPart>();
evaluationContext.Result = tagPart.CurrentTags != null && tagPart.CurrentTags.Any(tag => tag.Equals(tagName, StringComparison.OrdinalIgnoreCase));
}
else
{
evaluationContext.Result = false;
}
}
private IContent GetContentItemForCurrentRequest()
{
var requestUrl = _workContextAccessor.GetContext().HttpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(1).Trim('/');
var requestItemRoute = _aliasService.Get(requestUrl);
return requestItemRoute == null ? _contentManager.New("Dummy") : _contentManager.Get(Convert.ToInt32(requestItemRoute["Id"]));
}
}
} |
||||
TheStack | bda104a67e1418470fa8b85e75268976bbdf62af | C#code:C# | {"size": 416, "ext": "cs", "max_stars_repo_path": "BurgerBuilderBackend/BurgerBuilder.DTOs/Classes/Address.cs", "max_stars_repo_name": "Duch003/ReactBurger", "max_stars_repo_stars_event_min_datetime": "2021-02-22T12:21:47.000Z", "max_stars_repo_stars_event_max_datetime": "2021-02-22T12:21:47.000Z", "max_issues_repo_path": "BurgerBuilderBackend/BurgerBuilder.DTOs/Classes/Address.cs", "max_issues_repo_name": "Duch003/ReactBurger", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "BurgerBuilderBackend/BurgerBuilder.DTOs/Classes/Address.cs", "max_forks_repo_name": "Duch003/ReactBurger", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 21.8947368421, "max_line_length": 44, "alphanum_fraction": 0.6274038462} | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace BurgerBuilder.DTOs.Classes
{
public class Address
{
public int ID { get; set; }
[Required]
public string Street { get; set; }
[Required]
public string Zipcode { get; set; }
[Required]
public string Country { get; set; }
}
}
|
||||
TheStack | bda1d8133dbe94db18910abd1be3fc0bc1ce7119 | C#code:C# | {"size": 1934, "ext": "cs", "max_stars_repo_path": "AESharp/KeyExpressions/ImportExpr.cs", "max_stars_repo_name": "prozum/ae-sharp", "max_stars_repo_stars_event_min_datetime": "2016-04-07T11:16:49.000Z", "max_stars_repo_stars_event_max_datetime": "2016-04-07T11:16:49.000Z", "max_issues_repo_path": "AESharp/KeyExpressions/ImportExpr.cs", "max_issues_repo_name": "prozum/ae-sharp", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AESharp/KeyExpressions/ImportExpr.cs", "max_forks_repo_name": "prozum/ae-sharp", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.175, "max_line_length": 75, "alphanum_fraction": 0.4508790072} | using AESharp.Values;
namespace AESharp.KeyExpressions
{
public class ImportExpr : Expression
{
public Expression Expression;
public ImportExpr(Expression expr, Scope scope)
{
Expression = expr;
CurScope = scope;
}
public override bool Visit(IVisitor v) => v.Visit(this);
public override Expression Evaluate()
{
var res = Expression.Value;
if (res is Error)
return res;
if (res is List)
{
foreach (var expr in (res as List).Items)
{
res = expr.Value;
if (res is Error)
return res;
if (res is VarFunc)
res = Expression.Evaluate();
if (res is Error)
return res;
if (res is Scope)
ImportScope(res as Scope);
else
return new Error(Expression, "contains Non-Scope");
}
}
if (res is VarFunc)
res = Expression.Evaluate();
if (res is Error)
return res;
if (res is Scope)
ImportScope(res as Scope);
else
return new Error(Expression, "contains Non-Scope");
return Constant.Null;
}
public void ImportScope(Scope scope)
{
foreach (var @var in scope.Locals)
{
CurScope.SetVar(@var.Key, @var.Value);
}
}
public override Expression Clone(Scope scope)
{
return new ImportExpr(Expression.Clone(scope), scope);
}
public override string ToString()
{
return "import " + Expression.ToString();
}
}
}
|
||||
TheStack | bda242297c330940721705d38d5fc952d0fa9d19 | C#code:C# | {"size": 1689, "ext": "cs", "max_stars_repo_path": "EIDSS v6/eidss.winclient/Administration/SettlementListPanel.cs", "max_stars_repo_name": "EIDSS/EIDSS-Legacy", "max_stars_repo_stars_event_min_datetime": "2017-09-14T03:03:40.000Z", "max_stars_repo_stars_event_max_datetime": "2017-09-15T14:58:47.000Z", "max_issues_repo_path": "EIDSS v6/eidss.winclient/Administration/SettlementListPanel.cs", "max_issues_repo_name": "EIDSS/EIDSS-Legacy", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "EIDSS v6/eidss.winclient/Administration/SettlementListPanel.cs", "max_forks_repo_name": "EIDSS/EIDSS-Legacy", "max_forks_repo_forks_event_min_datetime": "2017-09-14T03:03:45.000Z", "max_forks_repo_forks_event_max_datetime": "2019-03-25T23:09:43.000Z"} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": 2.0, "avg_line_length": 32.4807692308, "max_line_length": 122, "alphanum_fraction": 0.6039076377} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using bv.common.Core;
using bv.model.Model.Core;
using bv.winclient.BasePanel;
using bv.winclient.Core;
using eidss.model.Enums;
using eidss.model.Schema;
using eidss.winclient.Schema;
namespace eidss.winclient.Administration
{
public partial class SettlementListPanel : BaseListPanel_SettlementListItem
{
public SettlementListPanel()
{
InitializeComponent();
}
public override string GetDetailFormName(IObject o)
{
return "SettlementDetail";
}
public static void Register(Control parentControl)
{
MenuAction menuAdministration = MenuActionManager.Instance.FindAction("MenuAdministration",
MenuActionManager.Instance.System, 970);
new MenuAction(ShowMe, MenuActionManager.Instance, menuAdministration,
"MenuSettlementList", 949, false, (int)MenuIconsSmall.SettlementsList,
-1)
{
SelectPermission = PermissionHelper.SelectPermission(EIDSSPermissionObject.GisReference),
ShowInMenu = true,
};
}
private static void ShowMe()
{
BaseFormManager.ShowClient(typeof(SettlementListPanel), BaseFormManager.MainForm,
SettlementListItem.CreateInstance());
}
}
}
|
||||
TheStack | bda2bc892ee04c92792e8995d43fbbbbb8348a2d | C#code:C# | {"size": 90, "ext": "cs", "max_stars_repo_path": "Business Logic/Entities/LeagueManager.Financial.Models/PaymentReceipt.cs", "max_stars_repo_name": "kicker3082/LeagueManager", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Business Logic/Entities/LeagueManager.Financial.Models/PaymentReceipt.cs", "max_issues_repo_name": "kicker3082/LeagueManager", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Business Logic/Entities/LeagueManager.Financial.Models/PaymentReceipt.cs", "max_forks_repo_name": "kicker3082/LeagueManager", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 12.8571428571, "max_line_length": 41, "alphanum_fraction": 0.6888888889} | namespace LeagueManager.Financial.Models
{
public class PaymentReceipt
{
}
}
|
||||
TheStack | bda2ce886da4c439e4376fed70a4025fe6310980 | C#code:C# | {"size": 128, "ext": "cs", "max_stars_repo_path": "RayCasting.Core/Location2D.cs", "max_stars_repo_name": "davidwhitney/RayCastingDemo", "max_stars_repo_stars_event_min_datetime": "2020-04-27T13:02:54.000Z", "max_stars_repo_stars_event_max_datetime": "2020-04-27T13:02:54.000Z", "max_issues_repo_path": "RayCasting.Core/Location2D.cs", "max_issues_repo_name": "davidwhitney/RayCastingDemo", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RayCasting.Core/Location2D.cs", "max_forks_repo_name": "davidwhitney/RayCastingDemo", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 16.0, "max_line_length": 29, "alphanum_fraction": 0.5546875} | namespace RayCasting.Core
{
public struct Location2D
{
public double X;
public double Y;
}
} |
||||
TheStack | bda369c471178f8993964c2aaedf9663f61f2e55 | C#code:C# | {"size": 3841, "ext": "cs", "max_stars_repo_path": "sdk/src/Services/Outposts/Generated/Model/Internal/MarshallTransformations/RackPhysicalPropertiesMarshaller.cs", "max_stars_repo_name": "pcameron-/aws-sdk-net", "max_stars_repo_stars_event_min_datetime": "2015-01-15T19:41:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:25:23.000Z", "max_issues_repo_path": "sdk/src/Services/Outposts/Generated/Model/Internal/MarshallTransformations/RackPhysicalPropertiesMarshaller.cs", "max_issues_repo_name": "pcameron-/aws-sdk-net", "max_issues_repo_issues_event_min_datetime": "2015-01-05T19:40:22.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T19:57:40.000Z", "max_forks_repo_path": "sdk/src/Services/Outposts/Generated/Model/Internal/MarshallTransformations/RackPhysicalPropertiesMarshaller.cs", "max_forks_repo_name": "pcameron-/aws-sdk-net", "max_forks_repo_forks_event_min_datetime": "2015-01-17T12:51:09.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-28T09:59:50.000Z"} | {"max_stars_count": 1705.0, "max_issues_count": 1811.0, "max_forks_count": 839.0, "avg_line_length": 34.9181818182, "max_line_length": 118, "alphanum_fraction": 0.6370736787} | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the outposts-2019-12-03.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.Outposts.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Outposts.Model.Internal.MarshallTransformations
{
/// <summary>
/// RackPhysicalProperties Marshaller
/// </summary>
public class RackPhysicalPropertiesMarshaller : IRequestMarshaller<RackPhysicalProperties, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(RackPhysicalProperties requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetFiberOpticCableType())
{
context.Writer.WritePropertyName("FiberOpticCableType");
context.Writer.Write(requestObject.FiberOpticCableType);
}
if(requestObject.IsSetMaximumSupportedWeightLbs())
{
context.Writer.WritePropertyName("MaximumSupportedWeightLbs");
context.Writer.Write(requestObject.MaximumSupportedWeightLbs);
}
if(requestObject.IsSetOpticalStandard())
{
context.Writer.WritePropertyName("OpticalStandard");
context.Writer.Write(requestObject.OpticalStandard);
}
if(requestObject.IsSetPowerConnector())
{
context.Writer.WritePropertyName("PowerConnector");
context.Writer.Write(requestObject.PowerConnector);
}
if(requestObject.IsSetPowerDrawKva())
{
context.Writer.WritePropertyName("PowerDrawKva");
context.Writer.Write(requestObject.PowerDrawKva);
}
if(requestObject.IsSetPowerFeedDrop())
{
context.Writer.WritePropertyName("PowerFeedDrop");
context.Writer.Write(requestObject.PowerFeedDrop);
}
if(requestObject.IsSetPowerPhase())
{
context.Writer.WritePropertyName("PowerPhase");
context.Writer.Write(requestObject.PowerPhase);
}
if(requestObject.IsSetUplinkCount())
{
context.Writer.WritePropertyName("UplinkCount");
context.Writer.Write(requestObject.UplinkCount);
}
if(requestObject.IsSetUplinkGbps())
{
context.Writer.WritePropertyName("UplinkGbps");
context.Writer.Write(requestObject.UplinkGbps);
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static RackPhysicalPropertiesMarshaller Instance = new RackPhysicalPropertiesMarshaller();
}
} |
||||
TheStack | bda379d68d47a36d8655ec4108a96c680fb09b3c | C#code:C# | {"size": 2374, "ext": "cs", "max_stars_repo_path": "EssentialUIKit/ViewModels/Navigation/IconNamesListViewModel.cs", "max_stars_repo_name": "pqhcker/essential-ui-kit-for-xamarin.forms", "max_stars_repo_stars_event_min_datetime": "2019-05-21T06:57:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:56:49.000Z", "max_issues_repo_path": "EssentialUIKit/ViewModels/Navigation/IconNamesListViewModel.cs", "max_issues_repo_name": "pqhcker/essential-ui-kit-for-xamarin.forms", "max_issues_repo_issues_event_min_datetime": "2019-08-30T11:00:30.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-14T07:52:57.000Z", "max_forks_repo_path": "EssentialUIKit/ViewModels/Navigation/IconNamesListViewModel.cs", "max_forks_repo_name": "pqhcker/essential-ui-kit-for-xamarin.forms", "max_forks_repo_forks_event_min_datetime": "2019-07-05T11:14:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T17:29:27.000Z"} | {"max_stars_count": 1018.0, "max_issues_count": 48.0, "max_forks_count": 324.0, "avg_line_length": 26.6741573034, "max_line_length": 121, "alphanum_fraction": 0.5716090986} | using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using EssentialUIKit.Models.Navigation;
using Xamarin.Forms;
using Xamarin.Forms.Internals;
namespace EssentialUIKit.ViewModels.Navigation
{
/// <summary>
/// ViewModel for icon names list page.
/// </summary>
[Preserve(AllMembers = true)]
[DataContract]
public class IconNamesListViewModel : BaseViewModel
{
#region Fields
private Command<object> itemTappedCommand;
private Command nextCommand;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance for the <see cref="IconNamesListViewModel"/> class.
/// </summary>
public IconNamesListViewModel()
{
}
#endregion
#region Properties
/// <summary>
/// Gets the command that will be executed when an item is selected.
/// </summary>
public Command<object> ItemTappedCommand
{
get
{
return this.itemTappedCommand ?? (this.itemTappedCommand = new Command<object>(this.NavigateToNextPage));
}
}
/// <summary>
/// Gets the next command that will be executed when an item is selected.
/// </summary>
public Command NextCommand
{
get
{
return this.nextCommand ?? (this.nextCommand = new Command(this.NextClicked));
}
}
/// <summary>
/// Gets or sets a collction of value to be displayed in icon names list page.
/// </summary>
[DataMember(Name = "namesListPage")]
public ObservableCollection<Contact> IconNamesList { get; set; }
#endregion
#region Methods
/// <summary>
/// Invoked when an item is selected from the icon names list.
/// </summary>
/// <param name="selectedItem">Selected item from the list view.</param>
private void NavigateToNextPage(object selectedItem)
{
// Do something
}
/// <summary>
/// Invoked when the Next button is clicked.
/// </summary>
/// <param name="obj">The Object</param>
private void NextClicked(object obj)
{
// Do something
}
#endregion
}
}
|
||||
TheStack | bda3fec34061248c502524a0cf25473af3c2c104 | C#code:C# | {"size": 1776, "ext": "cs", "max_stars_repo_path": "sdk/dotnet/Maintenance/Inputs/ConfigurationWindowGetArgs.cs", "max_stars_repo_name": "henriktao/pulumi-azure", "max_stars_repo_stars_event_min_datetime": "2018-06-18T00:19:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-20T05:32:57.000Z", "max_issues_repo_path": "sdk/dotnet/Maintenance/Inputs/ConfigurationWindowGetArgs.cs", "max_issues_repo_name": "henriktao/pulumi-azure", "max_issues_repo_issues_event_min_datetime": "2018-06-18T21:08:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:10:11.000Z", "max_forks_repo_path": "sdk/dotnet/Maintenance/Inputs/ConfigurationWindowGetArgs.cs", "max_forks_repo_name": "henriktao/pulumi-azure", "max_forks_repo_forks_event_min_datetime": "2018-07-19T22:37:38.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-14T10:56:26.000Z"} | {"max_stars_count": 109.0, "max_issues_count": 663.0, "max_forks_count": 41.0, "avg_line_length": 35.52, "max_line_length": 161, "alphanum_fraction": 0.6283783784} | // *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Azure.Maintenance.Inputs
{
public sealed class ConfigurationWindowGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The duration of the maintenance window in HH:mm format.
/// </summary>
[Input("duration")]
public Input<string>? Duration { get; set; }
/// <summary>
/// Effective expiration date of the maintenance window in YYYY-MM-DD hh:mm format.
/// </summary>
[Input("expirationDateTime")]
public Input<string>? ExpirationDateTime { get; set; }
/// <summary>
/// The rate at which a maintenance window is expected to recur. The rate can be expressed as daily, weekly, or monthly schedules.
/// </summary>
[Input("recurEvery")]
public Input<string>? RecurEvery { get; set; }
/// <summary>
/// Effective start date of the maintenance window in YYYY-MM-DD hh:mm format.
/// </summary>
[Input("startDateTime", required: true)]
public Input<string> StartDateTime { get; set; } = null!;
/// <summary>
/// The time zone for the maintenance window. A list of timezones can be obtained by executing [System.TimeZoneInfo]::GetSystemTimeZones() in PowerShell.
/// </summary>
[Input("timeZone", required: true)]
public Input<string> TimeZone { get; set; } = null!;
public ConfigurationWindowGetArgs()
{
}
}
}
|
||||
TheStack | bda58d3c81536f77c525f29d6ab2682bd2150852 | C#code:C# | {"size": 2015, "ext": "cs", "max_stars_repo_path": "Source/StatWorker_TurretWeaponDPS.cs", "max_stars_repo_name": "RadHazard/RimworldRangedDPS", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Source/StatWorker_TurretWeaponDPS.cs", "max_issues_repo_name": "RadHazard/RimworldRangedDPS", "max_issues_repo_issues_event_min_datetime": "2020-06-23T02:21:14.000Z", "max_issues_repo_issues_event_max_datetime": "2020-06-23T02:21:14.000Z", "max_forks_repo_path": "Source/StatWorker_TurretWeaponDPS.cs", "max_forks_repo_name": "RadHazard/RimworldRangedDPS", "max_forks_repo_forks_event_min_datetime": "2022-01-04T21:33:36.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-04T21:33:36.000Z"} | {"max_stars_count": null, "max_issues_count": 1.0, "max_forks_count": 1.0, "avg_line_length": 33.0327868852, "max_line_length": 161, "alphanum_fraction": 0.6004962779} | using System;
using System.Linq;
using RangedDPS.StatUtilities;
using RimWorld;
using Verse;
namespace RangedDPS
{
public class StatWorker_TurretWeaponDPS : StatWorker_TurretDPSBase
{
public override float GetValueUnfinalized(StatRequest req, bool applyPostProcess = true)
{
if (!ShouldShowFor(req))
{
return 0f;
}
RangedWeaponStats weaponStats = GetTurretStats(req);
float bestAccuracy = new[] {
weaponStats.AccuracyTouch,
weaponStats.AccuracyShort,
weaponStats.AccuracyMedium,
weaponStats.AccuracyLong
}.Max();
return weaponStats.GetRawDPS() * Math.Min(bestAccuracy, 1f);
}
public override string GetStatDrawEntryLabel(StatDef stat, float value, ToStringNumberSense numberSense, StatRequest optionalReq, bool finalized = true)
{
RangedWeaponStats weaponStats = GetTurretStats(optionalReq);
(float, int) optimalRange = new[] {
(weaponStats.AccuracyTouch, (int) ShootTuning.DistTouch),
(weaponStats.AccuracyShort, (int) ShootTuning.DistShort),
(weaponStats.AccuracyMedium, (int) ShootTuning.DistMedium),
(weaponStats.AccuracyLong, (int) ShootTuning.DistLong)
}.MaxBy(acc => acc.Item1);
return string.Format("{0} ({1})",
value.ToStringByStyle(stat.toStringStyle, numberSense),
string.Format("StatsReport_RangedDPSOptimalRange".Translate(), optimalRange.Item2));
}
public override string GetExplanationUnfinalized(StatRequest req, ToStringNumberSense numberSense)
{
if (!ShouldShowFor(req))
{
return "";
}
RangedWeaponStats weaponStats = GetTurretStats(req);
return DPSRangeBreakdown(weaponStats);
}
}
}
|
||||
TheStack | bda5a0579203265bacb4baa2085f7ffd1ab143b2 | C#code:C# | {"size": 2478, "ext": "cs", "max_stars_repo_path": "CtfPlayback/Metadata/NamedScopes/CtfClockDescriptor.cs", "max_stars_repo_name": "jim-wordelman-msft/Microsoft-Performance-Tools-Linux-Android", "max_stars_repo_stars_event_min_datetime": "2021-08-28T01:19:10.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T21:19:56.000Z", "max_issues_repo_path": "CtfPlayback/Metadata/NamedScopes/CtfClockDescriptor.cs", "max_issues_repo_name": "jim-wordelman-msft/Microsoft-Performance-Tools-Linux-Android", "max_issues_repo_issues_event_min_datetime": "2021-09-02T21:13:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T21:10:08.000Z", "max_forks_repo_path": "CtfPlayback/Metadata/NamedScopes/CtfClockDescriptor.cs", "max_forks_repo_name": "jim-wordelman-msft/Microsoft-Performance-Tools-Linux-Android", "max_forks_repo_forks_event_min_datetime": "2021-09-23T23:47:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-23T19:40:24.000Z"} | {"max_stars_count": 179.0, "max_issues_count": 16.0, "max_forks_count": 19.0, "avg_line_length": 29.1529411765, "max_line_length": 109, "alphanum_fraction": 0.5282485876} | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using CtfPlayback.Metadata.Interfaces;
using CtfPlayback.Metadata.InternalHelpers;
using System;
using System.Diagnostics;
namespace CtfPlayback.Metadata.NamedScopes
{
/// <summary>
/// A clock definition in the trace.
/// </summary>
internal class CtfClockDescriptor
: ICtfClockDescriptor
{
internal CtfClockDescriptor(CtfPropertyBag bag)
{
Debug.Assert(bag != null);
this.Name = bag.GetString("name");
if (bag.ContainsKey("uuid"))
{
string uuid = bag.GetString("uuid").Replace("\"", string.Empty);
if (!Guid.TryParse(uuid, out var id))
{
throw new ArgumentException($"Unable to parse the uuid value: {bag.GetString("uuid")}.");
}
this.Uuid = id;
}
this.Description = bag.GetString("description");
// According to CTF specification 1.8.2 section 8, if the 'freq' field is not present,
// it will default to 1 ns.
this.Frequency = bag.ContainsKey("freq") ? bag.GetUlong("freq") : (ulong) 1000000000;
if (bag.ContainsKey("offset"))
{
this.Offset = bag.GetUlong("offset");
}
else if (bag.ContainsKey("offset_s"))
{
// todo:this might not be the best approach from an overflow perspective.
// leaving for now until we have reason to change it
ulong offsetInSeconds = bag.GetUlong("offset_s");
this.Offset = offsetInSeconds * this.Frequency;
}
if (bag.ContainsKey("precision"))
{
this.Precision = bag.GetUlong("precision");
}
if (bag.ContainsKey("absolute"))
{
this.Absolute = bag.GetBoolean("absolute");
}
}
/// <inheritdoc />
public string Description { get; }
/// <inheritdoc />
public ulong Frequency { get; }
/// <inheritdoc />
public ulong Precision { get; }
/// <inheritdoc />
public string Name { get; }
/// <inheritdoc />
public ulong Offset { get; }
/// <inheritdoc />
public Guid Uuid { get; }
/// <inheritdoc />
public bool Absolute { get; }
}
}
|
||||
TheStack | bda5fd24c9264ed68e828d0ac0e33bf50c886800 | C#code:C# | {"size": 2332, "ext": "cs", "max_stars_repo_path": "NetFabric.Hyperlinq.SourceGenerator.UnitTests/TestData/Source/Dictionary.Bindings.cs", "max_stars_repo_name": "reegeek/NetFabric.Hyperlinq", "max_stars_repo_stars_event_min_datetime": "2021-02-21T20:33:57.000Z", "max_stars_repo_stars_event_max_datetime": "2021-03-23T17:16:18.000Z", "max_issues_repo_path": "NetFabric.Hyperlinq.SourceGenerator.UnitTests/TestData/Source/Dictionary.Bindings.cs", "max_issues_repo_name": "reegeek/NetFabric.Hyperlinq", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "NetFabric.Hyperlinq.SourceGenerator.UnitTests/TestData/Source/Dictionary.Bindings.cs", "max_forks_repo_name": "reegeek/NetFabric.Hyperlinq", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 13.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 44.0, "max_line_length": 117, "alphanum_fraction": 0.6325042882} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace NetFabric.Hyperlinq
{
public static partial class DictionaryBindings
{
[GeneratorMapping("TSource", "System.Collections.Generic.KeyValuePair<TKey, TValue>", true)]
public readonly partial struct ValueWrapper<TKey, TValue>
: IValueReadOnlyCollection<KeyValuePair<TKey, TValue>, Dictionary<TKey, TValue>.Enumerator>
, ICollection<KeyValuePair<TKey, TValue>>
where TKey : notnull
{
readonly Dictionary<TKey, TValue> source;
public ValueWrapper(Dictionary<TKey, TValue> source)
=> this.source = source;
public readonly int Count
=> source.Count;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public readonly Dictionary<TKey, TValue>.Enumerator GetEnumerator()
=> source.GetEnumerator();
readonly IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
=> source.GetEnumerator();
readonly IEnumerator IEnumerable.GetEnumerator()
=> source.GetEnumerator();
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
=> true;
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
=> ((ICollection<KeyValuePair<TKey, TValue>>)source).CopyTo(array, arrayIndex);
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
=> throw new NotSupportedException();
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
=> throw new NotSupportedException();
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
=> throw new NotSupportedException();
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
=> throw new NotSupportedException();
}
public static int Count<TKey, TValue>(this ValueWrapper<TKey, TValue> source)
where TKey : notnull
=> source.Count;
}
} |
||||
TheStack | bda602e5279a587671a0dd1f6b0bd66fb6c9253f | C#code:C# | {"size": 797, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/Menu/ButtonAudioHandler.cs", "max_stars_repo_name": "Archimagus/GameJamStarterKit", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Scripts/Menu/ButtonAudioHandler.cs", "max_issues_repo_name": "Archimagus/GameJamStarterKit", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/Menu/ButtonAudioHandler.cs", "max_forks_repo_name": "Archimagus/GameJamStarterKit", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 36.2272727273, "max_line_length": 103, "alphanum_fraction": 0.7603513174} | using System.Linq;
using UnityEngine;
using UnityEngine.EventSystems;
[RequireComponent(typeof(EventTrigger))]
public class ButtonAudioHandler : MonoBehaviour
{
[SerializeField] private AudioClip _clickClip = null;
[SerializeField] private AudioClip _hoverClip = null;
void Start()
{
EventTrigger trigger = GetComponent<EventTrigger>();
var entry = new EventTrigger.Entry{eventID = EventTriggerType.PointerClick};
entry.callback.AddListener((data) => AudioManager.PlaySound(null, _clickClip, SoundType.Interface));
trigger.triggers.Add(entry);
entry = new EventTrigger.Entry { eventID = EventTriggerType.PointerEnter };
entry.callback.AddListener((data) => AudioManager.PlaySound(null, _hoverClip, SoundType.Interface));
trigger.triggers.Add(entry);
}
}
|
||||
TheStack | bda7977f018ae2d8483e3b31f6bdade22edc6fed | C#code:C# | {"size": 3055, "ext": "cs", "max_stars_repo_path": "test/FunctionalTests/Tests/DataOData/Tests/OData.Scenario.Tests/Streaming/ODataStreamingTestCase.cs", "max_stars_repo_name": "Sreejithpin/odata.net", "max_stars_repo_stars_event_min_datetime": "2015-01-02T08:40:43.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T15:28:06.000Z", "max_issues_repo_path": "test/FunctionalTests/Tests/DataOData/Tests/OData.Scenario.Tests/Streaming/ODataStreamingTestCase.cs", "max_issues_repo_name": "Sreejithpin/odata.net", "max_issues_repo_issues_event_min_datetime": "2015-01-06T05:44:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T08:37:22.000Z", "max_forks_repo_path": "test/FunctionalTests/Tests/DataOData/Tests/OData.Scenario.Tests/Streaming/ODataStreamingTestCase.cs", "max_forks_repo_name": "Sreejithpin/odata.net", "max_forks_repo_forks_event_min_datetime": "2015-01-06T06:57:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-11T13:40:39.000Z"} | {"max_stars_count": 629.0, "max_issues_count": 2078.0, "max_forks_count": 412.0, "avg_line_length": 47.0, "max_line_length": 130, "alphanum_fraction": 0.6261865794} | //---------------------------------------------------------------------
// <copyright file="ODataStreamingTestCase.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
namespace Microsoft.Test.Taupo.OData.Scenario.Tests.Streaming
{
using System.Linq;
using Microsoft.OData.Edm;
using Microsoft.Test.OData.Utils.ODataLibTest;
using Microsoft.Test.Taupo.Astoria.Contracts.OData;
using Microsoft.Test.Taupo.Contracts;
using Microsoft.Test.Taupo.OData.Common;
using Microsoft.Test.Taupo.OData.Json;
using Microsoft.Test.Taupo.OData.JsonLight;
using Microsoft.Test.Taupo.OData.Reader.Tests;
using Microsoft.Test.Taupo.OData.Writer.Tests.Common;
public class ODataStreamingTestCase : ODataReaderTestCase
{
public static ComplexInstance GetComplexInstanceWithManyPrimitiveProperties(EdmModel model)
{
var primitiveValues = TestValues.CreatePrimitiveValuesWithMetadata(true).Where(
(v) =>
{
var edmPrimitiveType =
v.Annotations.OfType<EntityModelTypeAnnotation>().Single().EdmModelType as
IEdmPrimitiveTypeReference;
var edmPrimitiveKind = edmPrimitiveType.PrimitiveKind();
if (edmPrimitiveKind != EdmPrimitiveTypeKind.None)
return edmPrimitiveKind != EdmPrimitiveTypeKind.DateTimeOffset;
return false;
}).ToArray();
string typeName = "ComplexTypeWithManyPrimitiveProperties";
var complexType = model.ComplexType(typeName);
for (int i = 0; i < primitiveValues.Count(); ++i)
{
complexType.Property("property" + i, primitiveValues[i].GetAnnotation<EntityModelTypeAnnotation>().EdmModelType);
}
var complexValue = PayloadBuilder.ComplexValue("TestModel." + typeName).WithTypeAnnotation(complexType);
for (int j = 0; j < primitiveValues.Count(); ++j)
{
complexValue.PrimitiveProperty("property" + j, primitiveValues[j].ClrValue);
}
return complexValue;
}
protected override void ConfigureDependencies(Taupo.Contracts.DependencyInjectionContainer container)
{
base.ConfigureDependencies(container);
container.Register<IProtocolFormatNormalizerSelector, DefaultProtocolFormatNormalizerSelector>();
container.Register<IPayloadElementToJsonConverter, AnnotatedPayloadElementToJsonConverter>();
container.Register<IPayloadElementToJsonLightConverter, AnnotatedPayloadElementToJsonLightConverter>();
container.Register<IEntityModelSchemaComparer, ODataEntityModelSchemaComparer>();
}
}
}
|
||||
TheStack | bda9cfb35f0abd7c3c5484805866c33e1a891d5f | C#code:C# | {"size": 5925, "ext": "cs", "max_stars_repo_path": "t3dsharp/T3DSharpFramework/Generated/Classes/Sim/SimPersistSet.cs", "max_stars_repo_name": "lukaspj/T3DSharp-Sample", "max_stars_repo_stars_event_min_datetime": "2021-01-06T18:41:27.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-06T18:41:27.000Z", "max_issues_repo_path": "t3dsharp/T3DSharpFramework/Generated/Classes/Sim/SimPersistSet.cs", "max_issues_repo_name": "lukaspj/T3DSharp-Sample", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "t3dsharp/T3DSharpFramework/Generated/Classes/Sim/SimPersistSet.cs", "max_forks_repo_name": "lukaspj/T3DSharp-Sample", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 2.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 40.0337837838, "max_line_length": 200, "alphanum_fraction": 0.6081012658} | using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using T3DSharpFramework.Engine;
using T3DSharpFramework.Engine.Util;
using T3DSharpFramework.Generated.Classes.Global;
using T3DSharpFramework.Generated.Classes.Reflection;
using T3DSharpFramework.Generated.Classes.Sim;
using T3DSharpFramework.Generated.Classes.Sim.Net;
using T3DSharpFramework.Generated.Enums.Global;
using T3DSharpFramework.Generated.Enums.Reflection;
using T3DSharpFramework.Generated.Structs.Global;
using T3DSharpFramework.Generated.Structs.Gui;
using T3DSharpFramework.Generated.Structs.Math;
using T3DSharpFramework.Interop;
namespace T3DSharpFramework.Generated.Classes.Sim {
/// <summary>A SimSet that can be safely persisted.</summary>
/// <description>
/// Uses SimPersistIDs to reference objects in the set while persisted on disk. This allows the set to resolve its references no matter whether they are loaded before or after the set is created.
///
/// Not intended for game development, for editors or internal use only.
/// </description>
public unsafe class SimPersistSet : SimSet {
public SimPersistSet(bool pRegister = false)
: base(pRegister) {
}
public SimPersistSet(string pName, bool pRegister)
: this(false) {
Name = pName;
if (pRegister) {
RegisterObject();
}
}
public SimPersistSet(string pName)
: this(pName, false) {
}
public SimPersistSet(string pName, string pParent, bool pRegister = false)
: this(pName, pRegister) {
CopyFrom(Engine.Sim.FindObject<SimObject>(pParent));
}
public SimPersistSet(string pName, SimObject pParent, bool pRegister = false)
: this(pName, pRegister) {
CopyFrom(pParent);
}
public SimPersistSet(SimObject pObj)
: base(pObj) {
}
public SimPersistSet(IntPtr pObj)
: base(pObj) {
}
protected override void CreateObjectPtr()
{
ObjectPtr = InternalUnsafeMethods.Create()(new InternalUnsafeMethods.Create__Args());
}
#region UnsafeNativeMethods
new internal struct InternalUnsafeMethods {
[StructLayout(LayoutKind.Sequential)]
internal struct ResolvePersistentIds__Args
{
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void _ResolvePersistentIds(IntPtr _this, ResolvePersistentIds__Args args);
private static _ResolvePersistentIds _ResolvePersistentIdsFunc;
internal static _ResolvePersistentIds ResolvePersistentIds() {
if (_ResolvePersistentIdsFunc == null) {
_ResolvePersistentIdsFunc =
(_ResolvePersistentIds)Marshal.GetDelegateForFunctionPointer(
Torque3D.DllLoadUtils.GetProcAddress(
Torque3D.Torque3DLibHandle,
"fnSimPersistSet_resolvePersistentIds"), typeof(_ResolvePersistentIds));
}
return _ResolvePersistentIdsFunc;
}
[StructLayout(LayoutKind.Sequential)]
internal struct StaticGetType__Args
{
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate IntPtr _StaticGetType(StaticGetType__Args args);
private static _StaticGetType _StaticGetTypeFunc;
internal static _StaticGetType StaticGetType() {
if (_StaticGetTypeFunc == null) {
_StaticGetTypeFunc =
(_StaticGetType)Marshal.GetDelegateForFunctionPointer(
Torque3D.DllLoadUtils.GetProcAddress(
Torque3D.Torque3DLibHandle,
"fnSimPersistSet_staticGetType"), typeof(_StaticGetType));
}
return _StaticGetTypeFunc;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Create__Args
{
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate IntPtr _Create(Create__Args args);
private static _Create _CreateFunc;
internal static _Create Create() {
if (_CreateFunc == null) {
_CreateFunc =
(_Create)Marshal.GetDelegateForFunctionPointer(
Torque3D.DllLoadUtils.GetProcAddress(
Torque3D.Torque3DLibHandle,
"fnSimPersistSet_create"), typeof(_Create));
}
return _CreateFunc;
}
}
#endregion
/// <description>
/// () - Try to bind unresolved persistent IDs in the set.
/// </description>
public void ResolvePersistentIds() {
InternalUnsafeMethods.ResolvePersistentIds__Args _args = new InternalUnsafeMethods.ResolvePersistentIds__Args() {
};
InternalUnsafeMethods.ResolvePersistentIds()(ObjectPtr, _args);
}
/// <description>
/// Get the type info object for the SimPersistSet class.
/// </description>
/// <returns>The type info object for SimPersistSet</returns>
public static EngineTypeInfo StaticGetType() {
InternalUnsafeMethods.StaticGetType__Args _args = new InternalUnsafeMethods.StaticGetType__Args() {
};
IntPtr _engineResult = InternalUnsafeMethods.StaticGetType()(_args);
return new EngineTypeInfo(_engineResult);
}
}
} |
||||
TheStack | bdace758d737b282f447db6404d25a8991d27a79 | C#code:C# | {"size": 1341, "ext": "cs", "max_stars_repo_path": "src/GenericNEAT/Populations/SpeciationStrategyBase.cs", "max_stars_repo_name": "liebasam/GenericNEAT", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/GenericNEAT/Populations/SpeciationStrategyBase.cs", "max_issues_repo_name": "liebasam/GenericNEAT", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/GenericNEAT/Populations/SpeciationStrategyBase.cs", "max_forks_repo_name": "liebasam/GenericNEAT", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.4772727273, "max_line_length": 77, "alphanum_fraction": 0.6137211037} | using GeneticSharp.Domain.Chromosomes;
using System;
namespace GenericNEAT.Populations
{
/// <summary>
/// Base class for speciation strategies.
/// </summary>
public abstract class SpeciationStrategyBase : ISpeciationStrategy
{
#region Fields
/// <summary>
/// Minimum distance between any two chromosomes to be
/// considered of the same specie.
/// </summary>
public double DistanceThreshold { get; set; }
#endregion
#region Constructors
/// <summary>
/// Creates a speciation strategy with the provided
/// distance threshold.
/// </summary>
/// <param name="distanceThreshold">Minimum distance
/// between any two chromosomes to be considered in
/// the same specie.</param>
public SpeciationStrategyBase(double distanceThreshold)
{
DistanceThreshold = distanceThreshold;
}
#endregion
#region Methods
public virtual bool AreSameSpecies(IChromosome a, IChromosome b) =>
DistanceBetween(a, b) <= DistanceThreshold;
/// <summary>
/// Gets the distance between two chromosomes.
/// </summary>
public abstract double DistanceBetween(IChromosome a, IChromosome b);
#endregion
}
}
|
||||
TheStack | bdae7e84d29f0150d6f528f90f3c3ac99fad9513 | C#code:C# | {"size": 2558, "ext": "cs", "max_stars_repo_path": "Assets/Scripts/Objects/Clock/DigitalClockAlarmEntryDisplay.cs", "max_stars_repo_name": "polylith/PlumploriGame", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Assets/Scripts/Objects/Clock/DigitalClockAlarmEntryDisplay.cs", "max_issues_repo_name": "polylith/PlumploriGame", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Assets/Scripts/Objects/Clock/DigitalClockAlarmEntryDisplay.cs", "max_forks_repo_name": "polylith/PlumploriGame", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.8349514563, "max_line_length": 104, "alphanum_fraction": 0.6243158718} | using UnityEngine;
using UnityEngine.UI;
using TMPro;
using Language;
public class DigitalClockAlarmEntryDisplay : MonoBehaviour
{
public static readonly float Height = 55f;
public DigitalClockAlarmEntryDisplay Instantiate(DigitalClockUI ui, DigitalClockAlarmData alarmdata)
{
DigitalClockAlarmEntryDisplay display = Instantiate< DigitalClockAlarmEntryDisplay>(this);
display.Init(ui, alarmdata);
return display;
}
public DigitalClockAlarmData Alarmdata { get; private set; }
public TextMeshProUGUI timeDisplay;
public Image activeIcon;
public Image isOnIcon;
public UIIconButton isOnBtn;
public UIIconButton activateBtn;
public UIIconButton deleteBtn;
private DigitalClockUI ui;
private void Init(DigitalClockUI ui, DigitalClockAlarmData alarmdata)
{
Alarmdata = alarmdata;
this.ui = ui;
ShowAlarmTime();
isOnBtn.SetAction(StopAlarm);
isOnBtn.SetActiveColor(Color.yellow);
activateBtn.SetAction(ToggleActive);
deleteBtn.SetAction(Delete);
isOnBtn.SetToolTip(
LanguageManager.GetText(
LangKey.Stopp,
LanguageManager.GetText(LangKey.Alarm)
)
);
deleteBtn.SetToolTip(
LanguageManager.GetText(
LangKey.Delete,
LanguageManager.GetText(LangKey.Alarm)
)
);
SetActive(Alarmdata.IsActive);
UpdateIsOnButton();
}
public void UpdateIsOnButton()
{
isOnBtn.IsEnabled = Alarmdata.IsOn;
isOnBtn.SetState(Alarmdata.IsOn ? 0 : -1);
isOnIcon.gameObject.SetActive(Alarmdata.IsOn);
}
private void StopAlarm()
{
ui.StopAlarm(this);
}
public void ShowAlarmTime()
{
timeDisplay.SetText(Alarmdata.TimeString);
}
public void SetActive(bool isActive)
{
Alarmdata.IsActive = isActive;
activeIcon.color = isActive ? Color.red : Color.gray;
activateBtn.SetToolTip(
LanguageManager.GetText(
isActive ? LangKey.Deactivate : LangKey.Activate,
LanguageManager.GetText(LangKey.Alarm)
)
);
activateBtn.SetActiveColor(isActive ? Color.gray : Color.red);
if (!isActive && Alarmdata.IsOn)
{
StopAlarm();
}
}
private void ToggleActive()
{
SetActive(!Alarmdata.IsActive);
}
private void Delete()
{
ui.Delete(this);
}
}
|
||||
TheStack | bdae87187ba07fcc4b2c626957b1160462c19dd5 | C#code:C# | {"size": 12733, "ext": "cs", "max_stars_repo_path": "src/Polly.Contrib.Simmy.Specs/Latency/InjectLatencyAsyncSpecs.cs", "max_stars_repo_name": "samueleresca/Simmy", "max_stars_repo_stars_event_min_datetime": "2019-08-31T12:03:21.000Z", "max_stars_repo_stars_event_max_datetime": "2019-08-31T12:03:21.000Z", "max_issues_repo_path": "src/Polly.Contrib.Simmy.Specs/Latency/InjectLatencyAsyncSpecs.cs", "max_issues_repo_name": "samueleresca/Simmy", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Polly.Contrib.Simmy.Specs/Latency/InjectLatencyAsyncSpecs.cs", "max_forks_repo_name": "samueleresca/Simmy", "max_forks_repo_forks_event_min_datetime": "2021-06-22T14:00:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-06-22T14:00:09.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 35.6666666667, "max_line_length": 133, "alphanum_fraction": 0.5664807979} | using System;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Polly.Contrib.Simmy.Utilities;
using Polly.Utilities;
using Xunit;
namespace Polly.Contrib.Simmy.Specs.Latency
{
[Collection(Helpers.Constants.AmbientContextDependentTestCollection)]
public class InjectLatencyAsyncSpecs : IDisposable
{
private int _totalTimeSlept = 0;
public InjectLatencyAsyncSpecs()
{
ThreadSafeRandom_LockOncePerThread.NextDouble = () => 0.5;
SystemClock.SleepAsync = async (span, ct) => _totalTimeSlept += await Task.FromResult(span.Milliseconds);
}
public void Dispose()
{
_totalTimeSlept = 0;
SystemClock.Reset();
ThreadSafeRandom_LockOncePerThread.Reset();
}
#region Context Free
[Fact]
public async Task InjectLatency_Context_Free_Should_Introduce_Delay_If_Enabled()
{
var delay = TimeSpan.FromMilliseconds(500);
var policy = MonkeyPolicy.InjectLatencyAsync(delay, 0.6, () => true);
var executed = false;
Func<Task> actionAsync = () => { executed = true; return TaskHelper.EmptyTask; };
await policy.ExecuteAsync(actionAsync);
executed.Should().BeTrue();
_totalTimeSlept.Should().Be(delay.Milliseconds);
}
[Fact]
public async Task InjectLatency_Context_Free_Should_Not_Introduce_Delay_If_Dissabled()
{
var policy = MonkeyPolicy.InjectLatencyAsync(TimeSpan.FromMilliseconds(500), 0.6, () => false);
var executed = false;
Func<Task> actionAsync = () => { executed = true; return TaskHelper.EmptyTask; };
await policy.ExecuteAsync(actionAsync);
executed.Should().BeTrue();
_totalTimeSlept.Should().Be(0);
}
[Fact]
public async Task InjectLatency_Context_Free_Should_Introduce_Delay_If_InjectionRate_Is_Covered()
{
var delay = TimeSpan.FromMilliseconds(500);
var policy = MonkeyPolicy.InjectLatencyAsync(delay, 0.6, () => true);
var executed = false;
Func<Task> actionAsync = () => { executed = true; return TaskHelper.EmptyTask; };
await policy.ExecuteAsync(actionAsync);
executed.Should().BeTrue();
_totalTimeSlept.Should().Be(delay.Milliseconds);
}
[Fact]
public async Task InjectLatency_Context_Free_Should_Not_Introduce_Delay_If_InjectionRate_Is_Not_Covered()
{
var delay = TimeSpan.FromMilliseconds(500);
var policy = MonkeyPolicy.InjectLatencyAsync(delay, 0.3, () => true);
var executed = false;
Func<Task> actionAsync = () => { executed = true; return TaskHelper.EmptyTask; };
await policy.ExecuteAsync(actionAsync);
executed.Should().BeTrue();
_totalTimeSlept.Should().Be(0);
}
#endregion
#region With Context
[Fact]
public async Task InjectLatency_With_Context_With_Enabled_Lambda_Should_Introduce_Delay()
{
var delay = TimeSpan.FromMilliseconds(500);
var context = new Context();
context["Enabled"] = true;
Func<Context, Task<bool>> enabled = async (ctx) =>
{
return await Task.FromResult((bool)ctx["Enabled"]);
};
var policy = MonkeyPolicy.InjectLatencyAsync(delay, 0.6, enabled);
Boolean executed = false;
Func<Context, Task> actionAsync = _ => { executed = true; return TaskHelper.EmptyTask; };
await policy.ExecuteAsync(actionAsync, context);
executed.Should().BeTrue();
_totalTimeSlept.Should().Be(delay.Milliseconds);
}
[Fact]
public async Task InjectLatency_With_Context_With_Enabled_Lambda_Should_Not_Introduce_Delay()
{
var delay = TimeSpan.FromMilliseconds(500);
var context = new Context();
context["Enabled"] = false;
Func<Context, Task<bool>> enabled = async (ctx) =>
{
return await Task.FromResult((bool)ctx["Enabled"]);
};
var policy = MonkeyPolicy.InjectLatencyAsync(delay, 0.6, enabled);
Boolean executed = false;
Func<Context, Task> actionAsync = _ => { executed = true; return TaskHelper.EmptyTask; };
await policy.ExecuteAsync(actionAsync, context);
executed.Should().BeTrue();
_totalTimeSlept.Should().Be(0);
}
[Fact]
public async Task InjectLatency_With_Context_With_Enabled_Lambda_Should_Not_Introduce_Delay_If_InjectionRate_Is_Not_Covered()
{
var delay = TimeSpan.FromMilliseconds(500);
var context = new Context();
context["Enabled"] = true;
Func<Context, Task<bool>> enabled = async (ctx) =>
{
return await Task.FromResult((bool)ctx["Enabled"]);
};
var policy = MonkeyPolicy.InjectLatencyAsync(delay, 0.3, enabled);
Boolean executed = false;
Func<Context, Task> actionAsync = _ => { executed = true; return TaskHelper.EmptyTask; };
await policy.ExecuteAsync(actionAsync, context);
executed.Should().BeTrue();
_totalTimeSlept.Should().Be(0);
}
[Fact]
public async Task InjectLatency_With_Context_With_InjectionRate_Lambda_Should_Introduce_Delay()
{
var delay = TimeSpan.FromMilliseconds(500);
var context = new Context();
context["Enabled"] = true;
context["InjectionRate"] = 0.6;
Func<Context, Task<bool>> enabled = async (ctx) =>
{
return await Task.FromResult((bool)ctx["Enabled"]);
};
Func<Context, Task<double>> injectionRate = async (ctx) =>
{
if (ctx["InjectionRate"] != null)
{
return await Task.FromResult((double) ctx["InjectionRate"]);
}
return await Task.FromResult(0);
};
var policy = MonkeyPolicy.InjectLatencyAsync(delay, injectionRate, enabled);
Boolean executed = false;
Func<Context, Task> actionAsync = _ => { executed = true; return TaskHelper.EmptyTask; };
await policy.ExecuteAsync(actionAsync, context);
executed.Should().BeTrue();
_totalTimeSlept.Should().Be(delay.Milliseconds);
}
[Fact]
public async Task InjectLatency_With_Context_With_InjectionRate_Lambda_Should_Not_Introduce_Delay()
{
var delay = TimeSpan.FromMilliseconds(500);
var context = new Context();
context["Enabled"] = true;
context["InjectionRate"] = 0.3;
Func<Context, Task<bool>> enabled = async (ctx) =>
{
return await Task.FromResult((bool)ctx["Enabled"]);
};
Func<Context, Task<double>> injectionRate = async (ctx) =>
{
if (ctx["InjectionRate"] != null)
{
return await Task.FromResult((double) ctx["InjectionRate"]);
}
return await Task.FromResult(0);
};
var policy = MonkeyPolicy.InjectLatencyAsync(delay, injectionRate, enabled);
Boolean executed = false;
Func<Context, Task> actionAsync = _ => { executed = true; return TaskHelper.EmptyTask; };
await policy.ExecuteAsync(actionAsync, context);
executed.Should().BeTrue();
_totalTimeSlept.Should().Be(0);
}
[Fact]
public async Task InjectLatency_With_Context_With_Latency_Lambda_Should_Introduce_Delay()
{
var delay = TimeSpan.FromMilliseconds(500);
var context = new Context();
context["ShouldInjectLatency"] = true;
context["Enabled"] = true;
context["InjectionRate"] = 0.6;
Func<Context, CancellationToken, Task<TimeSpan>> latencyProvider = async (ctx, ct) =>
{
if ((bool)ctx["ShouldInjectLatency"])
{
return await Task.FromResult(delay);
}
return await Task.FromResult(TimeSpan.FromMilliseconds(0));
};
Func<Context, Task<bool>> enabled = async (ctx) =>
{
return await Task.FromResult((bool)ctx["Enabled"]);
};
Func<Context, Task<double>> injectionRate = async (ctx) =>
{
if (ctx["InjectionRate"] != null)
{
return await Task.FromResult((double) ctx["InjectionRate"]);
}
return await Task.FromResult(0);
};
var policy = MonkeyPolicy.InjectLatencyAsync(latencyProvider, injectionRate, enabled);
Boolean executed = false;
Func<Context, Task> actionAsync = _ => { executed = true; return TaskHelper.EmptyTask; };
await policy.ExecuteAsync(actionAsync, context);
executed.Should().BeTrue();
_totalTimeSlept.Should().Be(delay.Milliseconds);
}
[Fact]
public async Task InjectLatency_With_Context_With_Latency_Lambda_Should_Not_Introduce_Delay()
{
var delay = TimeSpan.FromMilliseconds(500);
var context = new Context();
context["ShouldInjectLatency"] = false;
context["Enabled"] = true;
context["InjectionRate"] = 0.6;
Func<Context, CancellationToken, Task<TimeSpan>> latencyProvider = async (ctx, ct) =>
{
if ((bool)ctx["ShouldInjectLatency"])
{
return await Task.FromResult(delay);
}
return await Task.FromResult(TimeSpan.FromMilliseconds(0));
};
Func<Context, Task<bool>> enabled = async (ctx) =>
{
return await Task.FromResult((bool)ctx["Enabled"]);
};
Func<Context, Task<double>> injectionRate = async (ctx) =>
{
if (ctx["InjectionRate"] != null)
{
return await Task.FromResult((double) ctx["InjectionRate"]);
}
return await Task.FromResult(0);
};
var policy = MonkeyPolicy.InjectLatencyAsync(latencyProvider, injectionRate, enabled);
Boolean executed = false;
Func<Context, Task> actionAsync = _ => { executed = true; return TaskHelper.EmptyTask; };
await policy.ExecuteAsync(actionAsync, context);
executed.Should().BeTrue();
_totalTimeSlept.Should().Be(0);
}
[Fact]
public async Task InjectLatency_With_Context_With_Latency_Lambda_Should_Not_Introduce_Delay_If_InjectionRate_Is_Not_Covered()
{
var delay = TimeSpan.FromMilliseconds(500);
var context = new Context();
context["ShouldInjectLatency"] = true;
context["Enabled"] = true;
context["InjectionRate"] = 0.3;
Func<Context, CancellationToken, Task<TimeSpan>> latencyProvider = async (ctx, ct) =>
{
if ((bool)ctx["ShouldInjectLatency"])
{
return await Task.FromResult(delay);
}
return await Task.FromResult(TimeSpan.FromMilliseconds(0));
};
Func<Context, Task<bool>> enabled = async (ctx) =>
{
return await Task.FromResult((bool)ctx["Enabled"]);
};
Func<Context, Task<double>> injectionRate = async (ctx) =>
{
if (ctx["InjectionRate"] != null)
{
return await Task.FromResult((double) ctx["InjectionRate"]);
}
return await Task.FromResult(0);
};
var policy = MonkeyPolicy.InjectLatencyAsync(latencyProvider, injectionRate, enabled);
Boolean executed = false;
Func<Context, Task> actionAsync = _ => { executed = true; return TaskHelper.EmptyTask; };
await policy.ExecuteAsync(actionAsync, context);
executed.Should().BeTrue();
_totalTimeSlept.Should().Be(0);
}
#endregion
}
}
|
||||
TheStack | bdafa58ed1ce10d05f435a73f8e21e48835f216b | C#code:C# | {"size": 724, "ext": "cs", "max_stars_repo_path": "src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiCateringConfigModifyModel.cs", "max_stars_repo_name": "lotosbin/payment", "max_stars_repo_stars_event_min_datetime": "2020-08-06T11:31:55.000Z", "max_stars_repo_stars_event_max_datetime": "2020-08-06T11:31:55.000Z", "max_issues_repo_path": "src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiCateringConfigModifyModel.cs", "max_issues_repo_name": "xmsdn/payment", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiCateringConfigModifyModel.cs", "max_forks_repo_name": "xmsdn/payment", "max_forks_repo_forks_event_min_datetime": "2019-11-25T01:55:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-11-25T01:55:28.000Z"} | {"max_stars_count": 1.0, "max_issues_count": null, "max_forks_count": 1.0, "avg_line_length": 27.8461538462, "max_line_length": 97, "alphanum_fraction": 0.6505524862} | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Essensoft.AspNetCore.Payment.Alipay.Domain
{
/// <summary>
/// KoubeiCateringConfigModifyModel Data Structure.
/// </summary>
[Serializable]
public class KoubeiCateringConfigModifyModel : AlipayObject
{
/// <summary>
/// 外部请求ID; 标识ISV本次修改的请求,由开发者自定义,不同的请求使用不同的ID,在门店notify消息中也会带有该参数,以此标明本次notify消息是对哪个请求的回应
/// </summary>
[JsonProperty("request_id")]
public string RequestId { get; set; }
/// <summary>
/// 店铺配置信息列表
/// </summary>
[JsonProperty("shop_config_list")]
public List<ShopOrderConfigInfo> ShopConfigList { get; set; }
}
}
|
||||
TheStack | bdafb3e6c060f486fc93e3965c8e6400efa33c60 | C#code:C# | {"size": 1514, "ext": "cs", "max_stars_repo_path": "Api/Macro/ExecuteMacroContext.cs", "max_stars_repo_name": "Dennis-Rosenbaum/XTRF", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Api/Macro/ExecuteMacroContext.cs", "max_issues_repo_name": "Dennis-Rosenbaum/XTRF", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Api/Macro/ExecuteMacroContext.cs", "max_forks_repo_name": "Dennis-Rosenbaum/XTRF", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 37.85, "max_line_length": 101, "alphanum_fraction": 0.6334214003} | using System.Linq;
using System.Threading.Tasks;
using Xtrf.Api.Base;
using Xtrf.Api.Macro.Data;
namespace Xtrf.Api.Macro
{
public class ExecuteMacroContext : ContextBase
{
internal ExecuteMacroContext(Interface.IConnection xtrfConnection) : base(xtrfConnection) { }
#region GET
public Task<string> Execute(int macroId, params long[] ids)
=> ExecuteResult(ExecuteRun(macroId, ids));
private async Task<string> ExecuteResult(Task<XtrfResult<GetActionResult>> macroResult)
{
var runMacroResult = await macroResult;
if (!runMacroResult.Success)
return runMacroResult.ErrorMessage;
if (runMacroResult.Result == null)
return "no result";
var result = (await ExecuteGetOutput(runMacroResult.Result.Url)).Result;
if (result.EndsWith("\n")) result = result.Substring(0, result.Length - 1);
return result;
}
private Task<XtrfResult<string>> ExecuteGetOutput(string outputUrl)
=> Get<string>(new ExecuteParams(outputUrl));
private Task<XtrfResult<GetActionResult>> ExecuteRun(int macroId, long[] ids)
=> RunMacro(macroId, new { ids = ids.Select(i => i.ToString()) });
private Task<XtrfResult<GetActionResult>> RunMacro(int macroId, dynamic d)
=> Post<GetActionResult>(new ExecuteParams($"/macros/{macroId}/run?async=true", d));
#endregion
}
}
|
||||
TheStack | bdafec113880d315252f45d6a5fdbe9d85f35678 | C#code:C# | {"size": 12050, "ext": "cs", "max_stars_repo_path": "SymOntoClayCore/DebugHelpers/DebugHelperForRuleInstance.cs", "max_stars_repo_name": "Symontoclay/SymOntoClay", "max_stars_repo_stars_event_min_datetime": "2021-04-12T11:09:23.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-30T14:35:44.000Z", "max_issues_repo_path": "SymOntoClayCore/DebugHelpers/DebugHelperForRuleInstance.cs", "max_issues_repo_name": "Symontoclay/SymOntoClay", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SymOntoClayCore/DebugHelpers/DebugHelperForRuleInstance.cs", "max_forks_repo_name": "Symontoclay/SymOntoClay", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null} | {"max_stars_count": 6.0, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 30.5063291139, "max_line_length": 114, "alphanum_fraction": 0.5483817427} | /*MIT License
Copyright (c) 2020 - 2021 Sergiy Tolkachov
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
using SymOntoClay.Core.Internal.CodeModel;
using SymOntoClay.CoreHelper.CollectionsHelpers;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
namespace SymOntoClay.Core.DebugHelpers
{
public static class DebugHelperForRuleInstance
{
private static readonly CultureInfo _cultureInfo = new CultureInfo("en-GB");
public static string ToString(RuleInstance source)
{
var sb = new StringBuilder();
sb.Append("{:");
if(source.Name != null)
{
sb.Append($" {source.Name.NameValue}");
}
sb.Append(ToString(source.PrimaryPart));
if(!source.SecondaryParts.IsNullOrEmpty())
{
sb.Append(" -> ");
if(source.SecondaryParts.Count == 1)
{
var firstSecondaryRulePart = source.SecondaryParts.Single();
sb.Append(ToString(firstSecondaryRulePart));
}
else
{
throw new NotImplementedException();
}
}
sb.Append(" :}");
sb.Append(AnnotatedItemToString(source));
return sb.ToString();
}
public static string ToString(PrimaryRulePart primaryRulePart)
{
var sb = new StringBuilder();
sb.Append(" >: { ");
sb.Append(ToString(primaryRulePart.Expression));
sb.Append(" }");
sb.Append(AnnotatedItemToString(primaryRulePart));
return sb.ToString();
}
public static string BaseRulePartToString(BaseRulePart baseRulePart)
{
var b = baseRulePart as PrimaryRulePart;
if (b != null)
{
return ToString(b);
}
var c = baseRulePart as SecondaryRulePart;
if (c != null)
{
return ToString(c);
}
return string.Empty;
}
public static string ToString(SecondaryRulePart rulePart)
{
var sb = new StringBuilder();
sb.Append(" { ");
sb.Append(ToString(rulePart.Expression));
sb.Append(" }");
sb.Append(AnnotatedItemToString(rulePart));
return sb.ToString();
}
public static string ToString(LogicalQueryNode expr)
{
switch (expr.Kind)
{
case KindOfLogicalQueryNode.UnaryOperator:
return UnaryOperatorToString(expr);
case KindOfLogicalQueryNode.BinaryOperator:
return BinaryOperatorToString(expr);
case KindOfLogicalQueryNode.Relation:
return RelationToString(expr);
case KindOfLogicalQueryNode.Concept:
case KindOfLogicalQueryNode.QuestionVar:
case KindOfLogicalQueryNode.Entity:
case KindOfLogicalQueryNode.LogicalVar:
return ConceptToString(expr);
case KindOfLogicalQueryNode.Value:
return ValueToString(expr);
case KindOfLogicalQueryNode.FuzzyLogicNonNumericSequence:
return FuzzyLogicNonNumericSequenceValueToString(expr.FuzzyLogicNonNumericSequenceValue);
default:
throw new ArgumentOutOfRangeException(nameof(expr.Kind), expr.Kind, null);
}
}
private static string UnaryOperatorToString(LogicalQueryNode expr)
{
var mark = string.Empty;
switch (expr.KindOfOperator)
{
case KindOfOperatorOfLogicalQueryNode.Not:
mark = "not";
break;
default:
throw new ArgumentOutOfRangeException(nameof(expr.KindOfOperator), expr.KindOfOperator, null);
}
var sb = new StringBuilder();
sb.Append($" {mark} ");
sb.Append(AnnotatedItemToString(expr));
sb.Append(ToString(expr.Left));
return sb.ToString();
}
private static string BinaryOperatorToString(LogicalQueryNode expr)
{
var mark = string.Empty;
switch(expr.KindOfOperator)
{
case KindOfOperatorOfLogicalQueryNode.And:
mark = "&";
break;
case KindOfOperatorOfLogicalQueryNode.Or:
mark = "|";
break;
case KindOfOperatorOfLogicalQueryNode.Is:
mark = "is";
break;
case KindOfOperatorOfLogicalQueryNode.IsNot:
mark = "is not";
break;
case KindOfOperatorOfLogicalQueryNode.More:
mark = ">";
break;
case KindOfOperatorOfLogicalQueryNode.MoreOrEqual:
mark = ">=";
break;
case KindOfOperatorOfLogicalQueryNode.Less:
mark = "<";
break;
case KindOfOperatorOfLogicalQueryNode.LessOrEqual:
mark = "<=";
break;
default:
throw new ArgumentOutOfRangeException(nameof(expr.KindOfOperator), expr.KindOfOperator, null);
}
var sb = new StringBuilder();
sb.Append(ToString(expr.Left));
sb.Append($" {mark} ");
sb.Append(AnnotatedItemToString(expr));
sb.Append(ToString(expr.Right));
return sb.ToString();
}
private static string RelationToString(LogicalQueryNode expr)
{
var sb = new StringBuilder();
sb.Append($"{expr.Name.NameValue}(");
var resultParamsList = new List<string>();
foreach(var param in expr.ParamsList)
{
resultParamsList.Add(ToString(param));
}
sb.Append(string.Join(",", resultParamsList));
sb.Append(")");
sb.Append(AnnotatedItemToString(expr));
return sb.ToString();
}
private static string ConceptToString(LogicalQueryNode expr)
{
var sb = new StringBuilder();
sb.Append(expr.Name.NameValue);
sb.Append(AnnotatedItemToString(expr));
return sb.ToString();
}
private static string ValueToString(LogicalQueryNode expr)
{
var sb = new StringBuilder();
var value = expr.Value;
sb.Append(ToString(value));
sb.Append(AnnotatedItemToString(expr));
return sb.ToString();
}
public static string AnnotatedItemToString(AnnotatedItem source)
{
var sb = new StringBuilder();
if (source.HasModalitiesOrSections)
{
sb.Append(" |:");
if(!source.WhereSection.IsNullOrEmpty())
{
sb.Append(" ");
sb.Append(WhereSectionToString(source.WhereSection));
}
sb.Append(" :|");
}
return sb.ToString();
}
private static string WhereSectionToString(IList<Value> source)
{
return PrintModalityOrSection("where:", source);
}
private static string PrintModalityOrSection(string mark, IList<Value> source)
{
var sb = new StringBuilder(mark);
sb.Append(" {");
if (source.Count == 1)
{
sb.Append($" {ToString(source.First())} ");
}
else
{
var list = new List<string>();
foreach (var item in source)
{
list.Add($"{{ {ToString(item)} }}");
}
sb.Append(string.Join(",", list));
}
sb.Append("}");
return sb.ToString();
}
public static string ToString(Value value)
{
switch(value.KindOfValue)
{
case KindOfValue.NullValue:
return NullValueToString(value);
case KindOfValue.LogicalValue:
return LogicalValueToString(value.AsLogicalValue);
case KindOfValue.NumberValue:
return NumberValueToString(value.AsNumberValue);
case KindOfValue.FuzzyLogicNonNumericSequenceValue:
return FuzzyLogicNonNumericSequenceValueToString(value.AsFuzzyLogicNonNumericSequenceValue);
case KindOfValue.StrongIdentifierValue:
return StrongIdentifierValueToString(value.AsStrongIdentifierValue);
default:
throw new ArgumentOutOfRangeException(nameof(value.KindOfValue), value.KindOfValue, null);
}
}
private static string NullValueToString(Value value)
{
var sb = new StringBuilder("NULL");
sb.Append(AnnotatedItemToString(value));
return sb.ToString();
}
private static string NumberValueToString(NumberValue value)
{
var systemValue = value.SystemValue;
var sb = new StringBuilder();
if (systemValue.HasValue)
{
sb.Append(systemValue.Value.ToString(_cultureInfo));
}
else
{
sb.Append("NULL");
}
sb.Append(AnnotatedItemToString(value));
return sb.ToString();
}
private static string LogicalValueToString(LogicalValue value)
{
var systemValue = value.SystemValue;
var sb = new StringBuilder();
if(systemValue.HasValue)
{
sb.Append(systemValue.Value.ToString(_cultureInfo));
}
else
{
sb.Append("NULL");
}
sb.Append(AnnotatedItemToString(value));
return sb.ToString();
}
private static string FuzzyLogicNonNumericSequenceValueToString(FuzzyLogicNonNumericSequenceValue value)
{
var sb = new StringBuilder(value.DebugView);
sb.Append(AnnotatedItemToString(value));
return sb.ToString();
}
private static string StrongIdentifierValueToString(StrongIdentifierValue value)
{
var sb = new StringBuilder(value.NameValue);
sb.Append(AnnotatedItemToString(value));
return sb.ToString();
}
}
}
|