content
stringlengths 5
1.04M
| avg_line_length
float64 1.75
12.9k
| max_line_length
int64 2
244k
| alphanum_fraction
float64 0
0.98
| licenses
list | repository_name
stringlengths 7
92
| path
stringlengths 3
249
| size
int64 5
1.04M
| lang
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace QM2D.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 39.222222 | 151 | 0.578848 |
[
"Unlicense",
"MIT"
] |
arajar/EasyWFC
|
EasyWFC/Properties/Settings.Designer.cs
| 1,061 |
C#
|
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using Xamarin.Auth;
using Xamarin.Forms;
using Xamarin.Forms.Platform.WinPhone;
using XamFormsAuthenticateProviders;
using XamFormsAuthenticateProviders.WinPhone.Custom_Pages;
using Button = Xamarin.Forms.Button;
using Page = Xamarin.Forms.Page;
[assembly: ExportRenderer(typeof(LoginPage), typeof(LoginPageRenderer))]
namespace XamFormsAuthenticateProviders.WinPhone.Custom_Pages
{
public class LoginPageRenderer : PageRenderer
{
LoginPage page;
bool loginInProgress;
private WebView webView;
protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
base.OnElementChanged(e);
if (e.OldElement != null ||
Element == null)
return;
page = e.NewElement as LoginPage;
if (page == null ||
loginInProgress)
return;
loginInProgress = true;
try
{
OAuth2Authenticator auth = new OAuth2Authenticator(
page.ProviderOAuthSettings.ClientId, // your OAuth2 client id
page.ProviderOAuthSettings.ClientSecret, // your OAuth2 client secret
page.ProviderOAuthSettings.ScopesString, // scopes
new Uri(page.ProviderOAuthSettings.AuthorizeUrl), // the scopes, delimited by the "+" symbol
new Uri(page.ProviderOAuthSettings.RedirectUrl), // the redirect URL for the service
new Uri(page.ProviderOAuthSettings.AccessTokenUrl));
auth.AllowCancel = true;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += async (sender, args) =>
{
if (args.IsAuthenticated)
{
Console.WriteLine("Authenticated!");
}
else
{
Console.WriteLine("Canceled!");
}
await page.Navigation.PopAsync();
loginInProgress = false;
};
auth.Error += (sender, args) =>
{
Console.WriteLine("Authentication Error: {0}", args.Exception);
};
//string url = auth.GetUI().AbsolutePath;
auth.GetUI();
Uri uri = auth.GetUI();
WebBrowser browser = new WebBrowser
{
Source = new Uri("http://www.xplatsolutions.com", UriKind.Absolute),
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Height = Double.NaN,
Width = Double.NaN,
IsScriptEnabled = true,
Visibility = Visibility.Visible
};
StackPanel stackPanel1 = new StackPanel
{
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch
};
TextBlock printTextBlock = new TextBlock();
printTextBlock.Text = "Hello, World!";
stackPanel1.Children.Add(printTextBlock);
stackPanel1.Children.Add(browser);
TextBlock printTextBlock2 = new TextBlock();
printTextBlock2.Text = "Hello, World2!";
stackPanel1.Children.Add(printTextBlock2);
Children.Add(stackPanel1);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private void WebViewOnNavigated(object sender, WebNavigatedEventArgs webNavigatedEventArgs)
{
Debug.WriteLine("Navigated: {0}", webNavigatedEventArgs.Url);
}
private string OAuthURL(Provider provider)
{
string url = string.Empty;
switch (provider)
{
case Provider.Facebook:
url = string.Format("{0}?scope=openid&client_id={1}&response_type=token&redirect_uri={2}",
page.ProviderOAuthSettings.AuthorizeUrl, page.ProviderOAuthSettings.ClientId,
page.ProviderOAuthSettings.RedirectUrl);
break;
case Provider.Google:
break;
}
return url;
}
}
}
| 36.88189 | 112 | 0.541204 |
[
"MIT"
] |
PacktPublishing/Xamarin-Cross-Platform-Mobile-Application-Development
|
Module 2/Chapter 1/Windows/s4/xamformsauthenticateproviders/XamFormsAuthenticateProviders.WinPhone/Custom Pages/LoginPageRenderer.cs
| 4,686 |
C#
|
using FluentValidation;
using FluentValidation.Internal;
using Microsoft.AspNetCore.Components.Forms;
using System;
using System.Linq;
using System.Reflection;
namespace Web.WebApp.Extensions
{
// Ref: https://chrissainty.com/using-fluentvalidation-for-forms-validation-in-razor-components/
public static class EditContextFluentValidationExtensions
{
public static EditContext AddFluentValidation<T, TValidator>(this EditContext editContext) where TValidator : AbstractValidator<T>
{
if (editContext == null)
{
throw new ArgumentNullException("Edit context cannot be null");
}
var validator = (IValidator)Activator.CreateInstance(typeof(TValidator));
var messages = new ValidationMessageStore(editContext);
editContext.OnValidationRequested +=
(sender, eventArgs) => ValidateModel<T>((EditContext)sender, messages, validator);
editContext.OnFieldChanged +=
(sender, eventArgs) => ValidateField(editContext, messages, eventArgs.FieldIdentifier, validator);
return editContext;
}
private static void ValidateModel<T>(EditContext editContext, ValidationMessageStore messages, IValidator validator)
{
var context = new ValidationContext<T>((T)editContext.Model);
//var validator = GetValidatorForModel(editContext.Model);
var validationResults = validator.Validate(context);
messages.Clear();
foreach (var validationResult in validationResults.Errors)
{
messages.Add(editContext.Field(validationResult.PropertyName), validationResult.ErrorMessage);
}
editContext.NotifyValidationStateChanged();
}
private static void ValidateField(EditContext editContext, ValidationMessageStore messages, in FieldIdentifier fieldIdentifier, IValidator validator)
{
var properties = new[] { fieldIdentifier.FieldName };
var context = new ValidationContext<object>(fieldIdentifier.Model, new PropertyChain(), new MemberNameValidatorSelector(properties));
//var validator = GetValidatorForModel(fieldIdentifier.Model);
var validationResults = validator.Validate(context);
messages.Clear();
foreach(var error in validationResults.Errors)
{
messages.Clear(fieldIdentifier);
messages.Add(fieldIdentifier, error.ErrorMessage);
}
editContext.NotifyValidationStateChanged();
}
// *** Fails to get from different assembly
private static IValidator GetValidatorForModel(object model)
{
var abstractValidatorType = typeof(AbstractValidator<>).MakeGenericType(model.GetType());
var modelValidatorType = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(t => t.IsSubclassOf(abstractValidatorType));
var modelValidatorInstance = (IValidator)Activator.CreateInstance(modelValidatorType);
return modelValidatorInstance;
}
}
}
| 40.897436 | 157 | 0.671787 |
[
"MIT"
] |
tolaveng/TrackMyExpense
|
src/Web.WebApp/Extensions/EditContextFluentValidationExtensions.cs
| 3,192 |
C#
|
using System;
using System.Threading;
namespace GitHub.Unity
{
class GitLockTask : ProcessTask<string>
{
private const string TaskName = "git lfs lock";
private readonly string arguments;
public GitLockTask(string path,
CancellationToken token, IOutputProcessor<string> processor = null)
: base(token, processor ?? new SimpleOutputProcessor())
{
Name = TaskName;
Guard.ArgumentNotNullOrWhiteSpace(path, "path");
arguments = String.Format("lfs lock \"{0}\"", path);
}
public override string ProcessArguments => arguments;
public override TaskAffinity Affinity { get { return TaskAffinity.Exclusive; } }
}
}
| 30.708333 | 88 | 0.63772 |
[
"MIT"
] |
Frozenfire92/Unity
|
src/GitHub.Api/Git/Tasks/GitLockTask.cs
| 737 |
C#
|
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using osu.Game.Rulesets.Replays;
using osu.Game.Utils;
namespace osu.Game.Replays
{
public class Replay : IDeepCloneable<Replay>
{
/// <summary>
/// Whether all frames for this replay have been received.
/// If false, gameplay would be paused to wait for further data, for instance.
/// </summary>
public bool HasReceivedAllFrames = true;
public List<ReplayFrame> Frames = new List<ReplayFrame>();
public Replay DeepClone()
{
return new Replay
{
HasReceivedAllFrames = HasReceivedAllFrames,
// individual frames are mutable for now but hopefully this will not be a thing in the future.
Frames = Frames.ToList(),
};
}
}
}
| 30.823529 | 111 | 0.609733 |
[
"MIT"
] |
peppy/osu-new
|
osu.Game/Replays/Replay.cs
| 1,017 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// See LICENSE file in the project root for full license information.
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "TEMP", Scope = "member", Target = "~M:K2Bridge.Tests.UnitTests.DAL.KustoDataAccessTests.DatabaseAndTableNamesAreSetOnKustoQuery(System.String,System.String,System.String)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "TEMP", Scope = "member", Target = "~M:K2Bridge.Tests.UnitTests.DAL.KustoDataAccessTests.WhenGetIndexListWithValidIndexReturnFieldCaps")]
| 90.818182 | 310 | 0.7998 |
[
"MIT"
] |
AsafMah/K2Bridge
|
K2Bridge.Tests.UnitTests/GlobalSuppressions.cs
| 1,001 |
C#
|
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 02.05.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.LessThan.Complete.NullableSingle.Double{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Nullable<System.Single>;
using T_DATA2 =System.Double;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__01__VV
public static class TestSet_504__param__01__VV
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001__less()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ vv2);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001__less
//-----------------------------------------------------------------------
[Test]
public static void Test_002__equal()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=4;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002__equal
//-----------------------------------------------------------------------
[Test]
public static void Test_003__greater()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=4;
T_DATA2 vv2=3;
var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_003__greater
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ < /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => vv1 /*OP{*/ < /*}OP*/ ((T_DATA2)vv2__null_obj));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ < /*}OP*/ ((T_DATA2)vv2__null_obj));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA03NN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ < /*}OP*/ vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ < /*}OP*/ ((T_DATA2)vv2__null_obj)));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ < /*}OP*/ ((T_DATA2)vv2__null_obj)));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB03NN
};//class TestSet_504__param__01__VV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.LessThan.Complete.NullableSingle.Double
| 24.712042 | 137 | 0.531886 |
[
"MIT"
] |
ibprovider/Lcpi.EFCore.LcpiOleDb
|
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/LessThan/Complete/NullableSingle/Double/TestSet_504__param__01__VV.cs
| 9,442 |
C#
|
using System;
[Serializable]
public class NoteHashSet : SerializableHashSet<Note>
{
}
| 12.428571 | 52 | 0.781609 |
[
"MIT"
] |
SirLangley/Play
|
UltraStar Play/Assets/Common/Model/Song/NoteHashSet.cs
| 87 |
C#
|
using Ocelot.Configuration.Creator;
using Ocelot.Configuration.File;
using Ocelot.Values;
using Shouldly;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.Configuration
{
public class UpstreamTemplatePatternCreatorTests
{
private FileRoute _fileRoute;
private readonly UpstreamTemplatePatternCreator _creator;
private UpstreamPathTemplate _result;
public UpstreamTemplatePatternCreatorTests()
{
_creator = new UpstreamTemplatePatternCreator();
}
[Fact]
public void should_match_up_to_next_slash()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/api/v{apiVersion}/cards",
Priority = 0
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^(?i)/api/v[^/]+/cards$"))
.And(x => ThenThePriorityIs(0))
.BDDfy();
}
[Fact]
public void should_use_re_route_priority()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/orders/{catchAll}",
Priority = 0
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^(?i)/orders(|/.+|/[\\?&#].+)$"))
.And(x => ThenThePriorityIs(0))
.BDDfy();
}
[Fact]
public void should_use_zero_priority()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/{catchAll}",
Priority = 1
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/.*"))
.And(x => ThenThePriorityIs(0))
.BDDfy();
}
[Fact]
public void should_set_upstream_template_pattern_to_ignore_case_sensitivity()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/PRODUCTS/{productId}",
RouteIsCaseSensitive = false
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^(?i)/PRODUCTS(|/.+|/[\\?&#].+)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_match_forward_slash_or_no_forward_slash_if_template_end_with_forward_slash()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/PRODUCTS/",
RouteIsCaseSensitive = false
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^(?i)/PRODUCTS(/|)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_set_upstream_template_pattern_to_respect_case_sensitivity()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/PRODUCTS/{productId}",
RouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/PRODUCTS(|/.+|/[\\?&#].+)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_anything_to_end_of_string()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/api/products/{productId}",
RouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/api/products(|/.+|/[\\?&#].+)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_more_than_one_placeholder()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/api/products/{productId}/variants/{variantId}",
RouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/api/products/[^/]+/variants(|/.+|/[\\?&#].+)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_more_than_one_placeholder_with_trailing_slash()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/api/products/{productId}/variants/{variantId}/",
RouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/api/products/[^/]+/variants/[^/]+(/|)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_to_end_of_string()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/"
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_to_end_of_string_when_slash_and_placeholder()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/{url}"
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/.*"))
.And(x => ThenThePriorityIs(0))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_starts_with_placeholder_then_has_another_later()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/{productId}/products/variants/{variantId}/",
RouteIsCaseSensitive = true
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^/[^/]+/products/variants/[^/]+(/|)$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_query_string()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}"
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^(?i)/api/subscriptions/[^/]+/updates\\?unitId=.+$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
[Fact]
public void should_create_template_pattern_that_matches_query_string_with_multiple_params()
{
var fileRoute = new FileRoute
{
UpstreamPathTemplate = "/api/subscriptions/{subscriptionId}/updates?unitId={unitId}&productId={productId}"
};
this.Given(x => x.GivenTheFollowingFileRoute(fileRoute))
.When(x => x.WhenICreateTheTemplatePattern())
.Then(x => x.ThenTheFollowingIsReturned("^(?i)/api/subscriptions/[^/]+/updates\\?unitId=.+&productId=.+$"))
.And(x => ThenThePriorityIs(1))
.BDDfy();
}
private void GivenTheFollowingFileRoute(FileRoute fileRoute)
{
_fileRoute = fileRoute;
}
private void WhenICreateTheTemplatePattern()
{
_result = _creator.Create(_fileRoute);
}
private void ThenTheFollowingIsReturned(string expected)
{
_result.Template.ShouldBe(expected);
}
private void ThenThePriorityIs(int v)
{
_result.Priority.ShouldBe(v);
}
}
}
| 36.578544 | 124 | 0.527181 |
[
"MIT"
] |
AndyConlisk/Ocelot
|
test/Ocelot.UnitTests/Configuration/UpstreamTemplatePatternCreatorTests.cs
| 9,547 |
C#
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Management.Automation.Runspaces;
using System.Reflection;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Threading;
using Microsoft.Management.Infrastructure;
using Microsoft.PowerShell.Cmdletization;
using Dbg = System.Management.Automation.Diagnostics;
using System.Management.Automation.Language;
using Parser = System.Management.Automation.Language.Parser;
using ScriptBlock = System.Management.Automation.ScriptBlock;
using Token = System.Management.Automation.Language.Token;
#if LEGACYTELEMETRY
using Microsoft.PowerShell.Telemetry.Internal;
#endif
//
// Now define the set of commands for manipulating modules.
//
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Implements a cmdlet that loads a module
/// </summary>
[Cmdlet(VerbsData.Import, "Module", DefaultParameterSetName = ParameterSet_Name, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=141553")]
[OutputType(typeof(PSModuleInfo))]
public sealed class ImportModuleCommand : ModuleCmdletBase, IDisposable
{
#region Cmdlet parameters
private const string ParameterSet_Name = "Name";
private const string ParameterSet_FQName = "FullyQualifiedName";
private const string ParameterSet_ModuleInfo = "ModuleInfo";
private const string ParameterSet_Assembly = "Assembly";
private const string ParameterSet_ViaPsrpSession = "PSSession";
private const string ParameterSet_ViaCimSession = "CimSession";
private const string ParameterSet_FQName_ViaPsrpSession = "FullyQualifiedNameAndPSSession";
/// <summary>
/// This parameter specifies whether to import to the current session state
/// or to the global / top-level session state
/// </summary>
[Parameter]
public SwitchParameter Global
{
set { base.BaseGlobal = value; }
get { return base.BaseGlobal; }
}
/// <summary>
/// This parameter specified a prefix used to modify names of imported commands
/// </summary>
[Parameter]
[ValidateNotNull]
public string Prefix
{
set { BasePrefix = value; }
get { return BasePrefix; }
}
/// <summary>
/// This parameter names the module to load.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Name, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[Parameter(ParameterSetName = ParameterSet_ViaPsrpSession, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[Parameter(ParameterSetName = ParameterSet_ViaCimSession, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] Name { set; get; } = Utils.EmptyArray<string>();
/// <summary>
/// This parameter specifies the current pipeline object
/// </summary>
[Parameter(ParameterSetName = ParameterSet_FQName, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[Parameter(ParameterSetName = ParameterSet_FQName_ViaPsrpSession, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public ModuleSpecification[] FullyQualifiedName { get; set; }
/// <summary>
/// A list of assembly objects to process as modules.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
[Parameter(ParameterSetName = ParameterSet_Assembly, Mandatory = true, ValueFromPipeline = true, Position = 0)]
public Assembly[] Assembly { get; set; }
/// <summary>
/// This patterns matching the names of functions to import from the module...
/// </summary>
[Parameter]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] Function
{
set
{
if (value == null)
return;
_functionImportList = value;
// Create the list of patterns to match at parameter bind time
// so errors will be reported before loading the module...
BaseFunctionPatterns = new List<WildcardPattern>();
foreach (string pattern in _functionImportList)
{
BaseFunctionPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase));
}
}
get { return _functionImportList; }
}
private string[] _functionImportList = Utils.EmptyArray<string>();
/// <summary>
/// This patterns matching the names of cmdlets to import from the module...
/// </summary>
[Parameter]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] Cmdlet
{
set
{
if (value == null)
return;
_cmdletImportList = value;
// Create the list of patterns to match at parameter bind time
// so errors will be reported before loading the module...
BaseCmdletPatterns = new List<WildcardPattern>();
foreach (string pattern in _cmdletImportList)
{
BaseCmdletPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase));
}
}
get { return _cmdletImportList; }
}
private string[] _cmdletImportList = Utils.EmptyArray<string>();
/// <summary>
/// This parameter specifies the variables to import from the module...
/// </summary>
[Parameter]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] Variable
{
set
{
if (value == null)
return;
_variableExportList = value;
// Create the list of patterns to match at parameter bind time
// so errors will be reported before loading the module...
BaseVariablePatterns = new List<WildcardPattern>();
foreach (string pattern in _variableExportList)
{
BaseVariablePatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase));
}
}
get { return _variableExportList; }
}
private string[] _variableExportList;
/// <summary>
/// This parameter specifies the aliases to import from the module...
/// </summary>
[Parameter]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public string[] Alias
{
set
{
if (value == null)
return;
_aliasExportList = value;
// Create the list of patterns to match at parameter bind time
// so errors will be reported before loading the module...
BaseAliasPatterns = new List<WildcardPattern>();
foreach (string pattern in _aliasExportList)
{
BaseAliasPatterns.Add(WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase));
}
}
get { return _aliasExportList; }
}
private string[] _aliasExportList;
/// <summary>
/// This parameter causes a module to be loaded over top of the current one...
/// </summary>
[Parameter]
public SwitchParameter Force
{
get { return (SwitchParameter)BaseForce; }
set { BaseForce = value; }
}
/// <summary>
/// This parameter causes the session state instance to be written...
/// </summary>
[Parameter]
public SwitchParameter PassThru
{
get { return (SwitchParameter)BasePassThru; }
set { BasePassThru = value; }
}
/// <summary>
/// This parameter causes the session state instance to be written as a custom object...
/// </summary>
[Parameter]
public SwitchParameter AsCustomObject
{
get { return (SwitchParameter)BaseAsCustomObject; }
set { BaseAsCustomObject = value; }
}
/// <summary>
/// The minimum version of the module to load.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Name)]
[Parameter(ParameterSetName = ParameterSet_ViaPsrpSession)]
[Parameter(ParameterSetName = ParameterSet_ViaCimSession)]
[Alias("Version")]
public Version MinimumVersion
{
get { return BaseMinimumVersion; }
set { BaseMinimumVersion = value; }
}
/// <summary>
/// The maximum version of the module to load.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Name)]
[Parameter(ParameterSetName = ParameterSet_ViaPsrpSession)]
[Parameter(ParameterSetName = ParameterSet_ViaCimSession)]
public string MaximumVersion
{
get
{
if (BaseMaximumVersion == null)
return null;
else
return BaseMaximumVersion.ToString();
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
BaseMaximumVersion = null;
}
else
{
BaseMaximumVersion = GetMaximumVersion(value);
}
}
}
/// <summary>
/// The version of the module to load.
/// </summary>
[Parameter(ParameterSetName = ParameterSet_Name)]
[Parameter(ParameterSetName = ParameterSet_ViaPsrpSession)]
[Parameter(ParameterSetName = ParameterSet_ViaCimSession)]
public Version RequiredVersion
{
get { return BaseRequiredVersion; }
set { BaseRequiredVersion = value; }
}
/// <summary>
/// This parameter specifies the current pipeline object
/// </summary>
[Parameter(ParameterSetName = ParameterSet_ModuleInfo, Mandatory = true, ValueFromPipeline = true, Position = 0)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public PSModuleInfo[] ModuleInfo { set; get; } = Utils.EmptyArray<PSModuleInfo>();
/// <summary>
/// The arguments to pass to the module script.
/// </summary>
[Parameter]
[Alias("Args")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")]
public object[] ArgumentList
{
get { return BaseArgumentList; }
set { BaseArgumentList = value; }
}
/// <summary>
/// Disable warnings on cmdlet and function names that have non-standard verbs
/// or non-standard characters in the noun.
/// </summary>
[Parameter]
public SwitchParameter DisableNameChecking
{
get { return BaseDisableNameChecking; }
set { BaseDisableNameChecking = value; }
}
/// <summary>
/// Does not import a command if a command with same name exists on the target sessionstate.
/// </summary>
[Parameter, Alias("NoOverwrite")]
public SwitchParameter NoClobber { get; set; }
/// <summary>
/// Imports a command to the scope specified
/// </summary>
[Parameter]
[ValidateSet("Local", "Global")]
public String Scope
{
get { return _scope; }
set
{
_scope = value;
_isScopeSpecified = true;
}
}
private string _scope = string.Empty;
private bool _isScopeSpecified = false;
/// <summary>
/// If specified, then Import-Module will attempt to import PowerShell modules from a remote computer using the specified session
/// </summary>
[Parameter(ParameterSetName = ParameterSet_ViaPsrpSession, Mandatory = true)]
[Parameter(ParameterSetName = ParameterSet_FQName_ViaPsrpSession, Mandatory = true)]
[ValidateNotNull]
public PSSession PSSession { get; set; }
/// Construct the Import-Module cmdlet object
public ImportModuleCommand()
{
base.BaseDisableNameChecking = false;
}
/// <summary>
/// If specified, then Import-Module will attempt to import PS-CIM modules from a remote computer using the specified session
/// </summary>
[Parameter(ParameterSetName = ParameterSet_ViaCimSession, Mandatory = true)]
[ValidateNotNull]
public CimSession CimSession { get; set; }
/// <summary>
/// For interoperability with 3rd party CIM servers, user can specify custom resource URI
/// </summary>
[Parameter(ParameterSetName = ParameterSet_ViaCimSession, Mandatory = false)]
[ValidateNotNull]
public Uri CimResourceUri { get; set; }
/// <summary>
/// For interoperability with 3rd party CIM servers, user can specify custom namespace
/// </summary>
[Parameter(ParameterSetName = ParameterSet_ViaCimSession, Mandatory = false)]
[ValidateNotNullOrEmpty]
public string CimNamespace { get; set; }
#endregion Cmdlet parameters
#region Local import
private void ImportModule_ViaLocalModuleInfo(ImportModuleOptions importModuleOptions, PSModuleInfo module)
{
try
{
PSModuleInfo alreadyLoadedModule = null;
Context.Modules.ModuleTable.TryGetValue(module.Path, out alreadyLoadedModule);
if (!BaseForce && IsModuleAlreadyLoaded(alreadyLoadedModule))
{
AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, alreadyLoadedModule);
// Even if the module has been loaded, import the specified members...
ImportModuleMembers(alreadyLoadedModule, this.BasePrefix, importModuleOptions);
if (BaseAsCustomObject)
{
if (alreadyLoadedModule.ModuleType != ModuleType.Script)
{
string message = StringUtil.Format(Modules.CantUseAsCustomObjectWithBinaryModule, alreadyLoadedModule.Path);
InvalidOperationException invalidOp = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(invalidOp, "Modules_CantUseAsCustomObjectWithBinaryModule",
ErrorCategory.PermissionDenied, null);
WriteError(er);
}
else
{
WriteObject(alreadyLoadedModule.AsCustomObject());
}
}
else if (BasePassThru)
{
WriteObject(alreadyLoadedModule);
}
}
else
{
PSModuleInfo moduleToRemove;
if (Context.Modules.ModuleTable.TryGetValue(module.Path, out moduleToRemove))
{
Dbg.Assert(BaseForce, "We should only remove and reload if -Force was specified");
RemoveModule(moduleToRemove);
}
PSModuleInfo moduleToProcess = module;
try
{
// If we're passing in a dynamic module, then the session state will not be
// null and we want to just add the module to the module table. Otherwise, it's
// a module info from Get-Module -list so we need to read the actual module file.
if (module.SessionState == null)
{
if (File.Exists(module.Path))
{
bool found;
moduleToProcess = LoadModule(module.Path, null, this.BasePrefix, /*SessionState*/ null,
ref importModuleOptions,
ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
out found);
Dbg.Assert(found, "Module should be found when referenced by its absolute path");
}
}
else if (!string.IsNullOrEmpty(module.Name))
{
// It has a session state and a name but it's not in the module
// table so it's ok to add it
// Add it to the all module tables
AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, moduleToProcess);
if (moduleToProcess.SessionState != null)
{
ImportModuleMembers(moduleToProcess, this.BasePrefix, importModuleOptions);
}
if (BaseAsCustomObject && moduleToProcess.SessionState != null)
{
WriteObject(module.AsCustomObject());
}
else if (BasePassThru)
{
WriteObject(moduleToProcess);
}
}
}
catch (IOException)
{
;
}
}
}
catch (PSInvalidOperationException e)
{
ErrorRecord er = new ErrorRecord(e.ErrorRecord, e);
WriteError(er);
}
}
private void ImportModule_ViaAssembly(ImportModuleOptions importModuleOptions, Assembly suppliedAssembly)
{
bool moduleLoaded = false;
// Loop through Module Cache to ensure that the module is not already imported.
if (suppliedAssembly != null && Context.Modules.ModuleTable != null)
{
foreach (KeyValuePair<string, PSModuleInfo> pair in Context.Modules.ModuleTable)
{
// if the module in the moduleTable is an assembly module without path, the moduleName is the key.
string moduleName = "dynamic_code_module_" + suppliedAssembly;
if (pair.Value.Path == "")
{
if (pair.Key.Equals(moduleName, StringComparison.OrdinalIgnoreCase))
{
moduleLoaded = true;
if (BasePassThru)
{
WriteObject(pair.Value);
}
break;
}
else
{
continue;
}
}
if (pair.Value.Path.Equals(suppliedAssembly.Location, StringComparison.OrdinalIgnoreCase))
{
moduleLoaded = true;
if (BasePassThru)
{
WriteObject(pair.Value);
}
break;
}
}
}
if (!moduleLoaded)
{
bool found;
PSModuleInfo module = LoadBinaryModule(false, null, null, suppliedAssembly, null, null,
importModuleOptions,
ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
this.BasePrefix, false /* loadTypes */ , false /* loadFormats */, out found);
if (found && module != null)
{
// Add it to all module tables ...
AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module);
if (BasePassThru)
{
WriteObject(module);
}
}
}
}
private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModuleOptions, string name)
{
try
{
bool found = false;
PSModuleInfo foundModule = null;
string cachedPath = null;
string rootedPath = null;
// See if we can use the cached path for the file. If a version number has been specified, then
// we won't look in the cache
if (this.MinimumVersion == null && this.MaximumVersion == null && this.RequiredVersion == null && PSModuleInfo.UseAppDomainLevelModuleCache && !this.BaseForce)
{
// See if the name is in the appdomain-level module path name cache...
cachedPath = PSModuleInfo.ResolveUsingAppDomainLevelModuleCache(name);
}
if (!string.IsNullOrEmpty(cachedPath))
{
if (File.Exists(cachedPath))
{
rootedPath = cachedPath;
}
else
{
PSModuleInfo.RemoveFromAppDomainLevelCache(name);
}
}
if (rootedPath == null)
{
// Check for full-qualified paths - either absolute or relative
rootedPath = ResolveRootedFilePath(name, this.Context);
}
bool alreadyLoaded = false;
if (!String.IsNullOrEmpty(rootedPath))
{
// TODO/FIXME: use IsModuleAlreadyLoaded to get consistent behavior
// TODO/FIXME: (for example checking ModuleType != Manifest below seems incorrect - cdxml modules also declare their own version)
// PSModuleInfo alreadyLoadedModule = null;
// Context.Modules.ModuleTable.TryGetValue(rootedPath, out alreadyLoadedModule);
// if (!BaseForce && IsModuleAlreadyLoaded(alreadyLoadedModule))
// If the module has already been loaded, just emit it and continue...
PSModuleInfo module;
if (!BaseForce && Context.Modules.ModuleTable.TryGetValue(rootedPath, out module))
{
if (RequiredVersion == null
|| module.Version.Equals(RequiredVersion)
|| (BaseMinimumVersion == null && BaseMaximumVersion == null)
|| module.ModuleType != ModuleType.Manifest
|| (BaseMinimumVersion == null && BaseMaximumVersion != null && module.Version <= BaseMaximumVersion)
|| (BaseMinimumVersion != null && BaseMaximumVersion == null && module.Version >= BaseMinimumVersion)
|| (BaseMinimumVersion != null && BaseMaximumVersion != null && module.Version >= BaseMinimumVersion && module.Version <= BaseMaximumVersion))
{
alreadyLoaded = true;
AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module);
ImportModuleMembers(module, this.BasePrefix, importModuleOptions);
if (BaseAsCustomObject)
{
if (module.ModuleType != ModuleType.Script)
{
string message = StringUtil.Format(Modules.CantUseAsCustomObjectWithBinaryModule, module.Path);
InvalidOperationException invalidOp = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(invalidOp, "Modules_CantUseAsCustomObjectWithBinaryModule",
ErrorCategory.PermissionDenied, null);
WriteError(er);
}
else
{
WriteObject(module.AsCustomObject());
}
}
else if (BasePassThru)
{
WriteObject(module);
}
found = true;
foundModule = module;
}
}
if (!alreadyLoaded)
{
// If the path names a file, load that file...
if (File.Exists(rootedPath))
{
PSModuleInfo moduleToRemove;
if (Context.Modules.ModuleTable.TryGetValue(rootedPath, out moduleToRemove))
{
RemoveModule(moduleToRemove);
}
foundModule = LoadModule(rootedPath, null, this.BasePrefix, null, ref importModuleOptions,
ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
out found);
}
else if (Directory.Exists(rootedPath))
{
// If the path ends with a directory separator, remove it
if (rootedPath.EndsWith(Path.DirectorySeparatorChar))
{
rootedPath = Path.GetDirectoryName(rootedPath);
}
// Load the latest valid version if it is a multi-version module directory
foundModule = LoadUsingMultiVersionModuleBase(rootedPath,
ManifestProcessingFlags.LoadElements |
ManifestProcessingFlags.WriteErrors |
ManifestProcessingFlags.NullOnFirstError,
importModuleOptions, out found);
if (!found)
{
// If the path is a directory, double up the end of the string
// then try to load that using extensions...
rootedPath = Path.Combine(rootedPath, Path.GetFileName(rootedPath));
foundModule = LoadUsingExtensions(null, rootedPath, rootedPath, null, null, this.BasePrefix, /*SessionState*/ null,
importModuleOptions,
ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
out found);
}
}
}
}
else
{
// Check if module could be a snapin. This was the case for PowerShell version 2 engine modules.
if (InitialSessionState.IsEngineModule(name))
{
PSSnapInInfo snapin = ModuleCmdletBase.GetEngineSnapIn(Context, name);
// Return the command if we found a module
if (snapin != null)
{
// warn that this module already exists as a snapin
string warningMessage = string.Format(
CultureInfo.InvariantCulture,
Modules.ModuleLoadedAsASnapin,
snapin.Name);
WriteWarning(warningMessage);
found = true;
return foundModule;
}
}
// At this point, the name didn't resolve to an existing file or directory.
// It may still be rooted (relative or absolute). If it is, then we'll only use
// the extension search. If it's not rooted, use a path-based search.
if (IsRooted(name))
{
// If there is no extension, we'll have to search using the extensions
if (!string.IsNullOrEmpty(Path.GetExtension(name)))
{
foundModule = LoadModule(name, null, this.BasePrefix, null, ref importModuleOptions,
ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
out found);
}
else
{
foundModule = LoadUsingExtensions(null, name, name, null, null, this.BasePrefix, /*SessionState*/ null,
importModuleOptions,
ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
out found);
}
}
else
{
IEnumerable<string> modulePath = ModuleIntrinsics.GetModulePath(false, this.Context);
if (this.MinimumVersion == null && this.RequiredVersion == null && this.MaximumVersion == null)
{
this.AddToAppDomainLevelCache = true;
}
found = LoadUsingModulePath(found, modulePath, name, /* SessionState*/ null,
importModuleOptions,
ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
out foundModule);
}
}
if (!found)
{
ErrorRecord er = null;
string message = null;
if (BaseRequiredVersion != null)
{
message = StringUtil.Format(Modules.ModuleWithVersionNotFound, name, BaseRequiredVersion);
}
else if (BaseMinimumVersion != null && BaseMaximumVersion != null)
{
message = StringUtil.Format(Modules.MinimumVersionAndMaximumVersionNotFound, name, BaseMinimumVersion, BaseMaximumVersion);
}
else if (BaseMinimumVersion != null)
{
message = StringUtil.Format(Modules.ModuleWithVersionNotFound, name, BaseMinimumVersion);
}
else if (BaseMaximumVersion != null)
{
message = StringUtil.Format(Modules.MaximumVersionNotFound, name, BaseMaximumVersion);
}
if (BaseRequiredVersion != null || BaseMinimumVersion != null || BaseMaximumVersion != null)
{
FileNotFoundException fnf = new FileNotFoundException(message);
er = new ErrorRecord(fnf, "Modules_ModuleWithVersionNotFound",
ErrorCategory.ResourceUnavailable, name);
}
else
{
message = StringUtil.Format(Modules.ModuleNotFound, name);
FileNotFoundException fnf = new FileNotFoundException(message);
er = new ErrorRecord(fnf, "Modules_ModuleNotFound",
ErrorCategory.ResourceUnavailable, name);
}
WriteError(er);
}
return foundModule;
}
catch (PSInvalidOperationException e)
{
ErrorRecord er = new ErrorRecord(e.ErrorRecord, e);
WriteError(er);
}
return null;
}
#endregion Local import
#region Remote import
#region PSSession parameterset
private IList<PSModuleInfo> ImportModule_RemotelyViaPsrpSession(
ImportModuleOptions importModuleOptions,
IEnumerable<string> moduleNames,
IEnumerable<ModuleSpecification> fullyQualifiedNames,
PSSession psSession)
{
var remotelyImportedModules = new List<PSModuleInfo>();
if (moduleNames != null)
{
foreach (string moduleName in moduleNames)
{
var tmp = ImportModule_RemotelyViaPsrpSession(importModuleOptions, moduleName, null, psSession);
remotelyImportedModules.AddRange(tmp);
}
}
if (fullyQualifiedNames != null)
{
foreach (var fullyQualifiedName in fullyQualifiedNames)
{
var tmp = ImportModule_RemotelyViaPsrpSession(importModuleOptions, null, fullyQualifiedName, psSession);
remotelyImportedModules.AddRange(tmp);
}
}
return remotelyImportedModules;
}
private IList<PSModuleInfo> ImportModule_RemotelyViaPsrpSession(
ImportModuleOptions importModuleOptions,
string moduleName,
ModuleSpecification fullyQualifiedName,
PSSession psSession)
{
//
// import the module in the remote session first
//
List<PSObject> remotelyImportedModules;
using (var powerShell = System.Management.Automation.PowerShell.Create())
{
powerShell.Runspace = psSession.Runspace;
powerShell.AddCommand("Import-Module");
powerShell.AddParameter("DisableNameChecking", this.DisableNameChecking);
powerShell.AddParameter("PassThru", true);
if (fullyQualifiedName != null)
{
powerShell.AddParameter("FullyQualifiedName", fullyQualifiedName);
}
else
{
powerShell.AddParameter("Name", moduleName);
if (this.MinimumVersion != null)
{
powerShell.AddParameter("Version", this.MinimumVersion);
}
if (this.RequiredVersion != null)
{
powerShell.AddParameter("RequiredVersion", this.RequiredVersion);
}
if (this.MaximumVersion != null)
{
powerShell.AddParameter("MaximumVersion", this.MaximumVersion);
}
}
if (this.ArgumentList != null)
{
powerShell.AddParameter("ArgumentList", this.ArgumentList);
}
if (this.BaseForce)
{
powerShell.AddParameter("Force", true);
}
string errorMessageTemplate = string.Format(
CultureInfo.InvariantCulture,
Modules.RemoteDiscoveryRemotePsrpCommandFailed,
string.Format(CultureInfo.InvariantCulture, "Import-Module -Name '{0}'", moduleName));
remotelyImportedModules = RemoteDiscoveryHelper.InvokePowerShell(
powerShell,
this.CancellationToken,
this,
errorMessageTemplate).ToList();
}
List<PSModuleInfo> result = new List<PSModuleInfo>();
foreach (PSObject remotelyImportedModule in remotelyImportedModules)
{
PSPropertyInfo nameProperty = remotelyImportedModule.Properties["Name"];
if (nameProperty != null)
{
string remoteModuleName = (string)LanguagePrimitives.ConvertTo(
nameProperty.Value,
typeof(string),
CultureInfo.InvariantCulture);
PSPropertyInfo helpInfoProperty = remotelyImportedModule.Properties["HelpInfoUri"];
string remoteHelpInfoUri = null;
if (helpInfoProperty != null)
{
remoteHelpInfoUri = (string)LanguagePrimitives.ConvertTo(
helpInfoProperty.Value,
typeof(string),
CultureInfo.InvariantCulture);
}
PSPropertyInfo guidProperty = remotelyImportedModule.Properties["Guid"];
Guid remoteModuleGuid = Guid.Empty;
if (guidProperty != null)
{
LanguagePrimitives.TryConvertTo(guidProperty.Value, out remoteModuleGuid);
}
PSPropertyInfo versionProperty = remotelyImportedModule.Properties["Version"];
Version remoteModuleVersion = null;
if (versionProperty != null)
{
Version tmp;
if (LanguagePrimitives.TryConvertTo<Version>(versionProperty.Value, CultureInfo.InvariantCulture, out tmp))
{
remoteModuleVersion = tmp;
}
}
PSModuleInfo moduleInfo = ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule(
importModuleOptions,
remoteModuleName,
remoteModuleVersion,
psSession);
// Set the HelpInfoUri and Guid as necessary, so that Save-Help can work with this module object
// to retrieve help files from the remote site.
if (moduleInfo != null)
{
// set the HelpInfoUri if it's needed
if (string.IsNullOrEmpty(moduleInfo.HelpInfoUri) && !string.IsNullOrEmpty(remoteHelpInfoUri))
{
moduleInfo.SetHelpInfoUri(remoteHelpInfoUri);
}
// set the Guid if it's needed
if (remoteModuleGuid != Guid.Empty)
{
moduleInfo.SetGuid(remoteModuleGuid);
}
result.Add(moduleInfo);
}
}
}
return result;
}
private PSModuleInfo ImportModule_RemotelyViaPsrpSession_SinglePreimportedModule(
ImportModuleOptions importModuleOptions,
string remoteModuleName,
Version remoteModuleVersion,
PSSession psSession)
{
string temporaryModulePath = RemoteDiscoveryHelper.GetModulePath(
remoteModuleName,
remoteModuleVersion,
psSession.ComputerName,
this.Context.CurrentRunspace);
string wildcardEscapedPath = WildcardPattern.Escape(temporaryModulePath);
try
{
//
// avoid importing a module twice
//
string localPsm1File = Path.Combine(temporaryModulePath, Path.GetFileName(temporaryModulePath) + ".psm1");
PSModuleInfo alreadyImportedModule = this.IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded(
localPsm1File, this.BasePrefix, importModuleOptions);
if (alreadyImportedModule != null)
{
return alreadyImportedModule;
}
//
// create proxy module in a temporary folder
//
using (var powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
{
powerShell.AddCommand("Export-PSSession");
powerShell.AddParameter("OutputModule", wildcardEscapedPath);
powerShell.AddParameter("AllowClobber", true);
powerShell.AddParameter("Module", remoteModuleName); // remoteModulePath is currently unsupported by Get-Command and implicit remoting
powerShell.AddParameter("Force", true);
powerShell.AddParameter("FormatTypeName", "*");
powerShell.AddParameter("Session", psSession);
string errorMessageTemplate = string.Format(
CultureInfo.InvariantCulture,
Modules.RemoteDiscoveryFailedToGenerateProxyForRemoteModule,
remoteModuleName);
int numberOfLocallyCreatedFiles = RemoteDiscoveryHelper.InvokePowerShell(powerShell, this.CancellationToken, this, errorMessageTemplate).Count();
if (numberOfLocallyCreatedFiles == 0)
{
return null;
}
}
//
// rename the psd1 file
//
string localPsd1File = Path.Combine(temporaryModulePath, remoteModuleName + ".psd1");
if (File.Exists(localPsd1File))
{
File.Delete(localPsd1File);
}
File.Move(
sourceFileName: Path.Combine(temporaryModulePath, Path.GetFileName(temporaryModulePath) + ".psd1"),
destFileName: localPsd1File);
string wildcardEscapedPsd1Path = WildcardPattern.Escape(localPsd1File);
//
// import the proxy module just as any other local module
//
object[] oldArgumentList = this.ArgumentList;
Version originalBaseMinimumVersion = BaseMinimumVersion;
Version originalBaseMaximumVersion = BaseMaximumVersion;
Version originalBaseRequiredVersion = BaseRequiredVersion;
try
{
this.ArgumentList = new object[] { psSession };
// The correct module version has already been imported from the remote session and created locally.
// The locally created module always has a version of 1.0 regardless of the actual module version
// imported from the remote session, and version checking is no longer needed and will not work while
// importing this created local module.
BaseMinimumVersion = null;
BaseMaximumVersion = null;
BaseRequiredVersion = null;
ImportModule_LocallyViaName(importModuleOptions, wildcardEscapedPsd1Path);
}
finally
{
this.ArgumentList = oldArgumentList;
BaseMinimumVersion = originalBaseMinimumVersion;
BaseMaximumVersion = originalBaseMaximumVersion;
BaseRequiredVersion = originalBaseRequiredVersion;
}
//
// make sure the temporary folder gets removed when the module is removed
//
PSModuleInfo moduleInfo;
string psm1Path = Path.Combine(temporaryModulePath, Path.GetFileName(temporaryModulePath) + ".psm1");
if (!this.Context.Modules.ModuleTable.TryGetValue(psm1Path, out moduleInfo))
{
if (Directory.Exists(temporaryModulePath))
{
Directory.Delete(temporaryModulePath, recursive: true);
}
return null;
}
const string onRemoveScriptBody = @"
Microsoft.PowerShell.Management\Remove-Item `
-LiteralPath $temporaryModulePath `
-Force `
-Recurse `
-ErrorAction SilentlyContinue
if ($null -ne $previousOnRemoveScript)
{
& $previousOnRemoveScript $args
}
";
ScriptBlock onRemoveScriptBlock = this.Context.Engine.ParseScriptBlock(onRemoveScriptBody, false);
onRemoveScriptBlock = onRemoveScriptBlock.GetNewClosure(); // create a separate scope for variables set below
onRemoveScriptBlock.Module.SessionState.PSVariable.Set("temporaryModulePath", temporaryModulePath);
onRemoveScriptBlock.Module.SessionState.PSVariable.Set("previousOnRemoveScript", moduleInfo.OnRemove);
moduleInfo.OnRemove = onRemoveScriptBlock;
return moduleInfo;
}
catch
{
if (Directory.Exists(temporaryModulePath))
{
Directory.Delete(temporaryModulePath, recursive: true);
}
throw;
}
}
#endregion PSSession parameterset
#region CimSession parameterset
private static bool IsNonEmptyManifestField(Hashtable manifestData, string key)
{
object value = manifestData[key];
if (value == null)
{
return false;
}
object[] array;
if (LanguagePrimitives.TryConvertTo(value, CultureInfo.InvariantCulture, out array))
{
return array.Length != 0;
}
else
{
return true;
}
}
private bool IsMixedModePsCimModule(RemoteDiscoveryHelper.CimModule cimModule)
{
string temporaryModuleManifestPath = RemoteDiscoveryHelper.GetModulePath(cimModule.ModuleName, null, string.Empty, this.Context.CurrentRunspace);
bool containedErrors = false;
RemoteDiscoveryHelper.CimModuleFile mainManifestFile = cimModule.MainManifest;
if (mainManifestFile == null)
{
return true;
}
Hashtable manifestData = RemoteDiscoveryHelper.ConvertCimModuleFileToManifestHashtable(
mainManifestFile,
temporaryModuleManifestPath,
this,
ref containedErrors);
if (containedErrors || manifestData == null)
{
return false;
}
if (IsNonEmptyManifestField(manifestData, "ScriptsToProcess") ||
IsNonEmptyManifestField(manifestData, "RequiredAssemblies"))
{
return true;
}
int numberOfSubmodules = 0;
string[] nestedModules = null;
if (LanguagePrimitives.TryConvertTo(manifestData["NestedModules"], CultureInfo.InvariantCulture, out nestedModules))
{
if (nestedModules != null)
{
numberOfSubmodules += nestedModules.Length;
}
}
object rootModuleValue = manifestData["RootModule"];
if (rootModuleValue != null)
{
string rootModule;
if (LanguagePrimitives.TryConvertTo(rootModuleValue, CultureInfo.InvariantCulture, out rootModule))
{
if (!string.IsNullOrEmpty(rootModule))
{
numberOfSubmodules += 1;
}
}
}
else
{
object moduleToProcessValue = manifestData["ModuleToProcess"];
string moduleToProcess;
if (moduleToProcessValue != null && LanguagePrimitives.TryConvertTo(moduleToProcessValue, CultureInfo.InvariantCulture, out moduleToProcess))
{
if (!string.IsNullOrEmpty(moduleToProcess))
{
numberOfSubmodules += 1;
}
}
}
int numberOfCmdletizationFiles = 0;
foreach (var moduleFile in cimModule.ModuleFiles)
{
if (moduleFile.FileCode == RemoteDiscoveryHelper.CimFileCode.CmdletizationV1)
numberOfCmdletizationFiles++;
}
bool isMixedModePsCimModule = numberOfSubmodules > numberOfCmdletizationFiles;
return isMixedModePsCimModule;
}
private void ImportModule_RemotelyViaCimSession(
ImportModuleOptions importModuleOptions,
string[] moduleNames,
CimSession cimSession,
Uri resourceUri,
string cimNamespace)
{
//
// find all remote PS-CIM modules
//
IEnumerable<RemoteDiscoveryHelper.CimModule> remoteModules = RemoteDiscoveryHelper.GetCimModules(
cimSession,
resourceUri,
cimNamespace,
moduleNames,
false /* onlyManifests */,
this,
this.CancellationToken).ToList();
IEnumerable<RemoteDiscoveryHelper.CimModule> remotePsCimModules = remoteModules.Where(cimModule => cimModule.IsPsCimModule);
IEnumerable<string> remotePsrpModuleNames = remoteModules.Where(cimModule => !cimModule.IsPsCimModule).Select(cimModule => cimModule.ModuleName);
foreach (string psrpModuleName in remotePsrpModuleNames)
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
Modules.PsModuleOverCimSessionError,
psrpModuleName);
ErrorRecord errorRecord = new ErrorRecord(
new ArgumentException(errorMessage),
"PsModuleOverCimSessionError",
ErrorCategory.InvalidArgument,
psrpModuleName);
this.WriteError(errorRecord);
}
//
// report an error if some modules were not found
//
IEnumerable<string> allFoundModuleNames = remoteModules.Select(cimModule => cimModule.ModuleName).ToList();
foreach (string requestedModuleName in moduleNames)
{
var wildcardPattern = WildcardPattern.Get(requestedModuleName, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant);
bool requestedModuleWasFound = allFoundModuleNames.Any(foundModuleName => wildcardPattern.IsMatch(foundModuleName));
if (!requestedModuleWasFound)
{
string message = StringUtil.Format(Modules.ModuleNotFound, requestedModuleName);
FileNotFoundException fnf = new FileNotFoundException(message);
ErrorRecord er = new ErrorRecord(fnf, "Modules_ModuleNotFound",
ErrorCategory.ResourceUnavailable, requestedModuleName);
WriteError(er);
}
}
//
// import the PS-CIM modules
//
foreach (RemoteDiscoveryHelper.CimModule remoteCimModule in remotePsCimModules)
{
ImportModule_RemotelyViaCimModuleData(importModuleOptions, remoteCimModule, cimSession);
}
}
private bool IsPs1xmlFileHelper_IsPresentInEntries(RemoteDiscoveryHelper.CimModuleFile cimModuleFile, IEnumerable<string> manifestEntries)
{
if (manifestEntries.Any(s => s.EndsWith(cimModuleFile.FileName, StringComparison.OrdinalIgnoreCase)))
{
return true;
}
if (manifestEntries.Any(s => FixupFileName("", s, ".ps1xml").EndsWith(cimModuleFile.FileName, StringComparison.OrdinalIgnoreCase)))
{
return true;
}
return false;
}
private bool IsPs1xmlFileHelper(RemoteDiscoveryHelper.CimModuleFile cimModuleFile, Hashtable manifestData, string goodKey, string badKey)
{
if (!Path.GetExtension(cimModuleFile.FileName).Equals(".ps1xml", StringComparison.OrdinalIgnoreCase))
{
return false;
}
List<string> goodEntries;
if (!this.GetListOfStringsFromData(manifestData, null, goodKey, 0, out goodEntries))
{
goodEntries = new List<string>();
}
if (goodEntries == null)
{
goodEntries = new List<string>();
}
List<string> badEntries;
if (!this.GetListOfStringsFromData(manifestData, null, badKey, 0, out badEntries))
{
badEntries = new List<string>();
}
if (badEntries == null)
{
badEntries = new List<string>();
}
bool presentInGoodEntries = IsPs1xmlFileHelper_IsPresentInEntries(cimModuleFile, goodEntries);
bool presentInBadEntries = IsPs1xmlFileHelper_IsPresentInEntries(cimModuleFile, badEntries);
return presentInGoodEntries && !presentInBadEntries;
}
private bool IsTypesPs1XmlFile(RemoteDiscoveryHelper.CimModuleFile cimModuleFile, Hashtable manifestData)
{
return IsPs1xmlFileHelper(cimModuleFile, manifestData, goodKey: "TypesToProcess", badKey: "FormatsToProcess");
}
private bool IsFormatPs1XmlFile(RemoteDiscoveryHelper.CimModuleFile cimModuleFile, Hashtable manifestData)
{
return IsPs1xmlFileHelper(cimModuleFile, manifestData, goodKey: "FormatsToProcess", badKey: "TypesToProcess");
}
private static bool IsCmdletizationFile(RemoteDiscoveryHelper.CimModuleFile cimModuleFile)
{
return cimModuleFile.FileCode == RemoteDiscoveryHelper.CimFileCode.CmdletizationV1;
}
private IEnumerable<string> CreateCimModuleFiles(
RemoteDiscoveryHelper.CimModule remoteCimModule,
RemoteDiscoveryHelper.CimFileCode fileCode,
Func<RemoteDiscoveryHelper.CimModuleFile, bool> filesFilter,
string temporaryModuleDirectory)
{
string fileNameTemplate = null;
switch (fileCode)
{
case RemoteDiscoveryHelper.CimFileCode.CmdletizationV1:
fileNameTemplate = "{0}_{1}.cdxml";
break;
case RemoteDiscoveryHelper.CimFileCode.TypesV1:
fileNameTemplate = "{0}_{1}.types.ps1xml";
break;
case RemoteDiscoveryHelper.CimFileCode.FormatV1:
fileNameTemplate = "{0}_{1}.format.ps1xml";
break;
default:
Dbg.Assert(false, "Unrecognized file code");
break;
}
List<string> relativePathsToCreatedFiles = new List<string>();
foreach (RemoteDiscoveryHelper.CimModuleFile file in remoteCimModule.ModuleFiles)
{
if (!filesFilter(file))
{
continue;
}
string originalFileName = Path.GetFileName(file.FileName);
string fileName = string.Format(
CultureInfo.InvariantCulture,
fileNameTemplate,
originalFileName.Substring(0, Math.Min(originalFileName.Length, 20)),
Path.GetRandomFileName());
relativePathsToCreatedFiles.Add(fileName);
string fullPath = Path.Combine(temporaryModuleDirectory, fileName);
File.WriteAllBytes(
fullPath,
file.RawFileData);
#if !UNIX
AlternateDataStreamUtilities.SetZoneOfOrigin(fullPath, SecurityZone.Intranet);
#endif
}
return relativePathsToCreatedFiles;
}
private PSModuleInfo ImportModule_RemotelyViaCimModuleData(
ImportModuleOptions importModuleOptions,
RemoteDiscoveryHelper.CimModule remoteCimModule,
CimSession cimSession)
{
try
{
if (remoteCimModule.MainManifest == null)
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
Modules.EmptyModuleManifest,
remoteCimModule.ModuleName + ".psd1");
ArgumentException argumentException = new ArgumentException(errorMessage);
throw argumentException;
}
bool containedErrors = false;
PSModuleInfo moduleInfo = null;
//
// read the original manifest
//
string temporaryModuleDirectory = RemoteDiscoveryHelper.GetModulePath(
remoteCimModule.ModuleName,
null,
cimSession.ComputerName,
this.Context.CurrentRunspace);
string temporaryModuleManifestPath = Path.Combine(
temporaryModuleDirectory,
remoteCimModule.ModuleName + ".psd1");
Hashtable data = null;
Hashtable localizedData = null;
{
ScriptBlockAst scriptBlockAst = null;
Token[] throwAwayTokens;
ParseError[] parseErrors;
scriptBlockAst = Parser.ParseInput(
remoteCimModule.MainManifest.FileData,
temporaryModuleManifestPath,
out throwAwayTokens,
out parseErrors);
if ((scriptBlockAst == null) ||
(parseErrors != null && parseErrors.Length > 0))
{
throw new ParseException(parseErrors);
}
ScriptBlock scriptBlock = new ScriptBlock(scriptBlockAst, isFilter: false);
data = LoadModuleManifestData(
temporaryModuleManifestPath,
scriptBlock,
ModuleManifestMembers,
ManifestProcessingFlags.NullOnFirstError | ManifestProcessingFlags.WriteErrors, /* - don't load elements */
ref containedErrors);
if ((data == null) || containedErrors)
{
return null;
}
localizedData = data;
}
//
// flatten module contents and rewrite the manifest to point to the flattened file hierarchy
//
// recalculate module path, taking into account the module version fetched above
Version moduleVersion;
if (!GetScalarFromData<Version>(data, null, "ModuleVersion", 0, out moduleVersion))
{
moduleVersion = null;
}
temporaryModuleDirectory = RemoteDiscoveryHelper.GetModulePath(
remoteCimModule.ModuleName,
moduleVersion,
cimSession.ComputerName,
this.Context.CurrentRunspace);
temporaryModuleManifestPath = Path.Combine(
temporaryModuleDirectory,
remoteCimModule.ModuleName + ".psd1");
// avoid loading an already loaded module
PSModuleInfo alreadyImportedModule = this.IsModuleImportUnnecessaryBecauseModuleIsAlreadyLoaded(
temporaryModuleManifestPath, this.BasePrefix, importModuleOptions);
if (alreadyImportedModule != null)
{
return alreadyImportedModule;
}
try
{
Directory.CreateDirectory(temporaryModuleDirectory);
IEnumerable<string> typesToProcess = CreateCimModuleFiles(
remoteCimModule,
RemoteDiscoveryHelper.CimFileCode.TypesV1,
cimModuleFile => IsTypesPs1XmlFile(cimModuleFile, data),
temporaryModuleDirectory);
IEnumerable<string> formatsToProcess = CreateCimModuleFiles(
remoteCimModule,
RemoteDiscoveryHelper.CimFileCode.FormatV1,
cimModuleFile => IsFormatPs1XmlFile(cimModuleFile, data),
temporaryModuleDirectory);
IEnumerable<string> nestedModules = CreateCimModuleFiles(
remoteCimModule,
RemoteDiscoveryHelper.CimFileCode.CmdletizationV1,
IsCmdletizationFile,
temporaryModuleDirectory);
data = RemoteDiscoveryHelper.RewriteManifest(
data,
nestedModules: nestedModules,
typesToProcess: typesToProcess,
formatsToProcess: formatsToProcess);
localizedData = RemoteDiscoveryHelper.RewriteManifest(localizedData);
//
// import the module
// (from memory - this avoids the authenticode signature problems
// that would be introduced by rewriting the contents of the manifest)
//
moduleInfo = LoadModuleManifest(
temporaryModuleManifestPath,
null, //scriptInfo
data,
localizedData,
ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError,
BaseMinimumVersion,
BaseMaximumVersion,
BaseRequiredVersion,
BaseGuid,
ref importModuleOptions,
ref containedErrors);
if (moduleInfo == null)
{
return null;
}
foreach (PSModuleInfo nestedModule in moduleInfo.NestedModules)
{
Type cmdletAdapter;
bool gotCmdletAdapter = PSPrimitiveDictionary.TryPathGet(
nestedModule.PrivateData as IDictionary,
out cmdletAdapter,
"CmdletsOverObjects",
"CmdletAdapter");
Dbg.Assert(gotCmdletAdapter, "PrivateData from cdxml should always include cmdlet adapter");
if (!cmdletAdapter.AssemblyQualifiedName.Equals(StringLiterals.DefaultCmdletAdapter, StringComparison.OrdinalIgnoreCase))
{
string errorMessage = string.Format(
CultureInfo.InvariantCulture,
CmdletizationCoreResources.ImportModule_UnsupportedCmdletAdapter,
cmdletAdapter.FullName);
ErrorRecord errorRecord = new ErrorRecord(
new InvalidOperationException(errorMessage),
"UnsupportedCmdletAdapter",
ErrorCategory.InvalidData,
cmdletAdapter);
this.ThrowTerminatingError(errorRecord);
}
}
if (IsMixedModePsCimModule(remoteCimModule))
{
// warn that some commands have not been imported
string warningMessage = string.Format(
CultureInfo.InvariantCulture,
Modules.MixedModuleOverCimSessionWarning,
remoteCimModule.ModuleName);
this.WriteWarning(warningMessage);
}
//
// store the default session
//
Dbg.Assert(moduleInfo.ModuleType == ModuleType.Manifest, "Remote discovery should always produce a 'manifest' module");
Dbg.Assert(moduleInfo.NestedModules != null, "Remote discovery should always produce a 'manifest' module with nested modules entry");
Dbg.Assert(moduleInfo.NestedModules.Count > 0, "Remote discovery should always produce a 'manifest' module with some nested modules");
foreach (PSModuleInfo nestedModule in moduleInfo.NestedModules)
{
IDictionary cmdletsOverObjectsPrivateData;
bool cmdletsOverObjectsPrivateDataWasFound = PSPrimitiveDictionary.TryPathGet<IDictionary>(
nestedModule.PrivateData as IDictionary,
out cmdletsOverObjectsPrivateData,
ScriptWriter.PrivateDataKey_CmdletsOverObjects);
Dbg.Assert(cmdletsOverObjectsPrivateDataWasFound, "Cmdletization should always set the PrivateData properly");
cmdletsOverObjectsPrivateData[ScriptWriter.PrivateDataKey_DefaultSession] = cimSession;
}
//
// make sure the temporary folder gets removed when the module is removed
//
const string onRemoveScriptBody =
@"
Microsoft.PowerShell.Management\Remove-Item `
-LiteralPath $temporaryModulePath `
-Force `
-Recurse `
-ErrorAction SilentlyContinue
if ($null -ne $previousOnRemoveScript)
{
& $previousOnRemoveScript $args
}
";
ScriptBlock onRemoveScriptBlock = this.Context.Engine.ParseScriptBlock(onRemoveScriptBody, false);
onRemoveScriptBlock = onRemoveScriptBlock.GetNewClosure();
// create a separate scope for variables set below
onRemoveScriptBlock.Module.SessionState.PSVariable.Set("temporaryModulePath", temporaryModuleDirectory);
onRemoveScriptBlock.Module.SessionState.PSVariable.Set("previousOnRemoveScript", moduleInfo.OnRemove);
moduleInfo.OnRemove = onRemoveScriptBlock;
//
// Some processing common for local and remote modules
//
AddModuleToModuleTables(
this.Context,
this.TargetSessionState.Internal,
moduleInfo);
if (BasePassThru)
{
WriteObject(moduleInfo);
}
return moduleInfo;
}
catch
{
if (Directory.Exists(temporaryModuleDirectory))
{
Directory.Delete(temporaryModuleDirectory, recursive: true);
}
throw;
}
finally
{
if (moduleInfo == null)
{
if (Directory.Exists(temporaryModuleDirectory))
{
Directory.Delete(temporaryModuleDirectory, recursive: true);
}
}
}
}
catch (Exception e)
{
ErrorRecord errorRecord = RemoteDiscoveryHelper.GetErrorRecordForProcessingOfCimModule(e, remoteCimModule.ModuleName);
this.WriteError(errorRecord);
return null;
}
}
#endregion CimSession parameterset
#endregion Remote import
#region Cancellation support
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private CancellationToken CancellationToken
{
get
{
return _cancellationTokenSource.Token;
}
}
/// <summary>
/// When overridden in the derived class, interrupts currently
/// running code within the command. It should interrupt BeginProcessing,
/// ProcessRecord, and EndProcessing.
/// Default implementation in the base class just returns.
/// </summary>
protected override void StopProcessing()
{
_cancellationTokenSource.Cancel();
}
#endregion
#region IDisposable Members
/// <summary>
/// Releases resources associated with this object
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases resources associated with this object
/// </summary>
private void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
_cancellationTokenSource.Dispose();
}
_disposed = true;
}
private bool _disposed;
#endregion
/// <summary>
/// BeginProcessing override
/// </summary>
protected override void BeginProcessing()
{
// Make sure that only one of (Global | Scope) is specified
if (Global.IsPresent && _isScopeSpecified)
{
InvalidOperationException ioe = new InvalidOperationException(Modules.GlobalAndScopeParameterCannotBeSpecifiedTogether);
ErrorRecord er = new ErrorRecord(ioe, "Modules_GlobalAndScopeParameterCannotBeSpecifiedTogether",
ErrorCategory.InvalidOperation, null);
ThrowTerminatingError(er);
}
if (!string.IsNullOrEmpty(Scope) && Scope.Equals(StringLiterals.Global, StringComparison.OrdinalIgnoreCase))
{
base.BaseGlobal = true;
}
}
/// <summary>
/// Load the specified modules...
/// </summary>
/// <remarks>
/// Examples:
/// c:\temp\mdir\mdir.psm1 # load absolute path
/// ./mdir.psm1 # load relative path
/// c:\temp\mdir\mdir # resolve by using extensions. mdir is a directory, mdir.xxx is a file.
/// c:\temp\mdir # load default module if mdir is directory
/// module # $PSScriptRoot/module/module.psd1 (ps1,psm1,dll)
/// module/foobar.psm1 # $PSScriptRoot/module/module.psm1
/// module/foobar # $PSScriptRoot/module/foobar.XXX if foobar is not a directory...
/// module/foobar # $PSScriptRoot/module/foobar is a directory and $PSScriptRoot/module/foobar/foobar.XXX exists
/// module/foobar/foobar.XXX
/// </remarks>
protected override void ProcessRecord()
{
if (BaseMaximumVersion != null && BaseMinimumVersion != null && BaseMaximumVersion < BaseMinimumVersion)
{
string message = StringUtil.Format(Modules.MinimumVersionAndMaximumVersionInvalidRange, BaseMinimumVersion, BaseMaximumVersion);
throw new PSArgumentOutOfRangeException(message);
}
ImportModuleOptions importModuleOptions = new ImportModuleOptions();
importModuleOptions.NoClobber = NoClobber;
if (!string.IsNullOrEmpty(Scope) && Scope.Equals(StringLiterals.Local, StringComparison.OrdinalIgnoreCase))
{
importModuleOptions.Local = true;
}
if (this.ParameterSetName.Equals(ParameterSet_ModuleInfo, StringComparison.OrdinalIgnoreCase))
{
// Process all of the specified PSModuleInfo objects. These would typically be coming in as a result
// of doing Get-Module -list
foreach (PSModuleInfo module in ModuleInfo)
{
RemoteDiscoveryHelper.DispatchModuleInfoProcessing(
module,
localAction: delegate ()
{
ImportModule_ViaLocalModuleInfo(importModuleOptions, module);
SetModuleBaseForEngineModules(module.Name, this.Context);
},
cimSessionAction: (cimSession, resourceUri, cimNamespace) => ImportModule_RemotelyViaCimSession(
importModuleOptions,
new string[] { module.Name },
cimSession,
resourceUri,
cimNamespace),
psSessionAction: psSession => ImportModule_RemotelyViaPsrpSession(
importModuleOptions,
new string[] { module.Path },
null,
psSession));
}
}
else if (this.ParameterSetName.Equals(ParameterSet_Assembly, StringComparison.OrdinalIgnoreCase))
{
// Now load all of the supplied assemblies...
if (Assembly != null)
{
foreach (Assembly suppliedAssembly in Assembly)
{
ImportModule_ViaAssembly(importModuleOptions, suppliedAssembly);
}
}
}
else if (this.ParameterSetName.Equals(ParameterSet_Name, StringComparison.OrdinalIgnoreCase))
{
foreach (string name in Name)
{
PSModuleInfo foundModule = ImportModule_LocallyViaName(importModuleOptions, name);
if (null != foundModule)
{
SetModuleBaseForEngineModules(foundModule.Name, this.Context);
#if LEGACYTELEMETRY
TelemetryAPI.ReportModuleLoad(foundModule);
#endif
}
}
}
else if (this.ParameterSetName.Equals(ParameterSet_ViaPsrpSession, StringComparison.OrdinalIgnoreCase))
{
ImportModule_RemotelyViaPsrpSession(importModuleOptions, this.Name, null, this.PSSession);
}
else if (this.ParameterSetName.Equals(ParameterSet_ViaCimSession, StringComparison.OrdinalIgnoreCase))
{
ImportModule_RemotelyViaCimSession(importModuleOptions, this.Name, this.CimSession, this.CimResourceUri, this.CimNamespace);
}
else if (this.ParameterSetName.Equals(ParameterSet_FQName, StringComparison.OrdinalIgnoreCase))
{
foreach (var modulespec in FullyQualifiedName)
{
RequiredVersion = modulespec.RequiredVersion;
MinimumVersion = modulespec.Version;
MaximumVersion = modulespec.MaximumVersion;
BaseGuid = modulespec.Guid;
PSModuleInfo foundModule = ImportModule_LocallyViaName(importModuleOptions, modulespec.Name);
if (null != foundModule)
{
SetModuleBaseForEngineModules(foundModule.Name, this.Context);
}
}
}
else if (this.ParameterSetName.Equals(ParameterSet_FQName_ViaPsrpSession, StringComparison.OrdinalIgnoreCase))
{
ImportModule_RemotelyViaPsrpSession(importModuleOptions, null, FullyQualifiedName, this.PSSession);
}
else
{
Dbg.Assert(false, "Unrecognized parameter set");
}
}
private void SetModuleBaseForEngineModules(string moduleName, System.Management.Automation.ExecutionContext context)
{
// Set modulebase of engine modules to point to $pshome
// This is so that Get-Help can load the correct help.
if (InitialSessionState.IsEngineModule(moduleName))
{
foreach (var m in context.EngineSessionState.ModuleTable.Values)
{
if (m.Name.Equals(moduleName, StringComparison.OrdinalIgnoreCase))
{
m.SetModuleBase(Utils.DefaultPowerShellAppBase);
// Also set ModuleBase for nested modules of Engine modules
foreach (var nestedModule in m.NestedModules)
{
nestedModule.SetModuleBase(Utils.DefaultPowerShellAppBase);
}
}
}
foreach (var m in context.Modules.ModuleTable.Values)
{
if (m.Name.Equals(moduleName, StringComparison.OrdinalIgnoreCase))
{
m.SetModuleBase(Utils.DefaultPowerShellAppBase);
// Also set ModuleBase for nested modules of Engine modules
foreach (var nestedModule in m.NestedModules)
{
nestedModule.SetModuleBase(Utils.DefaultPowerShellAppBase);
}
}
}
}
}
}
} // Microsoft.PowerShell.Commands
| 45.217559 | 184 | 0.526481 |
[
"Apache-2.0",
"MIT-0"
] |
Lolle2000la/PowerShell
|
src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs
| 81,889 |
C#
|
using System.Runtime.InteropServices;
namespace THNETII.WinApi.Native.WinNT
{
using static WinNTConstants;
// C:\Program Files (x86)\Windows Kits\10\Include\10.0.17134.0\um\winnt.h, line 12312
/// <summary>
/// Describes cache attributes. This structure is used with the <see cref="GetLogicalProcessorInformationEx"/> function.
/// </summary>
/// <remarks>
/// <para>Microsoft Docs page: <a href="https://docs.microsoft.com/en-us/windows/desktop/api/winnt/ns-winnt-cache_relationship">CACHE_RELATIONSHIP structure</a></para>
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
public unsafe struct CACHE_RELATIONSHIP
{
/// <summary>The cache level.</summary>
/// <value>
/// This member can currently be one of the following values; other values may be supported in the future.
/// <list type="table">
/// <listheader><term>Value</term><description>Meaning</description></listheader>
/// <item><term><c>1</c></term><description>L1</description></item>
/// <item><term><c>2</c></term><description>L2</description></item>
/// <item><term><c>3</c></term><description>L3</description></item>
/// </list>
/// </value>
public byte Level;
/// <summary>
/// The cache associativity. If this member is <see cref="CACHE_FULLY_ASSOCIATIVE"/> (<c>0xFF</c>), the cache is fully associative.
/// </summary>
public byte Associativity;
/// <summary>
/// The cache line size, in bytes.
/// </summary>
public short LineSize;
/// <summary>
/// The cache size, in bytes.
/// </summary>
public int CacheSize;
/// <summary>
/// The cache type. This member is a <see cref="PROCESSOR_CACHE_TYPE"/> value.
/// </summary>
public PROCESSOR_CACHE_TYPE Type;
public fixed byte Reserved[20];
/// <summary>
/// A <see cref="GROUP_AFFINITY"/> structure that specifies a group number and processor affinity within the group.
/// </summary>
public GROUP_AFFINITY GroupMask;
}
}
| 42.176471 | 171 | 0.613203 |
[
"MIT"
] |
couven92/thnetii-windows-api
|
src-native/THNETII.WinApi.Headers.WinNT/CACHE_RELATIONSHIP.cs
| 2,151 |
C#
|
namespace BookingsApi.AcceptanceTests.Helpers
{
public enum Scenario
{
Valid,
Invalid,
Negative,
Nonexistent
}
}
| 14.363636 | 46 | 0.575949 |
[
"MIT"
] |
hmcts/vh-bookings-api
|
BookingsApi/BookingsApi.AcceptanceTests/Helpers/Scenario.cs
| 160 |
C#
|
using Discord;
using Discord.WebSocket;
using System;
using System.Threading.Tasks;
namespace NadekoBot.Services.Discord
{
public class ReactionEventWrapper : IDisposable
{
public IUserMessage Message { get; }
public event Action<SocketReaction> OnReactionAdded = delegate { };
public event Action<SocketReaction> OnReactionRemoved = delegate { };
public event Action OnReactionsCleared = delegate { };
public ReactionEventWrapper(DiscordSocketClient client, IUserMessage msg)
{
Message = msg ?? throw new ArgumentNullException(nameof(msg));
_client = client;
_client.ReactionAdded += Discord_ReactionAdded;
_client.ReactionRemoved += Discord_ReactionRemoved;
_client.ReactionsCleared += Discord_ReactionsCleared;
}
private Task Discord_ReactionsCleared(Cacheable<IUserMessage, ulong> msg, ISocketMessageChannel channel)
{
try
{
if (msg.Id == Message.Id)
OnReactionsCleared?.Invoke();
}
catch { }
return Task.CompletedTask;
}
private Task Discord_ReactionRemoved(Cacheable<IUserMessage, ulong> msg, ISocketMessageChannel channel, SocketReaction reaction)
{
try
{
if (msg.Id == Message.Id)
OnReactionRemoved?.Invoke(reaction);
}
catch { }
return Task.CompletedTask;
}
private Task Discord_ReactionAdded(Cacheable<IUserMessage, ulong> msg, ISocketMessageChannel channel, SocketReaction reaction)
{
try
{
if (msg.Id == Message.Id)
OnReactionAdded?.Invoke(reaction);
}
catch { }
return Task.CompletedTask;
}
public void UnsubAll()
{
_client.ReactionAdded -= Discord_ReactionAdded;
_client.ReactionRemoved -= Discord_ReactionRemoved;
_client.ReactionsCleared -= Discord_ReactionsCleared;
OnReactionAdded = null;
OnReactionRemoved = null;
OnReactionsCleared = null;
}
private bool disposing = false;
private readonly DiscordSocketClient _client;
public void Dispose()
{
if (disposing)
return;
disposing = true;
UnsubAll();
}
}
}
| 30.26506 | 136 | 0.58121 |
[
"MIT"
] |
moonantonio/NadekoBot
|
src/NadekoBot/Services/Discord/SocketMessageEventWrapper.cs
| 2,514 |
C#
|
using Recipe_Book.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
namespace RecipeBook
{
public partial class Form1 : Form
{
public int num_recipes = 0;
public List<Recipe> recipes = new List<Recipe>();
public List<Recipe> current_search_results = new List<Recipe>();
public List<Recipe> ing_search_results = new List<Recipe>();
public Recipe selected_recipe = null;
public SplitContainer fullRecipeSplit = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
loadRecipes();
initializeSmallRecipeView();
}
private void loadRecipes()
{
string path = Directory.GetCurrentDirectory();
path = path.Remove(path.Length - 10);
path += @"\Resources\recipes.txt";
System.IO.StreamReader file = new System.IO.StreamReader(path); //how do I access specific resource file
string line;
bool end = false;
// may want to refactor in the future
while (!file.EndOfStream)
{
// create each recipe, populate variables
Recipe a_recipe = new Recipe();
line = file.ReadLine();
a_recipe.setName(line);
line = file.ReadLine();
a_recipe.setImagePath(line);
// ingredient amounts
line = file.ReadLine();
string[] str_amounts = line.Split(',');
double[] amounts = new double[str_amounts.Length];
for (int i = 0; i < str_amounts.Length; i++)
amounts[i] = Convert.ToDouble(str_amounts[i]);
a_recipe.setAmounts(amounts);
// ingredient units
line = file.ReadLine();
string[] units = line.Split(',');
a_recipe.setUnits(units);
// ingredients
line = file.ReadLine();
string[] ingredients = line.Split(',');
a_recipe.setIngredients(ingredients);
// ingredient notes
line = file.ReadLine();
string[] ing_notes = line.Split(',');
a_recipe.setIngNotes(ing_notes);
// process
string full_process = "";
while (!end) // read full process until last line (which starts with *)
{
line = file.ReadLine();
if (line[0] == '*')
{
end = true;
line = line.Substring(1); // do I want to keep the * in the string for re-writing?
}
else
line += "\r\n\n";
full_process += line;
}
a_recipe.setProcess(full_process);
end = false;
// additional notes
string full_notes = "";
while (!end) // read full notes until last line (which starts with *)
{
line = file.ReadLine();
if (line[0] == '*')
{
end = true;
line = line.Substring(1); // do I want to keep the * in the string for re-writing?
}
else
line += "\r\n\n";
full_notes += line;
}
a_recipe.setNotes(line);
end = false;
// add recipe to root list
recipes.Add(a_recipe);
num_recipes++;
}
file.Close();
ing_search_results = recipes;
updateSearchResults(recipes);
}
private void initializeSmallRecipeView()
{
pictureSlim.Visible = false;
fullRecipeButton.Visible = false;
processTextSlim.Visible = false;
tableExample.Visible = false;
}
private void updateSearchResults(List<Recipe> search_results)
{
// add recipes to listview, position in current search results added as item tag
recipeSearchResults.Items.Clear();
current_search_results = search_results;
for (int i = 0; i < search_results.Count(); i++)
{
ListViewItem item = new ListViewItem(search_results[i]._name);
item.Tag = i;
recipeSearchResults.Items.Add(item);
}
}
private void textSearch (string text)
{
// update search results
List<Recipe> matching_recipes = new List<Recipe>();
ListViewItem item = recipeSearchResults.FindItemWithText(text);
while (item != null)
{
matching_recipes.Add(current_search_results[Convert.ToInt32(item.Tag)]);
recipeSearchResults.Items.Remove(item);
item = recipeSearchResults.FindItemWithText(text);
}
updateSearchResults(matching_recipes);
}
List<Recipe> ingredientSearch(List<string> ing_list)
{
// search for checked ingredients
var ing_pairs = new List<KeyValuePair<Recipe, double>>();
List<Recipe> result = new List<Recipe>();
for(int i = 0; i < num_recipes; i++)
{
for (int j = 0; j < ing_list.Count(); j++)
{
double amount = recipes[i].hasIngredient(ing_list[j]);
if (amount > 0)
ing_pairs.Add(new KeyValuePair<Recipe, double> (recipes[i], amount));
}
}
// TODO: sort ing_pairs by amount (second parameter), then return array of sorted recipes
for (int i = 0; i < ing_pairs.Count(); i++)
{
result.Add(ing_pairs[i].Key);
}
return result;
}
private void drawRecipeSlim(Recipe recipe)
{
foreach (TableLayoutPanel table_instance in splitContainerRecipeSlim.Panel2.Controls.OfType<TableLayoutPanel>())
{
splitContainerRecipeSlim.Panel2.Controls.Remove(table_instance);
table_instance.Dispose();
}
pictureSlim.Visible = true;
pictureSlim.Image = recipe._image;
fullRecipeButton.Visible = true;
TableLayoutPanel table = new TableLayoutPanel();
table.Parent = splitContainerRecipeSlim.Panel2;
table.Dock = DockStyle.Top;
populateIngrTable(table, recipe);
// process
processTextSlim.Visible = true;
processTextSlim.Text = recipe._process;
// notes?
}
private void populateIngrTable(TableLayoutPanel table, Recipe recipe)
{
table.ColumnCount = 4;
table.RowCount = recipe._ingredient_list.Length;
table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 12F));
table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 14F));
table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 37F));
table.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 37F));
table.AutoSize = true;
table.AutoSizeMode = AutoSizeMode.GrowAndShrink;
// ingredients
for (int i = 0; i < recipe._ingredient_list.Length; i++)
{
Label item_amount = new Label();
item_amount.Text = recipe._amounts[i].ToString();
item_amount.BorderStyle = BorderStyle.None;
item_amount.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
item_amount.Dock = DockStyle.Fill;
table.Controls.Add(item_amount, 0, i);
}
for (int i = 0; i < recipe._ingredient_list.Length; i++)
{
ComboBox item_unit = new ComboBox();
item_unit.Text = recipe._units[i];
item_unit.FlatStyle = FlatStyle.Flat;
table.Controls.Add(item_unit, 1, i);
}
for (int i = 0; i < recipe._ingredient_list.Length; i++)
{
TextBox item_ing = new TextBox();
item_ing.Text = recipe._ingredient_list[i];
item_ing.BorderStyle = BorderStyle.None;
item_ing.Dock = DockStyle.Fill;
table.Controls.Add(item_ing, 2, i);
}
for (int i = 0; i < recipe._ingredient_list.Length; i++)
{
TextBox item_notes = new TextBox();
item_notes.Text = recipe._ing_notes[i];
item_notes.BorderStyle = BorderStyle.None;
item_notes.Dock = DockStyle.Fill;
table.Controls.Add(item_notes, 3, i);
}
}
private void createButton(Button button, string text)
{
button.Width = 115;
button.Height = 40;
button.Text = text;
}
// event handlers
private void recipeListView_SelectedIndexChanged(object sender, EventArgs e) // when recipe is selected from list
{
var s = recipeSearchResults.SelectedItems;
if (s.Count > 0)
{
var i = s[0].Tag;
int selection_index = Convert.ToInt32(i.ToString());
Recipe selection = current_search_results[selection_index];
selected_recipe = selection;
drawRecipeSlim(selection);
}
}
private void searchButton_Click(object sender, EventArgs e) //ingredient search button pressed
{
// get checked ingredients and add to list
CheckedListBox.CheckedItemCollection checked_obj = ingredientChecklist.CheckedItems;
List<string> checked_list = new List<string>();
foreach (object item in checked_obj)
{
checked_list.Add(item.ToString());
}
List<Recipe> recipe_list = ingredientSearch(checked_list); //currently returns unsorted list of recipes
ing_search_results = recipe_list;
updateSearchResults(ing_search_results);
}
private void textSearchEnterKeyHandler(object sender, KeyEventArgs e) // user typed text search term into search bar and pressed enter
{
if (e.KeyCode == Keys.Enter)
textSearch(textSearchBox.Text);
}
// search clears
private void clearSearchButton_Click(object sender, EventArgs e)
{
textSearchBox.Text = "Search...";
for(int i = 0; i < ingredientChecklist.Items.Count; i++)
ingredientChecklist.SetItemCheckState(i, CheckState.Unchecked);
updateSearchResults(recipes);
}
private void textSearchClearButton_Click(object sender, EventArgs e)
{
// resets text search, doesn't clear ingredient search
textSearchBox.Text = "Search...";
updateSearchResults(ing_search_results);
}
private void fullRecipeButton_Click(object sender, EventArgs e)
{
// create new split container, pic and ingredients on left, name process and notes on right
// full page splitter
recipeTabContainer.Visible = false;
fullRecipeSplit = new SplitContainer();
fullRecipeSplit.Parent = recipeSearchTab;
fullRecipeSplit.Dock = DockStyle.Fill;
fullRecipeSplit.Orientation = Orientation.Vertical;
fullRecipeSplit.SplitterDistance = 565;
// Panel 1
// image/ingredients splitter
SplitContainer fullImgIngrSplit = new SplitContainer();
fullImgIngrSplit.Parent = fullRecipeSplit.Panel1;
fullImgIngrSplit.Dock = DockStyle.Fill;
fullImgIngrSplit.Orientation = Orientation.Horizontal;
fullImgIngrSplit.SplitterDistance = 300;
// image
PictureBox full_picture = new PictureBox();
full_picture.Parent = fullImgIngrSplit.Panel1;
full_picture.Height = 325;
full_picture.SizeMode = PictureBoxSizeMode.StretchImage;
full_picture.Dock = DockStyle.Top;
full_picture.Image = selected_recipe._image;
// ingredients
TableLayoutPanel ing_table = new TableLayoutPanel();
ing_table.Parent = fullImgIngrSplit.Panel2;
ing_table.Dock = DockStyle.Top;
populateIngrTable(ing_table, selected_recipe);
// Panel 2
// 3 split containers
// 1st sections off the buttons
SplitContainer buttonSplit = new SplitContainer();
buttonSplit.Parent = fullRecipeSplit.Panel2;
buttonSplit.Dock = DockStyle.Fill;
buttonSplit.Orientation = Orientation.Horizontal;
buttonSplit.SplitterDistance = 50;
buttonSplit.IsSplitterFixed = true;
// 2nd splits off recipe name
SplitContainer nameSplit = new SplitContainer();
nameSplit.Parent = buttonSplit.Panel2;
nameSplit.Dock = DockStyle.Fill;
nameSplit.Orientation = Orientation.Horizontal;
nameSplit.SplitterDistance = 100;
// 3rd splits process and notes
SplitContainer processSplit = new SplitContainer();
processSplit.Parent = nameSplit.Panel2;
processSplit.Dock = DockStyle.Fill;
processSplit.Orientation = Orientation.Horizontal;
processSplit.BackColor = ColorTranslator.FromHtml("#FFB0C4DE");
// edit/cooking mode/exit buttons
Button editButton = new Button();
editButton.Parent = buttonSplit.Panel1;
createButton(editButton, "Edit Recipe");
editButton.Dock = DockStyle.Left;
// editButton.BackColor = ColorTranslator.FromHtml("#FFB0C4DE");
editButton.Enabled = false; // delete me when implementing edit recipe, and uncomment previous
// TODO: fix and implement cooking mode button
/*Button cookingModeButton = new Button();
cookingModeButton.Parent = buttonSplit.Panel1;
createButton(cookingModeButton, "Cooking Mode");
cookingModeButton.Anchor = AnchorStyles.None;*/
Button exitButton = new Button();
exitButton.Parent = buttonSplit.Panel1;
createButton(exitButton, "Exit");
exitButton.Dock = DockStyle.Right;
exitButton.BackColor = ColorTranslator.FromHtml("#FFB0C4DE");
editButton.Click += new EventHandler(editButton_Click);
exitButton.Click += new EventHandler(exitButton_Click);
// recipe name label
Label name = new Label();
name.UseMnemonic = false;
name.Text = selected_recipe._name;
name.Font = new Font("Elephant", 20);
name.Parent = nameSplit.Panel1;
name.Dock = DockStyle.Fill;
name.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
// process text box
TextBox processBox = new TextBox();
processBox.Multiline = true;
processBox.Text = selected_recipe._process;
processBox.Parent = processSplit.Panel1;
processBox.Dock = DockStyle.Fill;
processBox.BackColor = ColorTranslator.FromHtml("#FFB0C4DE");
processBox.BorderStyle = BorderStyle.None;
processBox.ReadOnly = true;
// recipe notes text box
TextBox notesBox = new TextBox();
notesBox.Multiline = true;
notesBox.Text = selected_recipe._add_notes;
notesBox.Parent = processSplit.Panel2;
notesBox.Dock = DockStyle.Fill;
notesBox.BackColor = ColorTranslator.FromHtml("#FFB0C4DE");
notesBox.BorderStyle = BorderStyle.None;
notesBox.ReadOnly = true;
}
private void editButton_Click(object sender, EventArgs e) //TODO: implement editing
{
// in fullRecipeButton_Click delete line making edit button enabled false
}
private void exitButton_Click(object sender, EventArgs e)
{
recipeSearchTab.Controls.Remove(fullRecipeSplit);
fullRecipeSplit.Dispose();
recipeTabContainer.Visible = true;
}
}
public class Recipe
{
public string _name;
public Image _image;
public double[] _amounts;
public string[] _units;
public string[] _ingredient_list;
public string[] _ing_notes;
public string _process;
public string _add_notes;
// write getters if making ing private
public void setName(string name)
{
_name = name;
}
public void setImagePath(string file_name)
{
string path = Directory.GetCurrentDirectory();
path = path.Remove(path.Length - 10);
path += @"\Resources\" + file_name;
_image = Image.FromFile(path);
}
public void setAmounts(double[] amounts)
{
_amounts = amounts;
}
public void setUnits(string[] units)
{
_units = units;
}
public void setIngredients(string[] ingredients)
{
_ingredient_list = ingredients;
}
public void setIngNotes(string[] notes)
{
_ing_notes = notes;
}
public void setProcess(string process)
{
_process = process;
}
public void setNotes(string notes)
{
_add_notes = notes;
}
public double hasIngredient(string ingredient)
{
for (int i = 0; i < _ingredient_list.Length; i++)
{
if (_ingredient_list[i] == ingredient)
{
return _amounts[i];
}
}
return 0;
}
public void scaleRecipe(double factor)
{
for (int i = 0; i < _amounts.Length; i++)
{
_amounts[i] = _amounts[i] * factor;
}
}
}
}
| 38.112224 | 144 | 0.551635 |
[
"Apache-2.0"
] |
AutumnO/Recipe_Book
|
Recipe_Book/Form1.cs
| 19,020 |
C#
|
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
// ReSharper disable StringLiteralTypo
namespace MathCore.Tests.Extensions
{
[TestClass, SuppressMessage("ReSharper", "InconsistentNaming")]
public class IDictionaryExtensionsTests
{
[TestMethod]
public void AddValue_Test()
{
var dictionary = new Dictionary<string, IList<string>>();
dictionary.AddValue("t1", "0");
Assert.AreEqual(1, dictionary.Count);
Assert.IsTrue(dictionary.ContainsKey("t1"));
Assert.AreEqual("0", dictionary["t1"][0]);
dictionary.AddValue("t1", "5");
Assert.AreEqual(1, dictionary.Count);
Assert.AreEqual("5", dictionary["t1"][1]);
dictionary.AddValue("q3", "6");
Assert.AreEqual(2, dictionary.Count);
Assert.IsTrue(dictionary.ContainsKey("q3"));
Assert.AreEqual("6", dictionary["q3"][0]);
}
[TestMethod]
public void AddValue_KeySelector_Test()
{
var dictionary = new Dictionary<string, IList<string>>();
dictionary.AddValue(5, i => i.ToString(), i => new string('a', i));
Assert.AreEqual(1, dictionary.Count);
Assert.IsTrue(dictionary.ContainsKey("5"));
Assert.AreEqual("aaaaa", dictionary["5"][0]);
dictionary.AddValue(7, i => "5", i => new string('a', i));
Assert.AreEqual(1, dictionary.Count);
Assert.AreEqual("aaaaaaa", dictionary["5"][1]);
dictionary.AddValue(7, i => i.ToString(), i => new string('a', i));
Assert.AreEqual(2, dictionary.Count);
Assert.IsTrue(dictionary.ContainsKey("7"));
Assert.AreEqual("aaaaaaa", dictionary["7"][0]);
}
[TestMethod]
public void AddValue_KeyValueSelector_Test()
{
var dictionary = new Dictionary<int, IList<string>>();
dictionary.AddValue("aa", s => s.Length);
dictionary.AddValue("bb", s => s.Length);
dictionary.AddValue("abc", s => s.Length);
dictionary.AddValue("xyz", s => s.Length);
Assert.AreEqual(2, dictionary.Count);
Assert.IsTrue(dictionary.ContainsKey(2));
Assert.AreEqual("aa", dictionary[2][0]);
Assert.AreEqual("bb", dictionary[2][1]);
Assert.IsTrue(dictionary.ContainsKey(3));
Assert.AreEqual("abc", dictionary[3][0]);
Assert.AreEqual("xyz", dictionary[3][1]);
}
[TestMethod]
public void AddValues_Test()
{
var dictionary = new Dictionary<int, string>();
dictionary.AddValues(new[] { "a", "bb", "ccc", "dddd" }, s => s.Length);
Assert.AreEqual(4, dictionary.Count);
Assert.IsTrue(dictionary.ContainsKey(1));
Assert.AreEqual("a", dictionary[1]);
Assert.IsTrue(dictionary.ContainsKey(2));
Assert.AreEqual("bb", dictionary[2]);
Assert.IsTrue(dictionary.ContainsKey(3));
Assert.AreEqual("ccc", dictionary[3]);
Assert.IsTrue(dictionary.ContainsKey(4));
Assert.AreEqual("dddd", dictionary[4]);
}
[TestMethod]
public void GetValueOrAddNew_KeySelector_Test()
{
var dictionary = new Dictionary<int, string>();
Assert.IsFalse(dictionary.ContainsKey(5));
Assert.AreEqual(0, dictionary.Count);
Assert.AreEqual("5", dictionary.GetValueOrAddNew(5, i => i.ToString()));
Assert.IsTrue(dictionary.ContainsKey(5));
Assert.AreEqual(1, dictionary.Count);
dictionary.Add(7, "qwe");
Assert.AreEqual("qwe", dictionary.GetValueOrAddNew(7, i => "qwe"));
Assert.AreEqual(2, dictionary.Count);
}
[TestMethod]
public void GetValueOrAddNew_KeySelector_Interface_Test()
{
IDictionary<int, string> dictionary = new Dictionary<int, string>();
Assert.IsFalse(dictionary.ContainsKey(5));
Assert.AreEqual(0, dictionary.Count);
Assert.AreEqual("5", dictionary.GetValueOrAddNew(5, i => i.ToString()));
Assert.IsTrue(dictionary.ContainsKey(5));
Assert.AreEqual(1, dictionary.Count);
dictionary.Add(7, "qwe");
Assert.AreEqual("qwe", dictionary.GetValueOrAddNew(7, i => "qwe"));
Assert.AreEqual(2, dictionary.Count);
}
[TestMethod]
public void GetValueOrAddNew_Test()
{
var dictionary = new Dictionary<int, string>();
Assert.AreEqual("test", dictionary.GetValueOrAddNew(5, () => "test"));
Assert.AreEqual(1, dictionary.Count);
Assert.IsTrue(dictionary.ContainsKey(5));
Assert.AreEqual("test", dictionary[5]);
}
[TestMethod]
public void GetValueOrAddNew_Interface_Test()
{
IDictionary<int, string> dictionary = new Dictionary<int, string>();
Assert.AreEqual("test", dictionary.GetValueOrAddNew(5, () => "test"));
Assert.AreEqual(1, dictionary.Count);
Assert.IsTrue(dictionary.ContainsKey(5));
Assert.AreEqual("test", dictionary[5]);
}
[TestMethod]
public void GetValue_Test()
{
var dictionary = new Dictionary<int, string> { { 7, "value7" } };
Assert.AreEqual("value7", dictionary.GetValue(7, "123"));
Assert.AreEqual("123", dictionary.GetValue(0, "123"));
}
[TestMethod]
public void GetValue_Interface_Test()
{
IDictionary<int, string> dictionary = new Dictionary<int, string> { { 7, "value7" } };
Assert.AreEqual("value7", dictionary.GetValue(7, "123"));
Assert.AreEqual("123", dictionary.GetValue(0, "123"));
}
[TestMethod]
public void GetValue_object_Test()
{
var dictionary = new Dictionary<string, object>
{
{ "a", 5 },
{ "b", new Complex(3, 7) }
};
Assert.AreEqual(5, dictionary.GetValue<int>("a"));
Assert.AreEqual(Complex.Mod(3, 7), dictionary.GetValue<Complex>("b"));
Assert.AreEqual(null, dictionary.GetValue<List<int>>("list"));
}
[TestMethod]
public void Initialize_Test()
{
var j = 0;
var dictionary = new Dictionary<int, string>()
.Initialize(5, () => new KeyValuePair<int, string>(j, j++.ToString()));
for (var i = 0; i < 5; i++)
{
Assert.IsTrue(dictionary.ContainsKey(i));
Assert.AreEqual(i.ToString(), dictionary[i]);
}
}
[TestMethod]
public void Initialize_Index_Test()
{
var dictionary = new Dictionary<int, string>()
.Initialize(5, i => new KeyValuePair<int, string>(i, i.ToString()));
for (var i = 0; i < 5; i++)
{
Assert.IsTrue(dictionary.ContainsKey(i));
Assert.AreEqual(i.ToString(), dictionary[i]);
}
}
[TestMethod]
public void Initialize_Keys_Test()
{
var dictionary = new Dictionary<int, string>()
.Initialize(new[] { 0, 1, 2, 3, 4 }, i => i.ToString());
for (var i = 0; i < 5; i++)
{
Assert.IsTrue(dictionary.ContainsKey(i));
Assert.AreEqual(i.ToString(), dictionary[i]);
}
}
[TestMethod]
public void RemoveWhere_Test()
{
var dictionary = new Dictionary<int, string>()
.Initialize(10, i => new KeyValuePair<int, string>(i, i.ToString()));
dictionary.RemoveWhere(kv => kv.Key % 2 != 0);
Assert.IsFalse(dictionary.Any(kv => kv.Key % 2 != 0));
}
[TestMethod]
public void ToPatternString_Test()
{
const string pattern_string = "{var1:000}-{var2:f3}[{date:yy-MM-ddTHH-mm-ss}].{str}";
const int var1 = 10;
const double var2 = Math.PI;
var date = DateTime.Now;
const string str = "Hello!";
var expected_string = $"{var1:000}-{var2:f3}[{date:yy-MM-ddTHH-mm-ss}].{str}";
var dict = new Dictionary<string, object>
{
{ "var1", var1 },
{ "var2", var2 },
{ "date", date },
{ "str", str }
};
var actual_string = dict.ToPatternString(pattern_string);
Assert.That.Value(actual_string).IsEqual(expected_string);
}
}
}
| 36.987552 | 98 | 0.545546 |
[
"MIT"
] |
Infarh/MathCore
|
Tests/MathCore.Tests/Extensions/IDictionaryExtensionsTests.cs
| 8,916 |
C#
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
namespace MvcTypescript.MvcWebClient.Models
{
public class IndexViewModel
{
public bool HasPassword { get; set; }
public IList<UserLoginInfo> Logins { get; set; }
public string PhoneNumber { get; set; }
public bool TwoFactor { get; set; }
public bool BrowserRemembered { get; set; }
}
public class ManageLoginsViewModel
{
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationDescription> OtherLogins { get; set; }
}
public class FactorViewModel
{
public string Purpose { get; set; }
}
public class SetPasswordViewModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ChangePasswordViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class AddPhoneNumberViewModel
{
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string Number { get; set; }
}
public class VerifyPhoneNumberViewModel
{
[Required]
[Display(Name = "Code")]
public string Code { get; set; }
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
}
public class ConfigureTwoFactorViewModel
{
public string SelectedProvider { get; set; }
public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
}
}
| 31.046512 | 110 | 0.627715 |
[
"MIT"
] |
krcourville/mvc-grid-experiment
|
MvcTypescript.MvcWebClient/Models/ManageViewModels.cs
| 2,672 |
C#
|
using MacomberMapCommunications.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MacomberMapCommunications.Messages.EMS
{
/// <summary>
/// © 2014, Michael E. Legatt, Ph.D., Electric Reliability Council of Texas, Inc. All Rights Reserved.
/// This class holds information on a state measurement (e.g., is a breaker closed)
/// </summary>
[RetrievalCommand("GetStateMeasurementData"), UpdateCommand("UpdateStateMeasurementData"), FileName("QKNET_STATUS_MEAS.csv")]
public class MM_State_Measurement
{
/// <summary></summary>
public int TEID_Stat { get; set; }
/// <summary></summary>
public bool Open_Stat { get; set; }
/// <summary></summary>
public bool Good_Stat { get; set; }
}
}
| 31.714286 | 130 | 0.656532 |
[
"MIT"
] |
geek96/MacomberMap
|
MacomberMapCommunications/Messages/EMS/MM_State_Measurement.cs
| 891 |
C#
|
using UnityEngine;
using System.Collections.Generic;
using UnityEditor;
[CustomEditor(typeof(PanelAnimator))]
public class PanelAnimatorInspector : Editor {
public override void OnInspectorGUI()
{
var t = (PanelAnimator)target;
var rt = ((RectTransform)t.transform);
GUILayout.BeginHorizontal();
GUI.color = Color.red;
if(GUILayout.Button("Store start"))
{
t.start_pos = rt.anchoredPosition;
t.startOffset = new PanelAnimator.Offset(rt);
}
if (GUILayout.Button("Store end"))
{
t.end_pos = rt.anchoredPosition;
t.endOffset = new PanelAnimator.Offset(rt);
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUI.color = Color.green;
if (GUILayout.Button("Move to start"))
{
t.JumpToStart();
}
if (GUILayout.Button("Move to end"))
{
t.JumpToEnd();
}
GUILayout.EndHorizontal();
GUI.color = Color.white;
base.OnInspectorGUI();
}
}
| 26.926829 | 57 | 0.568841 |
[
"Unlicense",
"MIT"
] |
L-Lawliet/JECSu
|
Assets/JECSU/JEdit/UI/Editor/PanelAnimatorInspector.cs
| 1,106 |
C#
|
using System;
using System.Timers;
namespace MagiCloud.NetWorks
{
/// <summary>
/// 心跳包控制端
/// </summary>
public sealed class HeartBeatController
{
Timer timer = new Timer(1000);
public long heartBeatTime = 20;
ControlTerminal controlTerminal;
public HeartBeatController(ControlTerminal server, long heartBeatTime = 10)
{
timer = new Timer(1000);
this.controlTerminal = server;
this.heartBeatTime = heartBeatTime;
timer.Elapsed += new ElapsedEventHandler(HandleMainTimer);
timer.AutoReset = false;
timer.Enabled = true;
Console.WriteLine("开启心跳包检查");
}
private void HandleMainTimer(object sender, ElapsedEventArgs e)
{
HeartBeat();
timer.Start();
}
private void HeartBeat()
{
long timeNow = TimeHelper.GetTimeStamp();
for (int i = 0; i < controlTerminal.connects.Length; i++)
{
ConnectControl connect = controlTerminal.connects[i];
if (connect == null) continue;
if (!connect.isUse) continue;
if (connect.lastTickTime < timeNow - heartBeatTime)
{
lock (connect)
{
connect.Close();
}
}
}
}
}
}
| 27.45283 | 83 | 0.514777 |
[
"MIT"
] |
LiiiiiWr/MagiCloudSDK
|
Assets/MagiCloud/Scripts/NetWorks/Scripts/Core/Control/HeartBeatController.cs
| 1,483 |
C#
|
// <auto-generated>
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.Avs
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for LocationsOperations.
/// </summary>
public static partial class LocationsOperationsExtensions
{
/// <summary>
/// Return trial status for subscription by region
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// Azure region
/// </param>
public static Trial CheckTrialAvailability(this ILocationsOperations operations, string location)
{
return operations.CheckTrialAvailabilityAsync(location).GetAwaiter().GetResult();
}
/// <summary>
/// Return trial status for subscription by region
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// Azure region
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Trial> CheckTrialAvailabilityAsync(this ILocationsOperations operations, string location, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckTrialAvailabilityWithHttpMessagesAsync(location, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Return quota for subscription by region
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// Azure region
/// </param>
public static Quota CheckQuotaAvailability(this ILocationsOperations operations, string location)
{
return operations.CheckQuotaAvailabilityAsync(location).GetAwaiter().GetResult();
}
/// <summary>
/// Return quota for subscription by region
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='location'>
/// Azure region
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Quota> CheckQuotaAvailabilityAsync(this ILocationsOperations operations, string location, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CheckQuotaAvailabilityWithHttpMessagesAsync(location, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| 38.946809 | 192 | 0.57416 |
[
"MIT"
] |
0rland0Wats0n/azure-sdk-for-net
|
sdk/avs/Microsoft.Azure.Management.Avs/src/Generated/LocationsOperationsExtensions.cs
| 3,661 |
C#
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace GluLamb.GH.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GluLamb.GH.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_Assembly_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_Assembly_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_Bisector_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_Bisector_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_BlankNormalToSrf_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_BlankNormalToSrf_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_BlankWithGuides_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_BlankWithGuides_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_CurvatureAnalysis_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_CurvatureAnalysis_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_Delaminate_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_Delaminate_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_FibreCutting_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_FibreCutting_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_FibreDeviation_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_FibreDeviation_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_FibreDirection_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_FibreDirection_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_FreeformGlulam_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_FreeformGlulam_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_GetGlulamSrf_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_GetGlulamSrf_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_GlulamData_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_GlulamData_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_GlulamEdges_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_GlulamEdges_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_GlulamFrame_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_GlulamFrame_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_GlulamFromBeam_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_GlulamFromBeam_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_InflateGlulam_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_InflateGlulam_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_OffsetGlulam_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_OffsetGlulam_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_StraightGlulam_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_StraightGlulam_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_Vector2Color_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_Vector2Color_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
public static System.Drawing.Bitmap glulamb_Workpiece_24x24 {
get {
object obj = ResourceManager.GetObject("glulamb_Workpiece_24x24", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 41.022727 | 176 | 0.575346 |
[
"MIT"
] |
tsvilans/glulamb
|
GluLamb.GH/Properties/Resources.Designer.cs
| 10,832 |
C#
|
using CsvHelper.Configuration.Attributes;
using MessagePack;
using Realms;
using System.Collections.Generic;
using System.Linq;
namespace LINZCsvConverter.Model
{
public class TownCityLocation : RealmObject
{
[Ignore] // CsvHelper
[Required] // Realm
private byte[] LocationRaw { get; set; }
[Ignore] // CsvHelper
public IList<SuburbLocalityLocation> Suburbs { get; }
/// <summary>
/// Gets or sets the primary DB key
/// </summary>
[PrimaryKey] // Realm
public int Id { get; set; }
/// <summary>
/// Gets or sets the name of the location
/// </summary>
[Name("suburb_locality")] // CsvHelper
[Required] // Getting the pattern?
[Indexed]
public string Name { get; set; }
/// <summary>
/// Gets or sets the NZ Geodetic Datum 2000 (NZGD2000) coordinate point for this location
/// </summary>
[Ignore]
public Gd2000Coordinate Location
{
get
{
if (LocationRaw != null)
return MessagePackSerializer.Deserialize<Gd2000Coordinate>(LocationRaw);
else
return new Gd2000Coordinate();
}
set => LocationRaw = MessagePackSerializer.Serialize(value);
}
public void Prepare()
{
List<double> gd2000X = new List<double>();
List<double> gd2000Y = new List<double>();
foreach (SuburbLocalityLocation sLoc in Suburbs)
{
gd2000X.Add(sLoc.Gd2000X);
gd2000Y.Add(sLoc.Gd2000Y);
}
double Gd2000X = gd2000X.Average();
double Gd2000Y = gd2000Y.Average();
Location = new Gd2000Coordinate
{
Gd2000X = Gd2000X,
Gd2000Y = Gd2000Y
};
}
#region Object overrides
public override string ToString() => Name;
public override bool Equals(object obj)
{
return obj is TownCityLocation lb
&& lb.Name.Equals(Name);
}
public override int GetHashCode()
{
unchecked
{
return (13 * 7) + Name.GetHashCode();
}
}
#endregion
}
}
| 26.719101 | 97 | 0.521867 |
[
"Apache-2.0"
] |
carlst99/TrialManager
|
LINZCsvConverter/Model/TownCityLocation.cs
| 2,380 |
C#
|
using System;
using Arctium.Connection.Tls.Protocol.HandshakeProtocol;
namespace Arctium.Connection.Tls.Protocol.BinaryOps.Builder.HandshakeBuilders
{
internal class ClientKeyExchangeBuilder : HandshakeBuilderBase
{
public override Handshake BuildFromBytes(byte[] buffer, int offset, int length)
{
byte[] exchangeKeysBytes = new byte[length];
Buffer.BlockCopy(buffer, offset, exchangeKeysBytes, 0, length);
ClientKeyExchange keyExchange = new ClientKeyExchange(exchangeKeysBytes);
return keyExchange;
}
}
}
| 31.315789 | 87 | 0.705882 |
[
"MIT"
] |
NeuroXiq/Arctium
|
src/Arctium/Arctium.Connection/Tls/Protocol/BinaryOps/Builder/HandshakeBuilders/ClientKeyExchangeBuilder.cs
| 597 |
C#
|
// 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.Collections.Concurrent;
using System.Collections.Generic;
using NuGet.Common;
using NuGet.Frameworks;
using NuGet.Packaging;
using NuGet.Packaging.Core;
using NuGet.ProjectModel;
using NuGet.Protocol.Core.Types;
using NuGet.RuntimeModel;
namespace NuGet.Commands
{
internal class ProjectRestoreRequest
{
public ProjectRestoreRequest(
RestoreRequest request,
PackageSpec packageSpec,
LockFile existingLockFile,
Dictionary<NuGetFramework, RuntimeGraph> runtimeGraphCache,
ConcurrentDictionary<PackageIdentity, RuntimeGraph> runtimeGraphCacheByPackage,
ILogger log)
{
CacheContext = request.CacheContext;
Log = log;
PackagesDirectory = request.PackagesDirectory;
ExistingLockFile = existingLockFile;
RuntimeGraphCache = runtimeGraphCache;
RuntimeGraphCacheByPackage = runtimeGraphCacheByPackage;
MaxDegreeOfConcurrency = request.MaxDegreeOfConcurrency;
PackageSaveMode = request.PackageSaveMode;
Project = packageSpec;
XmlDocFileSaveMode = request.XmlDocFileSaveMode;
}
public SourceCacheContext CacheContext { get; }
public ILogger Log { get; }
public string PackagesDirectory { get; }
public int MaxDegreeOfConcurrency { get; }
public LockFile ExistingLockFile { get; }
public PackageSpec Project { get; }
public PackageSaveMode PackageSaveMode { get; }
public XmlDocFileSaveMode XmlDocFileSaveMode { get; }
public Dictionary<NuGetFramework, RuntimeGraph> RuntimeGraphCache { get; }
public ConcurrentDictionary<PackageIdentity, RuntimeGraph> RuntimeGraphCacheByPackage { get; }
}
}
| 40.244898 | 111 | 0.700304 |
[
"Apache-2.0"
] |
aelij/NuGet.Client
|
src/NuGet.Core/NuGet.Commands/RestoreCommand/ProjectRestoreRequest.cs
| 1,974 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using Microsoft.CodeAnalysis.Internal.Log;
namespace Microsoft.CodeAnalysis.Notification
{
internal class GlobalOperationRegistration : IDisposable
{
private readonly AbstractGlobalOperationNotificationService _service;
private readonly CancellationTokenSource _source;
private readonly IDisposable _logging;
private bool _done;
public GlobalOperationRegistration(AbstractGlobalOperationNotificationService service, string operation)
{
_service = service;
_done = false;
this.Operation = operation;
_source = new CancellationTokenSource();
_logging = Logger.LogBlock(FunctionId.GlobalOperationRegistration, operation, _source.Token);
}
public string Operation { get; }
public void Done()
{
_done = true;
}
public void Dispose()
{
if (_done)
{
_service.Done(this);
_logging.Dispose();
}
else
{
_service.Cancel(this);
_source.Cancel();
_logging.Dispose();
}
}
}
}
| 27.074074 | 112 | 0.606019 |
[
"Apache-2.0"
] |
HenrikWM/roslyn
|
src/Workspaces/Core/Portable/Notification/GlobalOperationRegistration.cs
| 1,464 |
C#
|
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using NSubstitute;
using Shouldly;
using tusdotnet.Interfaces;
using tusdotnet.Models;
using tusdotnet.test.Extensions;
using Xunit;
namespace tusdotnet.test.Tests
{
/// <summary>
/// Tests that DELETE and PATCH requests for the same file cannot happen at the same time.
/// </summary>
public class CrossRequestLockTests
{
[Fact]
public async Task Returns_409_Conflict_For_A_Patch_Request_If_A_Delete_Is_Ongoing()
{
var fileId = Guid.NewGuid().ToString();
var store = Substitute.For<ITusStore, ITusTerminationStore>();
store.FileExistAsync(fileId, Arg.Any<CancellationToken>()).Returns(true);
((ITusTerminationStore)store).DeleteFileAsync(fileId, Arg.Any<CancellationToken>()).Returns(_ =>
{
Thread.Sleep(500);
return Task.FromResult(0);
});
using var server = TestServerFactory.Create(store);
var deleteRequest = server.CreateRequest($"/files/{fileId}")
.AddTusResumableHeader()
.SendAsync("DELETE");
await Task.Delay(50);
var patchRequest = server.CreateRequest($"/files/{fileId}")
.AddBody()
.AddHeader("Upload-Offset", "0")
.AddTusResumableHeader()
.SendAsync("PATCH");
await Task.WhenAll(deleteRequest, patchRequest);
deleteRequest.Result.StatusCode.ShouldBe(HttpStatusCode.NoContent);
patchRequest.Result.StatusCode.ShouldBe(HttpStatusCode.Conflict);
}
[Fact]
public async Task Returns_409_Conflict_For_A_Delete_Request_If_A_Patch_Is_Ongoing()
{
var fileId = Guid.NewGuid().ToString();
var store = Substitute.For<ITusStore, ITusTerminationStore>();
store.FileExistAsync(fileId, Arg.Any<CancellationToken>()).Returns(true);
store.GetUploadOffsetAsync(fileId, Arg.Any<CancellationToken>()).Returns(0);
store.GetUploadLengthAsync(fileId, Arg.Any<CancellationToken>()).Returns(10);
store.AppendDataAsync(fileId, Arg.Any<Stream>(), Arg.Any<CancellationToken>())
.Returns(_ =>
{
Thread.Sleep(5000);
return 3;
});
((ITusTerminationStore)store).DeleteFileAsync(fileId, Arg.Any<CancellationToken>())
.Returns(Task.FromResult(0));
using var server = TestServerFactory.Create(store);
var patchRequest = server.CreateRequest($"/files/{fileId}")
.AddBody()
.AddHeader("Upload-Offset", "0")
.AddTusResumableHeader()
.SendAsync("PATCH");
await Task.Delay(50);
var deleteRequest = server.CreateRequest($"/files/{fileId}")
.AddTusResumableHeader()
.SendAsync("DELETE");
await Task.WhenAll(deleteRequest, patchRequest);
deleteRequest.Result.StatusCode.ShouldBe(HttpStatusCode.Conflict);
patchRequest.Result.StatusCode.ShouldBe(HttpStatusCode.NoContent);
}
}
}
| 36.521739 | 108 | 0.611012 |
[
"MIT"
] |
SnGmng/tusdotnet
|
Source/tusdotnet.test/Tests/CrossRequestLockTests.cs
| 3,362 |
C#
|
/*<FILE_LICENSE>
* Azos (A to Z Application Operating System) Framework
* The A to Z Foundation (a.k.a. Azist) licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
</FILE_LICENSE>*/
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Azos.Data.Access.Cache
{
/// <summary>
/// Represents a table that stores cached items identified by keys
/// </summary>
public sealed class Table : Collections.INamed
{
#region CONSTS
public const int MAX_AGE_SEC_MINIMUM = 5;
public const int MAX_AGE_SEC_DEFAULT = 5 *//min
60;//sec
public const int BUCKET_COUNT_DEFAULT = 25111; //must be prime
public const int REC_PER_PAGE_DEFAULT = 7; //must be prime
#endregion
#region .ctor
internal Table(CacheStore store, string name, TableOptions opt)
{
var bucketCount = opt != null ? opt.BucketCount : 0;
var recPerPage = opt != null ? opt.RecPerPage : 0;
var lockCount = opt != null ? opt.LockCount : 0;
if (opt != null)
{
MaxAgeSec = opt.MaxAgeSec;
ParallelSweep = opt.ParallelSweep;
}
Debug.Assert(store != null);
Debug.Assert(name != null);
if (bucketCount <= 0) bucketCount = BUCKET_COUNT_DEFAULT;
if (recPerPage <= 0) recPerPage = REC_PER_PAGE_DEFAULT;
if (bucketCount == recPerPage)
{
recPerPage += 7;//prime
store.WriteLog(Log.MessageType.Warning, nameof(Table),
StringConsts.CACHE_TABLE_CTOR_SIZES_WARNING,
pars: "Table: {0} BucketCount: {1} RecPerPage: {2}".Args(name, bucketCount, recPerPage));
}
m_Store = store;
m_Name = name;
m_BucketCount = bucketCount;
m_RecPerPage = recPerPage;
m_Buckets = new Bucketed[m_BucketCount];
m_LockCount = lockCount > 0 ? lockCount : System.Environment.ProcessorCount * 16;
m_Locks = new object[m_LockCount];
for (var i = 0; i < m_LockCount; i++)
m_Locks[i] = new object();
}
#endregion
#region Private
private CacheStore m_Store;
private string m_Name;
private int m_LockCount;
private int m_BucketCount;
private int m_RecPerPage;
private object[] m_Locks;
private Bucketed[] m_Buckets;
private int m_MaxAgeSec = MAX_AGE_SEC_DEFAULT;
private int m_Count;
private int m_PageCount;
private bool m_ParallelSweep;
//statistics/instrumentation
internal int stat_LastTime;
/// <summary>
/// how many hits - get was called
/// </summary>
internal int stat_HitCount;
/// <summary>
/// how many complex key hits - get was called
/// </summary>
internal int stat_ComplexHitCount;
/// <summary>
/// how many misses - get was called
/// </summary>
internal int stat_MissCount;
/// <summary>
/// how many complex key misses - get was called
/// </summary>
internal int stat_ComplexMissCount;
/// <summary>
/// how many times factory called from GetOrPut
/// </summary>
internal int stat_ValueFactoryCount;
/// <summary>
/// how many times swept
/// </summary>
internal int stat_SweepTableCount;
/// <summary>
/// how many pages swept
/// </summary>
internal int stat_SweepPageCount;
/// <summary>
/// how many records removed by sweep
/// </summary>
internal int stat_SweepRemoveCount;
/// <summary>
/// how many times put was called
/// </summary>
internal int stat_PutCount;
/// <summary>
/// how many times new value successfully inserted without collision
/// </summary>
internal int stat_PutInsertCount;
/// <summary>
/// how many times new value successfully replaced existing one (by the same key) without collision
/// </summary>
internal int stat_PutReplaceCount;
/// <summary>
/// how many times bucket collision occured that resulted in page creation
/// </summary>
internal int stat_PutPageCreateCount;
/// <summary>
/// how many times new value overrode existing because of collision
/// </summary>
internal int stat_PutCollisionCount;
/// <summary>
/// how many times priority prevented collision
/// </summary>
internal int stat_PutPriorityPreventedCollisionCount;
/// <summary>
/// how many pages have been deleted, a page gets deleted when there are no records stored in it
/// </summary>
internal int stat_RemovePageCount;
/// <summary>
/// how many records have been found and removed
/// </summary>
internal int stat_RemoveHitCount;
/// <summary>
/// how many records have been sought to be removed but were not found
/// </summary>
internal int stat_RemoveMissCount;
#endregion
#region Properties
/// <summary>
/// Returns the store instance that this table is a part of
/// </summary>
public CacheStore Store => m_Store;
/// <summary>
/// Returns table name which is a unique string within the cache store
/// </summary>
public string Name => m_Name;
/// <summary>
/// Returns item count in the table
/// </summary>
public int Count => m_Count;
/// <summary>
/// Returns page count in the table
/// </summary>
public int PageCount => m_PageCount;
/// <summary>
/// Returns hit count stats
/// </summary>
public int StatHitCount => stat_HitCount;
/// <summary>
/// Returns hit count stats for using complex keys
/// </summary>
public int StatComplexHitCount => stat_ComplexHitCount;
/// <summary>
/// Returns miss count stats
/// </summary>
public int StatMissCount => stat_MissCount;
/// <summary>
/// Returns miss count stats for using complex keys
/// </summary>
public int StatComplexMissCount => stat_ComplexMissCount;
/// <summary>
/// Returns the ratio of how many buckets are loaded with pages vs. bucket count
/// </summary>
public double BucketPageLoadFactor => m_PageCount / (double)m_BucketCount;
/// <summary>
/// Returns the maximum number of items that this table can hold at any given time given that
/// no items will have any key hash collisions
/// </summary>
public int Capacity => m_BucketCount * m_RecPerPage;
/// <summary>
/// Returns how many locks can be used for thread coordination during table changes
/// </summary>
public int LockCount => m_LockCount;
/// <summary>
/// Returns how many slots/buckets are pre-allocated per table, the higher the number the more memory will be
/// reserved at table construction time, every slot is a reference (4 bytes on 32bit systems, 8 bytes on 64bit).
/// For optimal performance this number should be around 75% of total record count stored in the table (table load factor).
/// </summary>
public int BucketCount => m_BucketCount;
/// <summary>
/// Returns how many slots are pre-allocated per table's bucket(page) when more than one item produces hash collision.
/// The higher the number, the more primary hash collisions can be accomodated by re-hashing on pages (secondary hash table within primary buckets)
/// </summary>
public int RecPerPage => m_RecPerPage;
/// <summary>
/// Gets/sets maximum age of items in the table expressed in seconds. After this age is exceeded, the system will delete entries.
/// The system does not guarantee that items will expire right on time, however it does guarantee that items will be available for at least
/// this long.
/// </summary>
public int MaxAgeSec
{
get { return m_MaxAgeSec; }
set
{
if (value == 0)
value = MAX_AGE_SEC_DEFAULT;
else
if (value < MAX_AGE_SEC_MINIMUM) value = MAX_AGE_SEC_MINIMUM;
m_MaxAgeSec = value;
}
}
/// <summary>
/// When enabled, uses parallel execution while sweeping table buckets, otherwise sweeps sequentially (default behavior)
/// </summary>
public bool ParallelSweep
{
get { return m_ParallelSweep; }
set { m_ParallelSweep = value; }
}
#endregion
#region Public
/// <summary>
/// Puts a key-identified item into this table.
/// If item with such key is already in this table then replaces it and returns false, returns true otherwise
/// </summary>
/// <param name="key">Item's unique key</param>
/// <param name="value">Item</param>
/// <param name="maxAgeSec">For how long will the item exist in cache before it gets swept out. Pass 0 to use table-level setting (default)</param>
/// <param name="priority">Items priority relative to others in the table used during collision resolution, 0 = default</param>
/// <param name="absoluteExpirationUTC">Sets absolute UTC time stamp when item should be swept out of cache, null is default</param>
public bool Put(ulong key, object value, int maxAgeSec = 0, int priority = 0, DateTime? absoluteExpirationUTC = null)
{
CacheRec rec;
return Put(key, value, out rec, maxAgeSec, priority, absoluteExpirationUTC);
}
/// <summary>
/// Puts a key-identified item into this table.
/// If item with such key is already in this table then replaces it and returns false, returns true otherwise
/// </summary>
/// <param name="key">Item's unique key</param>
/// <param name="value">Item</param>
/// <param name="rec">Returns new or existing CacheRec</param>
/// <param name="maxAgeSec">For how long will the item exist in cache before it gets swept out. Pass 0 to use table-level setting (default)</param>
/// <param name="priority">Items priority relative to others in the table used during collision resolution, 0 = default</param>
/// <param name="absoluteExpirationUTC">Sets absolute UTC time stamp when item should be swept out of cache, null is default</param>
public bool Put(ulong key, object value, out CacheRec rec, int maxAgeSec = 0, int priority = 0, DateTime? absoluteExpirationUTC = null)
{
Interlocked.Increment(ref stat_PutCount);
return _Put(key, value, out rec, maxAgeSec, priority, absoluteExpirationUTC);
}
private bool _Put(ulong key, object value, out CacheRec rec, int maxAgeSec, int priority, DateTime? absoluteExpirationUTC)
{
if (value == null)
throw new DataAccessException(StringConsts.ARGUMENT_ERROR + "Cache.TablePut(item=null)");
var idx = getBucketIndex(key);
var lck = m_Locks[getLockIndex(idx)];
lock (lck)
{
var bucketed = m_Buckets[idx];
if (bucketed == null)
{
rec = new CacheRec(key, value, maxAgeSec, priority, absoluteExpirationUTC);
m_Buckets[idx] = rec;
Interlocked.Increment(ref m_Count);
Interlocked.Increment(ref stat_PutInsertCount);
return true;
}
else
{
if (bucketed is Page)
{
var page = (Page)bucketed;
lock (page)
{
var pidx = getPageIndex(key);
var existing = page.m_Records[pidx];
if (existing != null)
{
if (existing.Key == key) //reuse the CacheRec instance
{
existing.ReuseCTOR(value, maxAgeSec, priority, absoluteExpirationUTC);
Interlocked.Increment(ref stat_PutReplaceCount);
rec = existing;
return false;
}
if (existing.m_Priority <= priority)
{
rec = new CacheRec(key, value, maxAgeSec, priority, absoluteExpirationUTC);
page.m_Records[pidx] = rec;
Interlocked.Increment(ref stat_PutCollisionCount);
return false;
}
rec = existing;
Interlocked.Increment(ref stat_PutPriorityPreventedCollisionCount);
return false;
}
rec = new CacheRec(key, value, maxAgeSec, priority, absoluteExpirationUTC);
page.m_Records[pidx] = rec;
Interlocked.Increment(ref stat_PutInsertCount);
}
Interlocked.Increment(ref m_Count);
return true;
}
else
{
var existing = (CacheRec)bucketed;
if (existing.Key == key)
{
existing.ReuseCTOR(value, maxAgeSec, priority, absoluteExpirationUTC);
rec = existing;
Interlocked.Increment(ref stat_PutReplaceCount);
return false;
}
else
{//1st collision
var pidx = getPageIndex(existing.Key);
var npidx = getPageIndex(key);
if (npidx == pidx)//collision
{
if (existing.m_Priority <= priority)
{
rec = new CacheRec(key, value, maxAgeSec, priority, absoluteExpirationUTC);
m_Buckets[idx] = rec;
Interlocked.Increment(ref stat_PutCollisionCount);
return false;
}
rec = existing;
Interlocked.Increment(ref stat_PutPriorityPreventedCollisionCount);
return false;
}
// turn CacheRec into a Page
var page = new Page(m_RecPerPage);
Interlocked.Increment(ref stat_PutPageCreateCount);
Interlocked.Increment(ref m_PageCount);
page.m_Records[pidx] = existing;
rec = new CacheRec(key, value, maxAgeSec, priority, absoluteExpirationUTC);
page.m_Records[npidx] = rec;
Thread.MemoryBarrier();
m_Buckets[idx] = page;//assign page to backet AFTER page init above
Interlocked.Increment(ref m_Count);
Interlocked.Increment(ref stat_PutInsertCount);
return true;
}
}
}
}//lock
}
/// <summary>
/// Removes a key-identified item from the named table returning true when item was deleted
/// or false when item was not found
/// </summary>
public bool Remove(ulong key)
{
var result = _Remove(key);
if (result)
Interlocked.Increment(ref stat_RemoveHitCount);
else
Interlocked.Increment(ref stat_RemoveMissCount);
return result;
}
private bool _Remove(ulong key)
{
var idx = getBucketIndex(key);
var lck = m_Locks[getLockIndex(idx)];
lock (lck)
{
var bucketed = m_Buckets[idx];
if (bucketed == null) return false;
if (bucketed is Page)
{
var page = (Page)bucketed;
lock (page)
{
var pidx = getPageIndex(key);
var existing = page.m_Records[pidx];
if (existing == null) return false;
if (existing.Key != key) return false;//keys dont match
existing.Dispose();
page.m_Records[pidx] = null;
if (page.m_Records.All(r => r == null))
{
m_Buckets[idx] = null;
Interlocked.Increment(ref stat_RemovePageCount);
Interlocked.Decrement(ref m_PageCount);
}
}
Interlocked.Decrement(ref m_Count);
return true;
}
else
{
var existing = (CacheRec)bucketed;
if (existing.Key != key) return false;//keys dont match
bucketed.Dispose();
m_Buckets[idx] = null;
Interlocked.Decrement(ref m_Count);
return true;
}
}//lock
}
/// <summary>
/// Retrieves an item from this table by key where item age is less or equal to requested, or
/// calls the itemFactory function and inserts the value in the store
/// </summary>
/// <param name="key">Item key</param>
/// <param name="valueFactory">A function that returns new value for the specified tableName, key, and context</param>
/// <param name="factoryContext">An object to pass into the factory function if it gets invoked</param>
/// <param name="ageSec">Age of item in seconds, or 0 for any age</param>
/// <param name="putMaxAgeSec">MaxAge for item if Put is called</param>
/// <param name="putPriority">Priority for item if Put is called</param>
/// <param name="putAbsoluteExpirationUTC">Absolute expiration UTC timestamp for item if Put is called</param>
/// <typeparam name="TContext">A type of item factory context</typeparam>
public CacheRec GetOrPut<TContext>(ulong key,
Func<string, ulong, TContext, object> valueFactory,
TContext factoryContext = default(TContext),
int ageSec = 0,
int putMaxAgeSec = 0,
int putPriority = 0,
DateTime? putAbsoluteExpirationUTC = null)
{
var result = Get(key, ageSec);//1st check is lock-free
if (result != null) return result;
var idx = getBucketIndex(key);
var lck = m_Locks[getLockIndex(idx)];
lock (lck)
{
result = Get(key, ageSec); //dbl-check under lock
if (result != null) return result;
object value = null;
try
{
value = valueFactory(Name, key, factoryContext);
Interlocked.Increment(ref stat_ValueFactoryCount);
}
catch (Exception error)
{
throw new DataAccessException(StringConsts.CACHE_VALUE_FACTORY_ERROR.Args("Cache.Table.GetOrPut()", error.ToMessageWithType()), error);
}
CacheRec rec;
this.Put(key, value, out rec, putMaxAgeSec, putPriority, putAbsoluteExpirationUTC);
return rec;
}//lock
}
/// <summary>
/// Retrieves an item from this table by key where item age is less or equal to requested, or null if it does not exist
/// </summary>
/// <param name="key">Item key</param>
/// <param name="ageSec">Age of item in seconds, or 0 for any age</param>
public CacheRec Get(ulong key, int ageSec = 0)
{
var result = _Get(key, ageSec);
if (result != null)
{
Interlocked.Increment(ref stat_HitCount);
#pragma warning disable 420
Interlocked.Increment(ref result.m_HitCount);
#pragma warning restore 420
}
else
Interlocked.Increment(ref stat_MissCount);
return result;
}
private CacheRec _Get(ulong key, int ageSec)
{
//note: This implementation is not thread-safe in terms of data accuracy, but it does not have to be
//as this whole cache solution provides/finds "any data per key not older than X" as soon as possible, so
//the fact that some other thread may have mutated the CacheRec object does not matter
CacheRec result;
var idx = getBucketIndex(key);
var bucketed = m_Buckets[idx]; //atomic
if (bucketed == null) return null;
if (bucketed is CacheRec)
{
result = (CacheRec)bucketed;
if (result.Key != key) return null;//keys dont match
if (ageSec > 0 && result.m_AgeSec > ageSec) return null;//expired
return result;
}
else
{
var page = (Page)bucketed;
var pidx = getPageIndex(key);
result = page.m_Records[pidx];//atomic
if (result == null) return null;
if (result.Key != key) return null;//keys dont match
if (ageSec > 0 && result.m_AgeSec > ageSec) return null;//expired
return result;
}
}
#endregion
#region .pvt/.internal
private int getLockIndex(int bucketIndex)
{
var r = (bucketIndex % m_LockCount);
return (r >= 0) ? r : -r;
}
private int getBucketIndex(ulong key)
{
var hc = (int)(key >> 32) ^ (int)key;
var r = (hc % m_BucketCount);
return (r >= 0) ? r : -r;
}
private int getPageIndex(ulong key)
{
var hc = (int)(key >> 32) ^ (int)key;
var r = (hc % m_RecPerPage);
return (r >= 0) ? r : -r;
}
//called from another thread
internal void Sweep()
{
var now = Ambient.UTCNow;
if (m_ParallelSweep)
Parallel.For(0, m_BucketCount, (bidx, loop) =>
{
sweepBucket(now, m_Buckets[bidx]);
if (!m_Store.isRunning) loop.Stop();
});
else
for (var i = 0; m_Store.isRunning && i < m_BucketCount; i++)
{
sweepBucket(now, m_Buckets[i]);
}
Interlocked.Increment(ref stat_SweepTableCount);
}
private void sweepBucket(DateTime now, Bucketed bucketed)
{
if (bucketed == null) return;
if (bucketed is CacheRec)
{
sweepCacheRec(now, (CacheRec)bucketed);
return;
}
var page = (Page)bucketed;
for (int i = 0; i < m_RecPerPage; i++)
{
var rec = page.m_Records[i];
if (rec != null)
sweepCacheRec(now, rec);
}
Interlocked.Increment(ref stat_SweepPageCount);
}
private void sweepCacheRec(DateTime now, CacheRec rec)
{
var age = 0;
var cd = rec.m_CreateDate;
if (cd.Ticks != 0)
{
age = (int)(now - cd).TotalSeconds;
rec.m_AgeSec = age; // the Age field is needed for efficency not to compute dates on Table.Get()
}
else
{
rec.m_CreateDate = now;
return;
}
var rma = rec.m_MaxAgeSec;
var axp = rec.m_AbsoluteExpirationUTC;
if (
(age > (rma > 0 ? rma : this.m_MaxAgeSec)) ||
(axp.HasValue && now > axp.Value)
)
{
this.Remove(rec.Key);//delete expired
Interlocked.Increment(ref stat_SweepRemoveCount);
}
}
#endregion
}
}
| 32.325581 | 151 | 0.598291 |
[
"MIT"
] |
JohnPKosh/azos
|
src/Azos/Data/Access/Cache/Table.cs
| 22,240 |
C#
|
using System.Collections;
using Agava.YandexGames;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
namespace YandexGames.Tests
{
public class PlayerAccountTests
{
[UnitySetUp]
public IEnumerator WaitForSdkInitialization()
{
yield return YandexGamesSdk.WaitForInitialization();
}
[Test]
public void ShouldNotBeAuthorizedOnStart()
{
Assert.IsFalse(PlayerAccount.IsAuthorized);
}
[Test]
public void ShouldNotHaveProfileDataPermission()
{
Assert.IsFalse(PlayerAccount.HasPersonalProfileDataPermission);
}
[UnityTest]
public IEnumerator AuthorizeShouldInvokeErrorCallback()
{
bool callbackInvoked = false;
PlayerAccount.Authorize(onErrorCallback: (message) =>
{
callbackInvoked = true;
});
yield return new WaitForSecondsRealtime(1);
Assert.IsTrue(callbackInvoked);
}
[UnityTest]
public IEnumerator RequestProfileDataPermissionShouldInvokeErrorCallback()
{
bool callbackInvoked = false;
PlayerAccount.RequestPersonalProfileDataPermission(onErrorCallback: (message) =>
{
callbackInvoked = true;
});
yield return new WaitForSecondsRealtime(1);
Assert.IsTrue(callbackInvoked);
}
[UnityTest]
public IEnumerator GetProfileDataShouldInvokeErrorCallback()
{
bool callbackInvoked = false;
PlayerAccount.GetProfileData(null, onErrorCallback: (message) =>
{
callbackInvoked = true;
});
yield return new WaitForSecondsRealtime(1);
Assert.IsTrue(callbackInvoked);
}
[UnityTest]
public IEnumerator SetPlayerDataShouldInvokeErrorCallback()
{
bool callbackInvoked = false;
PlayerAccount.SetPlayerData(string.Empty, onErrorCallback: (message) =>
{
callbackInvoked = true;
});
yield return new WaitForSecondsRealtime(1);
Assert.IsTrue(callbackInvoked);
}
[UnityTest]
public IEnumerator GetPlayerDataShouldInvokeErrorCallback()
{
bool callbackInvoked = false;
PlayerAccount.GetPlayerData(onErrorCallback: (message) =>
{
callbackInvoked = true;
});
yield return new WaitForSecondsRealtime(1);
Assert.IsTrue(callbackInvoked);
}
}
}
| 26.92 | 92 | 0.587667 |
[
"MIT"
] |
forcepusher/YandexGamesUnity
|
Packages/com.agava.yandexgames/Tests/Runtime/PlayerAccountTests.cs
| 2,692 |
C#
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Lykke.Service.EthereumCore.Core.Common
{
public class IdCheckResult
{
public bool IsFree { get; set; }
public Guid ProposedId { get; set; }
}
}
| 19.307692 | 48 | 0.677291 |
[
"MIT"
] |
JTOne123/EthereumApiDotNetCore
|
src/Lykke.Service.EthereumCore.Core/Common/IdCheckResult.cs
| 253 |
C#
|
using NUnit.Framework;
using System.Drawing;
namespace ScottPlotTests
{
public class UnitTest1
{
[Test]
public void TestGetBitmap()
{
{
var plt = new ScottPlot.Plot(1, 1);
Bitmap bmp = plt.GetBitmap();
Assert.AreEqual(bmp.Width, 1);
Assert.AreEqual(bmp.Height, 1);
}
{
var plt = new ScottPlot.Plot(1, 1);
Bitmap bmp = plt.GetBitmap(false, false);
Assert.AreEqual(bmp.Width, 1);
Assert.AreEqual(bmp.Height, 1);
}
}
}
}
| 24.576923 | 57 | 0.471049 |
[
"MIT"
] |
790687382/ScottPlot
|
tests/UnitTest1.cs
| 639 |
C#
|
using SkeMapper.Settings;
using System;
namespace SkeMapper.Builder
{
public class MapperBuilder : IApplySettings, IBuildMapper
{
private readonly Lazy<SkeMapper> mapperInstance = new Lazy<SkeMapper>(() => SkeMapper.Instance, true);
private MapperBuilder() { }
public static IApplySettings Instance => new MapperBuilder();
public IBuildMapper ApplySettings(IMapperSettings mapperSettings)
{
mapperSettings.Config.Invoke(new MapperOptions(mapperInstance.Value.MapperContainer.Value));
return this;
}
public IMapper Build()
{
return mapperInstance.Value;
}
}
}
| 26.346154 | 110 | 0.658394 |
[
"MIT"
] |
keke1210/SkeMapper
|
src/SkeMapper/Builder/MapperBuilder.cs
| 687 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Formall.Persistence
{
using Formall.Reflection;
using Raven.Json.Linq;
internal class Repository : IRepository
{
private readonly Model _model;
private readonly string _keyPrefix;
private readonly RavenDocumentContext _context;
public Repository(string keyPrefix, Model model, RavenDocumentContext context)
{
_model = model;
_keyPrefix = keyPrefix;
_context = context;
}
public RavenDocumentContext Context
{
get { return _context; }
}
IDataContext IRepository.Context
{
get { return _context; }
}
public string KeyPrefix
{
get { return _keyPrefix; }
}
public Reflection.Model Model
{
get { return _model; }
}
public IEntity Create(object data)
{
var key = string.Empty;
var metadata = RavenJObject.FromObject(new {
@key = key,
EntryType = Model.Name
});
var entity = new Entity(Guid.NewGuid(), RavenJObject.FromObject(data), metadata, this);
using (var session = _context.DocumentStore.OpenSession())
{
_context.DocumentStore.DatabaseCommands.Put(key, null, entity.Data, entity.Metadata);
}
return entity;
}
public IResult Delete(Guid id)
{
_context.DocumentStore.DatabaseCommands.Delete(KeyPrefix + id, null);
return null;
}
public IEntity Read(Guid id)
{
string key = KeyPrefix + id;
var document = _context.DocumentStore.DatabaseCommands.Get(key);
var entity = new Entity(id, document.DataAsJson, document.Metadata, this);
return entity;
}
public IEntity[] Read(int skip, int take)
{
var documents = _context.DocumentStore.DatabaseCommands.StartsWith(KeyPrefix, null, skip, take);
return documents.Select(o => new Entity(Entity.ParseId(o.Key), o.DataAsJson, o.Metadata, this)).OfType<IEntity>().ToArray();
}
public IResult Remove(Guid id, string field, string value)
{
throw new NotImplementedException();
}
public IResult Patch(Guid id, object data)
{
throw new NotImplementedException();
}
public IResult Update(Guid id, object data)
{
throw new NotImplementedException();
}
}
}
| 28.744898 | 137 | 0.554491 |
[
"Apache-2.0"
] |
InnPad/Formall.NET
|
Formall.RavenDB/Persistence/Repository.cs
| 2,819 |
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("02.Print-Your-Name")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("02.Print-Your-Name")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5388960d-ff09-4e08-86f8-b4950321d001")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.567568 | 84 | 0.746321 |
[
"MIT"
] |
ykomitov/Homeworks-TA
|
01.CSharp1/Intro-Programming-Homework/05.Print-Your-Name/Properties/AssemblyInfo.cs
| 1,430 |
C#
|
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/SetupAPI.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop.Windows;
public unsafe partial struct SP_INF_SIGNER_INFO64_V2_A
{
[NativeTypeName("DWORD")]
public uint cbSize;
[NativeTypeName("CHAR [260]")]
public fixed sbyte CatalogFile[260];
[NativeTypeName("CHAR [260]")]
public fixed sbyte DigitalSigner[260];
[NativeTypeName("CHAR [260]")]
public fixed sbyte DigitalSignerVersion[260];
[NativeTypeName("DWORD")]
public uint SignerScore;
}
| 29.52 | 145 | 0.731707 |
[
"MIT"
] |
reflectronic/terrafx.interop.windows
|
sources/Interop/Windows/Windows/um/SetupAPI/SP_INF_SIGNER_INFO64_V2_A.Manual.cs
| 740 |
C#
|
using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Threading.Tasks;
using EasyAbp.AbpHelper.Extensions;
using EasyAbp.AbpHelper.Steps.Abp;
using EasyAbp.AbpHelper.Steps.Common;
using Elsa.Activities;
using Elsa.Expressions;
using Elsa.Scripting.JavaScript;
namespace EasyAbp.AbpHelper.Commands
{
public class ServiceCommand : CommandBase
{
public ServiceCommand(IServiceProvider serviceProvider) : base(serviceProvider, "service", "Generate service interface and class files according to the specified name")
{
AddArgument(new Argument<string>("name") {Description = "The service name(without 'AppService' postfix)"});
AddOption(new Option(new[] {"-d", "--directory"}, "The ABP project root directory. If no directory is specified, current directory is used")
{
Argument = new Argument<string>()
});
AddOption(new Option(new[] {"--no-overwrite"}, "Specify not to overwrite existing files")
{
Argument = new Argument<bool>()
});
AddOption(new Option(new[] {"-f", "--folder"}, "Specify the folder where the service files are generated. Multi-level(e.g., foo/bar) directory is supported")
{
Argument = new Argument<string>()
});
Handler = CommandHandler.Create((CommandOption optionType) => Run(optionType));
}
private async Task Run(CommandOption option)
{
string directory = GetBaseDirectory(option.Directory);
option.Folder = option.Folder.NormalizePath();
await RunWorkflow(builder => builder
.StartWith<SetVariable>(
step =>
{
step.VariableName = "BaseDirectory";
step.ValueExpression = new LiteralExpression(directory);
})
.Then<SetVariable>(
step =>
{
step.VariableName = "Option";
step.ValueExpression = new JavaScriptExpression<CommandOption>($"({option.ToJson()})");
})
.Then<SetVariable>(
step =>
{
step.VariableName = "Overwrite";
step.ValueExpression = new JavaScriptExpression<bool>("!Option.NoOverwrite");
})
.Then<SetVariable>(
step =>
{
step.VariableName = "TemplateDirectory";
step.ValueExpression = new LiteralExpression<string>("/Templates/Service");
})
.Then<ProjectInfoProviderStep>()
.Then<SetModelVariableStep>()
.Then<GroupGenerationStep>(
step =>
{
step.GroupName = "Service";
step.TargetDirectory = new JavaScriptExpression<string>("AspNetCoreDir");
})
.Build()
);
}
private class CommandOption
{
public string Directory { get; set; } = null!;
public string Name { get; set; } = null!;
public bool NoOverwrite { get; set; }
public string Folder { get; set; } = String.Empty;
}
}
}
| 41.86747 | 176 | 0.531511 |
[
"MIT"
] |
cnmediar/AbpHelper.CLI
|
src/AbpHelper/Commands/ServiceCommand.cs
| 3,477 |
C#
|
// Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using DotNetCore.CAP.Dashboard;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySql.Data.MySqlClient;
namespace DotNetCore.CAP.MySql
{
public class MySqlStorage : IStorage
{
private readonly IOptions<CapOptions> _capOptions;
private readonly IOptions<MySqlOptions> _options;
private readonly IDbConnection _existingConnection = null;
private readonly ILogger _logger;
public MySqlStorage(
ILogger<MySqlStorage> logger,
IOptions<MySqlOptions> options,
IOptions<CapOptions> capOptions)
{
_options = options;
_capOptions = capOptions;
_logger = logger;
}
public IStorageConnection GetConnection()
{
return new MySqlStorageConnection(_options, _capOptions);
}
public IMonitoringApi GetMonitoringApi()
{
return new MySqlMonitoringApi(this, _options);
}
public async Task InitializeAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
var sql = CreateDbTablesScript(_options.Value.TableNamePrefix);
using (var connection = new MySqlConnection(_options.Value.ConnectionString))
{
await connection.ExecuteAsync(sql);
}
_logger.LogDebug("Ensuring all create database tables script are applied.");
}
protected virtual string CreateDbTablesScript(string prefix)
{
var batchSql =
$@"
CREATE TABLE IF NOT EXISTS `{prefix}.received` (
`Id` bigint NOT NULL,
`Version` varchar(20) DEFAULT NULL,
`Name` varchar(400) NOT NULL,
`Group` varchar(200) DEFAULT NULL,
`Content` longtext,
`Retries` int(11) DEFAULT NULL,
`Added` datetime NOT NULL,
`ExpiresAt` datetime DEFAULT NULL,
`StatusName` varchar(50) NOT NULL,
PRIMARY KEY (`Id`),
INDEX `IX_ExpiresAt`(`ExpiresAt`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE IF NOT EXISTS `{prefix}.published` (
`Id` bigint NOT NULL,
`Version` varchar(20) DEFAULT NULL,
`Name` varchar(200) NOT NULL,
`Content` longtext,
`Retries` int(11) DEFAULT NULL,
`Added` datetime NOT NULL,
`ExpiresAt` datetime DEFAULT NULL,
`StatusName` varchar(40) NOT NULL,
PRIMARY KEY (`Id`),
INDEX `IX_ExpiresAt`(`ExpiresAt`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
";
return batchSql;
}
internal T UseConnection<T>(Func<IDbConnection, T> func)
{
IDbConnection connection = null;
try
{
connection = CreateAndOpenConnection();
return func(connection);
}
finally
{
ReleaseConnection(connection);
}
}
internal IDbConnection CreateAndOpenConnection()
{
var connection = _existingConnection ?? new MySqlConnection(_options.Value.ConnectionString);
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
return connection;
}
internal bool IsExistingConnection(IDbConnection connection)
{
return connection != null && ReferenceEquals(connection, _existingConnection);
}
internal void ReleaseConnection(IDbConnection connection)
{
if (connection != null && !IsExistingConnection(connection))
{
connection.Dispose();
}
}
}
}
| 29.548872 | 105 | 0.618066 |
[
"MIT"
] |
horbel/CAP
|
src/DotNetCore.CAP.MySql/IStorage.MySql.cs
| 3,930 |
C#
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the shield-2016-06-02.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.Shield.Model
{
/// <summary>
/// Container for the parameters to the DisassociateDRTRole operation.
/// Removes the Shield Response Team's (SRT) access to your Amazon Web Services account.
/// </summary>
public partial class DisassociateDRTRoleRequest : AmazonShieldRequest
{
}
}
| 30.897436 | 104 | 0.73361 |
[
"Apache-2.0"
] |
Hazy87/aws-sdk-net
|
sdk/src/Services/Shield/Generated/Model/DisassociateDRTRoleRequest.cs
| 1,205 |
C#
|
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT license. See LICENSE in the project root for license information.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: CLSCompliant(false)]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
#if DEVELOPMENT_KEY
[assembly: InternalsVisibleTo("DocumentationAnalyzers.CodeFixes, PublicKey=0024000004800000940000000602000000240000525341310004000001000100653fc78bb91f5f8741576d365ee395903ae2afe63f50c1fd5486729abb8fdd2815a95867090fc2e22d17a90c3fe35ec57ad06277427128d628ccd7b7c42fb9369bba28b2b7ca642b9d6231b5f0d984abbd65a780145e5efc9265fe0f4df9468e0e87fb4eb3f6125bac24aad003d97c1fe25ab65000ddbf7aabd744179169c1a2")]
#else
[assembly: InternalsVisibleTo("DocumentationAnalyzers.CodeFixes, PublicKey=00240000048000009400000006020000002400005253413100040000010001002164ae5e4cbf74e61559320713d2ada25842139fddf8665b1733e838ea1020d3df0569bb6b56e473173c3e9310f7600fb500fb93a56477eb94c0851c0196e9ea170b7b06d105c8ec15a1108e871c5daf738f8bcbb2a41d61a54a698c322d2fa0cf1cbc8a737c016d60f5e2a9a00bd59d73015bc681f54747ea1c73e1dbe1f4c7")]
#endif
[assembly: InternalsVisibleTo("DocumentationAnalyzers.Test, PublicKey=00240000048000009400000006020000002400005253413100040000010001004d394e527140f84e656e715fc026e74b57657f47ff20636a0d90719bd0fd86b49ccfe3feb0a486b08b994bf8d68ead40ce4a993019c701b4d52c4c86ed88491edae914154b238c8378736b87529fd91502426263242fc5b800ee7a25a8a34f838f2dd1d20a483ccdfa0f6e1f08afb0d650d90b024ab129c1b840189d27b845c8")]
[assembly: InternalsVisibleTo("DocumentationAnalyzers.Test.CSharp7, PublicKey=00240000048000009400000006020000002400005253413100040000010001004d394e527140f84e656e715fc026e74b57657f47ff20636a0d90719bd0fd86b49ccfe3feb0a486b08b994bf8d68ead40ce4a993019c701b4d52c4c86ed88491edae914154b238c8378736b87529fd91502426263242fc5b800ee7a25a8a34f838f2dd1d20a483ccdfa0f6e1f08afb0d650d90b024ab129c1b840189d27b845c8")]
| 93.76 | 401 | 0.90913 |
[
"MIT"
] |
DotNetAnalyzers/DocumentationAnalyzers
|
DocumentationAnalyzers/DocumentationAnalyzers/Properties/AssemblyInfo.cs
| 2,346 |
C#
|
using UnityEngine;
namespace UGF.Messages.Runtime.Physics
{
[AddComponentMenu("Unity Game Framework/Messages/Physics/Message Collision All", 2000)]
public class MessageCollisionAllReceiver : MonoBehaviour
{
[SerializeField] private MessageCollision m_onEnter = new MessageCollision();
[SerializeField] private MessageCollision m_onExit = new MessageCollision();
[SerializeField] private MessageCollision m_onStay = new MessageCollision();
public MessageCollision OnEnter { get { return m_onEnter; } }
public MessageCollision OnExit { get { return m_onExit; } }
public MessageCollision OnStay { get { return m_onStay; } }
private void OnCollisionEnter(Collision other)
{
m_onEnter.Invoke(other);
}
private void OnCollisionExit(Collision other)
{
m_onExit.Invoke(other);
}
private void OnCollisionStay(Collision other)
{
m_onStay.Invoke(other);
}
}
}
| 32.0625 | 91 | 0.664717 |
[
"MIT"
] |
unity-game-framework/ugf-messages
|
Packages/UGF.Messages/Runtime/Physics/MessageCollisionAllReceiver.cs
| 1,026 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JogoVelhaConsoleApp {
/// <summary>
/// Jogo da velha Com console App
/// Demo de Matrizes
/// Autor Alexander Silva
/// </summary>
class Program {
static void Main(string[] args) {
//Matriz do Jogo da Velha
const int plays = 9;
char[,] matriz = new char[3, 3];
char player = 'X'; //X sempre começa
for (int played = 0; played < plays; played++) {
Console.WriteLine("Digite a linha para player " + player);
int line = int.Parse(Console.ReadLine());
Console.WriteLine("Digite a coluna para player " + player);
int column = int.Parse(Console.ReadLine());
//Marca a posição escolhida
matriz[line, column] = player;
//Alterna o player atual
if (player == 'X')
player = 'O';
else
player = 'X';
if (VerifyWinner(matriz) != '\0') {
Console.WriteLine("Jogador " + VerifyWinner(matriz) + " ganhou!");
break;
}
}
}
static char VerifyWinner(char[,] matriz) {
//Verifico as linhas
for (int line = 0; line < 3; line++) {
char player = matriz[line, 0];
bool winner = true;
for (int column = 0; column < 3; column++) {
if (matriz[line, column] != player) {
winner = false;
break;
}
}
if (winner)
return player;
}
//Verifica colunas
for (int column = 0; column < 3; column++) {
char player = matriz[0, column];
bool winner = true;
for (int line = 0; line < 3; line++) {
if (matriz[line, column] != player) {
winner = false;
break;
}
}
if (winner)
return player;
}
//Verifica a Diagonal Principal
char generalPlayer = matriz[0, 0];
bool generalWinner = true;
for (int i = 0; i < 3; i++) {
if (matriz[i, i] != generalPlayer) {
generalWinner = false;
break;
}
}
if (generalWinner)
return generalPlayer;
//Verifica a outra Diagonal
if (matriz[0, 2] == matriz[1, 1] && matriz[1, 1] == matriz[2, 0])
return matriz[0, 2];
bool old = true;
for (int line = 0; line < 3; line++) {
for (int column = 0; column < 3; column++) {
if (matriz[line, column] == '\0'
|| matriz[line, column] == ' ') {
old = false;
break;
}
}
}
if (old)
return 'V';
return '0'; //Ninguém ganhou mas o jogo ainda não acabou
}
}
}
| 22.747664 | 71 | 0.570666 |
[
"MIT"
] |
AlexanderVieira/jogo-velha-consoleApp
|
JogoVelhaConsoleApp/JogoVelhaConsoleApp/Program.cs
| 2,441 |
C#
|
#nullable enable
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace FitsCs
{
public sealed class FitsWriter : BufferedStreamManager
{
// 16 * 2880 bytes is ~ 45 KB
// It allows to process up to 16 Fits IDUs at once
public FitsWriter(Stream stream) : base(stream, DefaultBufferSize, false)
{
}
public FitsWriter(
Stream stream,
int bufferSize) : base(stream, bufferSize, false)
{ }
public FitsWriter(
Stream stream,
int bufferSize, bool leaveOpen) : base(stream, bufferSize, leaveOpen)
{
}
public ValueTask<bool> WriteAsync(DataBlob blob, CancellationToken token = default)
=> WriteInnerAsync(blob, token, true);
public async ValueTask WriteBlockAsync(Block block, CancellationToken token = default)
{
if (block is null)
{
throw new ArgumentNullException(nameof(block), SR.NullArgument);
}
await Semaphore.WaitAsync(token);
try
{
foreach (var blob in block.AsBlobStream())
{
await WriteInnerAsync(blob, token, false);
}
}
finally
{
Semaphore.Release();
}
}
public ValueTask Flush(CancellationToken token = default)
=> FlushBufferAsync(token, true);
private async ValueTask<bool> WriteInnerAsync(DataBlob blob, CancellationToken token, bool @lock)
{
if (blob.IsInitialized != true)
return false;
if (@lock)
await Semaphore.WaitAsync(token);
try
{
if (Span.Length - NBytesAvailable < blob.Data.Length)
// Not enough space to write one blob
await FlushBufferAsync(token, false);
// Buffer is always larger than a blob's size
return blob.Data.TryCopyTo(Span.Slice(NBytesAvailable));
}
finally
{
Interlocked.Add(ref NBytesAvailable, DataBlob.SizeInBytes);
if (@lock)
Semaphore.Release();
}
}
private async ValueTask FlushBufferAsync(CancellationToken token, bool @lock)
{
if (NBytesAvailable <= 0)
{
return;
}
if (@lock)
{
await Semaphore.WaitAsync(token);
}
try
{
await Stream.WriteAsync(Buffer, 0, NBytesAvailable, token);
CompactBuffer(NBytesAvailable);
}
finally
{
if (@lock)
Semaphore.Release();
}
}
private void FlushBuffer(bool @lock)
{
if (@lock)
{
Semaphore.Wait();
}
if (NBytesAvailable <= 0)
{
return;
}
try
{
Stream.Write(Buffer, 0, NBytesAvailable);
CompactBuffer(NBytesAvailable);
}
finally
{
if (@lock)
Semaphore.Release();
}
}
protected override void Dispose(bool disposing)
{
if (!disposing) return;
if (NBytesAvailable > 0)
{
FlushBuffer(false);
}
base.Dispose(true);
}
public override async ValueTask DisposeAsync()
{
if (NBytesAvailable > 0)
{
await FlushBufferAsync(default, false);
}
Semaphore.Dispose();
if (LeaveOpen)
{
await Stream.DisposeAsync();
}
}
}
}
| 25.878205 | 105 | 0.471637 |
[
"MIT"
] |
Ilia-Kosenkov/Fits-Cs
|
Fits-Cs/FitsWriter.cs
| 4,039 |
C#
|
// This file may be edited manually or auto-generated using IfcKit at www.buildingsmart-tech.org.
// IFC content is copyright (C) 1996-2018 BuildingSMART International Ltd.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Xml.Serialization;
namespace BuildingSmart.IFC.IfcMeasureResource
{
public abstract partial class IfcNamedUnit :
BuildingSmart.IFC.IfcMeasureResource.IfcUnit
{
[DataMember(Order = 0)]
[XmlElement]
[Description("The dimensional exponents of the SI base units by which the named unit is defined.")]
[Required()]
public IfcDimensionalExponents Dimensions { get; set; }
[DataMember(Order = 1)]
[XmlAttribute]
[Description("The type of the unit.")]
[Required()]
public IfcUnitEnum UnitType { get; set; }
protected IfcNamedUnit(IfcDimensionalExponents __Dimensions, IfcUnitEnum __UnitType)
{
this.Dimensions = __Dimensions;
this.UnitType = __UnitType;
}
}
}
| 27.142857 | 101 | 0.769298 |
[
"Unlicense",
"MIT"
] |
BuildingSMART/IfcDoc
|
IfcKit/schemas/IfcMeasureResource/IfcNamedUnit.cs
| 1,140 |
C#
|
// Copyright © 2010-2015 Bertrand Le Roy. All Rights Reserved.
// This code released under the terms of the
// MIT License http://opensource.org/licenses/MIT
namespace SysExtensions.Fluent.IO
{
/// <summary>
/// Overwriting policy.
/// </summary>
public enum Overwrite
{
/// <summary>
/// Always overwrite the destination if it exists.
/// </summary>
Always,
/// <summary>
/// Never overwrite the destination and leave existing files as they are.
/// <remarks>
/// Methods should not throw if the destination file exists and
/// do nothing instead. There is a throw value for that.
/// </remarks>
/// </summary>
Never,
/// <summary>
/// Only overwrite an existing destination file with the same name
/// if the source file is newer.
/// <remarks>This value is recommended as the default.</remarks>
/// </summary>
IfNewer,
/// <summary>
/// Throw if the destination file already exists.
/// </summary>
Throw
}
}
| 30.763158 | 85 | 0.548332 |
[
"MIT"
] |
h10r/YouTubeNetworks
|
App/SysExtensions/Fluent.IO/Overwrite.cs
| 1,172 |
C#
|
namespace Aohost.Blog.BlazorApp.Models.Common
{
public class EmojiDto
{
public string Name { get; set; }
public string Char { get; set; }
public string Category { get; set; }
public string[] Keywords { get; set; }
}
}
| 20.384615 | 46 | 0.584906 |
[
"MIT"
] |
aohost/Aohost.Blog.Blazor
|
Models/Common/EmojiDto.cs
| 267 |
C#
|
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using log4net;
namespace Robust._32BitLaunch
{
class Program
{
static void Main(string[] args)
{
log4net.Config.XmlConfigurator.Configure();
System.Console.WriteLine("32-bit OpenSim executor");
System.Console.WriteLine("-----------------------");
System.Console.WriteLine("");
System.Console.WriteLine("This application is compiled for 32-bit CPU and will run under WOW32 or similar.");
System.Console.WriteLine("All 64-bit incompatibilities should be gone.");
System.Console.WriteLine("");
System.Threading.Thread.Sleep(300);
try
{
global::OpenSim.Server.OpenSimServer.Main(args);
}
catch (Exception ex)
{
System.Console.WriteLine("OpenSim threw an exception:");
System.Console.WriteLine(ex.ToString());
System.Console.WriteLine("");
System.Console.WriteLine("Application will now terminate!");
System.Console.WriteLine("");
}
}
}
}
| 45.393443 | 121 | 0.671362 |
[
"BSD-3-Clause"
] |
AlericInglewood/opensimulator
|
OpenSim/Tools/Robust.32BitLaunch/Program.cs
| 2,769 |
C#
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace ProjetoFinal.Core.Contrato
{
public interface IRepositorioGravacao<T>
where T : EntidadeBase
{
T Adicionar(T entidade);
IEnumerable<T> AdicionarLista(IEnumerable<T> listaEntidades);
void Deletar(Guid id);
void Deletar(T entidade);
void DeletarLista(IEnumerable<T> entidades);
T Editar(T entidade);
T Editar(T entidadeNoBanco, object entidadeNova);
Task GravarDadosAssincronamente();
void GravarDadosSincronamente();
}
}
| 21.75 | 69 | 0.676519 |
[
"MIT"
] |
JulioBorges/curso_c_sharp
|
ProjetoFinal/ProjetoFinal.Core/Contrato/IRepositorioGravacao.cs
| 611 |
C#
|
#define PLAT_NO_INTERLOCKED
using System.Threading;
namespace ProtoBuf
{
internal sealed class BufferPool
{
internal static void Flush()
{
#if PLAT_NO_INTERLOCKED
lock(pool)
{
for (int i = 0; i < pool.Length; i++) pool[i] = null;
}
#else
for (int i = 0; i < pool.Length; i++)
{
Interlocked.Exchange(ref pool[i], null); // and drop the old value on the floor
}
#endif
}
private BufferPool() { }
const int PoolSize = 20;
internal const int BufferLength = 1024;
private static readonly object[] pool = new object[PoolSize];
internal static byte[] GetBuffer()
{
object tmp;
#if PLAT_NO_INTERLOCKED
lock(pool)
{
for (int i = 0; i < pool.Length; i++)
{
if((tmp = pool[i]) != null)
{
pool[i] = null;
return (byte[])tmp;
}
}
}
#else
for (int i = 0; i < pool.Length; i++)
{
if ((tmp = Interlocked.Exchange(ref pool[i], null)) != null) return (byte[])tmp;
}
#endif
return new byte[BufferLength];
}
internal static void ResizeAndFlushLeft(ref byte[] buffer, int toFitAtLeastBytes, int copyFromIndex, int copyBytes)
{
Helpers.DebugAssert(buffer != null);
Helpers.DebugAssert(toFitAtLeastBytes > buffer.Length);
Helpers.DebugAssert(copyFromIndex >= 0);
Helpers.DebugAssert(copyBytes >= 0);
// try doubling, else match
int newLength = buffer.Length * 2;
if (newLength < toFitAtLeastBytes) newLength = toFitAtLeastBytes;
byte[] newBuffer = new byte[newLength];
if (copyBytes > 0)
{
Helpers.BlockCopy(buffer, copyFromIndex, newBuffer, 0, copyBytes);
}
if (buffer.Length == BufferPool.BufferLength)
{
BufferPool.ReleaseBufferToPool(ref buffer);
}
buffer = newBuffer;
}
internal static void ReleaseBufferToPool(ref byte[] buffer)
{
if (buffer == null) return;
if (buffer.Length == BufferLength)
{
#if PLAT_NO_INTERLOCKED
lock (pool)
{
for (int i = 0; i < pool.Length; i++)
{
if(pool[i] == null)
{
pool[i] = buffer;
break;
}
}
}
#else
for (int i = 0; i < pool.Length; i++)
{
if (Interlocked.CompareExchange(ref pool[i], buffer, null) == null)
{
break; // found a null; swapped it in
}
}
#endif
}
// if no space, just drop it on the floor
buffer = null;
}
}
}
| 30.971154 | 123 | 0.444582 |
[
"MIT"
] |
hcy12321/ProtoBufNetUnity3D
|
Assets/Plugins/protobuf-net/BufferPool.cs
| 3,223 |
C#
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Gcp.GkeHub.Inputs
{
public sealed class FeatureMembershipConfigmanagementConfigSyncGitArgs : Pulumi.ResourceArgs
{
[Input("gcpServiceAccountEmail")]
public Input<string>? GcpServiceAccountEmail { get; set; }
/// <summary>
/// URL for the HTTPS proxy to be used when communicating with the Git repo.
/// </summary>
[Input("httpsProxy")]
public Input<string>? HttpsProxy { get; set; }
/// <summary>
/// The path within the Git repository that represents the top level of the repo to sync. Default: the root directory of the repository.
/// </summary>
[Input("policyDir")]
public Input<string>? PolicyDir { get; set; }
/// <summary>
/// Type of secret configured for access to the Git repo.
/// </summary>
[Input("secretType")]
public Input<string>? SecretType { get; set; }
/// <summary>
/// The branch of the repository to sync from. Default: master.
/// </summary>
[Input("syncBranch")]
public Input<string>? SyncBranch { get; set; }
/// <summary>
/// The URL of the Git repository to use as the source of truth.
/// </summary>
[Input("syncRepo")]
public Input<string>? SyncRepo { get; set; }
/// <summary>
/// Git revision (tag or hash) to check out. Default HEAD.
/// </summary>
[Input("syncRev")]
public Input<string>? SyncRev { get; set; }
/// <summary>
/// Period in seconds between consecutive syncs. Default: 15.
/// </summary>
[Input("syncWaitSecs")]
public Input<string>? SyncWaitSecs { get; set; }
public FeatureMembershipConfigmanagementConfigSyncGitArgs()
{
}
}
}
| 33.061538 | 144 | 0.603071 |
[
"ECL-2.0",
"Apache-2.0"
] |
la3mmchen/pulumi-gcp
|
sdk/dotnet/GkeHub/Inputs/FeatureMembershipConfigmanagementConfigSyncGitArgs.cs
| 2,149 |
C#
|
using Newtonsoft.Json;
namespace stellar_dotnet_sdk.responses
{
public class OperationFeeStatsResponse : Response
{
[JsonProperty(PropertyName = "min_accepted_fee")]
public long Min { get; }
[JsonProperty(PropertyName = "mode_accepted_fee")]
public long Mode { get; }
[JsonProperty(PropertyName = "last_ledger_base_fee")]
public long LastLedgerBaseFee { get; }
[JsonProperty(PropertyName = "last_ledger")]
public long LastLedger { get; }
public OperationFeeStatsResponse(long min, long mode, long lastLedgerBaseFee, long lastLedger)
{
Min = min;
Mode = mode;
LastLedgerBaseFee = lastLedgerBaseFee;
LastLedger = lastLedger;
}
}
}
| 27.964286 | 102 | 0.630907 |
[
"Apache-2.0"
] |
alphapoint/dotnet-stellar-sdk
|
stellar_dotnet_sdk_4.5.2/responses/OperationFeeStatsResponse.cs
| 785 |
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
using Codeplex.Data; // DynamicJson はこれ。
using System.Diagnostics; // Trace とかこれ。
namespace FindFolder
{
class Program
{
static string targetDirDB = @" \\192.168.10.88\sv04\pool\sec\comic\FindFolder.json";
static string [] targetDirs = new string[]{
@" \\192.168.10.88\sv04\pool\sec\comic\00",
@" \\192.168.10.88\sv04\pool\sec\comic\10",
@" \\192.168.10.88\sv04\pool\sec\comic\20",
@" \\192.168.10.88\sv04\pool\sec\comic\30",
@" \\192.168.10.88\sv04\pool\sec\comic\40",
@" \\192.168.10.88\sv04\pool\sec\comic\99"
};
static void FindFolderName(ref List<DirectoryInfo> lst, string TargetName)
{
foreach(string s in targetDirs)
{
DirectoryInfo d1 = new DirectoryInfo(s);
if (d1.Exists == false) continue;
DirectoryInfo[] d2 = d1.GetDirectories("*" + TargetName + "*");
if (d2.Length>0)
{
foreach(DirectoryInfo d3 in d2)
{
lst.Add(d3);
}
}
}
}
static bool FindFolderNameDB(ref List<DirectoryInfo> lst, string TargetName)
{
bool ret = false;
if (File.Exists(targetDirDB) == false) return ret;
string pad = Path.GetDirectoryName(targetDirDB);
string js = File.ReadAllText(targetDirDB, Encoding.GetEncoding("utf-8"));
var json = DynamicJson.Parse(js);
if ( json.IsDefined("Data") ==true)
{
string[] sa = json.Data;
if(sa.Length>0)
{
int cnt = 0;
string tn = TargetName.ToLower();
foreach(string s in sa)
{
if( s.ToLower().IndexOf(tn)>=0)
{
lst.Add( new DirectoryInfo(Path.Combine(pad,s)) );
cnt++;
}
}
ret = (cnt > 0);
}
}
return ret;
}
static void Main(string[] args)
{
CgiUtil cu = new CgiUtil(args);
string TargetName = "";
string dirList = "";
if (cu.CheckLockFile("FindFolder") == false)
{
cu.WriteErr();
return;
}
if (cu.Data.FindValueFromTag("folder",out TargetName))
{
List<DirectoryInfo> lst = new List<DirectoryInfo>();
if (FindFolderNameDB(ref lst, TargetName) ==false)
{
FindFolderName(ref lst, TargetName);
}
if (lst.Count > 0)
{
foreach (DirectoryInfo d in lst)
{
dirList += "<li>" + d.Parent.Name + "/" + d.Name + "</li>\r\n";
}
}
else
{
dirList += "<li>None</li>\r\n";
}
}
dirList = "<ul class=\"big\">\r\n" + dirList + "</ul>\r\n";
FileInfo fi = new FileInfo(".\\body.html");
string html = "$FolderPath";
if (fi.Exists == true)
{
html = File.ReadAllText(fi.FullName, Encoding.GetEncoding("utf-8"));
}
else
{
html = Properties.Resources.baseHtml;
}
html = html.Replace("$FolderPath", dirList);
html = html.Replace("$TargetName", TargetName);
//html = html.Replace("$QUERY_STRING", "QUERY_STRING:" + cu.QUERY_STRING);
//html = html.Replace("$PATH_INFO", "PATH_INFO:" + cu.PATH_INFO);
cu.WriteHtml(html);
cu.CloseLockFile();
}
}
}
| 22.594406 | 86 | 0.599505 |
[
"MIT"
] |
bryful/GalleriaSupport
|
FindFolder/Program.cs
| 3,251 |
C#
|
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using ServiceStack.Common.Tests.Models;
namespace ServiceStack.OrmLite.MySql.Tests
{
[TestFixture]
public class OrmLiteBasicPersistenceProviderTests
: OrmLiteTestBase
{
[SetUp]
public void SetUp()
{
}
[Test]
public void Can_GetById_from_basic_persistence_provider()
{
using (var db = ConnectionString.OpenDbConnection())
{
db.CreateTable<ModelWithFieldsOfDifferentTypes>(true);
var basicProvider = new OrmLitePersistenceProvider(db);
var row = ModelWithFieldsOfDifferentTypes.Create(1);
db.Insert(row);
var providerRow = basicProvider.GetById<ModelWithFieldsOfDifferentTypes>(1);
ModelWithFieldsOfDifferentTypes.AssertIsEqual(providerRow, row);
}
}
[Test]
public void Can_GetByIds_from_basic_persistence_provider()
{
using (var db = ConnectionString.OpenDbConnection())
{
db.CreateTable<ModelWithFieldsOfDifferentTypes>(true);
var basicProvider = new OrmLitePersistenceProvider(db);
var rowIds = new List<int> { 1, 2, 3, 4, 5 };
var rows = rowIds.ConvertAll(x => ModelWithFieldsOfDifferentTypes.Create(x));
rows.ForEach(x => db.Insert(x));
var getRowIds = new[] { 2, 4 };
var providerRows = basicProvider.GetByIds<ModelWithFieldsOfDifferentTypes>(getRowIds).ToList();
var providerRowIds = providerRows.ConvertAll(x => x.Id);
Assert.That(providerRowIds, Is.EquivalentTo(getRowIds));
}
}
[Test]
public void Can_Store_from_basic_persistence_provider()
{
using (var db = ConnectionString.OpenDbConnection())
{
db.CreateTable<ModelWithFieldsOfDifferentTypes>(true);
var basicProvider = new OrmLitePersistenceProvider(db);
var rowIds = new List<int> { 1, 2, 3, 4, 5 };
var rows = rowIds.ConvertAll(x => ModelWithFieldsOfDifferentTypes.Create(x));
rows.ForEach(x => basicProvider.Store(x));
var getRowIds = new[] { 2, 4 };
var providerRows = db.GetByIds<ModelWithFieldsOfDifferentTypes>(getRowIds).ToList();
var providerRowIds = providerRows.ConvertAll(x => x.Id);
Assert.That(providerRowIds, Is.EquivalentTo(getRowIds));
}
}
[Test]
public void Can_Delete_from_basic_persistence_provider()
{
using (var db = ConnectionString.OpenDbConnection())
{
db.CreateTable<ModelWithFieldsOfDifferentTypes>(true);
var basicProvider = new OrmLitePersistenceProvider(db);
var rowIds = new List<int> { 1, 2, 3, 4, 5 };
var rows = rowIds.ConvertAll(x => ModelWithFieldsOfDifferentTypes.Create(x));
rows.ForEach(x => db.Insert(x));
var deleteRowIds = new List<int> { 2, 4 };
foreach (var row in rows)
{
if (deleteRowIds.Contains(row.Id))
{
basicProvider.Delete(row);
}
}
var providerRows = basicProvider.GetByIds<ModelWithFieldsOfDifferentTypes>(rowIds).ToList();
var providerRowIds = providerRows.ConvertAll(x => x.Id);
var remainingIds = new List<int>(rowIds);
deleteRowIds.ForEach(x => remainingIds.Remove(x));
Assert.That(providerRowIds, Is.EquivalentTo(remainingIds));
}
}
}
}
| 26.041667 | 99 | 0.70912 |
[
"BSD-3-Clause"
] |
augustoproiete-forks/ServiceStack--ServiceStack.OrmLite
|
src/ServiceStack.OrmLite.MySql.Tests/OrmLiteBasicPersistenceProviderTests.cs
| 3,125 |
C#
|
// WARNING
//
// This file has been generated automatically by Xamarin Studio to store outlets and
// actions made in the Xcode designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using Foundation;
namespace StateRestoration
{
[Register ("FilterViewController")]
partial class FilterViewController
{
[Outlet]
UIKit.UISwitch ActiveSwitch { get; set; }
[Outlet]
UIKit.UISlider Slider { get; set; }
void ReleaseDesignerOutlets ()
{
if (ActiveSwitch != null) {
ActiveSwitch.Dispose ();
ActiveSwitch = null;
}
if (Slider != null) {
Slider.Dispose ();
Slider = null;
}
}
}
}
| 19.941176 | 84 | 0.679941 |
[
"MIT"
] |
Art-Lav/ios-samples
|
StateRestoration/StateRestoration/FilterViewController.designer.cs
| 678 |
C#
|
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class CycleRoundDecisions : WeaponTransition
{
public CycleRoundDecisions(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 21.4 | 106 | 0.732087 |
[
"MIT"
] |
Eingin/CP77Tools
|
CP77.CR2W/Types/cp77/CycleRoundDecisions.cs
| 307 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class frmHeadwiseFeeRpt : DBUtility
{
string strQry = "";
DataSet dsObj;
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (Session["UserType_Id"] != null && Session["User_Id"] != null)
{
if (!IsPostBack)
{
fillAcademicYear();
FillSTD();
FillGrid();
geturl();
}
}
else
{
Response.Redirect("~\\login.aspx", false);
}
}
catch
{
}
}
protected void ddlSTD_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
int sum = 0;
strQry = "";
strQry = "exec usp_FeesAssignSTD @type='FillGrid',@intSchool_Id='" + Convert.ToString(Session["School_Id"]) + "',@intAcademic_id='" + Convert.ToString(drpAcademiYear.SelectedValue) + "',@intSTD_Id='" + Convert.ToString(ddlSTD.SelectedValue) + "'";
dsObj = sGetDataset(strQry);
grvDetail.DataSource = dsObj;
grvDetail.DataBind();
for (int i = 0; i < grvDetail.Rows.Count; i++)
{
String test = grvDetail.Rows[i].Cells[3].Text;
if (test == "Monthly")
{
sum += (int.Parse(grvDetail.Rows[i].Cells[2].Text) * 12);
}
else if (test == "Quarterly")
{
sum += (int.Parse(grvDetail.Rows[i].Cells[2].Text) * 4);
}
else if (test == "Half Yearly")
{
sum += (int.Parse(grvDetail.Rows[i].Cells[2].Text) * 2);
}
else
{
sum += (int.Parse(grvDetail.Rows[i].Cells[2].Text));
}
//sum += int.Parse(grvDetail.Rows[i].Cells[4].Text);
}
lblTotal.Text = sum.ToString();
}
catch
{
}
}
protected void drpAcademiYear_SelectedIndexChanged(object sender, EventArgs e)
{
ddlSTD.ClearSelection();
}
public void FillGrid()
{
try
{
strQry = "";
strQry = "exec usp_FeesAssignSTD @type='FillGrid',@intSchool_Id='" + Convert.ToString(Session["School_Id"]) + "',@intAcademic_id='" + Convert.ToString(drpAcademiYear.SelectedValue) + "',@intSTD_Id='" + Convert.ToString(ddlSTD.SelectedValue) + "'";
dsObj = sGetDataset(strQry);
grvDetail.DataSource = dsObj;
grvDetail.DataBind();
}
catch
{
}
}
public void fillAcademicYear()
{
try
{
strQry = "";
strQry = "exec usp_FeesAssignSTD @type='fillAcademicYear'";
sBindDropDownList(drpAcademiYear, strQry, "AcademicYear", "intAcademic_id");
ddlSTD.ClearSelection();
}
catch
{
}
}
public void FillSTD()
{
try
{
strQry = "";
strQry = "exec usp_FeesAssignSTD @type='FillSTD',@intSchool_Id='" + Convert.ToString(Session["School_Id"]) + "'";
sBindDropDownList(ddlSTD, strQry, "vchStandard_name", "intstandard_id");
}
catch
{
}
}
protected void btnReport_Click(object sender, EventArgs e)
{
if (drpAcademiYear.SelectedValue=="0")
{
drpAcademiYear.Focus();
MessageBox("Please Select Academic Year!");
return;
}
if (ddlSTD.SelectedValue == "0")
{
ddlSTD.Focus();
MessageBox("Please Select Standard!");
return;
}
DataSet dsObj = new DataSet();
strQry = "";
strQry = "exec usp_FeesAssignSTD @type='FillGrid',@intSchool_Id='" + Convert.ToString(Session["School_Id"]) + "',@intAcademic_id='" + Convert.ToString(drpAcademiYear.SelectedValue) + "',@intSTD_Id='" + Convert.ToString(ddlSTD.SelectedValue) + "'";
dsObj = sGetDataset(strQry);
Session["rptFeeHeadWise"] = dsObj;
Response.Redirect("frmFeeHeadWise.aspx", true);
}
}
| 30.367347 | 259 | 0.499328 |
[
"MIT"
] |
clearcodetechnologies/cctSchoolApplication
|
frmHeadwiseFeeRpt.aspx.cs
| 4,466 |
C#
|
using CommandLine;
namespace LangBuilder
{
public class Options
{
[Option('i', "input", Required = true, HelpText = "Input files to be processed")]
public string Input { get; set; }
[Option('o', "output", Required = true, HelpText = "Directory where translations should be created")]
public string Output { get; set; }
[Option('n', "name", Required = true, HelpText = "Name for phrases file")]
public string FileName { get; set; }
// [Option('w', "watermark", Required = false, Default = true, HelpText = "Manipulates the program watermark in translations file")]
// public bool Watermark { get; set; }
}
}
| 37.105263 | 141 | 0.604255 |
[
"MIT"
] |
CrazyHackGUT/sm-TranslationsBuilder
|
LangBuilder/Options.cs
| 707 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AndroidIconography {
static class Program {
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main () {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
Application.Run( new Form1() );
}
}
}
| 25.5 | 67 | 0.62549 |
[
"Apache-2.0"
] |
iboalali/Android-Iconography
|
AndroidIconography/Program.cs
| 512 |
C#
|
using System;
namespace Opds4Net.Server
{
/// <summary>
/// Converts data items to syndication items
/// </summary>
public interface IOpdsItemConverter
{
/// <summary>
/// Raise on a syndication item is generated.
/// </summary>
event EventHandler<ItemGeneratedEventArgs> ItemGenerated;
/// <summary>
/// Get opds entries according to a category id.
/// If there are sub-categories, show them first.
/// If the given categories id represents a leaf category. Shows the books in it.
/// </summary>
/// <param name="data">An instance of OpdsData represents the data you want to convert to opds items.</param>
/// <returns>The opds entries. If the category Id is not given, returns all root categories.</returns>
OpdsItems GetItems(OpdsData data);
}
}
| 34.88 | 117 | 0.633028 |
[
"MIT"
] |
atollkuci/calibre-reading-lists
|
source/Opds4Net/Opds4Net/Server/IOpdsItemConverter.cs
| 874 |
C#
|
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using wyUpdate;
public static class LimitedProcess
{
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern IntPtr GetShellWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(IntPtr hObject);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool CreateProcessWithTokenW(IntPtr hToken, uint dwLogonFlags, string lpApplicationName, string lpCommandLine, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool DuplicateTokenEx(
IntPtr hExistingToken,
uint dwDesiredAccess,
IntPtr lpTokenAttributes,
int ImpersonationLevel,
int TokenType,
out IntPtr phNewToken);
const UInt32 INFINITE = 0xFFFFFFFF;
const UInt32 WAIT_ABANDONED = 0x00000080;
const UInt32 WAIT_OBJECT_0 = 0x00000000;
const UInt32 WAIT_TIMEOUT = 0x00000102;
const UInt32 WAIT_FAILED = 0xFFFFFFFF;
const short SW_HIDE = 0;
const short SW_MAXIMIZE = 3;
const short SW_MINIMIZE = 6;
[DllImport("kernel32.dll", SetLastError = true)]
static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetExitCodeProcess(IntPtr hProcess, out uint lpExitCode);
const uint STARTF_USESHOWWINDOW = 0x00000001;
[StructLayout(LayoutKind.Sequential)]
struct STARTUPINFO
{
public int cb;
public String lpReserved;
public String lpDesktop;
public String lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
/// <summary>Starts the limited process.</summary>
/// <param name="filename">The file to start as a limited process.</param>
/// <param name="arguments">The arguments to pass to the process.</param>
/// <param name="fallback">Fallback on Process.Start() if this method fails (for whatever reason). We use a simple Process.Start(filename, arguments) call -- we don't pass in all the details.</param>
/// <param name="waitForExit">Whether to wait for the execution of the file to finish before continuing.</param>
/// <param name="windowStyle">How to show the started process.</param>
/// <returns>The exit code if waitForExit = true, otherwise it returns 0.</returns>
public static uint Start(string filename, string arguments = null, bool fallback = true, bool waitForExit = false, ProcessWindowStyle windowStyle = ProcessWindowStyle.Normal)
{
bool processCreated = false;
uint exitCode = 0;
string errorDetails = null;
int errorCode = 0;
if (VistaTools.AtLeastVista() && VistaTools.IsUserAnAdmin())
{
// early exit for files that don't exist
if (!File.Exists(filename))
throw new Exception("The system cannot find the file specified");
// Get window handle representing the desktop shell. This might not work if there is no shell window, or when
// using a custom shell. Also note that we're assuming that the shell is not running elevated.
IntPtr hShellWnd = GetShellWindow();
int dwShellPID = 0;
// If we're falling back then don't throw an error --
// just fall through to the end of function where Process.Start() is called.
if (hShellWnd == IntPtr.Zero)
{
if (!fallback)
throw new Exception("Unable to locate shell window; you might be using a custom shell");
}
else
{
// Get the ID of the desktop shell process.
GetWindowThreadProcessId(hShellWnd, out dwShellPID);
}
if (dwShellPID != 0)
{
//Open the desktop shell process in order to get the process token.
// PROCESS_QUERY_INFORMATION = 0x00000400
IntPtr hShellProcess = OpenProcess(0x0400, false, dwShellPID);
if (hShellProcess != IntPtr.Zero)
{
IntPtr hShellProcessToken;
//Get the process token of the desktop shell.
//TOKEN_DUPLICATE = 0x0002
if (OpenProcessToken(hShellProcess, 0x2, out hShellProcessToken))
{
IntPtr hPrimaryToken;
//Duplicate the shell's process token to get a primary token.
//TOKEN_QUERY = 0x0008
//TOKEN_ASSIGN_PRIMARY = 0x0001
//TOKEN_DUPLICATE = 0x0002
//TOKEN_ADJUST_DEFAULT = 0x0080
//TOKEN_ADJUST_SESSIONID = 0x0100;
const uint dwTokenRights = 0x0008 | 0x0001 | 0x0002 | 0x0080 | 0x0100;
//SecurityImpersonation = 2
//TokenPrimary = 1
if (DuplicateTokenEx(hShellProcessToken, dwTokenRights, IntPtr.Zero, 2, 1, out hPrimaryToken))
{
//Start the target process with the new token.
PROCESS_INFORMATION pi;
STARTUPINFO si = new STARTUPINFO();
if (windowStyle != ProcessWindowStyle.Normal)
{
// set how we'll be starting the process
si.dwFlags = STARTF_USESHOWWINDOW;
switch (windowStyle)
{
case ProcessWindowStyle.Hidden:
si.wShowWindow = SW_HIDE;
break;
case ProcessWindowStyle.Maximized:
si.wShowWindow = SW_MAXIMIZE;
break;
case ProcessWindowStyle.Minimized:
si.wShowWindow = SW_MINIMIZE;
break;
}
}
si.cb = Marshal.SizeOf(si);
if (filename.EndsWith(".exe"))
{
// build the arguments string
// filenames must be quoted or else the commandline args get blown
if (string.IsNullOrEmpty(arguments))
arguments = "\"" + filename + "\"";
else
arguments = "\"" + filename + "\" " + arguments;
}
else // *.bat and *.cmd files
{
string system32 = Environment.GetFolderPath(Environment.SpecialFolder.System);
if (string.IsNullOrEmpty(arguments))
arguments = "\"" + system32 + "\\cmd.exe\" /c \"" + filename + "\"";
else
arguments = "\"" + system32 + "\\cmd.exe\" /c \"\"" + filename + "\" " + arguments + "\"";
filename = system32 + "\\cmd.exe";
}
processCreated = CreateProcessWithTokenW(hPrimaryToken, 0, filename, arguments, 0, IntPtr.Zero, Path.GetDirectoryName(filename), ref si, out pi);
if (processCreated)
{
// wait for the process to finish executing
// then get the exit code
if (waitForExit)
{
if (WaitForSingleObject(pi.hProcess, INFINITE) == WAIT_FAILED)
{
// handle wait failure
errorCode = Marshal.GetLastWin32Error();
errorDetails = "WaitForSingleObject() failed with the error code " + errorCode + ".";
}
else if (!GetExitCodeProcess(pi.hProcess, out exitCode))
{
// getting the exit code failed
errorCode = Marshal.GetLastWin32Error();
errorDetails = "GetExitCodeProcess() failed with the error code " + errorCode + ".";
}
}
// cleanup the process handles
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
else if (!fallback)
{
// if we're not falling back to regular old "Process.Start()",
// then throw an error with enough info that the user can do something about it.
errorCode = Marshal.GetLastWin32Error();
errorDetails = "CreateProcessWithTokenW() failed with the error code " + errorCode + ".";
}
CloseHandle(hPrimaryToken);
}
else if (!fallback)
{
errorCode = Marshal.GetLastWin32Error();
errorDetails = "DuplicateTokenEx() on the desktop shell process failed with the error code " + errorCode + ".";
}
CloseHandle(hShellProcessToken);
}
else if (!fallback)
{
errorCode = Marshal.GetLastWin32Error();
errorDetails = "OpenProcessToken() on the desktop shell process failed with the error code " + errorCode + ".";
}
CloseHandle(hShellProcess);
}
else if (!fallback)
{
errorCode = Marshal.GetLastWin32Error();
errorDetails = "OpenProcess() on the desktop shell process failed with the error code " + errorCode + ".";
}
}
else if (!fallback)
{
errorDetails = "Unable to get the window thread process ID of the desktop shell process.";
}
}
// the process failed to be created for any number of reasons
// just create it using the regular method
if (!processCreated)
{
if (fallback)
Process.Start(filename, arguments);
else // not falling back and the process failed to execute
throw new ExternalException("Failed to start as a limited process. " + errorDetails, errorCode);
}
return exitCode;
}
}
| 46.778571 | 278 | 0.505802 |
[
"BSD-2-Clause"
] |
Amadeus-/wyupdate
|
Util/LimitedProcess.cs
| 13,100 |
C#
|
using System;
using System.Collections.Generic;
using Substrate.Nbt;
using System.Collections;
namespace Substrate
{
/// <summary>
/// Provides named id values for known item types.
/// </summary>
/// <remarks>See <see cref="BlockType"/> for additional information.</remarks>
public static class ItemType
{
public const int IRON_SHOVEL = 256;
public const int IRON_PICKAXE = 257;
public const int IRON_AXE = 258;
public const int FLINT_AND_STEEL = 259;
public const int APPLE = 260;
public const int BOW = 261;
public const int ARROW = 262;
public const int COAL = 263;
public const int DIAMOND = 264;
public const int IRON_INGOT = 265;
public const int GOLD_INGOT = 266;
public const int IRON_SWORD = 267;
public const int WOODEN_SWORD = 268;
public const int WOODEN_SHOVEL = 269;
public const int WOODEN_PICKAXE = 270;
public const int WOODEN_AXE = 271;
public const int STONE_SWORD = 272;
public const int STONE_SHOVEL = 273;
public const int STONE_PICKAXE = 274;
public const int STONE_AXE = 275;
public const int DIAMOND_SWORD = 276;
public const int DIAMOND_SHOVEL = 277;
public const int DIAMOND_PICKAXE = 278;
public const int DIAMOND_AXE = 279;
public const int STICK = 280;
public const int BOWL = 281;
public const int MUSHROOM_SOUP = 282;
public const int GOLD_SWORD = 283;
public const int GOLD_SHOVEL = 284;
public const int GOLD_PICKAXE = 285;
public const int GOLD_AXE = 286;
public const int STRING = 287;
public const int FEATHER = 288;
public const int GUNPOWDER = 289;
public const int WOODEN_HOE = 290;
public const int STONE_HOE = 291;
public const int IRON_HOE = 292;
public const int DIAMOND_HOE = 293;
public const int GOLD_HOE = 294;
public const int SEEDS = 295;
public const int WHEAT = 296;
public const int BREAD = 297;
public const int LEATHER_CAP = 298;
public const int LEATHER_TUNIC = 299;
public const int LEATHER_PANTS = 300;
public const int LEATHER_BOOTS = 301;
public const int CHAIN_HELMET = 302;
public const int CHAIN_CHESTPLATE = 303;
public const int CHAIN_LEGGINGS = 304;
public const int CHAIN_BOOTS = 305;
public const int IRON_HELMET = 306;
public const int IRON_CHESTPLATE = 307;
public const int IRON_LEGGINGS = 308;
public const int IRON_BOOTS = 309;
public const int DIAMOND_HELMET = 310;
public const int DIAMOND_CHESTPLATE = 311;
public const int DIAMOND_LEGGINGS = 312;
public const int DIAMOND_BOOTS = 313;
public const int GOLD_HELMET = 314;
public const int GOLD_CHESTPLATE = 315;
public const int GOLD_LEGGINGS = 316;
public const int GOLD_BOOTS = 317;
public const int FLINT = 318;
public const int RAW_PORKCHOP = 319;
public const int COOKED_PORKCHOP = 320;
public const int PAINTING = 321;
public const int GOLDEN_APPLE = 322;
public const int SIGN = 323;
public const int WOODEN_DOOR = 324;
public const int BUCKET = 325;
public const int WATER_BUCKET = 326;
public const int LAVA_BUCKET = 327;
public const int MINECART = 328;
public const int SADDLE = 329;
public const int IRON_DOOR = 330;
public const int REDSTONE_DUST = 331;
public const int SNOWBALL = 332;
public const int BOAT = 333;
public const int LEATHER = 334;
public const int MILK = 335;
public const int CLAY_BRICK = 336;
public const int CLAY = 337;
public const int SUGAR_CANE = 338;
public const int PAPER = 339;
public const int BOOK = 340;
public const int SLIMEBALL = 341;
public const int STORAGE_MINECART = 342;
public const int POWERED_MINECARD = 343;
public const int EGG = 344;
public const int COMPASS = 345;
public const int FISHING_ROD = 346;
public const int CLOCK = 347;
public const int GLOWSTONE_DUST = 348;
public const int RAW_FISH = 349;
public const int COOKED_FISH = 350;
public const int DYE = 351;
public const int BONE = 352;
public const int SUGAR = 353;
public const int CAKE = 354;
public const int BED = 355;
public const int REDSTONE_REPEATER = 356;
public const int COOKIE = 357;
public const int MAP = 358;
public const int SHEARS = 359;
public const int MELON_SLICE = 360;
public const int PUMPKIN_SEEDS = 361;
public const int MELON_SEEDS = 262;
public const int RAW_BEEF = 363;
public const int STEAK = 364;
public const int RAW_CHICKEN = 365;
public const int COOKED_CHICKEN = 366;
public const int ROTTEN_FLESH = 367;
public const int ENDER_PEARL = 368;
public const int BLAZE_ROD = 369;
public const int GHAST_TEAR = 370;
public const int GOLD_NUGGET = 371;
public const int NETHER_WART = 372;
public const int POTION = 373;
public const int GLASS_BOTTLE = 374;
public const int SPIDER_EYE = 375;
public const int FERMENTED_SPIDER_EYE = 376;
public const int BLAZE_POWDER = 377;
public const int MAGMA_CREAM = 378;
public const int BREWING_STAND = 379;
public const int CAULDRON = 380;
public const int EYE_OF_ENDER = 381;
public const int GLISTERING_MELON = 382;
public const int SPAWN_EGG = 383;
public const int BOTTLE_O_ENCHANTING = 384;
public const int FIRE_CHARGE = 385;
public const int BOOK_AND_QUILL = 386;
public const int WRITTEN_BOOK = 387;
public const int EMERALD = 388;
public const int ITEM_FRAME = 389;
public const int FLOWER_POT = 390;
public const int CARROT = 391;
public const int POTATO = 392;
public const int BAKED_POTATO = 393;
public const int POISON_POTATO = 394;
public const int EMPTY_MAP = 395;
public const int GOLDEN_CARROT = 396;
public const int MOB_HEAD = 397;
public const int CARROT_ON_A_STICK = 398;
public const int NETHER_STAR = 399;
public const int PUMPKIN_PIE = 400;
public const int FIREWORK_ROCKET = 401;
public const int FIREWORK_STAR = 402;
public const int ENCHANTED_BOOK = 403;
public const int REDSTONE_COMPARATOR = 404;
public const int NETHER_BRICK = 405;
public const int NETHER_QUARTZ = 406;
public const int TNT_MINECART = 407;
public const int HOPPER_MINECART = 408;
public const int IRON_HORSE_ARMOR = 417;
public const int GOLD_HORSE_ARMOR = 418;
public const int DIAMOND_HORSE_ARMOR = 419;
public const int LEAD = 420;
public const int NAME_TAG = 421;
public const int COMMAND_BLOCK_MINECART = 422;
public const int RAW_WUTTON = 423;
public const int COOKED_MUTTON = 424;
public const int BANNER = 425;
public const int SPRUCE_DOOR = 425;
public const int BIRCH_DOOR = 436;
public const int JUNGLE_DOOR = 437;
public const int ACACIA_DOOR = 438;
public const int DARK_OAK_DOOR = 439;
public const int
public const int MUSIC_DISC_13 = 2256;
public const int MUSIC_DISC_CAT = 2257;
public const int MUSIC_DISC_BLOCKS = 2258;
public const int MUSIC_DISC_CHIRP = 2259;
public const int MUSIC_DISC_FAR = 2260;
public const int MUSIC_DISC_MALL = 2261;
public const int MUSIC_DISC_MELLOHI = 2262;
public const int MUSIC_DISC_STAL = 2263;
public const int MUSIC_DISC_STRAD = 2264;
public const int MUSIC_DISC_WARD = 2265;
public const int MUSIC_DISC_11 = 2266;
}
/// <summary>
/// Provides information on a specific type of item.
/// </summary>
/// <remarks>By default, all known MC item types are already defined and registered, assuming Substrate
/// is up to date with the current MC version.
/// New item types may be created and used at runtime, and will automatically populate various static lookup tables
/// in the <see cref="ItemInfo"/> class.</remarks>
public class ItemInfo
{
private static Random _rand = new Random();
private class CacheTableDict<T> : ICacheTable<T>
{
private Dictionary<int, T> _cache;
public T this[int index]
{
get
{
T val;
if (_cache.TryGetValue(index, out val)) {
return val;
}
return default(T);
}
}
public CacheTableDict (Dictionary<int, T> cache)
{
_cache = cache;
}
public IEnumerator<T> GetEnumerator ()
{
foreach (T val in _cache.Values)
yield return val;
}
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator();
}
}
private static readonly Dictionary<int, ItemInfo> _itemTable;
private int _id = 0;
private string _name = "";
private int _stack = 1;
private static readonly CacheTableDict<ItemInfo> _itemTableCache;
/// <summary>
/// Gets the lookup table for id-to-info values.
/// </summary>
public static ICacheTable<ItemInfo> ItemTable
{
get { return _itemTableCache; }
}
/// <summary>
/// Gets the id of the item type.
/// </summary>
public int ID
{
get { return _id; }
}
/// <summary>
/// Gets the name of the item type.
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Gets the maximum stack size allowed for this item type.
/// </summary>
public int StackSize
{
get { return _stack; }
}
/// <summary>
/// Constructs a new <see cref="ItemInfo"/> record for the given item id.
/// </summary>
/// <param name="id">The id of an item type.</param>
public ItemInfo (int id)
{
_id = id;
_itemTable[_id] = this;
}
/// <summary>
/// Constructs a new <see cref="ItemInfo"/> record for the given item id and name.
/// </summary>
/// <param name="id">The id of an item type.</param>
/// <param name="name">The name of an item type.</param>
public ItemInfo (int id, string name)
{
_id = id;
_name = name;
_itemTable[_id] = this;
}
/// <summary>
/// Sets the maximum stack size for this item type.
/// </summary>
/// <param name="stack">A stack size between 1 and 64, inclusive.</param>
/// <returns>The object instance used to invoke this method.</returns>
public ItemInfo SetStackSize (int stack)
{
_stack = stack;
return this;
}
/// <summary>
/// Chooses a registered item type at random and returns it.
/// </summary>
/// <returns></returns>
public static ItemInfo GetRandomItem ()
{
List<ItemInfo> list = new List<ItemInfo>(_itemTable.Values);
return list[_rand.Next(list.Count)];
}
public static ItemInfo IronShovel;
public static ItemInfo IronPickaxe;
public static ItemInfo IronAxe;
public static ItemInfo FlintAndSteel;
public static ItemInfo Apple;
public static ItemInfo Bow;
public static ItemInfo Arrow;
public static ItemInfo Coal;
public static ItemInfo Diamond;
public static ItemInfo IronIngot;
public static ItemInfo GoldIngot;
public static ItemInfo IronSword;
public static ItemInfo WoodenSword;
public static ItemInfo WoodenShovel;
public static ItemInfo WoodenPickaxe;
public static ItemInfo WoodenAxe;
public static ItemInfo StoneSword;
public static ItemInfo StoneShovel;
public static ItemInfo StonePickaxe;
public static ItemInfo StoneAxe;
public static ItemInfo DiamondSword;
public static ItemInfo DiamondShovel;
public static ItemInfo DiamondPickaxe;
public static ItemInfo DiamondAxe;
public static ItemInfo Stick;
public static ItemInfo Bowl;
public static ItemInfo MushroomSoup;
public static ItemInfo GoldSword;
public static ItemInfo GoldShovel;
public static ItemInfo GoldPickaxe;
public static ItemInfo GoldAxe;
public static ItemInfo String;
public static ItemInfo Feather;
public static ItemInfo Gunpowder;
public static ItemInfo WoodenHoe;
public static ItemInfo StoneHoe;
public static ItemInfo IronHoe;
public static ItemInfo DiamondHoe;
public static ItemInfo GoldHoe;
public static ItemInfo Seeds;
public static ItemInfo Wheat;
public static ItemInfo Bread;
public static ItemInfo LeatherCap;
public static ItemInfo LeatherTunic;
public static ItemInfo LeatherPants;
public static ItemInfo LeatherBoots;
public static ItemInfo ChainHelmet;
public static ItemInfo ChainChestplate;
public static ItemInfo ChainLeggings;
public static ItemInfo ChainBoots;
public static ItemInfo IronHelmet;
public static ItemInfo IronChestplate;
public static ItemInfo IronLeggings;
public static ItemInfo IronBoots;
public static ItemInfo DiamondHelmet;
public static ItemInfo DiamondChestplate;
public static ItemInfo DiamondLeggings;
public static ItemInfo DiamondBoots;
public static ItemInfo GoldHelmet;
public static ItemInfo GoldChestplate;
public static ItemInfo GoldLeggings;
public static ItemInfo GoldBoots;
public static ItemInfo Flint;
public static ItemInfo RawPorkchop;
public static ItemInfo CookedPorkchop;
public static ItemInfo Painting;
public static ItemInfo GoldenApple;
public static ItemInfo Sign;
public static ItemInfo WoodenDoor;
public static ItemInfo Bucket;
public static ItemInfo WaterBucket;
public static ItemInfo LavaBucket;
public static ItemInfo Minecart;
public static ItemInfo Saddle;
public static ItemInfo IronDoor;
public static ItemInfo RedstoneDust;
public static ItemInfo Snowball;
public static ItemInfo Boat;
public static ItemInfo Leather;
public static ItemInfo Milk;
public static ItemInfo ClayBrick;
public static ItemInfo Clay;
public static ItemInfo SugarCane;
public static ItemInfo Paper;
public static ItemInfo Book;
public static ItemInfo Slimeball;
public static ItemInfo StorageMinecart;
public static ItemInfo PoweredMinecart;
public static ItemInfo Egg;
public static ItemInfo Compass;
public static ItemInfo FishingRod;
public static ItemInfo Clock;
public static ItemInfo GlowstoneDust;
public static ItemInfo RawFish;
public static ItemInfo CookedFish;
public static ItemInfo Dye;
public static ItemInfo Bone;
public static ItemInfo Sugar;
public static ItemInfo Cake;
public static ItemInfo Bed;
public static ItemInfo RedstoneRepeater;
public static ItemInfo Cookie;
public static ItemInfo Map;
public static ItemInfo Shears;
public static ItemInfo MelonSlice;
public static ItemInfo PumpkinSeeds;
public static ItemInfo MelonSeeds;
public static ItemInfo RawBeef;
public static ItemInfo Steak;
public static ItemInfo RawChicken;
public static ItemInfo CookedChicken;
public static ItemInfo RottenFlesh;
public static ItemInfo EnderPearl;
public static ItemInfo BlazeRod;
public static ItemInfo GhastTear;
public static ItemInfo GoldNugget;
public static ItemInfo NetherWart;
public static ItemInfo Potion;
public static ItemInfo GlassBottle;
public static ItemInfo SpiderEye;
public static ItemInfo FermentedSpiderEye;
public static ItemInfo BlazePowder;
public static ItemInfo MagmaCream;
public static ItemInfo BrewingStand;
public static ItemInfo Cauldron;
public static ItemInfo EyeOfEnder;
public static ItemInfo GlisteringMelon;
public static ItemInfo SpawnEgg;
public static ItemInfo BottleOEnchanting;
public static ItemInfo FireCharge;
public static ItemInfo BookAndQuill;
public static ItemInfo WrittenBook;
public static ItemInfo Emerald;
public static ItemInfo ItemFrame;
public static ItemInfo FlowerPot;
public static ItemInfo Carrot;
public static ItemInfo Potato;
public static ItemInfo BakedPotato;
public static ItemInfo PoisonPotato;
public static ItemInfo EmptyMap;
public static ItemInfo GoldenCarrot;
public static ItemInfo MobHead;
public static ItemInfo CarrotOnStick;
public static ItemInfo NetherStar;
public static ItemInfo PumpkinPie;
public static ItemInfo FireworkRocket;
public static ItemInfo FireworkStar;
public static ItemInfo EnchantedBook;
public static ItemInfo RedstoneComparator;
public static ItemInfo NetherBrick;
public static ItemInfo NetherQuartz;
public static ItemInfo TntMinecart;
public static ItemInfo HopperMinecart;
public static ItemInfo IronHorseArmor;
public static ItemInfo GoldHorseArmor;
public static ItemInfo DiamondHorseArmor;
public static ItemInfo Lead;
public static ItemInfo NameTag;
public static ItemInfo MusicDisc13;
public static ItemInfo MusicDiscCat;
public static ItemInfo MusicDiscBlocks;
public static ItemInfo MusicDiscChirp;
public static ItemInfo MusicDiscFar;
public static ItemInfo MusicDiscMall;
public static ItemInfo MusicDiscMellohi;
public static ItemInfo MusicDiscStal;
public static ItemInfo MusicDiscStrad;
public static ItemInfo MusicDiscWard;
public static ItemInfo MusicDisc11;
static ItemInfo ()
{
_itemTable = new Dictionary<int, ItemInfo>();
_itemTableCache = new CacheTableDict<ItemInfo>(_itemTable);
IronShovel = new ItemInfo(256, "Iron Shovel");
IronPickaxe = new ItemInfo(257, "Iron Pickaxe");
IronAxe = new ItemInfo(258, "Iron Axe");
FlintAndSteel = new ItemInfo(259, "Flint and Steel");
Apple = new ItemInfo(260, "Apple").SetStackSize(64);
Bow = new ItemInfo(261, "Bow");
Arrow = new ItemInfo(262, "Arrow").SetStackSize(64);
Coal = new ItemInfo(263, "Coal").SetStackSize(64);
Diamond = new ItemInfo(264, "Diamond").SetStackSize(64);
IronIngot = new ItemInfo(265, "Iron Ingot").SetStackSize(64);
GoldIngot = new ItemInfo(266, "Gold Ingot").SetStackSize(64);
IronSword = new ItemInfo(267, "Iron Sword");
WoodenSword = new ItemInfo(268, "Wooden Sword");
WoodenShovel = new ItemInfo(269, "Wooden Shovel");
WoodenPickaxe = new ItemInfo(270, "Wooden Pickaxe");
WoodenAxe = new ItemInfo(271, "Wooden Axe");
StoneSword = new ItemInfo(272, "Stone Sword");
StoneShovel = new ItemInfo(273, "Stone Shovel");
StonePickaxe = new ItemInfo(274, "Stone Pickaxe");
StoneAxe = new ItemInfo(275, "Stone Axe");
DiamondSword = new ItemInfo(276, "Diamond Sword");
DiamondShovel = new ItemInfo(277, "Diamond Shovel");
DiamondPickaxe = new ItemInfo(278, "Diamond Pickaxe");
DiamondAxe = new ItemInfo(279, "Diamond Axe");
Stick = new ItemInfo(280, "Stick").SetStackSize(64);
Bowl = new ItemInfo(281, "Bowl").SetStackSize(64);
MushroomSoup = new ItemInfo(282, "Mushroom Soup");
GoldSword = new ItemInfo(283, "Gold Sword");
GoldShovel = new ItemInfo(284, "Gold Shovel");
GoldPickaxe = new ItemInfo(285, "Gold Pickaxe");
GoldAxe = new ItemInfo(286, "Gold Axe");
String = new ItemInfo(287, "String").SetStackSize(64);
Feather = new ItemInfo(288, "Feather").SetStackSize(64);
Gunpowder = new ItemInfo(289, "Gunpowder").SetStackSize(64);
WoodenHoe = new ItemInfo(290, "Wooden Hoe");
StoneHoe = new ItemInfo(291, "Stone Hoe");
IronHoe = new ItemInfo(292, "Iron Hoe");
DiamondHoe = new ItemInfo(293, "Diamond Hoe");
GoldHoe = new ItemInfo(294, "Gold Hoe");
Seeds = new ItemInfo(295, "Seeds").SetStackSize(64);
Wheat = new ItemInfo(296, "Wheat").SetStackSize(64);
Bread = new ItemInfo(297, "Bread").SetStackSize(64);
LeatherCap = new ItemInfo(298, "Leather Cap");
LeatherTunic = new ItemInfo(299, "Leather Tunic");
LeatherPants = new ItemInfo(300, "Leather Pants");
LeatherBoots = new ItemInfo(301, "Leather Boots");
ChainHelmet = new ItemInfo(302, "Chain Helmet");
ChainChestplate = new ItemInfo(303, "Chain Chestplate");
ChainLeggings = new ItemInfo(304, "Chain Leggings");
ChainBoots = new ItemInfo(305, "Chain Boots");
IronHelmet = new ItemInfo(306, "Iron Helmet");
IronChestplate = new ItemInfo(307, "Iron Chestplate");
IronLeggings = new ItemInfo(308, "Iron Leggings");
IronBoots = new ItemInfo(309, "Iron Boots");
DiamondHelmet = new ItemInfo(310, "Diamond Helmet");
DiamondChestplate = new ItemInfo(311, "Diamond Chestplate");
DiamondLeggings = new ItemInfo(312, "Diamond Leggings");
DiamondBoots = new ItemInfo(313, "Diamond Boots");
GoldHelmet = new ItemInfo(314, "Gold Helmet");
GoldChestplate = new ItemInfo(315, "Gold Chestplate");
GoldLeggings = new ItemInfo(316, "Gold Leggings");
GoldBoots = new ItemInfo(317, "Gold Boots");
Flint = new ItemInfo(318, "Flint").SetStackSize(64);
RawPorkchop = new ItemInfo(319, "Raw Porkchop").SetStackSize(64);
CookedPorkchop = new ItemInfo(320, "Cooked Porkchop").SetStackSize(64);
Painting = new ItemInfo(321, "Painting").SetStackSize(64);
GoldenApple = new ItemInfo(322, "Golden Apple").SetStackSize(64);
Sign = new ItemInfo(323, "Sign");
WoodenDoor = new ItemInfo(324, "Door");
Bucket = new ItemInfo(325, "Bucket");
WaterBucket = new ItemInfo(326, "Water Bucket");
LavaBucket = new ItemInfo(327, "Lava Bucket");
Minecart = new ItemInfo(328, "Minecart");
Saddle = new ItemInfo(329, "Saddle");
IronDoor = new ItemInfo(330, "Iron Door");
RedstoneDust = new ItemInfo(331, "Redstone Dust").SetStackSize(64);
Snowball = new ItemInfo(332, "Snowball").SetStackSize(16);
Boat = new ItemInfo(333, "Boat");
Leather = new ItemInfo(334, "Leather").SetStackSize(64);
Milk = new ItemInfo(335, "Milk");
ClayBrick = new ItemInfo(336, "Clay Brick").SetStackSize(64);
Clay = new ItemInfo(337, "Clay").SetStackSize(64);
SugarCane = new ItemInfo(338, "Sugar Cane").SetStackSize(64);
Paper = new ItemInfo(339, "Paper").SetStackSize(64);
Book = new ItemInfo(340, "Book").SetStackSize(64);
Slimeball = new ItemInfo(341, "Slimeball").SetStackSize(64);
StorageMinecart = new ItemInfo(342, "Storage Minecart");
PoweredMinecart = new ItemInfo(343, "Powered Minecart");
Egg = new ItemInfo(344, "Egg").SetStackSize(16);
Compass = new ItemInfo(345, "Compass");
FishingRod = new ItemInfo(346, "Fishing Rod");
Clock = new ItemInfo(347, "Clock");
GlowstoneDust = new ItemInfo(348, "Glowstone Dust").SetStackSize(64);
RawFish = new ItemInfo(349, "Raw Fish").SetStackSize(64);
CookedFish = new ItemInfo(350, "Cooked Fish").SetStackSize(64);
Dye = new ItemInfo(351, "Dye").SetStackSize(64);
Bone = new ItemInfo(352, "Bone").SetStackSize(64);
Sugar = new ItemInfo(353, "Sugar").SetStackSize(64);
Cake = new ItemInfo(354, "Cake");
Bed = new ItemInfo(355, "Bed");
RedstoneRepeater = new ItemInfo(356, "Redstone Repeater").SetStackSize(64);
Cookie = new ItemInfo(357, "Cookie").SetStackSize(8);
Map = new ItemInfo(358, "Map");
Shears = new ItemInfo(359, "Shears");
MelonSlice = new ItemInfo(360, "Melon Slice").SetStackSize(64);
PumpkinSeeds = new ItemInfo(361, "Pumpkin Seeds").SetStackSize(64);
MelonSeeds = new ItemInfo(362, "Melon Seeds").SetStackSize(64);
RawBeef = new ItemInfo(363, "Raw Beef").SetStackSize(64);
Steak = new ItemInfo(364, "Steak").SetStackSize(64);
RawChicken = new ItemInfo(365, "Raw Chicken").SetStackSize(64);
CookedChicken = new ItemInfo(366, "Cooked Chicken").SetStackSize(64);
RottenFlesh = new ItemInfo(367, "Rotten Flesh").SetStackSize(64);
EnderPearl = new ItemInfo(368, "Ender Pearl").SetStackSize(64);
BlazeRod = new ItemInfo(369, "Blaze Rod").SetStackSize(64);
GhastTear = new ItemInfo(370, "Ghast Tear").SetStackSize(64);
GoldNugget = new ItemInfo(371, "Gold Nugget").SetStackSize(64);
NetherWart = new ItemInfo(372, "Nether Wart").SetStackSize(64);
Potion = new ItemInfo(373, "Potion");
GlassBottle = new ItemInfo(374, "Glass Bottle").SetStackSize(64);
SpiderEye = new ItemInfo(375, "Spider Eye").SetStackSize(64);
FermentedSpiderEye = new ItemInfo(376, "Fermented Spider Eye").SetStackSize(64);
BlazePowder = new ItemInfo(377, "Blaze Powder").SetStackSize(64);
MagmaCream = new ItemInfo(378, "Magma Cream").SetStackSize(64);
BrewingStand = new ItemInfo(379, "Brewing Stand").SetStackSize(64);
Cauldron = new ItemInfo(380, "Cauldron");
EyeOfEnder = new ItemInfo(381, "Eye of Ender").SetStackSize(64);
GlisteringMelon = new ItemInfo(382, "Glistering Melon").SetStackSize(64);
SpawnEgg = new ItemInfo(383, "Spawn Egg").SetStackSize(64);
BottleOEnchanting = new ItemInfo(384, "Bottle O' Enchanting").SetStackSize(64);
FireCharge = new ItemInfo(385, "Fire Charge").SetStackSize(64);
BookAndQuill = new ItemInfo(386, "Book and Quill");
WrittenBook = new ItemInfo(387, "Written Book");
Emerald = new ItemInfo(388, "Emerald").SetStackSize(64);
ItemFrame = new ItemInfo(389, "Item Frame").SetStackSize(64);
FlowerPot = new ItemInfo(390, "Flower Pot").SetStackSize(64);
Carrot = new ItemInfo(391, "Carrot").SetStackSize(64);
Potato = new ItemInfo(392, "Potato").SetStackSize(64);
BakedPotato = new ItemInfo(393, "Baked Potato").SetStackSize(64);
PoisonPotato = new ItemInfo(394, "Poisonous Potato").SetStackSize(64);
EmptyMap = new ItemInfo(395, "Empty Map").SetStackSize(64);
GoldenCarrot = new ItemInfo(396, "Golden Carrot").SetStackSize(64);
MobHead = new ItemInfo(397, "Mob Head").SetStackSize(64);
CarrotOnStick = new ItemInfo(398, "Carrot on a Stick");
NetherStar = new ItemInfo(399, "Nether Star").SetStackSize(64);
PumpkinPie = new ItemInfo(400, "Pumpkin Pie").SetStackSize(64);
FireworkRocket = new ItemInfo(401, "Firework Rocket");
FireworkStar = new ItemInfo(402, "Firework Star").SetStackSize(64);
EnchantedBook = new ItemInfo(403, "Enchanted Book");
RedstoneComparator = new ItemInfo(404, "Redstone Comparator").SetStackSize(64);
NetherBrick = new ItemInfo(405, "Nether Brick").SetStackSize(64);
NetherQuartz = new ItemInfo(406, "Nether Quartz").SetStackSize(64);
TntMinecart = new ItemInfo(407, "Minecart with TNT");
HopperMinecart = new ItemInfo(408, "Minecart with Hopper");
IronHorseArmor = new ItemInfo(417, "Iron Horse Armor");
GoldHorseArmor = new ItemInfo(418, "Gold Horse Armor");
DiamondHorseArmor = new ItemInfo(419, "Diamond Horse Armor");
Lead = new ItemInfo(420, "Lead").SetStackSize(64);
NameTag = new ItemInfo(421, "Name Tag").SetStackSize(64);
MusicDisc13 = new ItemInfo(2256, "13 Disc");
MusicDiscCat = new ItemInfo(2257, "Cat Disc");
MusicDiscBlocks = new ItemInfo(2258, "Blocks Disc");
MusicDiscChirp = new ItemInfo(2259, "Chirp Disc");
MusicDiscFar = new ItemInfo(2260, "Far Disc");
MusicDiscMall = new ItemInfo(2261, "Mall Disc");
MusicDiscMellohi = new ItemInfo(2262, "Mellohi Disc");
MusicDiscStal = new ItemInfo(2263, "Stal Disc");
MusicDiscStrad = new ItemInfo(2264, "Strad Disc");
MusicDiscWard = new ItemInfo(2265, "Ward Disc");
MusicDisc11 = new ItemInfo(2266, "11 Disc");
}
}
}
| 46.591928 | 120 | 0.60693 |
[
"MIT"
] |
Micalobia/Substrate
|
SubstrateCS/Source/ItemInfo.cs
| 31,172 |
C#
|
// MIT License - Copyright (c) Malte Rupprecht
// This file is subject to the terms and conditions defined in
// LICENSE, which is part of this source code package
using System;
using System.Collections.Generic;
namespace LibreLancer.Utf.Anm
{
public class Script
{
public float RootHeight { get; private set; }
public List<ObjectMap> ObjectMaps { get; private set; }
public List<JointMap> JointMaps { get; private set; }
public Script(IntermediateNode root, ConstructCollection constructs)
{
ObjectMaps = new List<ObjectMap>();
JointMaps = new List<JointMap>();
foreach (Node node in root)
{
if (node.Name.Equals("root height", StringComparison.OrdinalIgnoreCase)) RootHeight = (node as LeafNode).SingleData.Value;
else if (node.Name.StartsWith("object map", StringComparison.OrdinalIgnoreCase))
ObjectMaps.Add(new ObjectMap(node as IntermediateNode));
else if (node.Name.StartsWith("joint map", StringComparison.OrdinalIgnoreCase))
JointMaps.Add(new JointMap(node as IntermediateNode));
else throw new Exception("Invalid Node in script root: " + node.Name);
}
}
}
}
| 37.30303 | 126 | 0.672624 |
[
"MIT"
] |
lyzardiar/Librelancer
|
src/LibreLancer/Utf/Anm/Script.cs
| 1,233 |
C#
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace performance
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
| 17.619048 | 37 | 0.683784 |
[
"Apache-2.0"
] |
foxundermoon/MessageService
|
performance/Form1.cs
| 372 |
C#
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Skybot.Api.IntegTests.Controllers;
using Skybot.Api.Models;
using Skybot.Api.Services.IntentsServices;
using Skybot.Api.Services.Settings;
namespace Skybot.Api.IntegTests.Services.IntentsServices
{
[TestClass]
public class TranslateIntentTests : IntegTestBase
{
[TestMethod]
public async Task Execute_ReturnsTranslation_WhenEntitiesHaveTextAndTargetLanguage()
{
var testEntities = new List<LuisEntity>
{
new LuisEntity {Score = 1, Type = "Dictionary.Text", Name = "Hello"},
new LuisEntity {Score = 1, Type = "Dictionary.TargetLanguage", Name = "French"}
};
var settingsMock = new Mock<ISettings>();
settingsMock.Setup(x => x.TranslateApiKey)
.Returns(Config["GoogleTarnslateApiKey"]);
var translateIntent = new TranslateIntent(settingsMock.Object);
var result = await translateIntent.Execute(testEntities);
Assert.IsNotNull(result);
Assert.IsFalse(string.IsNullOrEmpty(result.Message));
Assert.AreEqual(result.Message, "Bonjour");
}
}
}
| 34 | 95 | 0.664861 |
[
"MIT"
] |
malekatwiz/Skybot
|
Skybot.Api.IntegTests/Services/IntentsServices/TranslateIntentTests.cs
| 1,294 |
C#
|
// Copyright (c) Rotorz Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
using System;
using System.Globalization;
namespace Rotorz.Json
{
/// <summary>
/// Node holding a 64-bit integer value.
/// </summary>
public sealed class JsonIntegerNode : JsonNode
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonIntegerNode"/> class with a
/// value of zero.
/// </summary>
public JsonIntegerNode()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonIntegerNode"/> class with
/// the specified integer value.
/// </summary>
/// <param name="value">Initial value of node.</param>
public JsonIntegerNode(long value)
{
this.Value = value;
}
/// <summary>
/// Gets or sets the value of the node.
/// </summary>
/// <seealso cref="UnsignedValue"/>
public long Value { get; set; }
/// <summary>
/// Gets or sets unsigned value of node. This property is only useful when using
/// the unsigned long (ulong) data type.
/// </summary>
/// <seealso cref="Value"/>
public ulong UnsignedValue {
get { return (ulong)this.Value; }
set { this.Value = (long)value; }
}
/// <inheritdoc/>
public override JsonNode Clone()
{
return new JsonIntegerNode(this.Value);
}
/// <inheritdoc/>
public override string ToString()
{
return this.Value.ToString(CultureInfo.InvariantCulture);
}
/// <inheritdoc/>
public override object ConvertTo(Type type)
{
if (type == null) {
throw new ArgumentNullException("type");
}
if (type.IsEnum) {
return Convert.ChangeType(this.Value, Enum.GetUnderlyingType(type));
}
else {
return Convert.ChangeType(this.Value, type);
}
}
/// <inheritdoc/>
public override void Write(IJsonWriter writer)
{
writer.WriteInteger(this.Value);
}
}
}
| 27.392857 | 88 | 0.532377 |
[
"MIT"
] |
Joey35233/FoxKit
|
FoxKit/Assets/Lib/dotnet-json/JsonIntegerNode.cs
| 2,303 |
C#
|
namespace CinemAPI.Data.EF
{
using System;
using System.Data.Entity.Migrations;
public partial class initDbCreate : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Cinemas",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false),
Address = c.String(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Rooms",
c => new
{
Id = c.Int(nullable: false, identity: true),
Number = c.Int(nullable: false),
SeatsPerRow = c.Short(nullable: false),
Rows = c.Short(nullable: false),
CinemaId = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Cinemas", t => t.CinemaId, cascadeDelete: true)
.Index(t => t.CinemaId);
CreateTable(
"dbo.Projections",
c => new
{
Id = c.Long(nullable: false, identity: true),
RoomId = c.Int(nullable: false),
MovieId = c.Int(nullable: false),
StartDate = c.DateTime(nullable: false),
AvailableSeatsCount = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Movies", t => t.MovieId, cascadeDelete: true)
.ForeignKey("dbo.Rooms", t => t.RoomId, cascadeDelete: true)
.Index(t => t.RoomId)
.Index(t => t.MovieId);
CreateTable(
"dbo.Movies",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false),
DurationMinutes = c.Short(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Tickets",
c => new
{
Id = c.Int(nullable: false, identity: true),
ProjectionStartDate = c.DateTime(nullable: false),
MovieName = c.String(nullable: false),
CinemaName = c.String(nullable: false),
RoomNumber = c.Int(nullable: false),
Row = c.Int(nullable: false),
Col = c.Int(nullable: false),
ProjectionId = c.Long(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Projections", t => t.ProjectionId, cascadeDelete: true)
.Index(t => t.ProjectionId);
CreateTable(
"dbo.Reservations",
c => new
{
Id = c.Int(nullable: false, identity: true),
ProjectionStartDate = c.DateTime(nullable: false),
MovieName = c.String(nullable: false),
CinemaName = c.String(nullable: false),
RoomNumber = c.Int(nullable: false),
Row = c.Int(nullable: false),
Column = c.Int(nullable: false),
ProjectionId = c.Long(nullable: false),
IsCancelled = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.Projections", t => t.ProjectionId, cascadeDelete: true)
.Index(t => t.ProjectionId);
}
public override void Down()
{
DropForeignKey("dbo.Reservations", "ProjectionId", "dbo.Projections");
DropForeignKey("dbo.Tickets", "ProjectionId", "dbo.Projections");
DropForeignKey("dbo.Projections", "RoomId", "dbo.Rooms");
DropForeignKey("dbo.Projections", "MovieId", "dbo.Movies");
DropForeignKey("dbo.Rooms", "CinemaId", "dbo.Cinemas");
DropIndex("dbo.Reservations", new[] { "ProjectionId" });
DropIndex("dbo.Tickets", new[] { "ProjectionId" });
DropIndex("dbo.Projections", new[] { "MovieId" });
DropIndex("dbo.Projections", new[] { "RoomId" });
DropIndex("dbo.Rooms", new[] { "CinemaId" });
DropTable("dbo.Reservations");
DropTable("dbo.Tickets");
DropTable("dbo.Movies");
DropTable("dbo.Projections");
DropTable("dbo.Rooms");
DropTable("dbo.Cinemas");
}
}
}
| 42.245763 | 88 | 0.435306 |
[
"MIT"
] |
ToniStoynev/CinemaApi
|
CinemaApi/CinemAPI.Data.EF/Migrations/201911210832562_initDbCreate.cs
| 4,985 |
C#
|
//-----------------------------------------------------------------------
// <copyright file="MiscExtensions.cs" company="TemporalCohesion.co.uk">
// Copyright 2011 - Present Stuart Grassie
//
// 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.
// </copyright>
//----------------------------------------------------------------------
namespace csharp_github_api.Extensions
{
using Exceptions;
using RestSharp;
using System.Collections.Generic;
using System.Net;
/// <summary>
/// Misc handy extensions
/// </summary>
public static class MiscExtensions
{
/// <summary>
/// The <see cref="HttpStatusCode"/> should be the one we expect.
/// </summary>
/// <param name="response">The actual status code returned from the response.</param>
/// <param name="expected">The expected status code.</param>
/// <returns><c>True</c> if the response is the expected one; otherwise <c>False</c>.</returns>
public static bool ShouldBe(this HttpStatusCode response, HttpStatusCode expected)
{
return response.Equals(expected);
}
public static void IfNotRaiseAnError<TModel>(this bool ok, IRestResponse<List<TModel>> response)
{
if (ok) return;
var exception = new GitHubResponseException(response.ErrorMessage)
{
Response = response
};
throw exception;
}
}
}
| 37.690909 | 104 | 0.576942 |
[
"Apache-2.0"
] |
aldass/csharp-github-api
|
csharp-github-api/Extensions/MiscExtensions.cs
| 2,075 |
C#
|
using System;
using UIKit;
using Foundation;
using CoreGraphics;
using QuartzSample;
public class RectDrawingView : QuartzView
{
public override void DrawInContext (CGContext context)
{
// Drawing with a white stroke color
context.SetStrokeColor (1, 1, 1, 1);
// And drawing with a blue fill color
context.SetFillColor (0, 0, 1, 1);
// Draw them with a 2 stroke width so they are a bit more visible.
context.SetLineWidth (2);
// Add Rect to the current path, then stroke it
context.AddRect (new CGRect (30, 30, 60, 60));
context.StrokePath ();
// Stroke Rect convenience that is equivalent to above
context.StrokeRect (new CGRect (30, 120, 60, 60));
// Stroke rect convenience equivalent to the above, plus a call to context.SetLineWidth ().
context.StrokeRectWithWidth (new CGRect (30, 210, 60, 60), 10);
// Demonstate the stroke is on both sides of the path.
context.SaveState ();
context.SetStrokeColor (1, 0, 0, 1);
context.StrokeRectWithWidth (new CGRect (30, 210, 60, 60), 2);
context.RestoreState ();
var rects = new CGRect [] {
new CGRect (120, 30, 60, 60),
new CGRect (120, 120, 60, 60),
new CGRect (120, 210, 60, 60),
};
// Bulk call to add rects to the current path.
context.AddRects (rects);
context.StrokePath ();
// Create filled rectangles via two different paths.
// Add/Fill path
context.AddRect (new CGRect (210, 30, 60, 60));
context.FillPath ();
// Fill convienience.
context.FillRect (new CGRect (210, 120, 60, 60));
}
}
public class PolyDrawingView : QuartzView
{
public override void DrawInContext (CGContext context)
{
// Drawing with a white stroke color
context.SetStrokeColor (1, 1, 1, 1);
// Drawing with a blue fill color
context.SetFillColor (0, 0, 1, 1);
// Draw them with a 2 stroke width so they are a bit more visible.
context.SetLineWidth (2);
CGPoint center;
// Draw a Star stroked
center = new CGPoint (90, 90);
context.MoveTo (center.X, center.Y + 60);
for (int i = 1; i < 5; ++i) {
float x = (float)(60 * Math.Sin (i * 4 * Math.PI / 5));
float y = (float)(60 * Math.Cos (i * 4 * Math.PI / 5));
context.AddLineToPoint (center.X + x, center.Y + y);
}
// Closing the path connects the current point to the start of the current path.
context.ClosePath ();
// And stroke the path
context.StrokePath ();
// Draw a Star filled
center = new CGPoint (90, 210);
context.MoveTo (center.X, center.Y + 60);
for (int i = 1; i < 5; ++i) {
float x = (float)(60 * Math.Sin (i * 4 * Math.PI / 5));
float y = (float)(60 * Math.Cos (i * 4 * Math.PI / 5));
context.AddLineToPoint (center.X + x, center.Y + y);
}
// Closing the path connects the current point to the start of the current path.
context.ClosePath ();
// Use the winding-rule fill mode.
context.FillPath ();
// Draw a Star filled
center = new CGPoint (90, 330);
context.MoveTo (center.X, center.Y + 60);
for (int i = 1; i < 5; ++i) {
float x = (float)(60 * Math.Sin (i * 4 * Math.PI / 5));
float y = (float)(60 * Math.Cos (i * 4 * Math.PI / 5));
context.AddLineToPoint (center.X + x, center.Y + y);
}
// Closing the path connects the current point to the start of the current path.
context.ClosePath ();
// Use the even-odd fill mode.
context.EOFillPath ();
// Draw a Hexagon stroked
center = new CGPoint (210, 90);
context.MoveTo (center.X, center.Y + 60);
for (int i = 1; i < 6; ++i) {
float x = (float)(60 * Math.Sin (i * 2 * Math.PI / 6));
float y = (float)(60 * Math.Cos (i * 2 * Math.PI / 6));
context.AddLineToPoint (center.X + x, center.Y + y);
}
// Closing the path connects the current point to the start of the current path.
context.ClosePath ();
// And stroke the path
context.StrokePath ();
// Draw a Hexagon stroked & filled
center = new CGPoint (210, 240);
context.MoveTo (center.X, center.Y + 60);
for (int i = 1; i < 6; ++i) {
float x = (float)(60 * Math.Sin (i * 2 * Math.PI / 6));
float y = (float)(60 * Math.Cos (i * 2 * Math.PI / 6));
context.AddLineToPoint (center.X + x, center.Y + y);
}
// Closing the path connects the current point to the start of the current path.
context.ClosePath ();
// Use the winding-rule fill mode, and stroke the path after.
context.DrawPath (CGPathDrawingMode.FillStroke);
}
}
| 32.931818 | 93 | 0.645963 |
[
"MIT"
] |
Art-Lav/ios-samples
|
QuartzSample/PolyDrawing.cs
| 4,347 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Windows.Forms
{
/// <summary>
/// Delegate to the WebBrowser Navigated event.
/// </summary>
public delegate void WebBrowserNavigatedEventHandler(object sender, WebBrowserNavigatedEventArgs e);
}
| 36.166667 | 104 | 0.746544 |
[
"MIT"
] |
ArrowCase/winforms
|
src/System.Windows.Forms/src/System/Windows/Forms/WebBrowserNavigatedEventHandler.cs
| 436 |
C#
|
using System;
using System.Threading;
namespace LogJoint
{
public static class IsBrowser
{
static Lazy<bool> value = new Lazy<bool>(() =>
{
var os = System.Runtime.InteropServices.RuntimeInformation.OSDescription;
return os == "web" || os == "Browser";
}, LazyThreadSafetyMode.PublicationOnly);
public static bool Value => value.Value;
}
}
| 24.117647 | 85 | 0.619512 |
[
"MIT"
] |
rkapl123/logjoint
|
trunk/model/generic/IsBrowser.cs
| 410 |
C#
|
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Text;
namespace Equinox.Infra.CrossCutting.Identity.Models.ManageViewModels
{
public class ManageLoginsViewModel
{
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationScheme> OtherLogins { get; set; }
}
}
| 25.5 | 69 | 0.762255 |
[
"MIT"
] |
duyxaoke/DEV
|
src/Equinox.Infra.CrossCutting.Identity/Models/ManageViewModels/ManageLoginsViewModel.cs
| 410 |
C#
|
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Numerics;
using System.Windows.Forms;
using ImGuiNET;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using T3.Core;
using T3.Core.Logging;
using T3.Gui.UiHelpers;
namespace T3.Gui.InputUi
{
public class StringInputUi : InputValueUi<string>
{
private const int MAX_STRING_LENGTH = 4000;
public enum UsageType
{
Default,
FilePath,
DirectoryPath,
Multiline,
}
public UsageType Usage { get; set; } = UsageType.Default;
public override IInputUi Clone()
{
return new StringInputUi
{
InputDefinition = InputDefinition,
Parent = Parent,
PosOnCanvas = PosOnCanvas,
Relevancy = Relevancy,
Size = Size,
Usage = Usage
};
}
protected override InputEditStateFlags DrawEditControl(string name, ref string value)
{
if (value == null)
{
// value was null!
ImGui.TextUnformatted(name + " is null?!");
return InputEditStateFlags.Nothing;
}
InputEditStateFlags inputEditStateFlags = InputEditStateFlags.Nothing;
switch (Usage)
{
case UsageType.Default:
inputEditStateFlags = DrawDefaultTextEdit(ref value);
break;
case UsageType.Multiline:
inputEditStateFlags = DrawMultilineTextEdit(ref value);
break;
case UsageType.FilePath:
inputEditStateFlags = DrawEditWithSelectors(FileOperations.FilePickerTypes.File, ref value);
break;
case UsageType.DirectoryPath:
inputEditStateFlags = DrawEditWithSelectors(FileOperations.FilePickerTypes.Folder, ref value);
break;
}
inputEditStateFlags |= ImGui.IsItemClicked() ? InputEditStateFlags.Started : InputEditStateFlags.Nothing;
inputEditStateFlags |= ImGui.IsItemDeactivatedAfterEdit() ? InputEditStateFlags.Finished : InputEditStateFlags.Nothing;
return inputEditStateFlags;
}
private static InputEditStateFlags DrawEditWithSelectors(FileOperations.FilePickerTypes type, ref string value)
{
ImGui.SetNextItemWidth(-70);
var inputEditStateFlags = DrawDefaultTextEdit(ref value);
if (ImGui.IsItemHovered() && ImGui.CalcTextSize(value).X > ImGui.GetItemRectSize().X)
{
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.One*5);
ImGui.BeginTooltip();
ImGui.TextUnformatted(value);
ImGui.EndTooltip();
ImGui.PopStyleVar();
}
ImGui.SameLine();
var modifiedByPicker = FileOperations.DrawFileSelector(type, ref value);
if (modifiedByPicker)
{
inputEditStateFlags = InputEditStateFlags.Modified | InputEditStateFlags.Finished;
}
return inputEditStateFlags;
}
private static InputEditStateFlags DrawDefaultTextEdit(ref string value)
{
bool changed = ImGui.InputText("##textEdit", ref value, MAX_STRING_LENGTH);
return changed ? InputEditStateFlags.Modified : InputEditStateFlags.Nothing;
}
private static InputEditStateFlags DrawMultilineTextEdit(ref string value)
{
ImGui.Dummy(new Vector2(1,1));
var changed = ImGui.InputTextMultiline("##textEdit", ref value, MAX_STRING_LENGTH, new Vector2(-1, 150));
return changed ? InputEditStateFlags.Modified : InputEditStateFlags.Nothing;
}
protected override void DrawReadOnlyControl(string name, ref string value)
{
if (value != null)
{
ImGui.InputText(name, ref value, MAX_STRING_LENGTH, ImGuiInputTextFlags.ReadOnly);
}
else
{
string nullString = "<null>";
ImGui.InputText(name, ref nullString, MAX_STRING_LENGTH, ImGuiInputTextFlags.ReadOnly);
}
}
public override void DrawSettings()
{
base.DrawSettings();
Type enumType = typeof(UsageType);
var values = Enum.GetValues(enumType);
var valueNames = new string[values.Length];
for (int i = 0; i < values.Length; i++)
{
valueNames[i] = Enum.GetName(typeof(UsageType), values.GetValue(i));
}
int index = (int)Usage;
ImGui.Combo("##dropDownStringUsage", ref index, valueNames, valueNames.Length);
Usage = (UsageType)index;
ImGui.SameLine();
ImGui.TextUnformatted("Usage");
}
public override void Write(JsonTextWriter writer)
{
base.Write(writer);
writer.WriteObject("Usage", Usage.ToString());
}
public override void Read(JToken inputToken)
{
base.Read(inputToken);
Usage = (UsageType)Enum.Parse(typeof(UsageType), inputToken["Usage"].Value<string>());
}
}
}
| 34.228395 | 131 | 0.572768 |
[
"MIT"
] |
still-scene/t3
|
T3/Gui/InputUi/StringInputUi.cs
| 5,547 |
C#
|
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the dynamodb-2012-08-10.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.DynamoDBv2.Model
{
/// <summary>
/// Container for the parameters to the DescribeGlobalTable operation.
/// Returns information about the specified global table.
///
/// <note>
/// <para>
/// This operation only applies to <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V1.html">Version
/// 2017.11.29</a> of global tables. If you are using global tables <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/globaltables.V2.html">Version
/// 2019.11.21</a> you can use <a href="https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_DescribeTable.html">DescribeTable</a>
/// instead.
/// </para>
/// </note>
/// </summary>
public partial class DescribeGlobalTableRequest : AmazonDynamoDBRequest
{
private string _globalTableName;
/// <summary>
/// Gets and sets the property GlobalTableName.
/// <para>
/// The name of the global table.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=3, Max=255)]
public string GlobalTableName
{
get { return this._globalTableName; }
set { this._globalTableName = value; }
}
// Check to see if GlobalTableName property is set
internal bool IsSetGlobalTableName()
{
return this._globalTableName != null;
}
}
}
| 34.75 | 175 | 0.671181 |
[
"Apache-2.0"
] |
DetlefGolze/aws-sdk-net
|
sdk/src/Services/DynamoDBv2/Generated/Model/DescribeGlobalTableRequest.cs
| 2,363 |
C#
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Internal;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using OrchardCore.BackgroundTasks;
using OrchardCore.Modules;
using OrchardCore.Modules.Manifest;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using Tubumu.Core.Extensions;
using Tubumu.Modules.Framework.Application.Services;
using Tubumu.Modules.Framework.Authorization;
using Tubumu.Modules.Framework.BackgroundTasks;
using Tubumu.Modules.Framework.Extensions;
using Tubumu.Modules.Framework.Mappings;
using Tubumu.Modules.Framework.Models;
using Tubumu.Modules.Framework.SignalR;
using Tubumu.Modules.Framework.Swagger;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment;
namespace Tubumu.Modules.Framework
{
/// <summary>
/// Startup
/// </summary>
public class Startup : StartupBase
{
private readonly IConfiguration _configuration;
private readonly IHostingEnvironment _environment;
private readonly ILogger<Startup> _logger;
/// <summary>
/// Constructor
/// </summary>
/// <param name="configuration"></param>
/// <param name="environment"></param>
/// <param name="logger"></param>
public Startup(
IConfiguration configuration,
IHostingEnvironment environment,
ILogger<Startup> logger)
{
_configuration = configuration;
_environment = environment;
_logger = logger;
}
/// <summary>
/// ConfigureServices
/// </summary>
/// <param name="services"></param>
public override void ConfigureServices(IServiceCollection services)
{
// Background Service
services.AddSingleton<IBackgroundTask, IdleBackgroundTask>();
// Cache
services.AddDistributedRedisCache(options =>
{
options.Configuration = "localhost";
options.InstanceName = _environment.ApplicationName + ":";
});
services.AddMemoryCache();
// Cors
services.AddCors(options => options.AddPolicy("DefaultPolicy",
builder => builder.WithOrigins("http://localhost:9090", "http://localhost:8080").AllowAnyMethod().AllowAnyHeader().AllowCredentials())
// builder => builder.AllowAnyOrigin.AllowAnyMethod().AllowAnyHeader().AllowCredentials())
);
// Cookie
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false; // 需保持为 false, 否则 Web API 不会 Set-Cookie 。
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// Session
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(10);
options.Cookie.Name = ".Tubumu.Session";
options.Cookie.HttpOnly = true;
});
// HTTP Client
services.AddHttpClient();
// ApiBehaviorOptions
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = context => new OkObjectResult(new ApiResult
{
Code = 400,
Message = context.ModelState.FirstErrorMessage()
});
});
// Authentication
var registeredServiceDescriptor = services.FirstOrDefault(s => s.Lifetime == ServiceLifetime.Transient && s.ServiceType == typeof(IApplicationModelProvider) && s.ImplementationType == typeof(AuthorizationApplicationModelProvider));
if (registeredServiceDescriptor != null)
{
services.Remove(registeredServiceDescriptor);
}
services.AddTransient<IApplicationModelProvider, PermissionAuthorizationApplicationModelProvider>();
services.AddSingleton<ITokenService, TokenService>();
var tokenValidationSettings = _configuration.GetSection("TokenValidationSettings").Get<TokenValidationSettings>();
services.AddSingleton(tokenValidationSettings);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidIssuer = tokenValidationSettings.ValidIssuer,
ValidateIssuer = true,
ValidAudience = tokenValidationSettings.ValidAudience,
ValidateAudience = true,
IssuerSigningKey = SignatureHelper.GenerateSigningKey(tokenValidationSettings.IssuerSigningKey),
ValidateIssuerSigningKey = tokenValidationSettings.ValidateLifetime,
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(tokenValidationSettings.ClockSkewSeconds),
};
// We have to hook the OnMessageReceived event in order to
// allow the JWT authentication handler to read the access
// token from the query string when a WebSocket or
// Server-Sent Events request comes in.
options.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
// If the request is for our hub...
var path = context.HttpContext.Request.Path;
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/hubs"))
{
// Read the token out of the query string
context.Token = accessToken;
}
return Task.CompletedTask;
},
OnAuthenticationFailed = context =>
{
_logger.LogError($"Authentication Failed(OnAuthenticationFailed): {context.Request.Path} Error: {context.Exception}");
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
},
OnChallenge = context =>
{
_logger.LogError($"Authentication Challenge(OnChallenge): {context.Request.Path}");
// TODO: (alby)为不同客户端返回不同的内容
var result = new ApiResultUrl()
{
Code = 400,
Message = "Authentication Challenge",
Url = _environment.IsProduction() ? tokenValidationSettings.LoginUrl : null,
};
var body = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result));
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
context.Response.ContentType = "application/json";
context.Response.Body.Write(body, 0, body.Length);
context.HandleResponse();
return Task.CompletedTask;
}
};
});
// JSON Date format
void JsonSetup(MvcJsonOptions options) => options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
services.Configure((Action<MvcJsonOptions>)JsonSetup);
// SignalR
services.AddSignalR();
services.Replace(ServiceDescriptor.Singleton(typeof(IUserIdProvider), typeof(NameUserIdProvider)));
// AutoMapper
services.AddAutoMapper();
Initalizer.Initialize();
// Swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = _environment.ApplicationName + " API", Version = "v1" });
c.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description = "权限认证(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = "header",
Type = "apiKey"
});
var security = new Dictionary<string, IEnumerable<string>>
{
{"Bearer", new string[] { }},
};
c.AddSecurityRequirement(security);
c.DescribeAllEnumsAsStrings();
c.DocumentFilter<HiddenApiDocumentFilter>();
IncludeXmlCommentsForModules(c);
c.OrderActionsBy(m => m.ActionDescriptor.DisplayName);
});
}
/// <summary>
/// Configure
/// </summary>
/// <param name="app"></param>
/// <param name="routes"></param>
/// <param name="serviceProvider"></param>
public override void Configure(IApplicationBuilder app, IRouteBuilder routes, IServiceProvider serviceProvider)
{
app.UseCookiePolicy();
app.UseSession();
app.UseCors("DefaultPolicy");
app.UseAuthentication();
// Swagger
var swaggerIndexAssembly = typeof(Startup).Assembly;
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", _environment.ApplicationName + " API v1");
c.DefaultModelsExpandDepth(-1);
c.IndexStream = () => swaggerIndexAssembly.GetManifestResourceStream(swaggerIndexAssembly.GetName().Name + ".Swagger>Tubumu.SwaggerUI.Index.html");
});
}
private void IncludeXmlCommentsForModules(SwaggerGenOptions swaggerGenOptions)
{
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var assembly = Assembly.Load(new AssemblyName(_environment.ApplicationName));
var moduleNames = assembly.GetCustomAttributes<ModuleNameAttribute>().Select(m => m.Name);
moduleNames.ForEach(m =>
{
var commentsFileName = m + ".XML";
var commentsFilePath = Path.Combine(baseDirectory, commentsFileName);
swaggerGenOptions.IncludeAuthorizationXmlComments(commentsFilePath);
});
}
}
}
| 43.251852 | 243 | 0.574927 |
[
"MIT"
] |
zhaoyanwenqi/Tubumu
|
src/Tubumu.Modules.Framework/Startup.cs
| 11,764 |
C#
|
//
// System.Web.Services.Description.SoapBodyBinding.cs
//
// Author:
// Tim Coleman ([email protected])
//
// Copyright (C) Tim Coleman, 2002
//
//
// 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.ComponentModel;
using System.Web.Services.Configuration;
using System.Xml.Serialization;
namespace System.Web.Services.Description {
[XmlFormatExtension ("body", "http://schemas.xmlsoap.org/wsdl/soap/", typeof (InputBinding), typeof (OutputBinding), typeof (MimePart))]
public class SoapBodyBinding : ServiceDescriptionFormatExtension {
#region Fields
string encoding;
string ns;
string[] parts;
string partsString;
SoapBindingUse use;
#endregion // Fields
#region Constructors
public SoapBodyBinding ()
{
encoding = String.Empty;
ns = String.Empty;
parts = null;
partsString = null;
use = SoapBindingUse.Default;
}
#endregion // Constructors
#region Properties
[DefaultValue ("")]
[XmlAttribute ("encodingStyle")]
public string Encoding {
get { return encoding; }
set { encoding = value; }
}
[DefaultValue ("")]
[XmlAttribute ("namespace")]
public string Namespace {
get { return ns; }
set { ns = value; }
}
[XmlIgnore]
public string[] Parts {
get { return parts; }
set {
parts = value;
if (value == null)
partsString = null;
else
partsString = String.Join(" ", value);
}
}
[XmlAttribute ("parts")]
public string PartsString {
get { return partsString; }
set {
partsString = value;
if (value == null)
parts = null;
else
parts = value.Split(' ');
}
}
[DefaultValue (SoapBindingUse.Default)]
[XmlAttribute ("use")]
public SoapBindingUse Use {
get { return use; }
set { use = value; }
}
#endregion // Properties
}
}
| 25.401786 | 137 | 0.691388 |
[
"Apache-2.0"
] |
121468615/mono
|
mcs/class/System.Web.Services/System.Web.Services.Description/SoapBodyBinding.cs
| 2,845 |
C#
|
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Double;
using System;
using System.IO;
using UnityEngine;
public class NeuralNetwork
{
private System.Random random = new System.Random(123);
private int[] layers;
private Matrix<double>[] nodes;
private Matrix<double>[] weights;
private Matrix<double>[] bias;
public NeuralNetwork(int[] layers)
{
this.layers = layers;
nodes = new Matrix<double>[layers.Length];
weights = new Matrix<double>[layers.Length - 1];
bias = new Matrix<double>[layers.Length];
// Initialize layers with random values from normal distribution
for (int i = 0; i < layers.Length; i++)
{
nodes[i] = DenseMatrix.Build.Random(layers[i], 1);
bias[i] = DenseMatrix.Build.Random(layers[i], 1);
if (i < layers.Length - 1)
{
weights[i] = DenseMatrix.Build.Random(layers[i + 1], layers[i]);
}
}
}
public Matrix<double> feed(Matrix<double> input)
{
if (layers[0] != input.RowCount)
{
Debug.LogError("Input size does not match number of input nodes!");
Debug.LogError("Given " + input.RowCount + ", expected " + layers[0]);
return nodes[layers.Length - 1];
}
if (1 != input.ColumnCount)
{
Debug.LogError("Input size does not have only one column!");
Debug.LogError("Given " + input.ColumnCount + ", expected " + 1);
return nodes[layers.Length - 1];
}
nodes[0] = input;
for (int i = 1; i < layers.Length; i++)
{
nodes[i] = act(weights[i - 1] * nodes[i - 1] + bias[i]);
}
return nodes[layers.Length - 1];
}
public NeuralNetwork Copy()
{
NeuralNetwork n = new NeuralNetwork(layers);
for (int i = 0; i < weights.Length; i++)
{
weights[i].CopyTo(n.weights[i]);
}
for (int i = 0; i < bias.Length; i++)
{
bias[i].CopyTo(n.bias[i]);
}
return n;
}
private Matrix<double> act(Matrix<double> m)
{
return tanh(m);
}
// Activation functions
private Matrix<double> sigmoid(Matrix<double> m)
{
return 1 / (1 + Matrix.Exp(-m));
}
private Matrix<double> tanh(Matrix<double> m)
{
return Matrix.Tanh(m);
}
private Matrix<double> relu(Matrix<double> m)
{
return m.PointwiseMaximum(0);
}
private Matrix<double> leaky_relu(Matrix<double> m)
{
return m.PointwiseMaximum(0.1 * m);
}
public Matrix<double>[] GetWeights()
{
return weights;
}
public Matrix<double>[] GetBias()
{
return bias;
}
public void SetWeights(int i, Matrix<double> m)
{
weights[i] = m;
}
public void SetBias(int i, Matrix<double> m)
{
bias[i] = m;
}
public void saveToFile(string fileName)
{
using (TextWriter tw = new StreamWriter(fileName))
{
for (int w = 0; w < weights.Length; w++)
{
Matrix<double> matrix = weights[w];
for (int j = 0; j < matrix.ColumnCount; j++)
{
for (int i = 0; i < matrix.RowCount; i++)
{
if (i != 0)
{
tw.Write(" ");
}
tw.Write(matrix[i, j]);
}
tw.WriteLine();
}
if (w + 1 < weights.Length)
{
tw.Write("+");
tw.WriteLine();
}
}
tw.Write("b");
tw.WriteLine();
for (int w = 0; w < bias.Length; w++)
{
Matrix<double> matrix = bias[w];
for (int j = 0; j < matrix.ColumnCount; j++)
{
for (int i = 0; i < matrix.RowCount; i++)
{
if (i != 0)
{
tw.Write(" ");
}
tw.Write(matrix[i, j]);
}
tw.WriteLine();
}
if (w + 1 < bias.Length)
{
tw.Write("+");
tw.WriteLine();
}
}
}
}
public void loadFromFile(string fileName)
{
string all = File.ReadAllText(fileName);
string[] wb = all.Split(new string[] { "b\r\n" }, StringSplitOptions.None);
string[] w = wb[0].Split(new string[] { "+\r\n" }, StringSplitOptions.None);
string[] b = wb[1].Split(new string[] { "+\r\n" }, StringSplitOptions.None);
for(int wi = 0; wi < w.Length; wi++)
{
Matrix<double> weight = weights[wi];
string[] rows = w[wi].Split(new string[] { "\r\n" }, StringSplitOptions.None);
for(int i = 0; i < weight.ColumnCount; i++)
{
string[] row = rows[i].Split(' ');
for(int j = 0; j < weight.RowCount; j++)
{
weight[j, i] = double.Parse(row[j]);
}
}
}
for (int bi = 0; bi < b.Length; bi++)
{
Matrix<double> biasMatrix = bias[bi];
string[] rows = b[bi].Split(new string[] { "\r\n" }, StringSplitOptions.None);
for (int i = 0; i < biasMatrix.ColumnCount; i++)
{
string[] row = rows[i].Split(' ');
for (int j = 0; j < biasMatrix.RowCount; j++)
{
biasMatrix[j, i] = double.Parse(row[j]);
}
}
}
}
}
| 28.066038 | 90 | 0.448908 |
[
"MIT"
] |
JureBevc/genetic-neural-networks
|
Assets/GA/NeuralNetwork.cs
| 5,952 |
C#
|
using System.Xml.Serialization;
namespace Artillery.DataProcessor.ExportDto
{
[XmlType("Country")]
public class ExportCountryDto
{
[XmlAttribute("Country")]
public string CountryName { get; set; }
[XmlAttribute]
public string ArmySize { get; set; }
}
}
| 20.266667 | 47 | 0.638158 |
[
"MIT"
] |
Plamen-Angelov/Entity-Framework
|
Exam Preparation/Exam 16.12.2021/Artillery/DataProcessor/ExportDto/ExportCountryDto.cs
| 306 |
C#
|
using System.Threading.Tasks;
namespace Plus.Authorization
{
public class AlwaysAllowMethodInvocationAuthorizationService : IMethodInvocationAuthorizationService
{
public Task CheckAsync(MethodInvocationAuthorizationContext context)
{
return Task.CompletedTask;
}
}
}
| 26.416667 | 104 | 0.731861 |
[
"MIT"
] |
Meowv/Plus.Core
|
Plus.Core/Plus/Authorization/AlwaysAllowMethodInvocationAuthorizationService.cs
| 319 |
C#
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the glacier-2012-06-01.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.Glacier.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.Glacier.Model.Internal.MarshallTransformations
{
/// <summary>
/// GetVaultLock Request Marshaller
/// </summary>
public class GetVaultLockRequestMarshaller : IMarshaller<IRequest, GetVaultLockRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((GetVaultLockRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(GetVaultLockRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.Glacier");
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2012-06-01";
request.HttpMethod = "GET";
request.AddPathResource("{accountId}", publicRequest.IsSetAccountId() ? StringUtils.FromString(publicRequest.AccountId) : string.Empty);
if (!publicRequest.IsSetVaultName())
throw new AmazonGlacierException("Request object does not have required field VaultName set");
request.AddPathResource("{vaultName}", StringUtils.FromString(publicRequest.VaultName));
request.ResourcePath = "/{accountId}/vaults/{vaultName}/lock-policy";
return request;
}
private static GetVaultLockRequestMarshaller _instance = new GetVaultLockRequestMarshaller();
internal static GetVaultLockRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static GetVaultLockRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
}
| 35.647727 | 148 | 0.661779 |
[
"Apache-2.0"
] |
Hazy87/aws-sdk-net
|
sdk/src/Services/Glacier/Generated/Model/Internal/MarshallTransformations/GetVaultLockRequestMarshaller.cs
| 3,137 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Money
{
class Program
{
static void Main(string[] args)
{
int bitcoinsNumber = int.Parse(Console.ReadLine());
double yuansNumber = double.Parse(Console.ReadLine());
double commision = double.Parse(Console.ReadLine());
int bitcoin = 1168 * bitcoinsNumber;
double yuans = yuansNumber * 0.15;
double dollars = yuans * 1.76;
double euros = (bitcoin + dollars) / 1.95;
double result = euros - euros * commision / 100;
Console.WriteLine(result);
}
}
}
| 28.76 | 66 | 0.59388 |
[
"MIT"
] |
BorisLechev/Programming-Basics
|
Exams/7.07.16/Money/Program.cs
| 721 |
C#
|
using System.Collections.Generic;
using ETModel;
using UnityEngine;
namespace ETHotfix
{
[ObjectSystem]
public class UIComponentAwakeSystem : AwakeSystem<UIComponent>
{
public override void Awake(UIComponent self)
{
self.Camera = Component.Global.transform.Find("UICamera").gameObject;
}
}
/// <summary>
/// 管理所有UI
/// </summary>
public class UIComponent: Component
{
public GameObject Camera;
public Dictionary<string, UI> uis = new Dictionary<string, UI>();
public void Add(UI ui)
{
ui.GameObject.GetComponent<Canvas>().worldCamera = this.Camera.GetComponent<Camera>();
this.uis.Add(ui.Name, ui);
ui.Parent = this;
}
public void Remove(string name)
{
if (!this.uis.TryGetValue(name, out UI ui))
{
return;
}
this.uis.Remove(name);
ui.Dispose();
}
}
}
| 19.232558 | 89 | 0.678356 |
[
"MIT"
] |
FlameskyDexive/Battle-Of-Balls
|
Unity/Assets/Hotfix/Module/UI/UIComponent.cs
| 837 |
C#
|
using System;
using System.IO;
using System.Linq;
using CsvHelper.Configuration;
using ESFA.DC.EAS.Tests.Base.Models;
using FluentAssertions;
using Microsoft.VisualBasic.FileIO;
using Xunit;
namespace ESFA.DC.EAS.Tests.Base.Helpers
{
public static class TestCsvHelper
{
public static void CheckCsv(string csv, params CsvEntry[] csvEntries)
{
try
{
using (TextReader textReader = new StringReader(csv))
{
using (TextFieldParser textFieldParser = new TextFieldParser(textReader))
{
textFieldParser.TextFieldType = FieldType.Delimited;
textFieldParser.Delimiters = new[] { "," };
foreach (CsvEntry csvEntry in csvEntries)
{
string[] currentRow = textFieldParser.ReadFields();
CheckHeader(currentRow, csvEntry.Mapper);
for (int i = 0; i < csvEntry.DataRows; i++)
{
currentRow = textFieldParser.ReadFields();
CheckRow(currentRow, csvEntry.Mapper);
}
}
}
}
}
catch (Exception ex)
{
Assert.Null(ex);
}
}
private static void CheckRow(string[] currentRow, ClassMap classMap)
{
currentRow.Length.Should().Be(classMap.MemberMaps.Count);
}
private static void CheckHeader(string[] currentRow, ClassMap classMap)
{
string[] names = classMap.MemberMaps.OrderBy(x => x.Data.Index).Select(x => x.Data.Names[0]).ToArray();
currentRow.Should().BeEquivalentTo(names);
}
}
}
| 34.527273 | 115 | 0.507636 |
[
"MIT"
] |
SkillsFundingAgency/DC-EAS-2021
|
src/ESFA.DC.EAS.Tests.Base/Helpers/TestCsvHelper.cs
| 1,901 |
C#
|
using System.Collections.Generic;
namespace Groceriz.Common.TranslationsConfigurationProvider
{
public interface ITranslationsConfigurationRefresherProvider
{
/// <summary>
/// List of instances of <see cref="IConfigurationRefresher"/> for App Configuration.
/// </summary>
IEnumerable<ITranslationsConfigurationRefresher> Refreshers { get; }
}
}
| 30.153846 | 93 | 0.719388 |
[
"Apache-2.0"
] |
mattletw/I18Next.Net
|
Groceriz.Common.TranslationsConfigurationProvider/ITranslationsConfigurationRefresherProvider.cs
| 392 |
C#
|
namespace GearSharp
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.inputOriginalSize = new System.Windows.Forms.TextBox();
this.inputNewSize = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.inputRatio = new System.Windows.Forms.TextBox();
this.outputNewRatio = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.ResetButton = new System.Windows.Forms.Button();
this.label5 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// inputOriginalSize
//
this.inputOriginalSize.Location = new System.Drawing.Point(26, 32);
this.inputOriginalSize.Name = "inputOriginalSize";
this.inputOriginalSize.Size = new System.Drawing.Size(100, 20);
this.inputOriginalSize.TabIndex = 0;
this.inputOriginalSize.TextChanged += new System.EventHandler(this.inputOriginalSize_TextChanged);
//
// inputNewSize
//
this.inputNewSize.Location = new System.Drawing.Point(26, 63);
this.inputNewSize.Name = "inputNewSize";
this.inputNewSize.Size = new System.Drawing.Size(100, 20);
this.inputNewSize.TabIndex = 3;
this.inputNewSize.TextChanged += new System.EventHandler(this.textBox3_TextChanged);
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(132, 35);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(127, 13);
this.label1.TabIndex = 4;
this.label1.Text = "Original Tire Size (Inches)";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.label1.Click += new System.EventHandler(this.label1_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(132, 66);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(73, 13);
this.label2.TabIndex = 5;
this.label2.Text = "New Tire Size";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.label2.Click += new System.EventHandler(this.label2_Click);
//
// inputRatio
//
this.inputRatio.Location = new System.Drawing.Point(26, 94);
this.inputRatio.Name = "inputRatio";
this.inputRatio.Size = new System.Drawing.Size(100, 20);
this.inputRatio.TabIndex = 6;
this.inputRatio.TextChanged += new System.EventHandler(this.textBox2_TextChanged);
//
// outputNewRatio
//
this.outputNewRatio.Location = new System.Drawing.Point(48, 209);
this.outputNewRatio.Name = "outputNewRatio";
this.outputNewRatio.ReadOnly = true;
this.outputNewRatio.Size = new System.Drawing.Size(100, 20);
this.outputNewRatio.TabIndex = 7;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(132, 97);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(95, 13);
this.label3.TabIndex = 8;
this.label3.Text = "Current Gear Ratio";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.label3.Click += new System.EventHandler(this.label3_Click);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(154, 212);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(83, 13);
this.label4.TabIndex = 9;
this.label4.Text = "New Gear Ratio";
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// button1
//
this.button1.Location = new System.Drawing.Point(64, 180);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 10;
this.button1.Text = "Calculate!";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// ResetButton
//
this.ResetButton.BackColor = System.Drawing.Color.IndianRed;
this.ResetButton.Location = new System.Drawing.Point(146, 180);
this.ResetButton.Name = "ResetButton";
this.ResetButton.Size = new System.Drawing.Size(75, 23);
this.ResetButton.TabIndex = 11;
this.ResetButton.Text = "Reset";
this.ResetButton.UseVisualStyleBackColor = false;
this.ResetButton.Click += new System.EventHandler(this.buttonReset_Click);
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(23, 9);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(240, 13);
this.label5.TabIndex = 13;
this.label5.Text = "Instructions: fill out the fields then click calculate. ";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.label5);
this.Controls.Add(this.ResetButton);
this.Controls.Add(this.button1);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.outputNewRatio);
this.Controls.Add(this.inputRatio);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.inputNewSize);
this.Controls.Add(this.inputOriginalSize);
this.Name = "Form1";
this.Text = "GearSharp";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox inputOriginalSize;
private System.Windows.Forms.TextBox inputNewSize;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox inputRatio;
private System.Windows.Forms.TextBox outputNewRatio;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button ResetButton;
private System.Windows.Forms.Label label5;
}
}
| 43.845745 | 110 | 0.58025 |
[
"MIT"
] |
jadelgre/GearSharp
|
GearSharp/Form1.Designer.cs
| 8,245 |
C#
|
using Microsoft.AspNetCore.Components;
using System.Text;
namespace BlazorDesk.Components
{
public static class col
{
public static FluentColumn _ { get { return new FluentColumn(""); } }
public static FluentColumn xs { get { return new FluentColumn("-xs"); } }
public static FluentColumn sm { get { return new FluentColumn("-sm"); } }
public static FluentColumn md { get { return new FluentColumn("-md"); } }
public static FluentColumn lg { get { return new FluentColumn("-lg"); } }
public static FluentColumn xl { get { return new FluentColumn("-xl"); } }
public static FluentColumn _1 { get { return new FluentColumn("-1"); } }
public static FluentColumn _2 { get { return new FluentColumn("-2"); } }
public static FluentColumn _3 { get { return new FluentColumn("-3"); } }
public static FluentColumn _4 { get { return new FluentColumn("-4"); } }
public static FluentColumn _5 { get { return new FluentColumn("-5"); } }
public static FluentColumn _6 { get { return new FluentColumn("-6"); } }
public static FluentColumn _7 { get { return new FluentColumn("-7"); } }
public static FluentColumn _8 { get { return new FluentColumn("-8"); } }
public static FluentColumn _9 { get { return new FluentColumn("-9"); } }
public static FluentColumn _10 { get { return new FluentColumn("-10"); } }
public static FluentColumn _11 { get { return new FluentColumn("-11"); } }
public static FluentColumn _12 { get { return new FluentColumn("-12"); } }
public static FluentColumn auto{ get { return new FluentColumn("-auto"); } }
public static FluentColumn w25 { get { return new FluentColumn("w-25", ""); } }
public static FluentColumn w50 { get { return new FluentColumn("w-50", ""); } }
public static FluentColumn w75 { get { return new FluentColumn("w-75", ""); } }
public static FluentColumn w100 { get { return new FluentColumn("w-100", ""); } }
//public static FluentColumn connectedSortable { get { return new FluentColumn(" .connectedSortable", ""); } }
}
public partial class Column
{
[Parameter]
public object Classes {
get
{
return classes;
} set
{
classes = value.ToString();
}
}
public string classes { get; set; } = "";
[Parameter]
public RenderFragment ChildContent { get; set; }
}
public class FluentClass
{
public override string ToString()
{
return _class.ToString();
}
internal StringBuilder _class { get; set; }
}
public class FluentColumn : FluentClass
{
public FluentColumn(string s, string col="col")
{
this._class = new StringBuilder();
_class.Append(col + s);
}
public FluentColumn()
{
this._class = new StringBuilder();
_class.Append("col");
}
public FluentColumn(FluentClass root)
{
this._class = root._class;
}
public FluentColumn xs { get { _class.Append("-xs"); return new FluentColumn(this); } }
public FluentColumn sm { get { _class.Append("-sm"); return new FluentColumn(this); } }
public FluentColumn md { get { _class.Append("-md"); return new FluentColumn(this); } }
public FluentColumn lg { get { _class.Append("-lg"); return new FluentColumn(this); } }
public FluentColumn xl { get { _class.Append("-xl"); return new FluentColumn(this); } }
public FluentColumn none { get { _class.Append(""); return new FluentColumn(this); } }
public FluentColumn _1 { get { _class.Append("-1"); return new FluentColumn(this); } }
public FluentColumn _2 { get { _class.Append("-2"); return new FluentColumn(this); } }
public FluentColumn _3 { get { _class.Append("-3"); return new FluentColumn(this); } }
public FluentColumn _4 { get { _class.Append("-4"); return new FluentColumn(this); } }
public FluentColumn _5 { get { _class.Append("-5"); return new FluentColumn(this); } }
public FluentColumn _6 { get { _class.Append("-6"); return new FluentColumn(this); } }
public FluentColumn _7 { get { _class.Append("-7"); return new FluentColumn(this); } }
public FluentColumn _8 { get { _class.Append("-8"); return new FluentColumn(this); } }
public FluentColumn _9 { get { _class.Append("-9"); return new FluentColumn(this); } }
public FluentColumn _10 { get { _class.Append("-10"); return new FluentColumn(this); } }
public FluentColumn _11 { get { _class.Append("-11"); return new FluentColumn(this); } }
public FluentColumn _12 { get { _class.Append("-12"); return new FluentColumn(this); } }
public FluentColumn auto { get { _class.Append("-auto"); return new FluentColumn(this); } }
public FluentColumn col { get { _class.Append(" col"); return new FluentColumn(this); } }
//public FluentColumn connectedSortable { get { _class.Append(" .connectedSortable"); return new FluentColumn(this); } }
}
}
| 47.990909 | 128 | 0.606933 |
[
"MIT"
] |
grammyleung/BlazorDesk
|
src/BlazorDesk/BlazorDesk.Components/Layout/Column.razor.cs
| 5,281 |
C#
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace abc_bank
{
public class Account
{
public const int CHECKING = 0;
public const int SAVINGS = 1;
public const int MAXI_SAVINGS = 2;
private readonly int accountType;
public List<Transaction> transactions;
public Account(int accountType)
{
this.accountType = accountType;
this.transactions = new List<Transaction>();
}
public void Deposit(double amount)
{
if (amount <= 0) {
throw new ArgumentException("amount must be greater than zero");
} else {
transactions.Add(new Transaction(amount));
}
}
public void Withdraw(double amount)
{
if (amount <= 0) {
throw new ArgumentException("amount must be greater than zero");
} else {
transactions.Add(new Transaction(-amount));
}
}
public double InterestEarned()
{
double amount = sumTransactions();
switch(accountType){
case SAVINGS:
if (amount <= 1000)
return amount * 0.001;
else
return 1 + (amount-1000) * 0.002;
// case SUPER_SAVINGS:
// if (amount <= 4000)
// return 20;
case MAXI_SAVINGS:
var withdraws = transactions.Where(x => x.amount < 0);
if (withdraws.Count() == 0)
return amount * 0.05;
DateTime lastTrans = withdraws.Last().transactionDate;
if (DateTime.Today.Subtract(lastTrans).Days < 10)
return amount * 0.001;
else
return amount * 0.05;
default:
return amount * 0.001;
}
}
public double sumTransactions() {
return CheckIfTransactionsExist(true);
}
private double CheckIfTransactionsExist(bool checkAll)
{
double amount = 0.0;
foreach (Transaction t in transactions)
amount += t.amount;
return amount;
}
public int GetAccountType()
{
return accountType;
}
}
}
| 28.75 | 80 | 0.486166 |
[
"Apache-2.0"
] |
joselarabo/AbcBankCSharpInterview
|
abc-bank/Account.cs
| 2,532 |
C#
|
using System;
using Xms.Core.Context;
using Xms.Core.Data;
namespace Xms.File
{
public interface IAttachmentFinder
{
Entity FindById(Guid id);
PagedList<Entity> QueryPaged(int page, int pageSize, Guid entityId, Guid objectId);
}
}
| 20.076923 | 91 | 0.693487 |
[
"MIT"
] |
861191244/xms
|
Libraries/File/Xms.File/IAttachmentFinder.cs
| 263 |
C#
|
using Fluky.Types;
namespace Fluky
{
public class FirstName
{
public FirstName()
{
}
public FirstName(string name, GenderType genderType)
{
Name = name;
GenderType = genderType;
}
public string Name { get; set; }
public GenderType GenderType { get; set; }
}
}
| 14.952381 | 56 | 0.60828 |
[
"MIT"
] |
EmphaticFist/Fluky
|
src/Fluky/FirstName.cs
| 316 |
C#
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics.Arm\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void Not_Vector64_Int64()
{
var test = new SimpleUnaryOpTest__Not_Vector64_Int64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (AdvSimd.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__Not_Vector64_Int64
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int64[] inArray1, Int64[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int64>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int64>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int64, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector64<Int64> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref testStruct._fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__Not_Vector64_Int64 testClass)
{
var result = AdvSimd.Not(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__Not_Vector64_Int64 testClass)
{
fixed (Vector64<Int64>* pFld1 = &_fld1)
{
var result = AdvSimd.Not(
AdvSimd.LoadVector64((Int64*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 8;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Int64>>() / sizeof(Int64);
private static Int64[] _data1 = new Int64[Op1ElementCount];
private static Vector64<Int64> _clsVar1;
private Vector64<Int64> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__Not_Vector64_Int64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
}
public SimpleUnaryOpTest__Not_Vector64_Int64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Int64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt64(); }
_dataTable = new DataTable(_data1, new Int64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Not(
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Not(
AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Not), new Type[] { typeof(Vector64<Int64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Not), new Type[] { typeof(Vector64<Int64>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Int64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Not(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector64<Int64>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Not(
AdvSimd.LoadVector64((Int64*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector64<Int64>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Not(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector64((Int64*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Not(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__Not_Vector64_Int64();
var result = AdvSimd.Not(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__Not_Vector64_Int64();
fixed (Vector64<Int64>* pFld1 = &test._fld1)
{
var result = AdvSimd.Not(
AdvSimd.LoadVector64((Int64*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Not(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector64<Int64>* pFld1 = &_fld1)
{
var result = AdvSimd.Not(
AdvSimd.LoadVector64((Int64*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Not(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Not(
AdvSimd.LoadVector64((Int64*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector64<Int64> op1, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Int64[] inArray1 = new Int64[Op1ElementCount];
Int64[] outArray = new Int64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Int64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Int64>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (var i = 0; i < RetElementCount; i++)
{
if (Helpers.Not(firstOp[i]) != result[i])
{
succeeded = false;
break;
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Not)}<Int64>(Vector64<Int64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| 37.308163 | 185 | 0.570264 |
[
"MIT"
] |
06needhamt/runtime
|
src/coreclr/tests/src/JIT/HardwareIntrinsics/Arm/AdvSimd/Not.Vector64.Int64.cs
| 18,281 |
C#
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChunkGenerator : MonoBehaviour
{
// Start is called before the first frame update
public GameObject[] chunks = new GameObject[4];
private int position = 50;
private int spawn = 400;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
position = position + 100;
this.transform.position = new Vector3(0, 0, position);
GameObject clone = (GameObject)Instantiate(chunks[Random.Range(0,chunks.Length)], new Vector3(0, 0, spawn),Quaternion.identity);
spawn = spawn + 100;
Destroy(clone, 15.0f);
}
}
| 22.823529 | 136 | 0.631443 |
[
"MIT"
] |
XP-Mr-Robot/Endless-Runner
|
Assets/_Game/Scripts/ChunkGenerator.cs
| 778 |
C#
|
// -----------------------------------------------------------------------
// <copyright file="LighthouseService.cs" company="Petabridge, LLC">
// Copyright (C) 2015 - 2019 Petabridge, LLC <https://petabridge.com>
// </copyright>
// -----------------------------------------------------------------------
using System.Threading.Tasks;
using Akka.Actor;
namespace Lighthouse
{
public class LighthouseService
{
private ActorSystem _lighthouseSystem;
/// <summary>
/// Task completes once the Lighthouse <see cref="ActorSystem" /> has terminated.
/// </summary>
/// <remarks>
/// Doesn't actually invoke termination. Need to call <see cref="StopAsync" /> for that.
/// </remarks>
public Task TerminationHandle => _lighthouseSystem.WhenTerminated;
public void Start()
{
_lighthouseSystem = LighthouseHostFactory.LaunchLighthouse();
}
public async Task StopAsync()
{
await CoordinatedShutdown.Get(_lighthouseSystem).Run();
}
}
}
| 32.058824 | 100 | 0.533945 |
[
"Apache-2.0"
] |
izavala/Cluster.WebCrawler
|
src/Lighthouse/LighthouseService.cs
| 1,092 |
C#
|
namespace eWAY.Rapid.Internals.Response
{
internal class Direct3DSecureEnrollResponse : BaseResponse
{
public string Default3dsUrl { get; set; }
public long TraceId { get; set; }
public string AccessCode { get; set; }
}
}
| 25.9 | 62 | 0.656371 |
[
"MIT"
] |
CareerHub/eway-rapid-net
|
eWAY.Rapid/Internals/Response/Direct3DSecureEnrollResponse.cs
| 261 |
C#
|
using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Vector2 = Catalyst.Engine.Utilities.Vector2;
using Vector3 = Catalyst.Engine.Utilities.Vector3;
using Vector4 = Catalyst.Engine.Utilities.Vector4;
using Color = Catalyst.Engine.Utilities.Color;
using Rectangle = Catalyst.Engine.Utilities.Rectangle;
namespace Catalyst.Engine.Rendering
{
[Serializable]
public class Particle
{
public bool Active { get; internal set; }
public Vector2 Position { get; internal set; }
public Vector2 Velocity
{
get
{
if (Mode == VelocityMode.RecalculateAngle)
{
return new Vector2((float)(Speed * Math.Cos(Angle * Math.PI / 180)), (float)(-Speed * Math.Sin(Angle * Math.PI / 180)));
}
else
{
return _velocity;
}
}
internal set { _velocity = value; }
}
private Vector2 _velocity;
public VelocityMode Mode { get; internal set; }
public int Life { get; internal set; }
public int LifeStart { get; internal set; }
public double Speed { get; internal set; }
public double Angle { get; internal set; }
public Color StartColor { get; internal set; }
public Color EndColor { get; internal set; }
public Color Color
{
get
{
return Color.Lerp(StartColor, EndColor, (float)(LifeStart - Life) / (float)LifeStart);
}
}
public float StartAlpha { get; internal set; }
public float EndAlpha { get; internal set; }
public float Alpha
{
get
{
return MathHelper.Lerp(StartAlpha, EndAlpha, (float)(LifeStart - Life) / (float)LifeStart);
}
}
public enum VelocityMode
{
Linear,
RecalculateAngle
}
public Particle(ParticleEmitter emitter)
{
this.Active = false;
}
public void Reset(ParticleEmitter emitter)
{
this.Active = true;
this.Position = emitter.Position + new Vector2(emitter.Rand.Next((int)-emitter.PositionVariance.X, (int)emitter.PositionVariance.X), emitter.Rand.Next((int)-emitter.PositionVariance.Y, (int)emitter.PositionVariance.Y)) + emitter.Offset;
this.Life = emitter.Rand.Next(emitter.Life - emitter.LifeVariance, emitter.Life + emitter.LifeVariance);
this.LifeStart = this.Life;
double min = (emitter.Angle * 180 / Math.PI) - emitter.Rand.NextDouble()*(emitter.AngleVariance * 180 / Math.PI);
double max = (emitter.Angle * 180 / Math.PI) + emitter.Rand.NextDouble() * (emitter.AngleVariance * 180 / Math.PI);
if (min<=max)
this.Angle = (min + emitter.Rand.NextDouble()*(max-min)) * Math.PI / 180;
else
this.Angle = (max + emitter.Rand.NextDouble() * (min - max)) * Math.PI / 180;
this.Speed = emitter.Rand.Next(emitter.Speed - emitter.SpeedVariance, emitter.Speed + emitter.SpeedVariance);
this.StartColor = emitter.StartColor;
this.EndColor = emitter.EndColor;
this.StartAlpha = emitter.StartAlpha;
this.EndAlpha = emitter.EndAlpha;
this.Mode = emitter.VelocityMode;
if (this.Mode == VelocityMode.Linear)
{
this.Velocity = new Vector2((float)(Speed * Math.Cos(Angle)), (float)(-Speed * Math.Sin(Angle)));
this.Velocity += emitter.InitialForce;
}
else
{
this.Velocity = this.Position * new Vector2((float)(Speed * Math.Cos(Angle)) / 500, (float)(-Speed * Math.Sin(Angle)) / 500);
}
}
}
}
| 37.650943 | 248 | 0.570784 |
[
"MIT"
] |
ttalexander2/catalystenginepublic
|
Catalyst.Engine/Rendering/Particle.cs
| 3,993 |
C#
|
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;
using zrak.Enumerators;
namespace zrak.Models
{
public class TicTacToeStoreModel
{
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonRepresentation(BsonType.String)]
public Guid? TicTacToeId { get; set; }
[BsonRepresentation(BsonType.Int32)]
public int XWins { get; set; }
[BsonRepresentation(BsonType.Int32)]
public int OWins { get; set; }
[BsonRepresentation(BsonType.Int32)]
public int Ties { get; set; }
public SpaceState[,] BoardSpaces { get; set; }
[BsonRepresentation(BsonType.String)]
public char Turn { get; set; }
}
}
| 31 | 55 | 0.625806 |
[
"MIT"
] |
Wineburner/zrak
|
zrak/zrak/Models/TicTacToeStoreModel.cs
| 777 |
C#
|
/*
* Copyright © 2017 EDDiscovery development team
*
* 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.
*
* EDDiscovery is not affiliated with Frontier Developments plc.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BaseUtils;
using ActionLanguage;
using EliteDangerousCore.DB;
using EliteDangerousCore;
namespace EDDiscovery.Actions
{
class ActionScan : ActionBase
{
public override bool AllowDirectEditingOfUserData { get { return true; } }
public override bool ConfigurationMenu(System.Windows.Forms.Form parent, ActionCoreController cp, List<BaseUtils.TypeHelpers.PropertyNameInfo> eventvars)
{
string promptValue = ExtendedControls.PromptSingleLine.ShowDialog(parent, "Scan system name", UserData, "Configure Scan Command" ,cp.Icon);
if (promptValue != null)
{
userdata = promptValue;
}
return (promptValue != null);
}
public override bool ExecuteAction(ActionProgramRun ap)
{
string res;
if (ap.Functions.ExpandString(UserData, out res) != BaseUtils.Functions.ExpandResult.Failed)
{
StringParser sp = new StringParser(res);
string prefix = "S_";
string cmdname = sp.NextQuotedWord();
if (cmdname != null && cmdname.Equals("PREFIX", StringComparison.InvariantCultureIgnoreCase))
{
prefix = sp.NextWord();
if (prefix == null)
{
ap.ReportError("Missing name after Prefix in Scan");
return true;
}
cmdname = sp.NextQuotedWord();
}
bool edsm = false;
if ( cmdname != null && cmdname.Equals("EDSM",StringComparison.InvariantCultureIgnoreCase))
{
edsm = true;
cmdname = sp.NextQuotedWord();
}
if (cmdname != null)
{
StarScan scan = (ap.ActionController as ActionController).HistoryList.StarScan;
ISystem sc = SystemCache.FindSystem(cmdname);
if (sc == null)
{
sc = new SystemClass(cmdname);
sc.EDSMID = 0;
}
StarScan.SystemNode sn = scan.FindSystemSynchronous(sc, edsm);
System.Globalization.CultureInfo ct = System.Globalization.CultureInfo.InvariantCulture;
if ( sn != null )
{
int starno = 1;
ap[prefix + "Stars"] = sn.StarNodes.Count.ToString(ct);
foreach (KeyValuePair<string, StarScan.ScanNode> scannode in sn.StarNodes)
{
DumpInfo(ap, scannode, prefix + "Star_" + starno.ToString(ct) , "_Planets");
int pcount = 1;
if (scannode.Value.Children != null)
{
foreach (KeyValuePair<string, StarScan.ScanNode> planetnodes in scannode.Value.Children)
{
DumpInfo(ap, planetnodes, prefix + "Planet_" + starno.ToString(ct) + "_" + pcount.ToString(ct) , "_Moons");
if (planetnodes.Value.Children != null)
{
int mcount = 1;
foreach (KeyValuePair<string, StarScan.ScanNode> moonnodes in planetnodes.Value.Children)
{
DumpInfo(ap, moonnodes, prefix + "Moon_" + starno.ToString(ct) + "_" + pcount.ToString(ct) + "_" + mcount.ToString(ct) , "_Submoons");
if (moonnodes.Value.Children != null)
{
int smcount = 1;
foreach (KeyValuePair<string, StarScan.ScanNode> submoonnodes in moonnodes.Value.Children)
{
DumpInfo(ap, submoonnodes, prefix + "SubMoon_" + starno.ToString(ct) + "_" + pcount.ToString(ct) + "_" + mcount.ToString(ct) + "_" + smcount.ToString(ct),null);
smcount++;
}
}
mcount++;
}
}
pcount++;
}
}
starno++;
}
}
else
{
ap[prefix + "Stars"] = "0";
}
}
else
ap.ReportError("Missing starname in Scan");
}
else
ap.ReportError(res);
return true;
}
void DumpInfo( ActionProgramRun ap, KeyValuePair<string, EliteDangerousCore.StarScan.ScanNode> scannode, string prefix , string subname )
{
EliteDangerousCore.JournalEvents.JournalScan sc = scannode.Value.ScanData;
ap[prefix] = scannode.Key;
ap[prefix + "_type"] = scannode.Value.NodeType.ToString();
ap[prefix + "_assignedname"] = scannode.Value.OwnName;
ap[prefix + "_assignedfullname"] = scannode.Value.FullName;
ap[prefix + "_data"] = (sc != null) ? "1" : "0";
ap[prefix + "_signals"] = scannode.Value.Signals != null ? EliteDangerousCore.JournalEvents.JournalSAASignalsFound.SignalList(scannode.Value.Signals, 0, ",", true) : "";
if ( sc != null )
{
ap[prefix + "_isstar"] = sc.IsStar ? "1" : "0";
ap[prefix + "_edsmbody"] = sc.IsEDSMBody ? "1" : "0";
ap[prefix + "_bodyname"] = sc.BodyName;
ap[prefix + "_bodydesignation"] = sc.BodyDesignationOrName;
ap[prefix + "_orbitalperiod"] = sc.nOrbitalPeriod.ToNANNullSafeString("0.###");
ap[prefix + "_rotationperiod"] = sc.nRotationPeriod.ToNANNullSafeString("0.###");
ap[prefix + "_surfacetemperature"] = sc.nSurfaceTemperature.ToNANNullSafeString("0.###");
ap[prefix + "_distls"] = sc.DistanceFromArrivalLS.ToNANSafeString("0.###");
if ( sc.IsStar )
{
ap[prefix + "_startype"] = sc.StarType;
ap[prefix + "_startypetext"] = sc.StarTypeText;
ap[prefix + "_stellarmass"] = (sc.nStellarMass ?? 0).ToString("0.###");
ap[prefix + "_age"] = sc.nAge.ToNANNullSafeString("0.##");
ap[prefix + "_mag"] = sc.nAbsoluteMagnitude.ToNANNullSafeString("0");
EliteDangerousCore.JournalEvents.JournalScan.HabZones hz = sc.GetHabZones();
ap[prefix + "_habinner"] = hz != null ? hz.HabitableZoneInner.ToString("0.##") : "";
ap[prefix + "_habouter"] = hz != null ? hz.HabitableZoneOuter.ToString("0.##") : "";
}
else
{
ap[prefix + "_class"] = sc.PlanetClass.ToNullSafeString();
ap[prefix + "_landable"] = sc.IsLandable ? "Landable" : "Not Landable";
ap[prefix + "_atmosphere"] = sc.Atmosphere.ToNullSafeString();
ap[prefix + "_terraformstate"] = sc.TerraformState.ToNullSafeString();
ap[prefix + "_volcanism"] = sc.Volcanism.ToNullSafeString();
ap[prefix + "_gravity"] = sc.nSurfaceGravity.ToNANNullSafeString("0.###");
ap[prefix + "_pressure"] = sc.nSurfacePressure.ToNANNullSafeString("0.###");
ap[prefix + "_mass"] = sc.nMassEM.ToNANNullSafeString("0.###");
ap.AddDataOfType(sc.Materials, typeof(Dictionary<string,double>), prefix + "_Materials");
}
ap[prefix + "_text"] = sc.DisplayString();
ap[prefix + "_value"] = sc.EstimatedValue.ToStringInvariant();
}
if ( subname != null )
{
int totalchildren = (scannode.Value.Children != null) ? scannode.Value.Children.Count : 0;
int totalbodies = (scannode.Value.Children != null) ? (from x in scannode.Value.Children where x.Value.NodeType == StarScan.ScanNodeType.body select x).Count() : 0;
ap[prefix + subname] = totalchildren.ToStringInvariant();
ap[prefix + subname + "_Only"] = totalbodies.ToStringInvariant(); // we do this, because children can be other than bodies..
}
}
}
class ActionStar : ActionBase
{
public override bool AllowDirectEditingOfUserData { get { return true; } }
public override bool ConfigurationMenu(System.Windows.Forms.Form parent, ActionCoreController cp, List<BaseUtils.TypeHelpers.PropertyNameInfo> eventvars)
{
string promptValue = ExtendedControls.PromptSingleLine.ShowDialog(parent, "Star system name", UserData, "Configure Star Command" , cp.Icon);
if (promptValue != null)
{
userdata = promptValue;
}
return (promptValue != null);
}
public override bool ExecuteAction(ActionProgramRun ap)
{
string res;
if (ap.Functions.ExpandString(UserData, out res) != BaseUtils.Functions.ExpandResult.Failed)
{
StringParser sp = new StringParser(res);
string prefix = "ST_";
string cmdname = sp.NextQuotedWord();
if (cmdname != null && cmdname.Equals("PREFIX", StringComparison.InvariantCultureIgnoreCase))
{
prefix = sp.NextWord();
if (prefix == null)
{
ap.ReportError("Missing name after Prefix in Star");
return true;
}
cmdname = sp.NextQuotedWord();
}
if (cmdname != null)
{
ISystem sc = SystemCache.FindSystem(cmdname);
ap[prefix + "Found"] = sc != null ? "1" : "0";
if (sc != null)
{
BaseUtils.Variables vars = new BaseUtils.Variables();
ActionVars.SystemVars(vars, sc, prefix);
ap.Add(vars);
ActionVars.SystemVarsFurtherInfo(ap, (ap.ActionController as ActionController).HistoryList, sc, prefix);
string options = sp.NextWord();
if ( options != null)
{
if ( options.Equals("NEAREST", StringComparison.InvariantCultureIgnoreCase))
{
double mindist = sp.NextDouble(0.01);
double maxdist = sp.NextDouble(20.0);
int number = sp.NextInt(50);
bool cube = (sp.NextWord() ?? "Spherical").Equals("Cube", StringComparison.InvariantCultureIgnoreCase); // spherical default for all but cube
StarDistanceComputer computer = new StarDistanceComputer();
apr = ap;
ret_prefix = prefix;
computer.CalculateClosestSystems(sc,
(sys,list)=> (apr.ActionController as ActionController).DiscoveryForm.BeginInvoke(new Action(() => NewStarListComputed(sys, list))),
(mindist>0) ? (number-1) : number, // adds an implicit 1 on for centre star
mindist, maxdist, !cube);
return false; // go to sleep until value computed
}
}
}
}
else
ap.ReportError("Missing starname in Star");
}
else
ap.ReportError(res);
return true;
}
ActionProgramRun apr;
string ret_prefix;
private void NewStarListComputed(ISystem sys, BaseUtils.SortedListDoubleDuplicate<ISystem> list) // In UI thread
{
System.Diagnostics.Debug.Assert(System.Windows.Forms.Application.MessageLoop);
int i = 1;
foreach( var s in list )
{
string p = ret_prefix + (i++).ToStringInvariant() + "_";
ActionVars.SystemVars(apr.variables, s.Value, p);
ActionVars.SystemVarsFurtherInfo(apr, (apr.ActionController as ActionController).HistoryList, s.Value, p);
apr[p + "Dist"] = Math.Sqrt(s.Key).ToStringInvariant("0.##");
}
apr[ret_prefix + "Count"] = list.Count.ToStringInvariant();
apr.ResumeAfterPause();
}
}
}
| 46.340764 | 213 | 0.485534 |
[
"Apache-2.0"
] |
nullx27/EDDiscovery
|
EDDiscovery/Actions/ActionsEDDCmds/ActionScanStar.cs
| 14,241 |
C#
|
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.DataBoxEdge.V20190801
{
public static class GetBandwidthSchedule
{
public static Task<GetBandwidthScheduleResult> InvokeAsync(GetBandwidthScheduleArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetBandwidthScheduleResult>("azure-nextgen:databoxedge/v20190801:getBandwidthSchedule", args ?? new GetBandwidthScheduleArgs(), options.WithVersion());
}
public sealed class GetBandwidthScheduleArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The device name.
/// </summary>
[Input("deviceName", required: true)]
public string DeviceName { get; set; } = null!;
/// <summary>
/// The bandwidth schedule name.
/// </summary>
[Input("name", required: true)]
public string Name { get; set; } = null!;
/// <summary>
/// The resource group name.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
public GetBandwidthScheduleArgs()
{
}
}
[OutputType]
public sealed class GetBandwidthScheduleResult
{
/// <summary>
/// The days of the week when this schedule is applicable.
/// </summary>
public readonly ImmutableArray<string> Days;
/// <summary>
/// The object name.
/// </summary>
public readonly string Name;
/// <summary>
/// The bandwidth rate in Mbps.
/// </summary>
public readonly int RateInMbps;
/// <summary>
/// The start time of the schedule in UTC.
/// </summary>
public readonly string Start;
/// <summary>
/// The stop time of the schedule in UTC.
/// </summary>
public readonly string Stop;
/// <summary>
/// The hierarchical type of the object.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetBandwidthScheduleResult(
ImmutableArray<string> days,
string name,
int rateInMbps,
string start,
string stop,
string type)
{
Days = days;
Name = name;
RateInMbps = rateInMbps;
Start = start;
Stop = stop;
Type = type;
}
}
}
| 28.71875 | 205 | 0.579616 |
[
"Apache-2.0"
] |
test-wiz-sec/pulumi-azure-nextgen
|
sdk/dotnet/DataBoxEdge/V20190801/GetBandwidthSchedule.cs
| 2,757 |
C#
|
namespace CodeFirstModels
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class CustomerDemographic
{
public CustomerDemographic()
{
this.Customers = new HashSet<Customer>();
}
[Key]
public string CustomerTypeID { get; set; }
public string CustomerDesc { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
}
}
| 23.666667 | 68 | 0.62173 |
[
"Apache-2.0"
] |
Daniel-Svensson/OpenRiaServices
|
src/OpenRiaServices.EntityFramework/Test/CodeFirstModel/CustomerDemographic.cs
| 497 |
C#
|
namespace GTVariable
{
[System.Serializable]
public class FloatReference : ReferenceVariable<float, FloatVariable>
{
}
}
| 18.125 | 74 | 0.668966 |
[
"MIT"
] |
GhooTS/PlanetExplorer
|
Assets/_Packages/GTScriptableVariable/Runtime/Variables/Reference/FloatReference.cs
| 147 |
C#
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Artifactory
{
/// <summary>
/// Creates a local Maven repository.
///
/// ## Example Usage
///
/// ```csharp
/// using Pulumi;
/// using Artifactory = Pulumi.Artifactory;
///
/// class MyStack : Stack
/// {
/// public MyStack()
/// {
/// var terraform_local_test_maven_repo_basic = new Artifactory.LocalMavenRepository("terraform-local-test-maven-repo-basic", new Artifactory.LocalMavenRepositoryArgs
/// {
/// ChecksumPolicyType = "client-checksums",
/// HandleReleases = true,
/// HandleSnapshots = true,
/// Key = "terraform-local-test-maven-repo-basic",
/// MaxUniqueSnapshots = 10,
/// SnapshotVersionBehavior = "unique",
/// SuppressPomConsistencyChecks = false,
/// });
/// }
///
/// }
/// ```
///
/// ## Import
///
/// Local repositories can be imported using their name, e.g.
///
/// ```sh
/// $ pulumi import artifactory:index/localMavenRepository:LocalMavenRepository terraform-local-test-maven-repo-basic terraform-local-test-maven-repo-basic
/// ```
/// </summary>
[ArtifactoryResourceType("artifactory:index/localMavenRepository:LocalMavenRepository")]
public partial class LocalMavenRepository : Pulumi.CustomResource
{
/// <summary>
/// When set, you may view content such as HTML or Javadoc files directly from Artifactory. This may not be safe and
/// therefore requires strict content moderation to prevent malicious users from uploading content that may compromise
/// security (e.g., cross-site scripting attacks).
/// </summary>
[Output("archiveBrowsingEnabled")]
public Output<bool?> ArchiveBrowsingEnabled { get; private set; } = null!;
/// <summary>
/// When set, the repository does not participate in artifact resolution and new artifacts cannot be deployed.
/// </summary>
[Output("blackedOut")]
public Output<bool?> BlackedOut { get; private set; } = null!;
/// <summary>
/// Checksum policy determines how Artifactory behaves when a client checksum for a deployed
/// resource is missing or conflicts with the locally calculated checksum (bad checksum). The options are
/// `client-checksums` and `generated-checksums`. For more details,
/// please refer to [Checksum Policy](https://www.jfrog.com/confluence/display/JFROG/Local+Repositories#LocalRepositories-ChecksumPolicy).
/// </summary>
[Output("checksumPolicyType")]
public Output<string?> ChecksumPolicyType { get; private set; } = null!;
[Output("description")]
public Output<string?> Description { get; private set; } = null!;
/// <summary>
/// When set, download requests to this repository will redirect the client to download the artifact directly from the cloud
/// storage provider. Available in Enterprise+ and Edge licenses only.
/// </summary>
[Output("downloadDirect")]
public Output<bool?> DownloadDirect { get; private set; } = null!;
/// <summary>
/// List of artifact patterns to exclude when evaluating artifact requests, in the form of x/y/**/z/*. By default no
/// artifacts are excluded.
/// </summary>
[Output("excludesPattern")]
public Output<string> ExcludesPattern { get; private set; } = null!;
/// <summary>
/// If set, Artifactory allows you to deploy release artifacts into this repository. Default is `true`.
/// </summary>
[Output("handleReleases")]
public Output<bool?> HandleReleases { get; private set; } = null!;
/// <summary>
/// If set, Artifactory allows you to deploy snapshot artifacts into this repository. Default is `true`.
/// </summary>
[Output("handleSnapshots")]
public Output<bool?> HandleSnapshots { get; private set; } = null!;
/// <summary>
/// List of artifact patterns to include when evaluating artifact requests in the form of x/y/**/z/*. When used, only
/// artifacts matching one of the include patterns are served. By default, all artifacts are included (**/*).
/// </summary>
[Output("includesPattern")]
public Output<string> IncludesPattern { get; private set; } = null!;
/// <summary>
/// the identity key of the repo.
/// </summary>
[Output("key")]
public Output<string> Key { get; private set; } = null!;
/// <summary>
/// The maximum number of unique snapshots of a single artifact to store.
/// Once the number of snapshots exceeds this setting, older versions are removed.
/// A value of 0 (default) indicates there is no limit, and unique snapshots are not cleaned up.
/// </summary>
[Output("maxUniqueSnapshots")]
public Output<int?> MaxUniqueSnapshots { get; private set; } = null!;
[Output("notes")]
public Output<string?> Notes { get; private set; } = null!;
[Output("packageType")]
public Output<string> PackageType { get; private set; } = null!;
/// <summary>
/// Setting repositories with priority will cause metadata to be merged only from repositories set with this field
/// </summary>
[Output("priorityResolution")]
public Output<bool?> PriorityResolution { get; private set; } = null!;
/// <summary>
/// Project environment for assigning this repository to. Allow values: "DEV" or "PROD"
/// </summary>
[Output("projectEnvironments")]
public Output<ImmutableArray<string>> ProjectEnvironments { get; private set; } = null!;
/// <summary>
/// Project key for assigning this repository to. When assigning repository to a project, repository key must be prefixed
/// with project key, separated by a dash.
/// </summary>
[Output("projectKey")]
public Output<string?> ProjectKey { get; private set; } = null!;
/// <summary>
/// List of property set name
/// </summary>
[Output("propertySets")]
public Output<ImmutableArray<string>> PropertySets { get; private set; } = null!;
/// <summary>
/// Repository layout key for the local repository
/// </summary>
[Output("repoLayoutRef")]
public Output<string?> RepoLayoutRef { get; private set; } = null!;
/// <summary>
/// Specifies the naming convention for Maven SNAPSHOT versions.
/// The options are -
/// * `unique`: Version number is based on a time-stamp (default)
/// * `non-unique`: Version number uses a self-overriding naming pattern of artifactId-version-SNAPSHOT.type
/// * `deployer`: Respects the settings in the Maven client that is deploying the artifact.
/// </summary>
[Output("snapshotVersionBehavior")]
public Output<string?> SnapshotVersionBehavior { get; private set; } = null!;
/// <summary>
/// By default, Artifactory keeps your repositories healthy by refusing POMs with incorrect coordinates (path).
/// If the groupId:artifactId:version information inside the POM does not match the deployed path, Artifactory rejects the deployment with a "409 Conflict" error.
/// You can disable this behavior by setting the Suppress POM Consistency Checks checkbox. False by default for Maven repository.
/// </summary>
[Output("suppressPomConsistencyChecks")]
public Output<bool?> SuppressPomConsistencyChecks { get; private set; } = null!;
/// <summary>
/// Enable Indexing In Xray. Repository will be indexed with the default retention period. You will be able to change it via
/// Xray settings.
/// </summary>
[Output("xrayIndex")]
public Output<bool?> XrayIndex { get; private set; } = null!;
/// <summary>
/// Create a LocalMavenRepository resource with the given unique name, arguments, and options.
/// </summary>
///
/// <param name="name">The unique name of the resource</param>
/// <param name="args">The arguments used to populate this resource's properties</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public LocalMavenRepository(string name, LocalMavenRepositoryArgs args, CustomResourceOptions? options = null)
: base("artifactory:index/localMavenRepository:LocalMavenRepository", name, args ?? new LocalMavenRepositoryArgs(), MakeResourceOptions(options, ""))
{
}
private LocalMavenRepository(string name, Input<string> id, LocalMavenRepositoryState? state = null, CustomResourceOptions? options = null)
: base("artifactory:index/localMavenRepository:LocalMavenRepository", name, state, MakeResourceOptions(options, id))
{
}
private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id)
{
var defaultOptions = new CustomResourceOptions
{
Version = Utilities.Version,
};
var merged = CustomResourceOptions.Merge(defaultOptions, options);
// Override the ID if one was specified for consistency with other language SDKs.
merged.Id = id ?? merged.Id;
return merged;
}
/// <summary>
/// Get an existing LocalMavenRepository resource's state with the given name, ID, and optional extra
/// properties used to qualify the lookup.
/// </summary>
///
/// <param name="name">The unique name of the resulting resource.</param>
/// <param name="id">The unique provider ID of the resource to lookup.</param>
/// <param name="state">Any extra arguments used during the lookup.</param>
/// <param name="options">A bag of options that control this resource's behavior</param>
public static LocalMavenRepository Get(string name, Input<string> id, LocalMavenRepositoryState? state = null, CustomResourceOptions? options = null)
{
return new LocalMavenRepository(name, id, state, options);
}
}
public sealed class LocalMavenRepositoryArgs : Pulumi.ResourceArgs
{
/// <summary>
/// When set, you may view content such as HTML or Javadoc files directly from Artifactory. This may not be safe and
/// therefore requires strict content moderation to prevent malicious users from uploading content that may compromise
/// security (e.g., cross-site scripting attacks).
/// </summary>
[Input("archiveBrowsingEnabled")]
public Input<bool>? ArchiveBrowsingEnabled { get; set; }
/// <summary>
/// When set, the repository does not participate in artifact resolution and new artifacts cannot be deployed.
/// </summary>
[Input("blackedOut")]
public Input<bool>? BlackedOut { get; set; }
/// <summary>
/// Checksum policy determines how Artifactory behaves when a client checksum for a deployed
/// resource is missing or conflicts with the locally calculated checksum (bad checksum). The options are
/// `client-checksums` and `generated-checksums`. For more details,
/// please refer to [Checksum Policy](https://www.jfrog.com/confluence/display/JFROG/Local+Repositories#LocalRepositories-ChecksumPolicy).
/// </summary>
[Input("checksumPolicyType")]
public Input<string>? ChecksumPolicyType { get; set; }
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// When set, download requests to this repository will redirect the client to download the artifact directly from the cloud
/// storage provider. Available in Enterprise+ and Edge licenses only.
/// </summary>
[Input("downloadDirect")]
public Input<bool>? DownloadDirect { get; set; }
/// <summary>
/// List of artifact patterns to exclude when evaluating artifact requests, in the form of x/y/**/z/*. By default no
/// artifacts are excluded.
/// </summary>
[Input("excludesPattern")]
public Input<string>? ExcludesPattern { get; set; }
/// <summary>
/// If set, Artifactory allows you to deploy release artifacts into this repository. Default is `true`.
/// </summary>
[Input("handleReleases")]
public Input<bool>? HandleReleases { get; set; }
/// <summary>
/// If set, Artifactory allows you to deploy snapshot artifacts into this repository. Default is `true`.
/// </summary>
[Input("handleSnapshots")]
public Input<bool>? HandleSnapshots { get; set; }
/// <summary>
/// List of artifact patterns to include when evaluating artifact requests in the form of x/y/**/z/*. When used, only
/// artifacts matching one of the include patterns are served. By default, all artifacts are included (**/*).
/// </summary>
[Input("includesPattern")]
public Input<string>? IncludesPattern { get; set; }
/// <summary>
/// the identity key of the repo.
/// </summary>
[Input("key", required: true)]
public Input<string> Key { get; set; } = null!;
/// <summary>
/// The maximum number of unique snapshots of a single artifact to store.
/// Once the number of snapshots exceeds this setting, older versions are removed.
/// A value of 0 (default) indicates there is no limit, and unique snapshots are not cleaned up.
/// </summary>
[Input("maxUniqueSnapshots")]
public Input<int>? MaxUniqueSnapshots { get; set; }
[Input("notes")]
public Input<string>? Notes { get; set; }
/// <summary>
/// Setting repositories with priority will cause metadata to be merged only from repositories set with this field
/// </summary>
[Input("priorityResolution")]
public Input<bool>? PriorityResolution { get; set; }
[Input("projectEnvironments")]
private InputList<string>? _projectEnvironments;
/// <summary>
/// Project environment for assigning this repository to. Allow values: "DEV" or "PROD"
/// </summary>
public InputList<string> ProjectEnvironments
{
get => _projectEnvironments ?? (_projectEnvironments = new InputList<string>());
set => _projectEnvironments = value;
}
/// <summary>
/// Project key for assigning this repository to. When assigning repository to a project, repository key must be prefixed
/// with project key, separated by a dash.
/// </summary>
[Input("projectKey")]
public Input<string>? ProjectKey { get; set; }
[Input("propertySets")]
private InputList<string>? _propertySets;
/// <summary>
/// List of property set name
/// </summary>
public InputList<string> PropertySets
{
get => _propertySets ?? (_propertySets = new InputList<string>());
set => _propertySets = value;
}
/// <summary>
/// Repository layout key for the local repository
/// </summary>
[Input("repoLayoutRef")]
public Input<string>? RepoLayoutRef { get; set; }
/// <summary>
/// Specifies the naming convention for Maven SNAPSHOT versions.
/// The options are -
/// * `unique`: Version number is based on a time-stamp (default)
/// * `non-unique`: Version number uses a self-overriding naming pattern of artifactId-version-SNAPSHOT.type
/// * `deployer`: Respects the settings in the Maven client that is deploying the artifact.
/// </summary>
[Input("snapshotVersionBehavior")]
public Input<string>? SnapshotVersionBehavior { get; set; }
/// <summary>
/// By default, Artifactory keeps your repositories healthy by refusing POMs with incorrect coordinates (path).
/// If the groupId:artifactId:version information inside the POM does not match the deployed path, Artifactory rejects the deployment with a "409 Conflict" error.
/// You can disable this behavior by setting the Suppress POM Consistency Checks checkbox. False by default for Maven repository.
/// </summary>
[Input("suppressPomConsistencyChecks")]
public Input<bool>? SuppressPomConsistencyChecks { get; set; }
/// <summary>
/// Enable Indexing In Xray. Repository will be indexed with the default retention period. You will be able to change it via
/// Xray settings.
/// </summary>
[Input("xrayIndex")]
public Input<bool>? XrayIndex { get; set; }
public LocalMavenRepositoryArgs()
{
}
}
public sealed class LocalMavenRepositoryState : Pulumi.ResourceArgs
{
/// <summary>
/// When set, you may view content such as HTML or Javadoc files directly from Artifactory. This may not be safe and
/// therefore requires strict content moderation to prevent malicious users from uploading content that may compromise
/// security (e.g., cross-site scripting attacks).
/// </summary>
[Input("archiveBrowsingEnabled")]
public Input<bool>? ArchiveBrowsingEnabled { get; set; }
/// <summary>
/// When set, the repository does not participate in artifact resolution and new artifacts cannot be deployed.
/// </summary>
[Input("blackedOut")]
public Input<bool>? BlackedOut { get; set; }
/// <summary>
/// Checksum policy determines how Artifactory behaves when a client checksum for a deployed
/// resource is missing or conflicts with the locally calculated checksum (bad checksum). The options are
/// `client-checksums` and `generated-checksums`. For more details,
/// please refer to [Checksum Policy](https://www.jfrog.com/confluence/display/JFROG/Local+Repositories#LocalRepositories-ChecksumPolicy).
/// </summary>
[Input("checksumPolicyType")]
public Input<string>? ChecksumPolicyType { get; set; }
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// When set, download requests to this repository will redirect the client to download the artifact directly from the cloud
/// storage provider. Available in Enterprise+ and Edge licenses only.
/// </summary>
[Input("downloadDirect")]
public Input<bool>? DownloadDirect { get; set; }
/// <summary>
/// List of artifact patterns to exclude when evaluating artifact requests, in the form of x/y/**/z/*. By default no
/// artifacts are excluded.
/// </summary>
[Input("excludesPattern")]
public Input<string>? ExcludesPattern { get; set; }
/// <summary>
/// If set, Artifactory allows you to deploy release artifacts into this repository. Default is `true`.
/// </summary>
[Input("handleReleases")]
public Input<bool>? HandleReleases { get; set; }
/// <summary>
/// If set, Artifactory allows you to deploy snapshot artifacts into this repository. Default is `true`.
/// </summary>
[Input("handleSnapshots")]
public Input<bool>? HandleSnapshots { get; set; }
/// <summary>
/// List of artifact patterns to include when evaluating artifact requests in the form of x/y/**/z/*. When used, only
/// artifacts matching one of the include patterns are served. By default, all artifacts are included (**/*).
/// </summary>
[Input("includesPattern")]
public Input<string>? IncludesPattern { get; set; }
/// <summary>
/// the identity key of the repo.
/// </summary>
[Input("key")]
public Input<string>? Key { get; set; }
/// <summary>
/// The maximum number of unique snapshots of a single artifact to store.
/// Once the number of snapshots exceeds this setting, older versions are removed.
/// A value of 0 (default) indicates there is no limit, and unique snapshots are not cleaned up.
/// </summary>
[Input("maxUniqueSnapshots")]
public Input<int>? MaxUniqueSnapshots { get; set; }
[Input("notes")]
public Input<string>? Notes { get; set; }
[Input("packageType")]
public Input<string>? PackageType { get; set; }
/// <summary>
/// Setting repositories with priority will cause metadata to be merged only from repositories set with this field
/// </summary>
[Input("priorityResolution")]
public Input<bool>? PriorityResolution { get; set; }
[Input("projectEnvironments")]
private InputList<string>? _projectEnvironments;
/// <summary>
/// Project environment for assigning this repository to. Allow values: "DEV" or "PROD"
/// </summary>
public InputList<string> ProjectEnvironments
{
get => _projectEnvironments ?? (_projectEnvironments = new InputList<string>());
set => _projectEnvironments = value;
}
/// <summary>
/// Project key for assigning this repository to. When assigning repository to a project, repository key must be prefixed
/// with project key, separated by a dash.
/// </summary>
[Input("projectKey")]
public Input<string>? ProjectKey { get; set; }
[Input("propertySets")]
private InputList<string>? _propertySets;
/// <summary>
/// List of property set name
/// </summary>
public InputList<string> PropertySets
{
get => _propertySets ?? (_propertySets = new InputList<string>());
set => _propertySets = value;
}
/// <summary>
/// Repository layout key for the local repository
/// </summary>
[Input("repoLayoutRef")]
public Input<string>? RepoLayoutRef { get; set; }
/// <summary>
/// Specifies the naming convention for Maven SNAPSHOT versions.
/// The options are -
/// * `unique`: Version number is based on a time-stamp (default)
/// * `non-unique`: Version number uses a self-overriding naming pattern of artifactId-version-SNAPSHOT.type
/// * `deployer`: Respects the settings in the Maven client that is deploying the artifact.
/// </summary>
[Input("snapshotVersionBehavior")]
public Input<string>? SnapshotVersionBehavior { get; set; }
/// <summary>
/// By default, Artifactory keeps your repositories healthy by refusing POMs with incorrect coordinates (path).
/// If the groupId:artifactId:version information inside the POM does not match the deployed path, Artifactory rejects the deployment with a "409 Conflict" error.
/// You can disable this behavior by setting the Suppress POM Consistency Checks checkbox. False by default for Maven repository.
/// </summary>
[Input("suppressPomConsistencyChecks")]
public Input<bool>? SuppressPomConsistencyChecks { get; set; }
/// <summary>
/// Enable Indexing In Xray. Repository will be indexed with the default retention period. You will be able to change it via
/// Xray settings.
/// </summary>
[Input("xrayIndex")]
public Input<bool>? XrayIndex { get; set; }
public LocalMavenRepositoryState()
{
}
}
}
| 45.656075 | 178 | 0.624539 |
[
"ECL-2.0",
"Apache-2.0"
] |
pulumi/pulumi-artifactory
|
sdk/dotnet/LocalMavenRepository.cs
| 24,426 |
C#
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ConsoleMenu")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConsoleMenu")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5c7e4264-7e12-42c5-8e51-ca5ba111cf76")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.702703 | 84 | 0.744803 |
[
"MIT"
] |
LukasRH/AAU_2.Semester
|
OOP/Ugeopgaver/ConsoleMenu/ConsoleMenu/Properties/AssemblyInfo.cs
| 1,398 |
C#
|
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// 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.
// File System.DirectoryServices.ActiveDirectory.AdamInstance.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.DirectoryServices.ActiveDirectory
{
public partial class AdamInstance : DirectoryServer
{
#region Methods and constructors
private AdamInstance()
{
}
public override void CheckReplicationConsistency()
{
}
protected override void Dispose(bool disposing)
{
}
public static AdamInstanceCollection FindAll(DirectoryContext context, string partitionName)
{
return default(AdamInstanceCollection);
}
public static AdamInstance FindOne(DirectoryContext context, string partitionName)
{
return default(AdamInstance);
}
public static AdamInstance GetAdamInstance(DirectoryContext context)
{
return default(AdamInstance);
}
public override ReplicationNeighborCollection GetAllReplicationNeighbors()
{
return default(ReplicationNeighborCollection);
}
public override ReplicationFailureCollection GetReplicationConnectionFailures()
{
return default(ReplicationFailureCollection);
}
public override ReplicationCursorCollection GetReplicationCursors(string partition)
{
return default(ReplicationCursorCollection);
}
public override ActiveDirectoryReplicationMetadata GetReplicationMetadata(string objectPath)
{
return default(ActiveDirectoryReplicationMetadata);
}
public override ReplicationNeighborCollection GetReplicationNeighbors(string partition)
{
return default(ReplicationNeighborCollection);
}
public override ReplicationOperationInformation GetReplicationOperationInformation()
{
return default(ReplicationOperationInformation);
}
public void Save()
{
}
public void SeizeRoleOwnership(AdamRole role)
{
}
public override void SyncReplicaFromAllServers(string partition, SyncFromAllServersOptions options)
{
}
public override void SyncReplicaFromServer(string partition, string sourceServer)
{
}
public void TransferRoleOwnership(AdamRole role)
{
}
public override void TriggerSyncReplicaFromNeighbors(string partition)
{
}
#endregion
#region Properties and indexers
public ConfigurationSet ConfigurationSet
{
get
{
return default(ConfigurationSet);
}
}
public string DefaultPartition
{
get
{
return default(string);
}
set
{
}
}
public string HostName
{
get
{
return default(string);
}
}
public override ReplicationConnectionCollection InboundConnections
{
get
{
return default(ReplicationConnectionCollection);
}
}
public override string IPAddress
{
get
{
return default(string);
}
}
public int LdapPort
{
get
{
return default(int);
}
}
public override ReplicationConnectionCollection OutboundConnections
{
get
{
return default(ReplicationConnectionCollection);
}
}
public AdamRoleCollection Roles
{
get
{
return default(AdamRoleCollection);
}
}
public override string SiteName
{
get
{
return default(string);
}
}
public int SslPort
{
get
{
return default(int);
}
}
public override SyncUpdateCallback SyncFromAllServersCallback
{
get
{
return default(SyncUpdateCallback);
}
set
{
}
}
#endregion
}
}
| 25.058296 | 463 | 0.697745 |
[
"MIT"
] |
Acidburn0zzz/CodeContracts
|
Microsoft.Research/Contracts/System.DirectoryServices/Sources/System.DirectoryServices.ActiveDirectory.AdamInstance.cs
| 5,588 |
C#
|
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Xml;
namespace Axiom.SceneManagers.Multiverse
{
public delegate void AngleMovedHandler( object sender, Guid pairId, float oldAngle, float newAngle );
public delegate void TextureIndexChangedHandler( object sender, Guid pairId, int oldIndex, int newIndex );
public delegate void AngleTexturePairHandler( object sender, Guid pairId, float angle, int textureIndex );
public class AutoSplatHeightAngleRange : IComparable<AutoSplatHeightAngleRange>
{
#region Public interface
#region Generated events
public event AngleTexturePairHandler AngleTexturePairAdded;
public event AngleTexturePairHandler AngleTexturePairRemoved;
public event AngleMovedHandler AngleMoved;
public event TextureIndexChangedHandler TextureIndexChanged;
#endregion Generated events
public long HeightMM
{
get { return m_heightMM; }
set { m_heightMM = value; }
}
long m_heightMM;
public Guid Id { get; private set; }
/// <summary>
/// Pairs (and therfore Ids) for Horizontal and Vertical are guaranteed to always exist.
/// </summary>
public Guid HorizontalId { get { return m_AngleSortedPairs[ 0 ].Id; } }
public Guid VerticalId { get { return m_AngleSortedPairs[ m_AngleSortedPairs.Count - 1 ].Id; } }
public IEnumerable<Guid> AllIdsInAscendingAngleOrder
{
get
{
for( int i = 0; i < m_AngleSortedPairs.Count; i++ )
{
yield return m_AngleSortedPairs[ i ].Id;
}
}
}
#region Constructors
public AutoSplatHeightAngleRange( long heightMM )
{
Id = Guid.NewGuid();
m_heightMM = heightMM;
}
public AutoSplatHeightAngleRange( long heightMM, int horizontalTextureIndex, int verticalTextureIndex ) :
this(heightMM)
{
InternalAddAngleTexturePair( new AutoSplatAngleTexturePair( AutoSplatAngleTexturePair.Horizontal, horizontalTextureIndex ) );
InternalAddAngleTexturePair( new AutoSplatAngleTexturePair( AutoSplatAngleTexturePair.Vertical, verticalTextureIndex ) );
}
public AutoSplatHeightAngleRange( long heightMM, AutoSplatHeightAngleRange other ) :
this(heightMM)
{
foreach( AutoSplatAngleTexturePair otherPair in other.m_AngleSortedPairs )
{
InternalAddAngleTexturePair( new AutoSplatAngleTexturePair( otherPair ) );
}
}
public AutoSplatHeightAngleRange( XmlReader reader )
{
Id = Guid.NewGuid();
FromXml( reader );
}
#endregion Constructors
#region Xml Serialization
public void FromXml( XmlReader reader )
{
Debug.Assert( reader.Name.Equals( "heightRange" ) );
XmlReader subReader = reader.ReadSubtree();
subReader.ReadToFollowing( "long" );
Debug.Assert( subReader.GetAttribute( "name" ).Equals( "height" ) );
m_heightMM = long.Parse( subReader.GetAttribute( "value" ) );
subReader.ReadToFollowing( "slopes" );
subReader.ReadToFollowing( "slope" );
do
{
InternalAddAngleTexturePair( new AutoSplatAngleTexturePair( subReader ) );
} while( subReader.ReadToNextSibling( "slope" ) );
subReader.Close();
}
public void ToXml( XmlWriter writer )
{
writer.WriteStartElement( "heightRange" );
writer.WriteStartElement( "long" );
writer.WriteAttributeString( "name", "height" );
writer.WriteAttributeString( "value", m_heightMM.ToString() );
writer.WriteEndElement();
writer.WriteStartElement( "slopes" );
foreach( AutoSplatAngleTexturePair pair in m_AngleSortedPairs )
{
pair.ToXml( writer );
}
writer.WriteEndElement();
writer.WriteEndElement();
}
#endregion Xml Serialization
/// <summary>
/// This is like an 'add' operation, but you need to restore the id of the
/// pair literally because further operations in the undo stack will refer
/// to the pair by id.
/// </summary>
/// <param name="angleDegrees">angle of the slope</param>
/// <param name="textureIndex">texture associated with the slope</param>
/// <param name="id">unique id by which the slope is accessed</param>
/// <returns></returns>
public AutoSplatAngleTexturePair UndoRemoveAngleTexturePair( float angleDegrees, int textureIndex, Guid id )
{
AutoSplatAngleTexturePair pair = new AutoSplatAngleTexturePair( angleDegrees, textureIndex, id );
InternalAddAngleTexturePair( pair );
return pair;
}
public AutoSplatAngleTexturePair AddAngleTexturePair( float angleDegrees, int textureIndex )
{
AutoSplatAngleTexturePair pair = new AutoSplatAngleTexturePair( angleDegrees, textureIndex );
InternalAddAngleTexturePair( pair );
return pair;
}
public void RemoveAngleTexturePair( Guid pairId )
{
InternalRemoveAngleTexturePair( GetPair( pairId ) );
}
public float GetAngleDegrees( Guid pairId )
{
Debug.Assert( m_IdToPairMap.ContainsKey( pairId ) );
return m_IdToPairMap[ pairId ].AngleDegrees;
}
public int GetTextureIndex( Guid pairId )
{
Debug.Assert( m_IdToPairMap.ContainsKey( pairId ) );
return m_IdToPairMap[ pairId ].TextureIndex;
}
public void MoveAngle( Guid pairId, float angleDegrees )
{
AutoSplatAngleTexturePair pair = GetPair( pairId );
if( ! pair.AngleDegrees.Equals( angleDegrees ) )
{
AutoSplatAngleTexturePair clone = null;
if( pair.IsCriticalAngle )
{
clone = new AutoSplatAngleTexturePair( pair );
// We won't need to 'infinitesimally bump' the new angle because
// we already tested to establish that the values are not equal.
}
else
{
// Guarenteed to be neither first nor last because it's not critical
int pairIndex = GetIndex( pairId );
float prevAngle = m_AngleSortedPairs[ pairIndex - 1 ].AngleDegrees;
float nextAngle = m_AngleSortedPairs[ pairIndex + 1 ].AngleDegrees;
if( angleDegrees < prevAngle || angleDegrees > nextAngle )
{
// Only Add and Remove should change the sorting order
throw new ConstraintException(
"MoveAngle would change ordering of pairs;" +
"only Add and Remove should change the sorting order." );
}
// If the move would make the angle coincide exactly with one of
// its neighbors, back it off a teensie-weensie bit.
const float infinitesimal = 0.0001f;
if( angleDegrees.Equals( prevAngle ) )
{
angleDegrees += infinitesimal;
}
else if( angleDegrees.Equals( nextAngle ) )
{
angleDegrees -= infinitesimal;
}
}
float oldAngle = pair.AngleDegrees;
pair.AngleDegrees = angleDegrees;
FireAngleMoved( pairId, oldAngle, angleDegrees );
if( null != clone )
{
// So we are splitting one of the critical pairs. By waiting until
// after we've moved the original pair to add the clone, we assure
// the sorting order stays the same for pre-existing pairs. The
// Outside World cares about this order.
InternalAddAngleTexturePair( clone );
}
}
}
public void SetPairTextureIndex( Guid pairId, int textureIndex )
{
int oldIndex = GetPair( pairId ).TextureIndex;
if( ! textureIndex.Equals( oldIndex ) )
{
GetPair( pairId ).TextureIndex = textureIndex;
FireTextureIndexChanged( pairId, oldIndex, textureIndex );
}
}
public float[] GetAutoSplatSampleNormalized( float angleDegrees )
{
AutoSplatAngleTexturePair lowerPair = null;
AutoSplatAngleTexturePair higherPair = null;
// We assume the pairs are sorted in increasing order by angle
foreach( AutoSplatAngleTexturePair pair in m_AngleSortedPairs )
{
if( pair.AngleDegrees == angleDegrees )
{
lowerPair = pair;
higherPair = pair;
break;
}
if( pair.AngleDegrees < angleDegrees )
{
lowerPair = pair;
continue;
}
if( pair.AngleDegrees > angleDegrees )
{
higherPair = pair;
// We should have both the lower & upper bounds now, so break;
break;
}
}
if (lowerPair == null)
{
Debug.Assert(lowerPair != null,
"Unable to find lower angle when getting autosplat sample. Angle=" + angleDegrees + " Range=" +
this);
}
if (higherPair == null)
{
Debug.Assert(higherPair != null,
"Unable to find higher angle when getting autosplat sample. Angle=" + angleDegrees +
" Range=" + this);
}
// Compute the gradiant weighting for the lower & higher angled textures
float lowerWeight;
float higherWeight;
float angleDiff = higherPair.AngleDegrees - lowerPair.AngleDegrees;
if( angleDiff == 0 || lowerPair.TextureIndex == higherPair.TextureIndex)
{
lowerWeight = 0f;
higherWeight = 1f;
}
else
{
// How close is the angle to the higher/lower angle? Normalize
// that distance from 0..1 and use that as the gradient weights
higherWeight = (angleDegrees - lowerPair.AngleDegrees) / angleDiff;
lowerWeight = 1f - higherWeight;
}
float[] normalizedSample = new float[AlphaSplatTerrainConfig.MAX_LAYER_TEXTURES];
// It's important that we set higher second because
// if lower & higher angle are equal the same, we
// set the higherWeight to 1f above and want to make
// sure it's set that way here.
normalizedSample[ lowerPair.TextureIndex ] = lowerWeight;
normalizedSample[ higherPair.TextureIndex ] = higherWeight;
return normalizedSample;
}
public IEnumerable<AutoSplatAngleTexturePair> GetAngleTexturePairs()
{
return m_AngleSortedPairs;
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append( m_heightMM );
builder.Append( "mm [" );
bool first = true;
foreach( AutoSplatAngleTexturePair pair in m_AngleSortedPairs )
{
if( first )
{
first = false;
}
else
{
builder.Append( ", " );
}
builder.Append( pair );
}
builder.Append( "]" );
return builder.ToString();
}
#region Implementation of IComparable<AutoSplatHeightAngleRange>
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other" /> parameter.Zero This object is equal to <paramref name="other" />. Greater than zero This object is greater than <paramref name="other" />.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo( AutoSplatHeightAngleRange other )
{
long diff = m_heightMM - other.m_heightMM;
return (int) diff;
}
#endregion
#endregion Public interface
#region Private implementation
readonly List<AutoSplatAngleTexturePair> m_AngleSortedPairs = new List<AutoSplatAngleTexturePair>();
readonly Dictionary<Guid,AutoSplatAngleTexturePair> m_IdToPairMap = new Dictionary<Guid, AutoSplatAngleTexturePair>();
void InternalAddAngleTexturePair( AutoSplatAngleTexturePair pair )
{
if( pair == null )
{
throw new NullReferenceException();
}
if( m_IdToPairMap.ContainsKey( pair.Id ) )
{
throw new ArgumentException( "Key already in dictionary" );
}
// Make sure the pair *angle* to be added is not a duplicated.
foreach( AutoSplatAngleTexturePair atPair in m_AngleSortedPairs )
{
if( atPair.AngleDegrees.Equals( pair.AngleDegrees ) )
{
throw new ArgumentException( "Duplicate angles are not allowed." );
}
}
m_AngleSortedPairs.Add( pair );
m_AngleSortedPairs.Sort(); // Keep sorted by angle
m_IdToPairMap.Add( pair.Id, pair );
FireAngleTexturePairAdded( pair );
}
void InternalRemoveAngleTexturePair( AutoSplatAngleTexturePair pair )
{
// You are not allowed to remove critical pairs! We have a design
// constraint that there are always a horizontal and a vertical pair.
//
// This is not as constraining as it might sound. Assume the 'remove'
// request is the outcome of a GUI action--like dragging to the trash.
// Even if you attempt to remove a critical pair, the act of moving it
// to the trash hotspot will move it away from the critical position,
// which in turn causes a new pair to be inserted to replace it in the
// critical position. You could do it all day if that's how you like
// to spend your time.
if( ! pair.IsCriticalAngle )
{
m_IdToPairMap.Remove( pair.Id );
m_AngleSortedPairs.Remove( pair );
FireAngleTexturePairRemoved( pair );
}
}
AutoSplatAngleTexturePair GetPair( Guid pairId )
{
if( m_IdToPairMap.ContainsKey( pairId ) )
{
return m_IdToPairMap[ pairId ];
}
throw new ArgumentException( "Attempting to get an unregistered AngleTexturePair" );
}
int GetIndex( Guid pairId )
{
int index = m_AngleSortedPairs.IndexOf( GetPair( pairId ) );
if( index >= 0 )
{
return index;
}
throw new IndexOutOfRangeException();
}
#region Event firing
void FireAngleMoved( Guid pairId, float oldAngle, float newAngle )
{
if( null != AngleMoved )
{
AngleMoved( this, pairId, oldAngle, newAngle );
}
}
void FireTextureIndexChanged( Guid pairId, int oldIndex, int newIndex )
{
if( null != TextureIndexChanged )
{
TextureIndexChanged( this, pairId, oldIndex, newIndex );
}
}
void FireAngleTexturePairAdded( AutoSplatAngleTexturePair pair )
{
if( null != AngleTexturePairAdded )
{
AngleTexturePairAdded( this, pair.Id, pair.AngleDegrees, pair.TextureIndex );
}
}
void FireAngleTexturePairRemoved( AutoSplatAngleTexturePair pair )
{
if( null != AngleTexturePairRemoved )
{
AngleTexturePairRemoved( this, pair.Id, pair.AngleDegrees, pair.TextureIndex );
}
}
#endregion Event firing
#endregion Private implementation
}
}
| 35.87619 | 369 | 0.564428 |
[
"MIT"
] |
AustralianDisabilityLimited/MultiversePlatform
|
mvsm/AutoSplatHeightAngleRange.cs
| 18,835 |
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.