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 |
|---|---|---|---|---|---|---|---|---|
namespace Notepads
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Storage;
using Notepads.Controls.TextEditor;
using Notepads.Services;
using Notepads.Utilities;
public sealed partial class NotepadsMainPage
{
private async Task OpenNewFiles()
{
IReadOnlyList<StorageFile> files;
try
{
files = await FilePickerFactory.GetFileOpenPicker().PickMultipleFilesAsync();
}
catch (Exception ex)
{
var fileOpenErrorDialog = NotepadsDialogFactory.GetFileOpenErrorDialog(filePath: null, ex.Message);
await DialogManager.OpenDialogAsync(fileOpenErrorDialog, awaitPreviousDialog: false);
if (!fileOpenErrorDialog.IsAborted)
{
NotepadsCore.FocusOnSelectedTextEditor();
}
return;
}
if (files == null || files.Count == 0)
{
NotepadsCore.FocusOnSelectedTextEditor();
return;
}
foreach (var file in files)
{
await OpenFile(file);
}
}
public async Task<bool> OpenFile(StorageFile file)
{
try
{
var openedEditor = NotepadsCore.GetTextEditor(file);
if (openedEditor != null)
{
NotepadsCore.SwitchTo(openedEditor);
NotificationCenter.Instance.PostNotification(
_resourceLoader.GetString("TextEditor_NotificationMsg_FileAlreadyOpened"), 2500);
return false;
}
var editor = await NotepadsCore.CreateTextEditor(Guid.NewGuid(), file);
NotepadsCore.OpenTextEditor(editor);
NotepadsCore.FocusOnSelectedTextEditor();
return true;
}
catch (Exception ex)
{
var fileOpenErrorDialog = NotepadsDialogFactory.GetFileOpenErrorDialog(file.Path, ex.Message);
await DialogManager.OpenDialogAsync(fileOpenErrorDialog, awaitPreviousDialog: false);
if (!fileOpenErrorDialog.IsAborted)
{
NotepadsCore.FocusOnSelectedTextEditor();
}
return false;
}
}
public async Task<int> OpenFiles(IReadOnlyList<IStorageItem> storageItems)
{
if (storageItems == null || storageItems.Count == 0) return 0;
int successCount = 0;
foreach (var storageItem in storageItems)
{
if (storageItem is StorageFile file)
{
if (await OpenFile(file))
{
successCount++;
}
}
}
return successCount;
}
private async Task<bool> Save(ITextEditor textEditor, bool saveAs, bool ignoreUnmodifiedDocument = false)
{
if (textEditor == null) return false;
if (ignoreUnmodifiedDocument && !textEditor.IsModified)
{
return true;
}
StorageFile file = null;
try
{
if (textEditor.EditingFile == null || saveAs ||
FileSystemUtility.IsFileReadOnly(textEditor.EditingFile) ||
!await FileSystemUtility.FileIsWritable(textEditor.EditingFile))
{
NotepadsCore.SwitchTo(textEditor);
file = await FilePickerFactory.GetFileSavePicker(textEditor, saveAs).PickSaveFileAsync();
NotepadsCore.FocusOnTextEditor(textEditor);
if (file == null)
{
return false; // User cancelled
}
}
else
{
file = textEditor.EditingFile;
}
await NotepadsCore.SaveContentToFileAndUpdateEditorState(textEditor, file);
return true;
}
catch (Exception ex)
{
var fileSaveErrorDialog = NotepadsDialogFactory.GetFileSaveErrorDialog((file == null) ? string.Empty : file.Path, ex.Message);
await DialogManager.OpenDialogAsync(fileSaveErrorDialog, awaitPreviousDialog: false);
if (!fileSaveErrorDialog.IsAborted)
{
NotepadsCore.FocusOnSelectedTextEditor();
}
return false;
}
}
}
} | 35.117647 | 142 | 0.518425 | [
"MIT"
] | Bolshevik35/Notepads | src/Notepads/NotepadsMainPage.IO.cs | 4,778 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel.Design;
using Xunit;
namespace System.Windows.Forms.Design.Editors.Tests.Serialization
{
public class SerializableAttributeTests
{
[Fact]
public void EnsureSerializableAttribute()
{
BinarySerialization.EnsureSerializableAttribute(
typeof(ArrayEditor).Assembly,
new List<string>
{
// This Assembly does not have any serializable types.
});
}
}
}
| 30.12 | 74 | 0.649402 | [
"MIT"
] | 15835229565/winforms-1 | src/System.Windows.Forms.Design.Editors/tests/UnitTests/SerializableAttributeTest.cs | 755 | C# |
using log4net.Core;
using System;
namespace Core.CrossCuttingConcerns.Logging.Log4Net
{
[Serializable]
public class SerializableLogEvent
{
private LoggingEvent _loggingEvent;
public SerializableLogEvent(LoggingEvent loggingEvent)
{
_loggingEvent = loggingEvent;
}
public object Message => _loggingEvent.MessageObject;
}
}
| 18.05 | 58 | 0.745152 | [
"MIT"
] | kurtbogan88/Sennedjem | Core/CrossCuttingConcerns/Logging/Log4Net/SerializableLogEvent.cs | 363 | C# |
using EmbedIO;
using EmbedIO.Routing;
using EmbedIO.WebApi;
using HttpMultipartParser;
using OneShare.Object;
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
namespace OneShare
{
public class ExternalController : WebApiController
{
[Route(HttpVerbs.Get, "/public-key")]
public async Task GetKey()
{
await HttpContext.SendStringAsync(API.RSA.PublicKey, "text/plain", Encoding.UTF8);
return;
}
}
} | 23.115385 | 94 | 0.705491 | [
"MIT"
] | Jerrylum/OneShare | OneShare-Win/Controller/ExternalController.cs | 603 | C# |
using System;
using System.Buffers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using TerraFX.Interop;
using static DirectX12Template.Common.Errors;
using static TerraFX.Interop.Windows;
#nullable enable
namespace DirectX12Template.Common
{
using HRESULT = Int32;
public interface COM_IUnknown
{
unsafe HRESULT QueryInterface(
Guid* riid,
void** ppvObject
);
uint AddRef();
uint Release();
}
[SuppressMessage("ReSharper", "InconsistentNaming")]
public static class DirectXHelper
{
private static int HRESULT(uint i) => (int)i;
private static readonly Dictionary<int, string> _detailedErrorMap = new Dictionary<int, string>
{
[HRESULT(0x00000000)] = "S_OK - Operation successful",
[HRESULT(0x80004004)] = "E_ABORT - Operation aborted",
[HRESULT(0x80070005)] = "E_ACCESSDENIED - General access denied error",
[HRESULT(0x80004005)] = "E_FAIL - Unspecified failure",
[HRESULT(0x80070006)] = "E_HANDLE - Handle that is not valid",
[HRESULT(0x80070057)] = "E_INVALIDARG - One or more arguments are not valid",
[HRESULT(0x80004002)] = "E_NOINTERFACE - No such interface supported",
[HRESULT(0x80004001)] = "E_NOTIMPL - Not implemented",
[HRESULT(0x8007000E)] = "E_OUTOFMEMORY - Failed to allocate necessary memory",
[HRESULT(0x80004003)] = "E_POINTER - Pointer that is not valid",
[HRESULT(0x8000FFFF)] = "E_UNEXPECTED - Unexpected failure"
};
//public static unsafe float* CornflowerBlue = (float*)Marshal.AllocHGlobal(sizeof(float) * 4);
public static unsafe float* CornflowerBlue = (float*)ArrayPool<float>.Shared.Rent(4).AsMemory().Pin().Pointer;
static unsafe DirectXHelper()
{
CornflowerBlue[0] = 0.392156899f;
CornflowerBlue[1] = 0.584313750f;
CornflowerBlue[2] = 0.929411829f;
CornflowerBlue[3] = 1.000000000f;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[DebuggerHidden]
public static unsafe void ReleaseCom(void* com)
{
if (com != null)
{
((IUnknown*)com)->Release();
}
}
[Conditional("DEBUG")]
public static unsafe void ReleaseCom<T>(T* pCom) where T : unmanaged, COM_IUnknown
{
if (pCom != null)
{
pCom->Release();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[DebuggerHidden]
public static void ThrowIfFailed(HRESULT hr)
{
if (FAILED(hr))
ThrowComException(hr);
}
private static unsafe char* Pin(string str)
{
return (char*)str.AsMemory().Pin().Pointer;
}
[Conditional("DEBUG")]
public static unsafe void NameObject(void* d3Dect, string name)
{
;
((ID3D12Object*)d3Dect)->SetName(Pin(name));
}
[Conditional("DEBUG")]
public static unsafe void NameObject<T>(ComPtr<T> d3Dect, string name) where T : unmanaged
{
((ID3D12Object*)d3Dect.Ptr)->SetName(Pin(name));
}
[Conditional("DEBUG")]
public static unsafe void NameObject<T>(ComPtrField<T> d3Dect, string name) where T : unmanaged
{
((ID3D12Object*)d3Dect.Ptr)->SetName(Pin(name));
}
private static string GetErrorDescription(HRESULT hr)
{
if (_detailedErrorMap.TryGetValue(hr, out string value))
{
return $"Unknown exception occured with HRESULT {hr:X8} - \"" +
$"{value}\"";
}
else if (ErrorMap.TryGetValue(hr, out value))
{
return $"Unknown exception occured with HRESULT {hr:X8} - \"" +
$"{value}\"";
}
else
{
return $"Unknown exception occured with HRESULT {hr:X8}";
}
}
public static void ThrowComException(string message)
{
throw new COMException(message);
}
public static void ThrowComException(HRESULT hr)
{
throw new COMException(GetErrorDescription(hr), hr);
}
public static void ThrowComException(string message, HRESULT hr)
{
throw new COMException(message, hr);
}
public static float ConvertDipsToPixels(float dips, float dpi)
{
const float dipsPerInch = 96;
return MathF.Floor(dips * dpi / dipsPerInch + 0.5F);
}
}
} | 31.858974 | 118 | 0.573441 | [
"MIT"
] | john-h-k/DirectX12Template | DirectX12Template/Common/DirectXHelper.cs | 4,972 | C# |
using MarcelloDB;
using MarcelloDB.Collections;
using Newtonsoft.Json;
using ProMama.Models;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
namespace ProMama.Database.Controllers
{
public class FotoDatabaseController
{
Session session = App.DB;
private CollectionFile FotoFile { get; set; }
private Collection<Foto, int> FotoCollection { get; set; }
public FotoDatabaseController()
{
FotoFile = session["fotos.dat"];
FotoCollection = FotoFile.Collection<Foto, int>("fotos", obj => obj.id);
}
public void Save(Foto obj)
{
FotoCollection.Persist(obj);
}
public void SaveIncrementing(Foto obj)
{
obj.id = GetAll().Count() + 1;
Save(obj);
}
public void SaveList(List<Foto> list)
{
foreach (var obj in list)
{
Save(obj);
}
}
public Foto Find(int id)
{
return FotoCollection.Find(id);
}
public List<Foto> GetAll()
{
return FotoCollection.All.ToList();
}
public List<Foto> GetAllByChildId(int id)
{
var retorno = new List<Foto>();
foreach (var obj in GetAll())
{
if (obj.crianca == id)
retorno.Add(obj);
}
return retorno;
}
public ImageSource GetMostRecent(int id)
{
var list = GetAllByChildId(id);
var mesMaisRecente = -1;
Foto maisRecente = null;
if (list.Count() == 0)
{
return "avatar_default.png";
}
else
{
foreach (var f in list)
{
if (f.mes > mesMaisRecente)
{
mesMaisRecente = f.mes;
maisRecente = f;
}
}
return maisRecente.caminho;
}
}
public void Delete(int id)
{
FotoCollection.Destroy(id);
}
public void DeleteByUserId(int id)
{
foreach (var obj in GetAll())
{
var crianca = App.CriancaDatabase.Find(obj.crianca);
if (crianca.user_id == id)
{
Delete(obj.id);
}
}
}
public void WipeTable()
{
foreach (var obj in GetAll())
{
Delete(obj.id);
}
}
public void DumpTable()
{
System.Diagnostics.Debug.WriteLine(JsonConvert.SerializeObject(FotoCollection.All, Formatting.Indented));
}
}
} | 24.372881 | 117 | 0.4621 | [
"Apache-2.0"
] | agharium/ProMama | ProMama/ProMama/Database/Controllers/FotoDatabaseController.cs | 2,878 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HIVCE.BusinessLayer;
using HIVCE.Common;
using System.Configuration;
namespace HIVCE.Presentation
{
public partial class ClinicalEncounter : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Session["PatientInformation"]
//Session["PatientSex"] = "Female";
//Session["PatientAge"] = "12";
int PatientId = 0;
int visitPK = 0;
int locationId = 0;
int userId = 0;
if (!IsPostBack)
{
if (ConfigurationManager.AppSettings["IsDevelopment"].ToString() == "false")
{
if (Session["AppLocationId"] == null)
{
Response.Redirect("~/frmlogin.aspx", true);
}
if (PatientId == 0)
{
Response.Redirect("~/ClinicalForms/frmPatient_Home.aspx", true);
}
}
if (!object.Equals(Session["PatientId"], null))
{
PatientId = Convert.ToInt32(Session["PatientId"]);
}
if (!object.Equals(Session["PatientVisitId"], null))
{
visitPK = Convert.ToInt32(Session["PatientVisitId"]);
}
if (!object.Equals(Session["AppLocationId"], null))
{
locationId = Convert.ToInt32(Session["AppLocationId"]);
}
if (!object.Equals(Session["AppUserId"], null))
{
userId = Convert.ToInt32(Session["AppUserId"]);
}
if (!object.Equals(Session["PatientSex"], null))
{
this.hidGender.Value = Session["PatientSex"].ToString();
}
if (!object.Equals(Session["PatientAge"], null))
{
this.hidDOB.Value = Session["PatientAge"].ToString();
}
if (!object.Equals(Request.QueryString["add"], null))
{
if (Request.QueryString["add"].ToString() == "0")
{
visitPK = 0;
}
}
if (!object.Equals(Request.QueryString["data"], null))
{
string response = string.Empty;
if (Request.QueryString["data"].ToString() == "getdata")
{
response = GetClinicalEnounter(Convert.ToInt32(PatientId), visitPK, locationId);
SendResponse(response);
}
if (Request.QueryString["data"].ToString() == "getpcdata")
{
response = GetPresentingComplaints(Convert.ToInt32(PatientId), visitPK, locationId);
SendResponse(response);
}
if (Request.QueryString["data"].ToString() == "getAddtionalHx")
{
response = GetAddtionalHx(Convert.ToInt32(PatientId), visitPK, locationId);
SendResponse(response);
}
if (Request.QueryString["data"].ToString() == "savetriage")
{
System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
string jsonString = "";
jsonString = sr.ReadToEnd();
response = SaveTriageData(jsonString, PatientId, visitPK, locationId, userId);
SendResponse(response);
}
if (Request.QueryString["data"].ToString() == "savepc")
{
System.IO.StreamReader sr = new System.IO.StreamReader(Request.InputStream);
string jsonString = "";
jsonString = sr.ReadToEnd();
response = SavePresentingComplaintsData(jsonString, PatientId, visitPK, locationId, userId);
SendResponse(response);
}
}
}
}
private string GetClinicalEnounter(int ptn_pk, int visitPK, int locationId)
{
string result = string.Empty;
try
{
BLClinicalEncounter bl = new BLClinicalEncounter();
HIVCE.Common.Entities.ClinicalEncounter obj = bl.GetData(ptn_pk, visitPK, locationId);
result = SerializerUtil.ConverToJson<HIVCE.Common.Entities.ClinicalEncounter>(obj);
}
catch (Exception ex)
{
///CLogger.WriteLog(ELogLevel.ERROR, "GetAnnouncements() exception: " + ex.ToString());
ResponseType response = new ResponseType() { Success = EnumUtil.GetEnumDescription(Success.False) };
result = SerializerUtil.ConverToJson<ResponseType>(response);
}
finally
{
}
return result;
}
private string GetPresentingComplaints(int ptn_pk, int visitPK, int locationId)
{
string result = string.Empty;
try
{
BLClinicalEncounter bl = new BLClinicalEncounter();
HIVCE.Common.Entities.PresentingComplaint obj = bl.GetPresentingComplaints(ptn_pk, visitPK, locationId);
result = SerializerUtil.ConverToJson<HIVCE.Common.Entities.PresentingComplaint>(obj);
}
catch (Exception ex)
{
///CLogger.WriteLog(ELogLevel.ERROR, "GetAnnouncements() exception: " + ex.ToString());
ResponseType response = new ResponseType() { Success = EnumUtil.GetEnumDescription(Success.False) };
result = SerializerUtil.ConverToJson<ResponseType>(response);
}
finally
{
}
return result;
}
private string GetAddtionalHx(int ptn_pk, int visitPK, int locationId)
{
string result = string.Empty;
try
{
BLClinicalEncounter bl = new BLClinicalEncounter();
HIVCE.Common.Entities.AddtionalHx obj = bl.GetAddtionalHx(ptn_pk, visitPK, locationId);
result = SerializerUtil.ConverToJson<HIVCE.Common.Entities.AddtionalHx>(obj);
}
catch (Exception ex)
{
///CLogger.WriteLog(ELogLevel.ERROR, "GetAnnouncements() exception: " + ex.ToString());
ResponseType response = new ResponseType() { Success = EnumUtil.GetEnumDescription(Success.False) };
result = SerializerUtil.ConverToJson<ResponseType>(response);
}
finally
{
}
return result;
}
private string SaveTriageData(string nodeJson, int ptn_pk, int visitPK, int locationId, int userId)
{
string result = string.Empty;
ResponseType ObjResponse = new ResponseType();
try
{
HIVCE.Common.Entities.Triage triage = SerializerUtil.ConverToObject<HIVCE.Common.Entities.Triage>(nodeJson);
BLClinicalEncounter blTP = new BLClinicalEncounter();
triage.Ptn_pk = ptn_pk;
triage.Visit_Id = visitPK;
triage.LocationId = locationId;
bool flag = blTP.SaveUpdateTriage(triage, userId);
if (flag)
{
ObjResponse.Success = EnumUtil.GetEnumDescription(Success.True);
}
else
{
ObjResponse.Success = EnumUtil.GetEnumDescription(Success.False);
}
}
catch (Exception ex)
{
ObjResponse.Success = EnumUtil.GetEnumDescription(Success.False);
}
finally
{
}
result = SerializerUtil.ConverToJson<ResponseType>(ObjResponse);
return result;
}
private string SavePresentingComplaintsData(string nodeJson, int ptn_pk, int visitPK, int locationId, int userId)
{
string result = string.Empty;
ResponseType ObjResponse = new ResponseType();
try
{
HIVCE.Common.Entities.PresentingComplaint obj = SerializerUtil.ConverToObject<HIVCE.Common.Entities.PresentingComplaint>(nodeJson);
BLClinicalEncounter blTP = new BLClinicalEncounter();
obj.Ptn_pk = ptn_pk;
obj.Visit_Id = visitPK;
obj.LocationId = locationId;
bool flag = blTP.SaveUpdatePresentingComplaintsData(obj, userId, locationId);
if (flag)
{
ObjResponse.Success = EnumUtil.GetEnumDescription(Success.True);
}
else
{
ObjResponse.Success = EnumUtil.GetEnumDescription(Success.False);
}
}
catch (Exception ex)
{
ObjResponse.Success = EnumUtil.GetEnumDescription(Success.False);
}
finally
{
}
result = SerializerUtil.ConverToJson<ResponseType>(ObjResponse);
return result;
}
private void SendResponse(string data)
{
Response.Clear();
Response.ContentType = "application/json";
Response.AddHeader("Content-type", "text/json");
Response.AddHeader("Content-type", "application/json");
Response.Write(data);
Response.End();
}
}
} | 37.902256 | 147 | 0.509423 | [
"MIT"
] | uon-crissp/IQCare | SourceBase/IQCare.HIVCE/HIVCE.Presentation/ClinicalEncounter.aspx.cs | 10,084 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DB_LAB2.Models.Shared
{
public class PageViewModel
{
public int PageNumber { get; private set; }
public int TotalPages { get; private set; }
public PageViewModel(long count, int pageNumber, int pageSize)
{
PageNumber = pageNumber;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
}
public bool HasPreviousPage
{
get
{
return (PageNumber > 1);
}
}
public bool HasNextPage
{
get
{
return (PageNumber < TotalPages);
}
}
}
}
| 21.388889 | 70 | 0.527273 | [
"MIT"
] | FireAndBlood12/DB_Lab2 | DB_LAB2/Models/Shared/PageViewModel.cs | 772 | C# |
using Dnc.WPF.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
namespace Dnc.WPF.Ui
{
/// <summary>
/// The basic class for a <see cref="Page"/>.
/// </summary>
public class BasePage<TViewModel>
: Page
where TViewModel : NotificationObject, new()
{
private TViewModel mVm;
public PageAnimation PageLoadAnimation { get; set; } = PageAnimation.SlideAndFadeInFromRight;
public PageAnimation PageUnloadAnimation { get; set; } = PageAnimation.SlideAndFadeOutToLeft;
public double SlideSeconds { get; set; } = 0.8;
public TViewModel Vm
{
get
{
return mVm;
}
set
{
if (mVm == value)
return;
mVm = value;
DataContext = mVm;
}
}
public BasePage()
{
if (PageLoadAnimation != PageAnimation.None)
Visibility = Visibility.Collapsed;
Loaded += BasePage_Loaded;
Vm = new TViewModel();
}
private async void BasePage_Loaded(object sender, RoutedEventArgs e)
{
await AnimateIn();
}
public async Task AnimateIn()
{
if (PageLoadAnimation == PageAnimation.None)
return;
switch (PageLoadAnimation)
{
case PageAnimation.SlideAndFadeInFromRight:
await this.SlideAndFadeInAsync(SlideSeconds, WindowWidth);
break;
default:
break;
}
}
public async Task AnimateOut()
{
if (PageUnloadAnimation == PageAnimation.None)
return;
switch (PageUnloadAnimation)
{
case PageAnimation.SlideAndFadeOutToLeft:
await this.SlideAndFadeOutAsync(SlideSeconds, WindowWidth);
break;
default:
break;
}
}
}
}
| 24.945055 | 101 | 0.522026 | [
"MIT"
] | gainorloss/Dnc.Core | src/Dnc.WPF.Ui/Pages/BasePage.cs | 2,272 | C# |
namespace Prometyum.Sample
{
public abstract class SampleDomainTestBase : SampleTestBase<SampleDomainTestModule>
{
}
}
| 16.75 | 88 | 0.738806 | [
"MIT"
] | ozturkmuslum/Prometyum.Abp.AspNetCore.Mvc.UI.Bootstrap | test/Prometyum.Sample.Domain.Tests/SampleDomainTestBase.cs | 136 | 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.Runtime.InteropServices;
namespace System.ComponentModel.Design
{
/// <summary>
/// This event is raised by the <see cref="DesignerActionService"/> when a shortcut is either added or removed to/from the related object.
/// </summary>
public delegate void DesignerActionListsChangedEventHandler(object sender, DesignerActionListsChangedEventArgs e);
}
| 41.928571 | 143 | 0.764906 | [
"MIT"
] | Amy-Li03/winforms | src/System.Windows.Forms.Design/src/System/ComponentModel/Design/DesignerActionListsChangedEventHandler.cs | 589 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using GitVersion;
using GitVersion.BuildServers;
using GitVersion.VersionCalculation;
using GitVersionCore.Tests.Helpers;
using Microsoft.Extensions.DependencyInjection;
using NUnit.Framework;
using Shouldly;
namespace GitVersionCore.Tests.BuildServers
{
[TestFixture]
public class GitLabCiTests : TestBase
{
private GitLabCi buildServer;
private IServiceProvider sp;
[SetUp]
public void SetUp()
{
sp = ConfigureServices(services =>
{
services.AddSingleton<GitLabCi>();
});
buildServer = sp.GetService<GitLabCi>();
}
[Test]
public void GenerateSetVersionMessageReturnsVersionAsIsAlthoughThisIsNotUsedByJenkins()
{
var vars = new TestableVersionVariables(fullSemVer: "0.0.0-Beta4.7");
buildServer.GenerateSetVersionMessage(vars).ShouldBe("0.0.0-Beta4.7");
}
[Test]
public void GenerateMessageTest()
{
var generatedParameterMessages = buildServer.GenerateSetParameterMessage("name", "value");
generatedParameterMessages.Length.ShouldBe(1);
generatedParameterMessages[0].ShouldBe("GitVersion_name=value");
}
[Test]
public void WriteAllVariablesToTheTextWriter()
{
var assemblyLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var f = Path.Combine(assemblyLocation, "jenkins_this_file_should_be_deleted.properties");
try
{
AssertVariablesAreWrittenToFile(f);
}
finally
{
File.Delete(f);
}
}
private void AssertVariablesAreWrittenToFile(string file)
{
var writes = new List<string>();
var semanticVersion = new SemanticVersion
{
Major = 1,
Minor = 2,
Patch = 3,
PreReleaseTag = "beta1",
BuildMetaData = "5"
};
semanticVersion.BuildMetaData.CommitDate = DateTimeOffset.Parse("2014-03-06 23:59:59Z");
semanticVersion.BuildMetaData.Sha = "commitSha";
var config = new TestEffectiveConfiguration();
var variableProvider = sp.GetService<IVariableProvider>();
var variables = variableProvider.GetVariablesFor(semanticVersion, config, false);
buildServer.WithPropertyFile(file);
buildServer.WriteIntegration(writes.Add, variables);
writes[1].ShouldBe("1.2.3-beta.1+5");
File.Exists(file).ShouldBe(true);
var props = File.ReadAllText(file);
props.ShouldContain("GitVersion_Major=1");
props.ShouldContain("GitVersion_Minor=2");
}
}
}
| 30.515464 | 102 | 0.607095 | [
"MIT"
] | rainersigwald/GitVersion | src/GitVersionCore.Tests/BuildServers/GitLabCiTests.cs | 2,960 | C# |
#region
//
// Bdev.Net.Dns by Rob Philpott, Big Developments Ltd. Please send all bugs/enhancements to
// rob@bigdevelopments.co.uk This file and the code contained within is freeware and may be
// distributed and edited without restriction.
//
// refactored by Hans Wolff
#endregion
using System.Net;
namespace Bdev.Net.Dns
{
/// <summary>
/// ANAME Resource Record (RR) (RFC1035 3.4.1)
/// </summary>
public class ANameRecord : RecordBase
{
// An ANAME records consists simply of an IP address
private readonly IPAddress _ipAddress;
// expose this IP address r/o to the world
public IPAddress IPAddress
{
get { return _ipAddress; }
}
/// <summary>
/// Constructs an ANAME record by reading bytes from a return message
/// </summary>
/// <param name="pointer">A logical pointer to the bytes holding the record</param>
internal ANameRecord(Pointer pointer)
{
byte b1 = pointer.ReadByte();
byte b2 = pointer.ReadByte();
byte b3 = pointer.ReadByte();
byte b4 = pointer.ReadByte();
// this next line's not brilliant - couldn't find a better way though
_ipAddress = IPAddress.Parse(string.Format("{0}.{1}.{2}.{3}", b1, b2, b3, b4));
}
public override string ToString()
{
return _ipAddress.ToString();
}
}
}
| 25.979592 | 92 | 0.689709 | [
"MIT"
] | RandallFlagg/simple.mailserver | Simple.MailServer/Dns/ANameRecord.cs | 1,273 | C# |
using LetsGraph.Model.Base.Graph;
namespace LetsGraph.Model.Base
{
/// <summary>
/// Base class of all relations in this model.
/// </summary>
public class Relation : Edge<Item>
{
/// <summary>
/// The type of this relation.
/// </summary>
public RelationType Type { get; private set; }
/// <summary>
/// Creates relation of given type between source and target item.
/// </summary>
/// <param name="source">Start item of the relation.</param>
/// <param name="target">End item of the relation.</param>
/// <param name="type">Type of the relation.</param>
internal Relation(Item source, Item target, RelationType type) : base(source, target)
{
Type = type;
}
}
}
| 28.821429 | 93 | 0.568773 | [
"MIT"
] | meolus/LetsGraph | LetsGraph.Model/Base/Relation.cs | 809 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Allgemeine Informationen über eine Assembly werden über folgende
// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern,
// die einer Assembly zugeordnet sind.
[assembly: AssemblyTitle("uprove_uprovecommunicationissuing_tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("uprove_uprovecommunicationissuing_tests")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Wenn ComVisible auf "false" festgelegt wird, sind die Typen innerhalb dieser Assembly
// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von
// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen.
[assembly: ComVisible(false)]
// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird
[assembly: Guid("4ac13834-94e5-40ba-ba8a-35e000f24719")]
// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten:
//
// Hauptversion
// Nebenversion
// Buildnummer
// Revision
//
// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern
// übernehmen, indem Sie "*" eingeben:
// [Assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 41.945946 | 106 | 0.76933 | [
"MIT"
] | fablei/uprove_uprovecommunicationissuing | uprove_uprovecommunicationissuing_tests/Properties/AssemblyInfo.cs | 1,569 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.Text.Json
{
public sealed partial class JsonDocument
{
private struct StackRowStack : IDisposable
{
private byte[] _rentedBuffer;
private int _topOfStack;
internal StackRowStack(int initialSize)
{
_rentedBuffer = ArrayPool<byte>.Shared.Rent(initialSize);
_topOfStack = _rentedBuffer.Length;
}
public void Dispose()
{
byte[] toReturn = _rentedBuffer;
_rentedBuffer = null!;
_topOfStack = 0;
if (toReturn != null)
{
// The data in this rented buffer only conveys the positions and
// lengths of tokens in a document, but no content; so it does not
// need to be cleared.
ArrayPool<byte>.Shared.Return(toReturn);
}
}
internal void Push(StackRow row)
{
if (_topOfStack < StackRow.Size)
{
Enlarge();
}
_topOfStack -= StackRow.Size;
MemoryMarshal.Write(_rentedBuffer.AsSpan(_topOfStack), ref row);
}
internal StackRow Pop()
{
Debug.Assert(_topOfStack <= _rentedBuffer.Length - StackRow.Size);
StackRow row = MemoryMarshal.Read<StackRow>(_rentedBuffer.AsSpan(_topOfStack));
_topOfStack += StackRow.Size;
return row;
}
private void Enlarge()
{
byte[] toReturn = _rentedBuffer;
_rentedBuffer = ArrayPool<byte>.Shared.Rent(toReturn.Length * 2);
Buffer.BlockCopy(
toReturn,
_topOfStack,
_rentedBuffer,
_rentedBuffer.Length - toReturn.Length + _topOfStack,
toReturn.Length - _topOfStack);
_topOfStack += _rentedBuffer.Length - toReturn.Length;
// The data in this rented buffer only conveys the positions and
// lengths of tokens in a document, but no content; so it does not
// need to be cleared.
ArrayPool<byte>.Shared.Return(toReturn);
}
}
}
}
| 33.265823 | 95 | 0.52207 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.StackRowStack.cs | 2,628 | C# |
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Wikiled.Text.Analysis.Tests")] | 25.75 | 61 | 0.815534 | [
"MIT"
] | AndMu/Wikiled.Text.Analysis | src/Wikiled.Text.Analysis/Properties/AssemblyInfo.cs | 105 | 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("ChainOfResponsibility")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ChainOfResponsibility")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[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("82c985f6-0f28-4a07-a1a2-f8cbd388084e")]
// 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.72973 | 84 | 0.75157 | [
"CC0-1.0"
] | Lenscorpx/GOF_DesignPatterns_Fun | ChainOfResponsibilityPattern/Properties/AssemblyInfo.cs | 1,436 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Eleon.Modding;
namespace EmpyrionNetAPIDefinitions
{
public class APIEvent
{
public CmdId CmdId;
public Type ParamType;
public APIEvent(CmdId cmdId, Type paramType)
{
CmdId = cmdId;
ParamType = paramType;
}
}
public class APIRequest
{
public CmdId CmdId;
public Type ParamType;
public CmdId ResponseCmdId;
public APIRequest(CmdId cmdId, Type paramType, CmdId responseCmdId)
{
CmdId = cmdId;
ParamType = paramType;
ResponseCmdId = responseCmdId;
}
}
public static class APIManifest
{
public static List<APIRequest> RequestManifest = new List<APIRequest>()
{
new APIRequest(CmdId.Request_Playfield_List, null, CmdId.Event_Playfield_List),
new APIRequest(CmdId.Request_Playfield_Stats, typeof(PString), CmdId.Event_Playfield_Stats),
new APIRequest(CmdId.Request_Dedi_Stats, null, CmdId.Event_Dedi_Stats),
new APIRequest(CmdId.Request_GlobalStructure_List, null, CmdId.Event_GlobalStructure_List),
new APIRequest(CmdId.Request_GlobalStructure_Update, typeof(PString), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Structure_Touch, typeof(Id), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Structure_BlockStatistics, typeof(Id), CmdId.Event_Structure_BlockStatistics),
new APIRequest(CmdId.Request_Player_Info, typeof(Id), CmdId.Event_Player_Info),
new APIRequest(CmdId.Request_Player_List, null, CmdId.Event_Player_List),
new APIRequest(CmdId.Request_Player_GetInventory, typeof(Id), CmdId.Event_Player_Inventory),
new APIRequest(CmdId.Request_Player_SetInventory, typeof(Inventory), CmdId.Event_Player_Inventory),
new APIRequest(CmdId.Request_Player_AddItem, typeof(IdItemStack), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Player_Credits, typeof(Id), CmdId.Event_Player_Credits),
new APIRequest(CmdId.Request_Player_SetCredits, typeof(IdCredits), CmdId.Event_Player_Credits),
new APIRequest(CmdId.Request_Player_AddCredits, typeof(IdCredits), CmdId.Event_Player_Credits),
new APIRequest(CmdId.Request_Blueprint_Finish, typeof(Id), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Blueprint_Resources, typeof(BlueprintResources), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Player_ChangePlayerfield, typeof(IdPlayfieldPositionRotation), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Player_ItemExchange, typeof(ItemExchangeInfo), CmdId.Event_Player_ItemExchange),
new APIRequest(CmdId.Request_Player_SetPlayerInfo, typeof(PlayerInfoSet), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Entity_Teleport, typeof(IdPositionRotation), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Entity_ChangePlayfield, typeof(IdPlayfieldPositionRotation), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Entity_Destroy, typeof(Id), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Entity_PosAndRot, typeof(Id), CmdId.Event_Entity_PosAndRot),
new APIRequest(CmdId.Request_Entity_Spawn, typeof(EntitySpawnInfo), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Get_Factions, typeof(Id), CmdId.Event_Get_Factions),
new APIRequest(CmdId.Request_NewEntityId, null, CmdId.Event_NewEntityId),
new APIRequest(CmdId.Request_AlliancesAll, null, CmdId.Event_AlliancesAll),
new APIRequest(CmdId.Request_AlliancesFaction, typeof(AlliancesFaction), CmdId.Event_AlliancesFaction),
new APIRequest(CmdId.Request_Load_Playfield, typeof(PlayfieldLoad), CmdId.Event_Ok),
new APIRequest(CmdId.Request_ConsoleCommand, typeof(PString), CmdId.Event_Ok),
new APIRequest(CmdId.Request_GetBannedPlayers, null, CmdId.Event_BannedPlayers),
new APIRequest(CmdId.Request_InGameMessage_SinglePlayer, typeof(IdMsgPrio), CmdId.Event_Ok),
new APIRequest(CmdId.Request_InGameMessage_AllPlayers, typeof(IdMsgPrio), CmdId.Event_Ok),
new APIRequest(CmdId.Request_InGameMessage_Faction, typeof(IdMsgPrio), CmdId.Event_Ok),
new APIRequest(CmdId.Request_ShowDialog_SinglePlayer, typeof(DialogBoxData), CmdId.Event_DialogButtonIndex),
new APIRequest(CmdId.Request_Player_GetAndRemoveInventory, typeof(Id), CmdId.Event_Player_GetAndRemoveInventory),
new APIRequest(CmdId.Request_Playfield_Entity_List, typeof(PString), CmdId.Event_Playfield_Entity_List),
new APIRequest(CmdId.Request_Entity_Destroy2, typeof(IdPlayfield), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Entity_Export, typeof(EntityExportInfo), CmdId.Event_Ok),
new APIRequest(CmdId.Request_Entity_SetName, typeof(IdPlayfieldName), CmdId.Event_Ok),
//new APIRequest(CmdId.Request_ChatMessageEx, typeof(ChatMsgData), CmdId.Event_Ok),
};
public static List<APIEvent> EventManifest = new List<APIEvent>()
{
new APIEvent(CmdId.Event_Playfield_Loaded, typeof(PlayfieldLoad)),
new APIEvent(CmdId.Event_Playfield_Unloaded, typeof(PlayfieldLoad)),
new APIEvent(CmdId.Event_Player_Connected, typeof(Id)),
new APIEvent(CmdId.Event_Player_Disconnected, typeof(Id)),
new APIEvent(CmdId.Event_Player_ChangedPlayfield, typeof(IdPlayfield)),
new APIEvent(CmdId.Event_Player_DisconnectedWaiting, typeof(Id)),
new APIEvent(CmdId.Event_Faction_Changed, typeof(FactionChangeInfo)),
new APIEvent(CmdId.Event_Statistics, typeof(StatisticsParam)),
new APIEvent(CmdId.Event_ChatMessage, typeof(ChatInfo)),
new APIEvent(CmdId.Event_TraderNPCItemSold, typeof(TraderNPCItemSoldInfo)),
new APIEvent(CmdId.Event_ConsoleCommand, typeof(ConsoleCommandInfo)),
new APIEvent(CmdId.Event_PdaStateChange, typeof(PdaStateInfo)),
new APIEvent(CmdId.Event_GameEvent, typeof(GameEventData)),
new APIEvent(CmdId.Event_AlliancesAll, typeof(AlliancesTable)),
new APIEvent(CmdId.Event_AlliancesFaction, typeof(AlliancesFaction)),
new APIEvent(CmdId.Event_BannedPlayers, typeof(IdList)),
new APIEvent(CmdId.Event_Dedi_Stats, typeof(DediStats)),
new APIEvent(CmdId.Event_Entity_PosAndRot, typeof(IdPositionRotation)),
new APIEvent(CmdId.Event_Get_Factions, typeof(FactionInfoList)),
new APIEvent(CmdId.Event_GlobalStructure_List, typeof(GlobalStructureList)),
new APIEvent(CmdId.Event_NewEntityId, typeof(Id)),
new APIEvent(CmdId.Event_Ok, null),
new APIEvent(CmdId.Event_Player_Credits, typeof(IdCredits)),
new APIEvent(CmdId.Event_Player_GetAndRemoveInventory, typeof(Inventory)),
new APIEvent(CmdId.Event_Player_Info, typeof(PlayerInfo)),
new APIEvent(CmdId.Event_Player_Inventory, typeof(Inventory)),
new APIEvent(CmdId.Event_Player_ItemExchange, typeof(ItemExchangeInfo)),
new APIEvent(CmdId.Event_Player_List, typeof(IdList)),
new APIEvent(CmdId.Event_Playfield_Entity_List, typeof(PlayfieldEntityList)),
new APIEvent(CmdId.Event_Playfield_List, typeof(PlayfieldList)),
new APIEvent(CmdId.Event_Playfield_Stats, typeof(PlayfieldStats)),
new APIEvent(CmdId.Event_Structure_BlockStatistics, typeof(IdStructureBlockInfo)),
new APIEvent(CmdId.Event_DialogButtonIndex, typeof(IdAndIntValue)),
new APIEvent(CmdId.Event_ChatMessageEx, typeof(ChatMsgData))
};
public static Dictionary<CmdId, APIEvent> APIEventTable = EventManifest.ToDictionary(x => x.CmdId);
public static Dictionary<CmdId, APIRequest> APIRequestTable = RequestManifest.ToDictionary(x => x.CmdId);
public static Dictionary<CmdId, APIEvent> APIRequestResponseTable = RequestManifest
.Select(x => new KeyValuePair<CmdId, APIEvent>(x.CmdId, APIEventTable[x.ResponseCmdId]))
.ToDictionary(x => x.Key, x => x.Value);
}
}
| 64.787402 | 125 | 0.727516 | [
"MIT"
] | GitHub-TC/EmpyrionNetAPIAccess | EmpyrionNetAPIDefinitions/APIManifest.cs | 8,230 | C# |
namespace Plugin.Firebase.Auth
{
public sealed class ActionCodeSettings
{
public void SetAndroidPackageName(string packageName, bool installIfNotAvailable, string minimumVersion)
{
AndroidPackageName = packageName;
AndroidInstallIfNotAvailable = installIfNotAvailable;
AndroidMinimumVersion = minimumVersion;
}
public string Url { get; set; }
public string IOSBundleId { get; set; }
public string AndroidPackageName { get; private set; }
public string AndroidMinimumVersion { get; private set; }
public bool AndroidInstallIfNotAvailable { get; private set; }
public bool HandleCodeInApp { get; set; }
}
} | 38.578947 | 112 | 0.667121 | [
"MIT"
] | TobiasBuchholz/Plugin.Firebase | src/Shared/Auth/ActionCodeSettings.cs | 733 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Tailviewer.Api;
// ReSharper disable once CheckNamespace
namespace Tailviewer.Core
{
/// <summary>
/// A simple accessor which provides access to log entries produced by a <see cref="ILogEntryParser" />.
/// Parsing happens on demand when corresponding properties are requested.
/// </summary>
public sealed class GenericTextLogSource
: ILogSource
{
private readonly ProxyLogListenerCollection _listeners;
private readonly ILogEntryParser _parser;
private readonly IReadOnlyList<IColumnDescriptor> _parsedColumns;
private readonly IReadOnlyList<IColumnDescriptor> _allColumns;
private readonly IReadOnlyLogEntry _nothingParsed;
private ILogSource _source;
/// <summary>
/// Initializes this object.
/// </summary>
/// <param name="source"></param>
/// <param name="parser"></param>
public GenericTextLogSource(ILogSource source,
ILogEntryParser parser)
{
_source = source ?? throw new ArgumentNullException(nameof(source));
_parser = parser;
_parsedColumns = _parser.Columns.ToList();
_allColumns = _source.Columns.Concat(_parsedColumns).Distinct().ToList();
_listeners = new ProxyLogListenerCollection(source, this);
_nothingParsed = new ReadOnlyLogEntry(_parsedColumns);
}
/// <inheritdoc />
public IReadOnlyList<IColumnDescriptor> Columns => _allColumns;
/// <inheritdoc />
public void AddListener(ILogSourceListener listener, TimeSpan maximumWaitTime, int maximumLineCount)
{
_listeners.AddListener(listener, maximumWaitTime, maximumLineCount);
}
/// <inheritdoc />
public void RemoveListener(ILogSourceListener listener)
{
_listeners.RemoveListener(listener);
}
/// <inheritdoc />
public IReadOnlyList<IReadOnlyPropertyDescriptor> Properties
{
get { return _source?.Properties ?? new IReadOnlyPropertyDescriptor[0]; }
}
/// <inheritdoc />
public object GetProperty(IReadOnlyPropertyDescriptor property)
{
var source = _source;
if (source != null)
return source.GetProperty(property);
return property.DefaultValue;
}
/// <inheritdoc />
public T GetProperty<T>(IReadOnlyPropertyDescriptor<T> property)
{
var source = _source;
if (source != null)
return source.GetProperty(property);
return property.DefaultValue;
}
/// <inheritdoc />
public void SetProperty(IPropertyDescriptor property, object value)
{
_source?.SetProperty(property, value);
}
/// <inheritdoc />
public void SetProperty<T>(IPropertyDescriptor<T> property, T value)
{
_source?.SetProperty(property, value);
}
/// <inheritdoc />
public void GetAllProperties(IPropertiesBuffer destination)
{
_source?.GetAllProperties(destination);
}
/// <inheritdoc />
public void GetColumn<T>(IReadOnlyList<LogLineIndex> sourceIndices,
IColumnDescriptor<T> column,
T[] destination,
int destinationIndex,
LogSourceQueryOptions queryOptions)
{
if (sourceIndices == null)
throw new ArgumentNullException(nameof(sourceIndices));
if (column == null)
throw new ArgumentNullException(nameof(column));
if (destination == null)
throw new ArgumentNullException(nameof(destination));
if (destinationIndex < 0)
throw new ArgumentOutOfRangeException(nameof(destinationIndex));
if (destinationIndex + sourceIndices.Count > destination.Length)
throw new ArgumentException("The given buffer must have an equal or greater length than destinationIndex+length");
GetEntries(sourceIndices,
new SingleColumnLogBufferView<T>(column, destination, destinationIndex, sourceIndices.Count),
0, queryOptions);
}
/// <inheritdoc />
public void GetEntries(IReadOnlyList<LogLineIndex> sourceIndices,
ILogBuffer destination,
int destinationIndex,
LogSourceQueryOptions queryOptions)
{
var source = _source;
if (source != null)
{
var columnsToCopy = new IColumnDescriptor[] {Core.Columns.Index, Core.Columns.RawContent};
var tmp = new LogBufferArray(sourceIndices.Count, columnsToCopy);
source.GetEntries(sourceIndices, tmp, 0, queryOptions);
foreach (var column in columnsToCopy)
{
if (destination.Contains(column))
{
destination.CopyFrom(column, destinationIndex, tmp, new Int32Range(0, sourceIndices.Count));
}
}
for (var i = 0; i < sourceIndices.Count; ++i)
{
var parsedLogEntry = _parser.Parse(tmp[i]);
if (parsedLogEntry != null)
destination[destinationIndex + i].CopyFrom(parsedLogEntry);
else
destination[destinationIndex + i].CopyFrom(_nothingParsed);
}
}
else
{
destination.FillDefault(destinationIndex, sourceIndices.Count);
}
}
/// <inheritdoc />
public LogLineIndex GetLogLineIndexOfOriginalLineIndex(LogLineIndex originalLineIndex)
{
return _source?.GetLogLineIndexOfOriginalLineIndex(originalLineIndex) ?? LogLineIndex.Invalid;
}
#region Implementation of IDisposable
/// <inheritdoc />
public void Dispose()
{
_source?.Dispose();
_source = null;
}
#endregion
}
} | 30.471264 | 118 | 0.698038 | [
"MIT"
] | Kittyfisto/SharpTail | src/Tailviewer.Core/Sources/Text/GenericTextLogSource.cs | 5,304 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
namespace OnlineStore.WebUI.Helper
{
public class ConfigurationHelper
{
public static string GetDefaultPassword()
{
return WebConfigurationManager.AppSettings["configFile"];
}
public static string GetAppId()
{
return WebConfigurationManager.AppSettings["CreditAppId"];
}
public static string GetSharedKey()
{
return WebConfigurationManager.AppSettings["CreditAppSharedKey"];
}
public static string GetAppId2()
{
return WebConfigurationManager.AppSettings["CreditAppId2"];
}
public static string GetSharedKey2()
{
return WebConfigurationManager.AppSettings["CreditAppSharedKey2"];
}
}
} | 28 | 78 | 0.643973 | [
"MIT"
] | BlueForeverI/online-store | OnlineStore.WebUI/Helper/ConfigurationHelper.cs | 898 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.IO;
using System.Threading.Tasks;
using System.Web.Hosting;
using System.Web.Http;
using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
namespace SynchronousIO.WebRole.Controllers
{
public class AsyncUploadController : ApiController
{
[HttpGet]
public async Task UploadFileAsync()
{
var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("uploadedfiles");
await container.CreateIfNotExistsAsync();
var blockBlob = container.GetBlockBlobReference("myblob");
// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = File.OpenRead(HostingEnvironment.MapPath("~/FileToUpload.txt")))
{
await blockBlob.UploadFromStreamAsync(fileStream);
}
}
}
}
| 35.382353 | 124 | 0.686617 | [
"MIT"
] | uQr/performance-optimization | SynchronousIO/SynchronousIO.WebRole/Controllers/AsyncUploadController.cs | 1,205 | 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("NikTileEditor")]
[assembly: AssemblyProduct("NikTileEditor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("Teterski Softworks Inc.")]
[assembly: AssemblyCopyright("© 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. Only Windows
// assemblies support COM.
[assembly: ComVisible(false)]
// On Windows, the following GUID is for the ID of the typelib if this
// project is exposed to COM. On other platforms, it unique identifies the
// title storage container when deploying this assembly to the device.
[assembly: Guid("1604d611-be96-499e-b12a-d1c4dcada19f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("0.1.0.0")] | 39.441176 | 77 | 0.756898 | [
"MIT"
] | TeterskiSoftworks/NikTiles | NikTilesEditor/NikTilesEditor/Properties/AssemblyInfo.cs | 1,344 | C# |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace GodLesZ.Library.Json.Bson
{
internal enum BsonType : sbyte
{
Number = 1,
String = 2,
Object = 3,
Array = 4,
Binary = 5,
Undefined = 6,
Oid = 7,
Boolean = 8,
Date = 9,
Null = 10,
Regex = 11,
Reference = 12,
Code = 13,
Symbol = 14,
CodeWScope = 15,
Integer = 16,
TimeStamp = 17,
Long = 18,
MinKey = -1,
MaxKey = 127
}
} | 30.705882 | 68 | 0.693487 | [
"MIT"
] | GodLesZ/godlesz.library | Json/Bson/BsonType.cs | 1,568 | C# |
// Licensed to Laurent Ellerbach under one or more agreements.
// Laurent Ellerbach licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
namespace Nabaztag.Net.Models
{
/// <summary>
/// {"type":"mode","request_id":request_id,"mode":mode,"events":events}
/// Emitter: services
/// </summary>
public class EventMode
{
/// <summary>
/// Type is mode
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
[JsonProperty(PropertyName = "type")]
public PaquetType Type { get { return PaquetType.Mode; } }
/// <summary>
/// A request id, optional?
/// </summary>
[JsonProperty(PropertyName = "request_id", NullValueHandling = NullValueHandling.Ignore)]
public string RequestId { get; set; }
/// <summary>
/// The mode type
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
[JsonProperty(PropertyName = "mode")]
public ModeType Mode { get; set; }
/// <summary>
/// The event type
/// </summary>
[JsonProperty(ItemConverterType = typeof(StringEnumConverter), PropertyName = "events")]
public IEnumerable<EventType> Events { get; set; }
}
}
| 32.045455 | 97 | 0.619149 | [
"MIT"
] | Ellerbach/Nabaztag.Net | Nabaztag.Net/Models/EventMode.cs | 1,412 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: IMethodRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The interface IDeviceManagementReportsGetUnhealthyDefenderAgentsReportRequestBuilder.
/// </summary>
public partial interface IDeviceManagementReportsGetUnhealthyDefenderAgentsReportRequestBuilder : IBaseRequestBuilder
{
/// <summary>
/// Builds the request.
/// </summary>
/// <param name="options">The query and header options for the request.</param>
/// <returns>The built request.</returns>
IDeviceManagementReportsGetUnhealthyDefenderAgentsReportRequest Request(IEnumerable<Option> options = null);
}
}
| 40.62069 | 153 | 0.620543 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/requests/IDeviceManagementReportsGetUnhealthyDefenderAgentsReportRequestBuilder.cs | 1,178 | C# |
namespace cqhttp.Cyan.Clients {
/// <summary>
/// 反向websocket连接方式
/// </summary>
public class CQReverseWSClient : CQApiClient {
/// <summary>
/// 当cqhttp中use_ws_reverse配置项为true时使用
/// </summary>
/// <param name="bind_port">端口</param>
/// <param name="api_path">即ws_reverse_api_url</param>
/// <param name="event_path">即ws_reverse_event_url</param>
/// <param name="access_token"></param>
/// <param name="use_group_table"></param>
/// <param name="use_message_table"></param>
/// <returns></returns>
public CQReverseWSClient (
int bind_port,
string api_path,
string event_path,
string access_token = "",
bool use_group_table = false,
bool use_message_table = false
) : base (
new Callers.ReverseWSCaller (bind_port, api_path, access_token),
new Listeners.ReverseWSListener (bind_port, event_path, access_token),
use_group_table, use_message_table) {
(this.listener as Listeners.ReverseWSListener).caller = this.caller;
this.listener.RegisterHandler (HandleEvent);
initiate_task = System.Threading.Tasks.Task.Run(Initiate);
}
}
} | 38.176471 | 82 | 0.598613 | [
"MIT"
] | frank-bots/cqhttp.Cyan | cqhttp.Cyan/Clients/CQReverseWSClient.cs | 1,336 | C# |
// <auto-generated>
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Balivo.AppCenterClient.Models
{
using Newtonsoft.Json;
using System.Linq;
public partial class UpdateCheckResponse : CodePushReleaseInfo
{
/// <summary>
/// Initializes a new instance of the UpdateCheckResponse class.
/// </summary>
public UpdateCheckResponse()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the UpdateCheckResponse class.
/// </summary>
public UpdateCheckResponse(bool isAvailable, string targetBinaryRange = default(string), string description = default(string), bool? isDisabled = default(bool?), bool? isMandatory = default(bool?), int? rollout = default(int?), string downloadUrl = default(string), double? packageSize = default(double?), bool? shouldRunBinaryVersion = default(bool?), bool? updateAppVersion = default(bool?), string packageHash = default(string), string label = default(string))
: base(targetBinaryRange, description, isDisabled, isMandatory, rollout)
{
DownloadUrl = downloadUrl;
IsAvailable = isAvailable;
PackageSize = packageSize;
ShouldRunBinaryVersion = shouldRunBinaryVersion;
UpdateAppVersion = updateAppVersion;
PackageHash = packageHash;
Label = label;
CustomInit();
}
/// <summary>
/// An initialization method that performs custom operations like setting defaults
/// </summary>
partial void CustomInit();
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "download_url")]
public string DownloadUrl { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "is_available")]
public bool IsAvailable { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "package_size")]
public double? PackageSize { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "should_run_binary_version")]
public bool? ShouldRunBinaryVersion { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "update_app_version")]
public bool? UpdateAppVersion { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "package_hash")]
public string PackageHash { get; set; }
/// <summary>
/// </summary>
[JsonProperty(PropertyName = "label")]
public string Label { get; set; }
/// <summary>
/// Validate the object.
/// </summary>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown if validation fails
/// </exception>
public override void Validate()
{
base.Validate();
}
}
}
| 34.5 | 471 | 0.597101 | [
"MIT"
] | balivo/appcenter-openapi-sdk | generated/Models/UpdateCheckResponse.cs | 3,105 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using P01_HospitalDatabase.Data;
namespace P01_HospitalDatabase.Migrations
{
[DbContext(typeof(HospitalContext))]
[Migration("20190308085612_DoctorAdded")]
partial class DoctorAdded
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.2.0-rtm-35687")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Diagnose", b =>
{
b.Property<int>("DiagnoseId")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Comments")
.HasMaxLength(250)
.IsUnicode(true);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(true);
b.Property<int>("PatientId");
b.HasKey("DiagnoseId");
b.HasIndex("PatientId");
b.ToTable("Diagnoses");
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Doctor", b =>
{
b.Property<int>("DoctorId")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(true);
b.Property<string>("Specialty")
.IsRequired()
.HasMaxLength(100)
.IsUnicode(true);
b.HasKey("DoctorId");
b.ToTable("Doctor");
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Medicament", b =>
{
b.Property<int>("MedicamentId")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(true);
b.HasKey("MedicamentId");
b.ToTable("Medicaments");
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Patient", b =>
{
b.Property<int>("PatientId")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Address")
.IsRequired()
.HasMaxLength(250)
.IsUnicode(true);
b.Property<string>("Email")
.HasMaxLength(80);
b.Property<string>("FirstName")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(true);
b.Property<bool>("HasInsurance");
b.Property<string>("LastName")
.IsRequired()
.HasMaxLength(50)
.IsUnicode(true);
b.HasKey("PatientId");
b.ToTable("Patients");
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.PatientMedicament", b =>
{
b.Property<int>("PatientId");
b.Property<int>("MedicamentId");
b.HasKey("PatientId", "MedicamentId");
b.HasIndex("MedicamentId");
b.ToTable("PatientMedicaments");
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Visitation", b =>
{
b.Property<int>("VisitationId")
.ValueGeneratedOnAdd()
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("Comments")
.HasMaxLength(250)
.IsUnicode(true);
b.Property<DateTime>("Date");
b.Property<int>("DoctorId");
b.Property<int>("PatientId");
b.HasKey("VisitationId");
b.HasIndex("DoctorId");
b.HasIndex("PatientId");
b.ToTable("Visitations");
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Diagnose", b =>
{
b.HasOne("P01_HospitalDatabase.Data.Models.Patient", "Patient")
.WithMany("Diagnoses")
.HasForeignKey("PatientId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.PatientMedicament", b =>
{
b.HasOne("P01_HospitalDatabase.Data.Models.Medicament", "Medicament")
.WithMany("Prescriptions")
.HasForeignKey("MedicamentId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("P01_HospitalDatabase.Data.Models.Patient", "Patient")
.WithMany("Prescriptions")
.HasForeignKey("PatientId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("P01_HospitalDatabase.Data.Models.Visitation", b =>
{
b.HasOne("P01_HospitalDatabase.Data.Models.Doctor", "Doctor")
.WithMany("Visitations")
.HasForeignKey("DoctorId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("P01_HospitalDatabase.Data.Models.Patient", "Patient")
.WithMany("Visitations")
.HasForeignKey("PatientId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}
| 37.057592 | 125 | 0.495338 | [
"MIT"
] | Ivelin153/SoftUni | C# DB/C# DB Advanced/EntityFrameworkCodeFirst/P01_HospitalDatabase/Migrations/20190308085612_DoctorAdded.Designer.cs | 7,080 | C# |
using System;
using Moq;
using Xunit;
namespace JustEat.StatsD.Buffered
{
public static class BufferBasedStatsDPublisherTests
{
[Fact]
public static void Increment_Is_Noop_If_Bucket_Is_Null()
{
// Arrange
var configuration = new StatsDConfiguration();
var transport = new Mock<IStatsDTransport>();
var publisher = new BufferBasedStatsDPublisher(configuration, transport.Object);
// Act
publisher.Increment(1, 1, null!);
// Assert
transport.Verify((p) => p.Send(It.Ref<ArraySegment<byte>>.IsAny), Times.Never());
}
[Fact]
public static void Increment_Sends_If_Default_Buffer_Is_Too_Small()
{
// Arrange
var configuration = new StatsDConfiguration() { Prefix = new string('a', 513) };
var transport = new Mock<IStatsDTransport>();
var publisher = new BufferBasedStatsDPublisher(configuration, transport.Object);
// Act
publisher.Increment(1, 1, "foo");
// Assert
transport.Verify((p) => p.Send(It.Ref<ArraySegment<byte>>.IsAny), Times.Once());
}
}
}
| 29.142857 | 93 | 0.590686 | [
"Apache-2.0"
] | Berezhnyk/JustEat.StatsD | tests/JustEat.StatsD.Tests/Buffered/BufferBasedStatsDPublisherTests.cs | 1,224 | C# |
using System;
using System.Globalization;
using Avalonia.Animation.Animators;
using Avalonia.Utilities;
namespace Avalonia
{
/// <summary>
/// Defines the reference point units of an <see cref="RelativePoint"/> or
/// <see cref="RelativeRect"/>.
/// </summary>
public enum RelativeUnit
{
/// <summary>
/// The point is expressed as a fraction of the containing element's size.
/// </summary>
Relative,
/// <summary>
/// The point is absolute (i.e. in pixels).
/// </summary>
Absolute,
}
/// <summary>
/// Defines a point that may be defined relative to a containing element.
/// </summary>
public readonly struct RelativePoint : IEquatable<RelativePoint>
{
/// <summary>
/// A point at the top left of the containing element.
/// </summary>
public static readonly RelativePoint TopLeft = new RelativePoint(0, 0, RelativeUnit.Relative);
/// <summary>
/// A point at the center of the containing element.
/// </summary>
public static readonly RelativePoint Center = new RelativePoint(0.5, 0.5, RelativeUnit.Relative);
/// <summary>
/// A point at the bottom right of the containing element.
/// </summary>
public static readonly RelativePoint BottomRight = new RelativePoint(1, 1, RelativeUnit.Relative);
private readonly Point _point;
private readonly RelativeUnit _unit;
static RelativePoint()
{
Animation.Animation.RegisterAnimator<RelativePointAnimator>(prop => typeof(RelativePoint).IsAssignableFrom(prop.PropertyType));
}
/// <summary>
/// Initializes a new instance of the <see cref="RelativePoint"/> struct.
/// </summary>
/// <param name="x">The X point.</param>
/// <param name="y">The Y point</param>
/// <param name="unit">The unit.</param>
public RelativePoint(double x, double y, RelativeUnit unit)
: this(new Point(x, y), unit)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RelativePoint"/> struct.
/// </summary>
/// <param name="point">The point.</param>
/// <param name="unit">The unit.</param>
public RelativePoint(Point point, RelativeUnit unit)
{
_point = point;
_unit = unit;
}
/// <summary>
/// Gets the point.
/// </summary>
public Point Point => _point;
/// <summary>
/// Gets the unit.
/// </summary>
public RelativeUnit Unit => _unit;
/// <summary>
/// Checks for equality between two <see cref="RelativePoint"/>s.
/// </summary>
/// <param name="left">The first point.</param>
/// <param name="right">The second point.</param>
/// <returns>True if the points are equal; otherwise false.</returns>
public static bool operator ==(RelativePoint left, RelativePoint right)
{
return left.Equals(right);
}
/// <summary>
/// Checks for inequality between two <see cref="RelativePoint"/>s.
/// </summary>
/// <param name="left">The first point.</param>
/// <param name="right">The second point.</param>
/// <returns>True if the points are unequal; otherwise false.</returns>
public static bool operator !=(RelativePoint left, RelativePoint right)
{
return !left.Equals(right);
}
/// <summary>
/// Checks if the <see cref="RelativePoint"/> equals another object.
/// </summary>
/// <param name="obj">The other object.</param>
/// <returns>True if the objects are equal, otherwise false.</returns>
public override bool Equals(object obj) => obj is RelativePoint other && Equals(other);
/// <summary>
/// Checks if the <see cref="RelativePoint"/> equals another point.
/// </summary>
/// <param name="p">The other point.</param>
/// <returns>True if the objects are equal, otherwise false.</returns>
public bool Equals(RelativePoint p)
{
return Unit == p.Unit && Point == p.Point;
}
/// <summary>
/// Gets a hashcode for a <see cref="RelativePoint"/>.
/// </summary>
/// <returns>A hash code.</returns>
public override int GetHashCode()
{
unchecked
{
return (_point.GetHashCode() * 397) ^ (int)_unit;
}
}
/// <summary>
/// Converts a <see cref="RelativePoint"/> into pixels.
/// </summary>
/// <param name="size">The size of the visual.</param>
/// <returns>The origin point in pixels.</returns>
public Point ToPixels(Size size)
{
return _unit == RelativeUnit.Absolute ?
_point :
new Point(_point.X * size.Width, _point.Y * size.Height);
}
/// <summary>
/// Parses a <see cref="RelativePoint"/> string.
/// </summary>
/// <param name="s">The string.</param>
/// <returns>The parsed <see cref="RelativePoint"/>.</returns>
public static RelativePoint Parse(string s)
{
using (var tokenizer = new StringTokenizer(s, CultureInfo.InvariantCulture, exceptionMessage: "Invalid RelativePoint."))
{
var x = tokenizer.ReadString();
var y = tokenizer.ReadString();
var unit = RelativeUnit.Absolute;
var scale = 1.0;
if (x.EndsWith("%"))
{
if (!y.EndsWith("%"))
{
throw new FormatException("If one coordinate is relative, both must be.");
}
x = x.TrimEnd('%');
y = y.TrimEnd('%');
unit = RelativeUnit.Relative;
scale = 0.01;
}
return new RelativePoint(
double.Parse(x, CultureInfo.InvariantCulture) * scale,
double.Parse(y, CultureInfo.InvariantCulture) * scale,
unit);
}
}
/// <summary>
/// Returns a String representing this RelativePoint instance.
/// </summary>
/// <returns>The string representation.</returns>
public override string ToString()
{
return _unit == RelativeUnit.Absolute ?
_point.ToString() :
string.Format(CultureInfo.InvariantCulture, "{0}%, {1}%", _point.X * 100, _point.Y * 100);
}
}
}
| 34.619289 | 139 | 0.53871 | [
"MIT"
] | 0x90d/Avalonia | src/Avalonia.Visuals/RelativePoint.cs | 6,820 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Cake.Core;
using Cake.Core.Diagnostics;
using Cake.Graph.Generators;
using Moq;
namespace Cake.Graph.Tests
{
public static class TestHelpers
{
public static Mock<ICakeContext> GetMockCakeContext()
{
var mockContext = new Mock<ICakeContext>();
mockContext
.Setup(x => x.Log)
.Returns(new Mock<ICakeLog>().Object);
return mockContext;
}
public static ITaskGraphGenerator GetEmptyTaskGraphGenerator()
{
var mockTaskGraphGenerator = new Mock<ITaskGraphGenerator>();
mockTaskGraphGenerator
.Setup(x => x.Extension)
.Returns("test");
mockTaskGraphGenerator.Setup(x => x.SerializeAsync(It.IsAny<ICakeContext>(), It.IsAny<ICakeTaskInfo>(),
It.IsAny<IReadOnlyList<ICakeTaskInfo>>()))
.Returns((ICakeContext context, ICakeTaskInfo task, IReadOnlyList<ICakeTaskInfo> tasks) => Task.FromResult(""));
return mockTaskGraphGenerator.Object;
}
public static IReadOnlyList<ICakeTaskInfo> CreateTasksWithDependencies()
{
var tasks = new List<ICakeTaskInfo>();
var taskA = new CakeTask("A");
var taskB = new CakeTask("B");
var taskC = new CakeTask("C");
var taskD = new CakeTask("D");
taskB.Dependencies.Add(new CakeTaskDependency("A", true));
taskC.Dependencies.Add(new CakeTaskDependency("B", true));
taskD.Dependencies.Add(new CakeTaskDependency("A", true));
tasks.Add(taskA);
tasks.Add(taskB);
tasks.Add(taskC);
tasks.Add(taskD);
return tasks;
}
public const string TaskCMermaidPattern = @"<div class=""mermaid"">\r?\ngraph TD;\r?\nC-->B;\r?\nB-->A;\r?\n<\/div>";
public const string TaskCCytoscapePattern = @"\[\{""data"":\{""id"":""C"",""source"":null,""target"":null\}\},\{""data"":\{""id"":""[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}"",""source"":""C"",""target"":""B""\}\},\{""data"":\{""id"":""B"",""source"":null,""target"":null\}\},\{""data"":\{""id"":""[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}"",""source"":""B"",""target"":""A""\}\},\{""data"":\{""id"":""A"",""source"":null,""target"":null\}\}\]";
}
} | 41.135593 | 453 | 0.557478 | [
"MIT"
] | cake-contrib/Cake.Graph | src/Cake.Graph.Tests/TestHelpers.cs | 2,429 | C# |
namespace AsmDude
{
internal static class Guids {
public const string GuidOptionsPageAsmDude = "3940DE73-43EF-44B6-8EC2-E3686FC40354";
}
}
| 22.142857 | 92 | 0.716129 | [
"MIT"
] | YellowAfterlife/asm-dude | VS/CSHARP/asm-dude-vsix/Properties/Guids.cs | 155 | 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;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using EnvDTE;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.Web.LibraryManager.Contracts;
using Microsoft.Web.LibraryManager.Vsix.Contracts;
using Microsoft.Web.LibraryManager.Vsix.Shared;
using NuGet.VisualStudio;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.Web.LibraryManager.Vsix.Commands
{
internal sealed class RestoreOnBuildCommand
{
private bool _isPackageInstalled;
private readonly IComponentModel _componentModel;
private readonly AsyncPackage _package;
private readonly IDependenciesFactory _dependenciesFactory;
private RestoreOnBuildCommand(AsyncPackage package, OleMenuCommandService commandService, IDependenciesFactory dependenciesFactory)
{
_package = package;
_componentModel = VsHelpers.GetService<SComponentModel, IComponentModel>();
_dependenciesFactory = dependenciesFactory;
var cmdId = new CommandID(PackageGuids.guidLibraryManagerPackageCmdSet, PackageIds.RestoreOnBuild);
var cmd = new OleMenuCommand((s, e) => _package.JoinableTaskFactory.RunAsync(() => ExecuteAsync(s, e)),
cmdId);
cmd.BeforeQueryStatus += (s, e) => _package.JoinableTaskFactory.RunAsync(() => BeforeQueryStatusAsync(s, e));
commandService.AddCommand(cmd);
}
public static RestoreOnBuildCommand Instance { get; private set; }
private IServiceProvider ServiceProvider
{
get { return _package; }
}
public static void Initialize(AsyncPackage package, OleMenuCommandService commandService, IDependenciesFactory dependenciesFactory)
{
Instance = new RestoreOnBuildCommand(package, commandService, dependenciesFactory);
}
private async Task BeforeQueryStatusAsync(object sender, EventArgs e)
{
var button = (OleMenuCommand)sender;
button.Visible = button.Enabled = false;
if (VsHelpers.DTE.SelectedItems.MultiSelect)
{
return;
}
ProjectItem item = await VsHelpers.GetSelectedItemAsync();
if (item != null && item.IsConfigFile())
{
button.Visible = true;
button.Enabled = KnownUIContexts.SolutionExistsAndNotBuildingAndNotDebuggingContext.IsActive;
_isPackageInstalled = IsPackageInstalled(item.ContainingProject);
if (_isPackageInstalled)
{
button.Text = Resources.Text.DisableRestoreOnBuild;
}
else
{
button.Text = Resources.Text.EnableRestoreOnBuild;
}
}
}
private async Task ExecuteAsync(object sender, EventArgs e)
{
ProjectItem projectItem = await VsHelpers.GetSelectedItemAsync();
Project project = await VsHelpers.GetProjectOfSelectedItemAsync();
try
{
var dependencies = _dependenciesFactory.FromConfigFile(projectItem.get_FileNames(1));
IEnumerable<string> packageIds = dependencies.Providers
.Where(p => p.NuGetPackageId != null)
.Select(p => p.NuGetPackageId)
.Distinct();
if (!_isPackageInstalled)
{
if (!UserWantsToInstall())
return;
await Task.Run(() =>
{
Logger.LogEvent(Resources.Text.Nuget_InstallingPackage, LogLevel.Status);
try
{
foreach (string packageId in packageIds)
{
IVsPackageInstaller2 installer = _componentModel.GetService<IVsPackageInstaller2>();
installer.InstallLatestPackage(null, project, packageId, true, false);
}
Telemetry.TrackUserTask("Install-NugetPackage");
Logger.LogEvent(Resources.Text.Nuget_PackageInstalled, LogLevel.Status);
}
catch (Exception ex)
{
Telemetry.TrackException(nameof(RestoreOnBuildCommand), ex);
Logger.LogEvent(Resources.Text.Nuget_PackageFailedToInstall, LogLevel.Status);
}
});
}
else
{
await Task.Run(() =>
{
Logger.LogEvent(Resources.Text.Nuget_UninstallingPackage, LogLevel.Status);
try
{
foreach (string packageId in packageIds)
{
IVsPackageUninstaller uninstaller = _componentModel.GetService<IVsPackageUninstaller>();
uninstaller.UninstallPackage(project, packageId, false);
}
Telemetry.TrackUserTask("Uninstall-NugetPackage");
Logger.LogEvent(Resources.Text.Nuget_PackageUninstalled, LogLevel.Status);
}
catch (Exception ex)
{
Telemetry.TrackException(nameof(RestoreOnBuildCommand), ex);
Logger.LogEvent(Resources.Text.Nuget_PackageFailedToUninstall, LogLevel.Status);
}
});
}
}
catch (Exception ex)
{
Telemetry.TrackException(nameof(RestoreOnBuildCommand), ex);
Logger.LogEvent(Resources.Text.Nuget_PackageFailedToInstall, LogLevel.Status);
}
}
private bool UserWantsToInstall()
{
int answer = VsShellUtilities.ShowMessageBox(
ServiceProvider,
Resources.Text.NugetInstallPrompt,
Vsix.Name,
OLEMSGICON.OLEMSGICON_INFO,
OLEMSGBUTTON.OLEMSGBUTTON_YESNO,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
);
return answer == 6; // 6 = Yes
}
private bool IsPackageInstalled(Project project)
{
IVsPackageInstallerServices installerServices = _componentModel.GetService<IVsPackageInstallerServices>();
return installerServices.IsPackageInstalled(project, Constants.MainNuGetPackageId);
}
}
}
| 41.528409 | 139 | 0.55329 | [
"Apache-2.0"
] | aspnet/LibraryManager | src/LibraryManager.Vsix/Commands/RestoreOnBuildCommand.cs | 7,311 | C# |
using System;
using UltimaOnline;
using UltimaOnline.Items;
namespace UltimaOnline.Mobiles
{
[CorpseName("a Coil corpse")]
public class Coil : SilverSerpent
{
// TODO: Check faction allegiance
[Constructable]
public Coil()
{
IsParagon = true;
Name = "Coil";
Hue = 0x3F;
SetStr(205, 343);
SetDex(202, 283);
SetInt(88, 142);
SetHits(628, 1291);
SetDamage(19, 28);
SetDamageType(ResistanceType.Physical, 50);
SetDamageType(ResistanceType.Poison, 50);
SetResistance(ResistanceType.Physical, 56, 62);
SetResistance(ResistanceType.Fire, 25, 30);
SetResistance(ResistanceType.Cold, 25, 30);
SetResistance(ResistanceType.Poison, 100);
SetResistance(ResistanceType.Energy, 25, 30);
SetSkill(SkillName.Wrestling, 124.5, 141.3);
SetSkill(SkillName.Tactics, 130.2, 142.0);
SetSkill(SkillName.MagicResist, 102.3, 113.0);
SetSkill(SkillName.Anatomy, 120.8, 138.1);
SetSkill(SkillName.Poisoning, 110.1, 133.4);
// TODO: Fame/Karma
PackGem(2);
PackItem(new Bone());
}
public override void GenerateLoot()
{
AddLoot(LootPack.UltraRich, 3);
}
public override WeaponAbility GetWeaponAbility()
{
return WeaponAbility.MortalStrike;
}
public override void OnDeath(Container c)
{
base.OnDeath(c);
c.DropItem(new CoilsFang());
/*
// TODO: uncomment once added
if ( Utility.RandomDouble() < 0.025 )
{
switch ( Utility.Random( 5 ) )
{
case 0: c.DropItem( new AssassinChest() ); break;
case 1: c.DropItem( new DeathGloves() ); break;
case 2: c.DropItem( new LeafweaveLegs() ); break;
case 3: c.DropItem( new HunterLegs() ); break;
case 4: c.DropItem( new MyrmidonLegs() ); break;
}
}
*/
}
public override Poison HitPoison { get { return Poison.Lethal; } }
public override Poison PoisonImmune { get { return Poison.Lethal; } }
public override bool GivesMLMinorArtifact { get { return true; } }
public override int Hides { get { return 48; } }
public override int Meat { get { return 1; } }
public Coil(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
| 27.64486 | 78 | 0.536173 | [
"MIT"
] | netcode-gamer/game.ultimaonline.io | UltimaOnline.Data/Mobiles/Monsters/ML/Blighted Grove/Coil.cs | 2,958 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by Entitas.CodeGeneration.Plugins.ComponentGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
[Game]
public sealed partial class SomeOtherClassComponent : Entitas.IComponent {
public SomeNamespace.SomeOtherClass value;
}
| 40.846154 | 84 | 0.521657 | [
"MIT"
] | CCludts/EntitasCSharpClone | Tests/Unity/VisualDebugging/Assets/Sources/Generated/Components/SomeOtherClassComponent.cs | 531 | C# |
//-----------------------------------------------------------------------
// <copyright file="HttpUrlReservationAccessRights.cs" company="P.O.S Informatique">
// Copyright (c) P.O.S Informatique. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace PosInformatique.Net.HttpServer
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
/// <summary>
/// Defines the access rights for the <see cref="HttpUrlReservation"/>.
/// </summary>
public enum HttpUrlReservationAccessRights
{
/// <summary>
/// Allows the designated user to register to receive requests from the <see cref="HttpUrlReservation.Url"/>, but does not allow the user to delegate sub-tree reservations to others.
/// </summary>
Listen = 0x20000000,
/// <summary>
/// Allows the designated user to reserve (delegate) a subtree of the <see cref="HttpUrlReservation.Url"/> for another user, but does not allow the user to register to receive requests from the URL.
/// </summary>
Delegate = 0x40000000,
/// <summary>
/// Allows the designated user to have the <see cref="Listen"/> and <see cref="Delegate"/> rights.
/// </summary>
ListenAndDelegate = Listen | Delegate
}
}
| 40.285714 | 206 | 0.589362 | [
"MIT"
] | PosInformatique/PosInformatique.Net.HttpServer | src/PosInformatique.Net.HttpServer/HttpUrlReservationAccessRights.cs | 1,412 | C# |
// This file isn't generated, but this comment is necessary to exclude it from StyleCop analysis.
// For more info see: https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/2108
// <auto-generated/>
using System;
using System.Globalization;
using Alba.CsConsoleFormat.Framework.Sys;
// ReSharper disable NonReadonlyMemberInGetHashCode
namespace Alba.CsConsoleFormat
{
internal struct ConsoleChar : IEquatable<ConsoleChar>
{
private byte _colors;
public char Char { get; set; }
public LineChar LineChar { get; set; }
public bool HasChar => Char != '\0';
public char PrintableChar
{
get
{
if (Char < ' ')
return ' ';
if (Char == Chars.NoBreakHyphen || Char == Chars.SoftHyphen)
return '-';
if (Char == Chars.NoBreakSpace || Char == Chars.ZeroWidthSpace)
return ' ';
return Char;
}
}
public ConsoleColor ForegroundColor
{
get => (ConsoleColor)Bits.Get(_colors, 0, 4);
set => Bits.Set(ref _colors, (byte)value, 0, 4);
}
public ConsoleColor BackgroundColor
{
get => (ConsoleColor)Bits.Get(_colors, 4, 4);
set => Bits.Set(ref _colors, (byte)value, 4, 4);
}
public override string ToString() =>
string.Format(CultureInfo.InvariantCulture, "{0}{1} ({2} @ {3})",
Char >= ' ' ? Char.ToString() : "#" + (int)Char,
LineChar != LineChar.None ? $" {LineChar}" : "",
ForegroundColor,
BackgroundColor);
public bool Equals(ConsoleChar other) => _colors == other._colors && Char == other.Char && LineChar == other.LineChar;
public override bool Equals(object obj) => obj is ConsoleChar && Equals((ConsoleChar)obj);
public override int GetHashCode() => _colors.GetHashCode() ^ Char.GetHashCode() ^ LineChar.GetHashCode();
public static bool operator ==(ConsoleChar left, ConsoleChar right) => left.Equals(right);
public static bool operator !=(ConsoleChar left, ConsoleChar right) => !left.Equals(right);
}
} | 37.016393 | 126 | 0.577502 | [
"MIT"
] | nseedio/nseed | src/NSeed/ThirdParty/CsConsoleFormat/Formatting/ConsoleChar.cs | 2,258 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.dataworks_public.Model.V20200518
{
public class GetMetaColumnLineageResponse : AcsResponse
{
private string requestId;
private string errorCode;
private string errorMessage;
private int? httpStatusCode;
private bool? success;
private GetMetaColumnLineage_Data data;
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public string ErrorCode
{
get
{
return errorCode;
}
set
{
errorCode = value;
}
}
public string ErrorMessage
{
get
{
return errorMessage;
}
set
{
errorMessage = value;
}
}
public int? HttpStatusCode
{
get
{
return httpStatusCode;
}
set
{
httpStatusCode = value;
}
}
public bool? Success
{
get
{
return success;
}
set
{
success = value;
}
}
public GetMetaColumnLineage_Data Data
{
get
{
return data;
}
set
{
data = value;
}
}
public class GetMetaColumnLineage_Data
{
private long? totalCount;
private int? pageNum;
private int? pageSize;
private List<GetMetaColumnLineage_DataEntityListItem> dataEntityList;
public long? TotalCount
{
get
{
return totalCount;
}
set
{
totalCount = value;
}
}
public int? PageNum
{
get
{
return pageNum;
}
set
{
pageNum = value;
}
}
public int? PageSize
{
get
{
return pageSize;
}
set
{
pageSize = value;
}
}
public List<GetMetaColumnLineage_DataEntityListItem> DataEntityList
{
get
{
return dataEntityList;
}
set
{
dataEntityList = value;
}
}
public class GetMetaColumnLineage_DataEntityListItem
{
private string columnName;
private string columnGuid;
private string clusterId;
private string databaseName;
private string tableName;
public string ColumnName
{
get
{
return columnName;
}
set
{
columnName = value;
}
}
public string ColumnGuid
{
get
{
return columnGuid;
}
set
{
columnGuid = value;
}
}
public string ClusterId
{
get
{
return clusterId;
}
set
{
clusterId = value;
}
}
public string DatabaseName
{
get
{
return databaseName;
}
set
{
databaseName = value;
}
}
public string TableName
{
get
{
return tableName;
}
set
{
tableName = value;
}
}
}
}
}
}
| 15.348178 | 73 | 0.561857 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-dataworks-public/Dataworks_public/Model/V20200518/GetMetaColumnLineageResponse.cs | 3,791 | C# |
/* Copyright 2013-2014 MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using FluentAssertions;
using MongoDB.Driver.Core.Misc;
using NUnit.Framework;
namespace MongoDB.Driver.Core.Misc
{
[TestFixture]
public class TimeSpanParserTests
{
[Test]
[TestCase("2", 2 * 1000)]
[TestCase("2ms", 2)]
[TestCase("2s", 2 * 1000)]
[TestCase("2m", 2 * 1000 * 60)]
[TestCase("2h", 2 * 1000 * 60 * 60)]
public void Parse_should_return_the_correct_TimeSpan(string value, long expectedMilliseconds)
{
TimeSpan result;
var success = TimeSpanParser.TryParse(value, out result);
success.Should().BeTrue();
result.TotalMilliseconds.Should().Be(expectedMilliseconds);
}
[Test]
[TestCase(2, "2ms")]
[TestCase(2 * 1000, "2s")]
[TestCase(2 * 1000 * 60, "2m")]
[TestCase(2 * 1000 * 60 * 60, "2h")]
public void ToString_should_return_the_correct_string(int milliseconds, string expectedString)
{
var result = TimeSpanParser.ToString(TimeSpan.FromMilliseconds(milliseconds));
result.Should().Be(expectedString);
}
}
}
| 32.259259 | 102 | 0.65155 | [
"Apache-2.0"
] | InternationNova/MEANJS | src/MongoDB.Driver.Core.Tests/Core/Misc/TimeSpanParserTests.cs | 1,744 | C# |
using System;
using System.Linq;
/// <summary> Class used by Localization Tool to hold strings intended for localization. </summary>
[Serializable]
public class StringToLocalize
{
public string String { get; set; }
public string Source { get; set; }
public string Comment { get; set; }
public static implicit operator StringToLocalize(EmbeddedLocString locString) => new StringToLocalize { String = locString.String };
public static implicit operator StringToLocalize(string str) => new StringToLocalize { String = str };
}
public static class StringToLocalizeExtensions
{
public static StringToLocalize[] AsStringsToLocalize(this EmbeddedLocString[] values) => values.Select(x => (StringToLocalize)x).ToArray();
} | 39 | 143 | 0.755735 | [
"MIT"
] | thetestgame/EcoGlueMod | Client/Assets/EcoModKit/Scripts/StringToLocalize.cs | 741 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Cecilifier.Core.Extensions;
using Cecilifier.Core.Misc;
using Cecilifier.Core.Mappings;
using Cecilifier.Core.Naming;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Mono.Cecil.Cil;
namespace Cecilifier.Core.AST
{
internal class ExpressionVisitor : SyntaxWalkerBase
{
private static readonly IDictionary<SyntaxKind, Action<IVisitorContext, string, ITypeSymbol, ITypeSymbol>> operatorHandlers =
new Dictionary<SyntaxKind, Action<IVisitorContext, string, ITypeSymbol, ITypeSymbol>>();
private static readonly IDictionary<string, uint> predefinedTypeSize = new Dictionary<string, uint>();
private static readonly IDictionary<SpecialType, OpCode> _opCodesForLdElem = new Dictionary<SpecialType, OpCode>()
{
[SpecialType.System_Byte] = OpCodes.Ldelem_I1,
[SpecialType.System_Boolean] = OpCodes.Ldelem_U1,
[SpecialType.System_Int16] = OpCodes.Ldelem_I2,
[SpecialType.System_Int32] = OpCodes.Ldelem_I4,
[SpecialType.System_Int64] = OpCodes.Ldelem_I8,
[SpecialType.System_Single] = OpCodes.Ldelem_R4,
[SpecialType.System_Double] = OpCodes.Ldelem_R8,
[SpecialType.System_Object] = OpCodes.Ldelem_Ref,
};
private readonly string ilVar;
private readonly Stack<LinkedListNode<string>> callFixList = new Stack<LinkedListNode<string>>();
private bool valueTypeNoArgObjCreation;
static ExpressionVisitor()
{
predefinedTypeSize["int"] = sizeof(int);
predefinedTypeSize["byte"] = sizeof(byte);
predefinedTypeSize["long"] = sizeof(long);
//TODO: Use AddCilInstruction instead.
operatorHandlers[SyntaxKind.PlusToken] = (ctx, ilVar, left, right) =>
{
if (left.SpecialType == SpecialType.System_String)
{
var concatArgType = right.SpecialType == SpecialType.System_String ? "string" : "object";
WriteCecilExpression(ctx,$"{ilVar}.Emit({OpCodes.Call.ConstantName()}, assembly.MainModule.Import(typeof(string).GetMethod(\"Concat\", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public, null, new[] {{ typeof({concatArgType}), typeof({concatArgType}) }}, null)));");
}
else
{
WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.Add.ConstantName()});");
}
};
operatorHandlers[SyntaxKind.SlashToken] = (ctx, ilVar, left, right) => WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.Div.ConstantName()});");
operatorHandlers[SyntaxKind.GreaterThanToken] = (ctx, ilVar, left, right) => WriteCecilExpression(ctx, $"{ilVar}.Emit({CompareOperatorFor(ctx, left, right).ConstantName()});");
operatorHandlers[SyntaxKind.EqualsEqualsToken] = (ctx, ilVar, left, right) => WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.Ceq.ConstantName()});");
operatorHandlers[SyntaxKind.LessThanToken] = (ctx, ilVar, left, right) => WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.Clt.ConstantName()});");
operatorHandlers[SyntaxKind.MinusToken] = (ctx, ilVar, left, right) => WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.Sub.ConstantName()});");
operatorHandlers[SyntaxKind.AsteriskToken] = (ctx, ilVar, left, right) => WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.Mul.ConstantName()});");
// Bitwise Operators
operatorHandlers[SyntaxKind.AmpersandToken] = (ctx, ilVar, _, _) => WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.And.ConstantName()});");
operatorHandlers[SyntaxKind.BarToken] = (ctx, ilVar, _, _) => WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.Or.ConstantName()});");
operatorHandlers[SyntaxKind.CaretToken] = (ctx, ilVar, _, _) => WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.Xor.ConstantName()});");
operatorHandlers[SyntaxKind.LessThanLessThanToken] = (ctx, ilVar, _, _) => WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.Shl.ConstantName()});");
operatorHandlers[SyntaxKind.GreaterThanGreaterThanToken] = (ctx, ilVar, _, _) => WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.Shr.ConstantName()});");
// Logical Operators
operatorHandlers[SyntaxKind.AmpersandAmpersandToken] = (ctx, ilVar, _, _) => WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.And.ConstantName()});");
operatorHandlers[SyntaxKind.BarBarToken] = (ctx, ilVar, _, _) => WriteCecilExpression(ctx, $"{ilVar}.Emit({OpCodes.Or.ConstantName()});");
}
private static OpCode CompareOperatorFor(IVisitorContext ctx, ITypeSymbol left, ITypeSymbol right)
{
switch (left.SpecialType)
{
case SpecialType.System_UInt16:
case SpecialType.System_UInt32:
case SpecialType.System_UInt64:
case SpecialType.System_Byte:
return OpCodes.Cgt_Un;
case SpecialType.None:
return left.Kind == SymbolKind.PointerType ? OpCodes.Cgt_Un : OpCodes.Cgt;
default:
return OpCodes.Cgt;
}
}
private ExpressionVisitor(IVisitorContext ctx, string ilVar) : base(ctx)
{
this.ilVar = ilVar;
}
internal static bool Visit(IVisitorContext ctx, string ilVar, SyntaxNode node)
{
if (node == null)
{
return true;
}
using var _ = LineInformationTracker.Track(ctx, node);
var ev = new ExpressionVisitor(ctx, ilVar);
ev.Visit(node);
return ev.valueTypeNoArgObjCreation;
}
public override void VisitReturnStatement(ReturnStatementSyntax node)
{
node.Expression.Accept(this);
InjectRequiredConversions(node.Expression);
}
public override void VisitArrowExpressionClause(ArrowExpressionClauseSyntax node)
{
node.Expression.Accept(this);
InjectRequiredConversions(node.Expression);
}
public override void VisitStackAllocArrayCreationExpression(StackAllocArrayCreationExpressionSyntax node)
{
using var _ = LineInformationTracker.Track(Context, node);
/*
// S *s = stackalloc S[n];
IL_0007: ldarg.1
IL_0008: conv.u
IL_0009: sizeof MyStruct
IL_000f: mul.ovf.un
IL_0010: localloc
// int *i = stackalloc int[10];
IL_0001: ldc.i4.s 40
IL_0003: conv.u
IL_0004: localloc
*/
var type = (ArrayTypeSyntax) node.Type;
var countNode = type.RankSpecifiers[0].Sizes[0];
if (type.RankSpecifiers.Count == 1 && countNode.IsKind(SyntaxKind.NumericLiteralExpression))
{
var sizeLiteral = Int32.Parse(countNode.GetFirstToken().Text) * predefinedTypeSize[type.ElementType.GetText().ToString()];
AddCilInstruction(ilVar, OpCodes.Ldc_I4, sizeLiteral);
AddCilInstruction(ilVar, OpCodes.Conv_U);
AddCilInstruction(ilVar, OpCodes.Localloc);
}
else
{
countNode.Accept(this);
AddCilInstruction(ilVar, OpCodes.Conv_U);
AddCilInstruction(ilVar, OpCodes.Sizeof, ResolveType(type.ElementType));
AddCilInstruction(ilVar, OpCodes.Mul_Ovf_Un);
AddCilInstruction(ilVar, OpCodes.Localloc);
}
}
public override void VisitArrayCreationExpression(ArrayCreationExpressionSyntax node)
{
using var _ = LineInformationTracker.Track(Context, node);
if (node.Initializer == null)
{
node.Type.RankSpecifiers[0].Accept(this);
}
else
{
AddCilInstruction(ilVar, OpCodes.Ldc_I4, node.Initializer.Expressions.Count);
}
var elementTypeInfo = Context.GetTypeInfo(node.Type.ElementType);
ProcessArrayCreation(elementTypeInfo.Type, node.Initializer);
}
public override void VisitImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node)
{
using var _ = LineInformationTracker.Track(Context, node);
var arrayType = Context.GetTypeInfo(node);
if (arrayType.Type == null)
{
throw new Exception($"Unable to infer array type: {node}");
}
AddCilInstruction(ilVar, OpCodes.Ldc_I4, node.Initializer.Expressions.Count);
var arrayTypeSymbol = (IArrayTypeSymbol) arrayType.Type;
ProcessArrayCreation(arrayTypeSymbol.ElementType, node.Initializer);
}
public override void VisitElementAccessExpression(ElementAccessExpressionSyntax node)
{
using var _ = LineInformationTracker.Track(Context, node);
var expressionInfo = Context.SemanticModel.GetSymbolInfo(node.Expression);
if (expressionInfo.Symbol == null)
return;
node.Expression.Accept(this);
node.ArgumentList.Accept(this);
var targetType = expressionInfo.Symbol.Accept(new ElementTypeSymbolResolver());
if (!node.Parent.IsKind(SyntaxKind.RefExpression) && _opCodesForLdElem.TryGetValue(targetType.SpecialType, out var opCode))
{
AddCilInstruction(ilVar, opCode);
}
else
{
var indexer = targetType.GetMembers().OfType<IPropertySymbol>().FirstOrDefault(p => p.IsIndexer && p.Parameters.Length == node.ArgumentList.Arguments.Count);
if (indexer != null)
{
EnsurePropertyExists(node, indexer);
AddMethodCall(ilVar, indexer.GetMethod);
}
else
{
if (node.Parent.IsKind(SyntaxKind.RefExpression))
AddCilInstruction(ilVar, OpCodes.Ldelema, targetType);
else
AddCilInstruction(ilVar, OpCodes.Ldelem_Ref);
}
}
}
public override void VisitEqualsValueClause(EqualsValueClauseSyntax node)
{
base.VisitEqualsValueClause(node);
InjectRequiredConversions(node.Value);
}
public override void VisitAssignmentExpression(AssignmentExpressionSyntax node)
{
var leftNodeMae = node.Left as MemberAccessExpressionSyntax;
CSharpSyntaxNode exp = leftNodeMae?.Name ?? node.Left;
// check if the left hand side of the assignment is a property (but not indexers) and handle that as a method (set) call.
var expSymbol = Context.SemanticModel.GetSymbolInfo(exp).Symbol;
if (expSymbol is IPropertySymbol propertySymbol && !propertySymbol.IsIndexer)
{
HandleMethodInvocation(node.Left, node.Right);
return;
}
var visitor = new AssignmentVisitor(Context, ilVar, node);
visitor.InstructionPrecedingValueToLoad = Context.CurrentLine;
Visit(node.Right);
if (!valueTypeNoArgObjCreation)
{
visitor.Visit(node.Left);
}
}
public override void VisitBinaryExpression(BinaryExpressionSyntax node)
{
using var _ = LineInformationTracker.Track(Context, node);
Visit(node.Left);
InjectRequiredConversions(node.Left);
Visit(node.Right);
InjectRequiredConversions(node.Right);
var handler = OperatorHandlerFor(node.OperatorToken);
handler(
Context,
ilVar,
Context.SemanticModel.GetTypeInfo(node.Left).Type,
Context.SemanticModel.GetTypeInfo(node.Right).Type);
}
public override void VisitLiteralExpression(LiteralExpressionSyntax node)
{
switch (node.Kind())
{
case SyntaxKind.NullLiteralExpression:
var nodeType = Context.SemanticModel.GetTypeInfo(node);
if (nodeType.ConvertedType?.TypeKind == TypeKind.Pointer)
{
AddCilInstruction(ilVar, OpCodes.Ldc_I4_0);
AddCilInstruction(ilVar, OpCodes.Conv_U);
}
else
AddCilInstruction(ilVar, OpCodes.Ldnull);
break;
case SyntaxKind.StringLiteralExpression:
AddCilInstruction(ilVar, OpCodes.Ldstr, node.ToFullString());
break;
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.NumericLiteralExpression:
AddLocalVariableAndHandleCallOnValueTypeLiterals(node, GetSpecialType(SpecialType.System_Int32), node.ToString());
break;
case SyntaxKind.TrueLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
AddLocalVariableAndHandleCallOnValueTypeLiterals(node, GetSpecialType(SpecialType.System_Boolean), bool.Parse(node.ToString()) ? 1 : 0);
break;
default:
throw new ArgumentException($"Literal ( {node}) of type {node.Kind()} not supported yet.");
}
void AddLocalVariableAndHandleCallOnValueTypeLiterals(LiteralExpressionSyntax literalNode, ITypeSymbol expressionType, object literalValue)
{
AddCilInstruction(ilVar, LoadOpCodeFor(literalNode), literalValue);
var localVarParent = (CSharpSyntaxNode) literalNode.Parent;
Debug.Assert(localVarParent != null);
if (localVarParent.Accept(new UsageVisitor()) == UsageKind.CallTarget)
StoreTopOfStackInLocalVariableAndLoadItsAddress(expressionType);
}
}
public override void VisitDeclarationExpression(DeclarationExpressionSyntax node)
{
if (node.Parent is ArgumentSyntax argument && argument.RefKindKeyword.Kind() == SyntaxKind.OutKeyword)
{
var localSymbol = (ILocalSymbol) Context.SemanticModel.GetSymbolInfo(node).Symbol;
var designation = ((SingleVariableDesignationSyntax) node.Designation);
var resolvedOutArgType = Context.TypeResolver.Resolve(localSymbol.Type);
var outLocalName = AddLocalVariableWithResolvedType(
designation.Identifier.Text,
Context.DefinitionVariables.GetLastOf(MemberKind.Method),
resolvedOutArgType
);
AddCilInstruction(ilVar, OpCodes.Ldloca_S, outLocalName);
}
base.VisitDeclarationExpression(node);
}
public override void VisitInvocationExpression(InvocationExpressionSyntax node)
{
HandleMethodInvocation(node.Expression, node.ArgumentList);
StoreTopOfStackInLocalVariableAndLoadItsAddressIfNeeded(node);
}
public override void VisitConditionalExpression(ConditionalExpressionSyntax node)
{
string Emit(OpCode op)
{
var instVarName = Context.Naming.Label(op.Name);
AddCecilExpression(@"var {0} = {1}.Create({2});", instVarName, ilVar, op.ConstantName());
return instVarName;
}
var conditionEnd = Emit(OpCodes.Nop);
var whenFalse = Emit(OpCodes.Nop);
Visit(node.Condition);
AddCilInstruction(ilVar, OpCodes.Brfalse_S, whenFalse);
Visit(node.WhenTrue);
AddCilInstruction(ilVar, OpCodes.Br_S, conditionEnd);
AddCecilExpression("{0}.Append({1});", ilVar, whenFalse);
Visit(node.WhenFalse);
AddCecilExpression("{0}.Append({1});", ilVar, conditionEnd);
}
public override void VisitIdentifierName(IdentifierNameSyntax node)
{
HandleIdentifier(node);
}
public override void VisitGenericName(GenericNameSyntax node)
{
HandleIdentifier(node);
}
public override void VisitArgument(ArgumentSyntax node)
{
// in the case the parent of the argument syntax is an array access
// *CurrentLine* will represent the instruction that loaded the array
// reference into the stack.
//
// If the argument is a System.Index the actual offset to be used
// need to be calculated based on the length of the array (due to
// Index supporting the concept of *from the end*)
//
// In this case InjectRequiredConversions will call the Action
// passed and we can add the same instruction to load
// the array again (the array reference is necessary to
// compute it's length)
var last = Context.CurrentLine;
base.VisitArgument(node);
InjectRequiredConversions(node.Expression, () =>
{
AddCecilExpression(last.Value);
});
}
public override void VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node)
{
using var _ = LineInformationTracker.Track(Context, node);
if (node.OperatorToken.Kind() == SyntaxKind.AmpersandToken)
{
Visit(node.Operand);
}
else if (node.IsKind(SyntaxKind.UnaryMinusExpression))
{
Visit(node.Operand);
InjectRequiredConversions(node.Operand);
AddCilInstruction(ilVar, OpCodes.Neg);
}
else if (node.IsKind(SyntaxKind.PreDecrementExpression))
{
ProcessPrefixPostfixOperators(node.Operand, OpCodes.Sub, true);
}
else if (node.IsKind(SyntaxKind.PreIncrementExpression))
{
ProcessPrefixPostfixOperators(node.Operand, OpCodes.Add, true);
}
else if (node.IsKind(SyntaxKind.LogicalNotExpression))
{
node.Operand.Accept(this);
AddCilInstruction(ilVar, OpCodes.Ldc_I4_0);
AddCilInstruction(ilVar, OpCodes.Ceq);
}
else if (node.IsKind(SyntaxKind.BitwiseNotExpression))
{
node.Operand.Accept(this);
AddCilInstruction(ilVar, OpCodes.Not);
}
else if (node.IsKind(SyntaxKind.IndexExpression))
{
Console.WriteLine();
}
else
{
LogUnsupportedSyntax(node);
}
}
public override void VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node)
{
if (node.IsKind(SyntaxKind.PostDecrementExpression))
{
ProcessPrefixPostfixOperators(node.Operand, OpCodes.Sub, false);
}
else if (node.IsKind(SyntaxKind.PostIncrementExpression))
{
ProcessPrefixPostfixOperators(node.Operand, OpCodes.Add, false);
}
else
{
LogUnsupportedSyntax(node);
}
}
public override void VisitParenthesizedExpression(ParenthesizedExpressionSyntax node)
{
base.VisitParenthesizedExpression(node);
var localVarParent = (CSharpSyntaxNode) node.Parent;
if (localVarParent.Accept(new UsageVisitor()) != UsageKind.CallTarget)
return;
StoreTopOfStackInLocalVariableAndLoadItsAddress(GetSpecialType(SpecialType.System_Int32));
}
public override void VisitObjectCreationExpression(ObjectCreationExpressionSyntax node)
{
using var _ = LineInformationTracker.Track(Context, node);
//TODO: Refactor to reuse code from VisitIdentifierName....
var ctorInfo = Context.SemanticModel.GetSymbolInfo(node);
var ctor = (IMethodSymbol) ctorInfo.Symbol;
if (TryProcessNoArgsCtorInvocationOnValueType(node, ctor, ctorInfo))
{
return;
}
EnsureMethodAvailable(Context.Naming.SyntheticVariable(node.Type.ToString(), ElementKind.LocalVariable), ctor, Array.Empty<TypeParameterSyntax>());
AddCilInstruction(ilVar, OpCodes.Newobj, ctor.MethodResolverExpression(Context));
PushCall();
Visit(node.ArgumentList);
FixCallSite();
StoreTopOfStackInLocalVariableAndLoadItsAddressIfNeeded(node);
}
private void ProcessPrefixPostfixOperators(ExpressionSyntax operand, OpCode opCode, bool isPrefix)
{
using var _ = LineInformationTracker.Track(Context, operand);
Visit(operand);
InjectRequiredConversions(operand);
var assignmentVisitor = new AssignmentVisitor(Context, ilVar);
var operandInfo = Context.SemanticModel.GetSymbolInfo(operand);
if (operandInfo.Symbol != null && operandInfo.Symbol.Kind != SymbolKind.Field && operandInfo.Symbol.Kind != SymbolKind.Property) // Fields / Properties requires more complex handling to load the owning reference.
{
if (!isPrefix) // For *postfix* operators we duplicate the value *before* applying the operator...
{
AddCilInstruction(ilVar, OpCodes.Dup);
}
AddCilInstruction(ilVar, OpCodes.Ldc_I4_1);
AddCilInstruction(ilVar, opCode);
if (isPrefix) // For prefix operators we duplicate the value *after* applying the operator...
{
AddCilInstruction(ilVar, OpCodes.Dup);
}
//assign (top of stack to the operand)
assignmentVisitor.InstructionPrecedingValueToLoad = Context.CurrentLine;
operand.Accept(assignmentVisitor);
return;
}
if (isPrefix)
{
AddCilInstruction(ilVar, OpCodes.Ldc_I4_1);
AddCilInstruction(ilVar, opCode);
}
var tempLocalName = AddLocalVariableWithResolvedType("tmp", Context.DefinitionVariables.GetLastOf(MemberKind.Method), Context.TypeResolver.Resolve(Context.SemanticModel.GetTypeInfo(operand).Type));
AddCilInstruction(ilVar, OpCodes.Stloc, tempLocalName);
AddCilInstruction(ilVar, OpCodes.Ldloc, tempLocalName);
assignmentVisitor.InstructionPrecedingValueToLoad = Context.CurrentLine;
AddCilInstruction(ilVar, OpCodes.Ldloc, tempLocalName);
if (!isPrefix)
{
AddCilInstruction(ilVar, OpCodes.Ldc_I4_1);
AddCilInstruction(ilVar, opCode);
}
// assign (top of stack to the operand)
operand.Accept(assignmentVisitor);
}
private bool TryProcessNoArgsCtorInvocationOnValueType(ObjectCreationExpressionSyntax node, IMethodSymbol methodSymbol, SymbolInfo ctorInfo)
{
if (ctorInfo.Symbol.ContainingType.IsReferenceType || methodSymbol.Parameters.Length > 0)
{
return false;
}
new ValueTypeNoArgCtorInvocationVisitor(Context, ilVar, ctorInfo).Visit(node.Parent);
return valueTypeNoArgObjCreation = true;
}
public override void VisitExpressionStatement(ExpressionStatementSyntax node)
{
base.Visit(node.Expression);
var info = Context.GetTypeInfo(node.Expression);
if (node.Expression.Kind() != SyntaxKind.SimpleAssignmentExpression && info.Type.SpecialType != SpecialType.System_Void)
{
AddCilInstruction(ilVar, OpCodes.Pop);
}
}
public override void VisitThisExpression(ThisExpressionSyntax node)
{
AddCilInstruction(ilVar, OpCodes.Ldarg_0);
base.VisitThisExpression(node);
}
public override void VisitRefExpression(RefExpressionSyntax node)
{
using (Context.WithFlag("ref-return"))
{
node.Expression.Accept(this);
}
}
public override void VisitCastExpression(CastExpressionSyntax node)
{
node.Expression.Accept(this);
var castSource = Context.GetTypeInfo(node.Expression);
var castTarget = Context.GetTypeInfo(node.Type);
if (castSource.Type == null)
throw new InvalidOperationException($"Failed to get type information for expression: {node.Expression}");
if (castTarget.Type == null)
throw new InvalidOperationException($"Failed to get type information for: {node.Type}");
if (castSource.Type.SpecialType == castTarget.Type.SpecialType && castSource.Type.SpecialType == SpecialType.System_Double)
{
/*
* Even though a cast from double => double can be view as an identity conversion (from the pov of the developer who wrote it)
* we still need to emit a *conv.r8* opcode. * (Fo more details see https://github.com/dotnet/roslyn/discussions/56198)
*/
AddCilInstruction(ilVar, OpCodes.Conv_R8);
return;
}
if (castSource.Type.SpecialType == castTarget.Type.SpecialType && castSource.Type.SpecialType != SpecialType.None ||
castSource.Type.SpecialType == SpecialType.System_Byte && castTarget.Type.SpecialType == SpecialType.System_Char ||
castSource.Type.SpecialType == SpecialType.System_Byte && castTarget.Type.SpecialType == SpecialType.System_Int16 ||
castSource.Type.SpecialType == SpecialType.System_Byte && castTarget.Type.SpecialType == SpecialType.System_Int32 ||
castSource.Type.SpecialType == SpecialType.System_Char && castTarget.Type.SpecialType == SpecialType.System_Int32 ||
castSource.Type.SpecialType == SpecialType.System_Int16 && castTarget.Type.SpecialType == SpecialType.System_Int32)
return;
var conversion = Context.SemanticModel.ClassifyConversion(node.Expression, castTarget.Type, true);
if (castTarget.Type.SpecialType != SpecialType.None && conversion.IsNumeric)
{
var opcode = castTarget.Type.SpecialType switch
{
SpecialType.System_Int16 => OpCodes.Conv_I2,
SpecialType.System_Int32 => OpCodes.Conv_I4,
SpecialType.System_Int64 => castSource.Type.SpecialType == SpecialType.System_Byte || castSource.Type.SpecialType == SpecialType.System_Char ? OpCodes.Conv_U8 : OpCodes.Conv_I8,
SpecialType.System_Single => OpCodes.Conv_R4,
SpecialType.System_Double => OpCodes.Conv_R8,
SpecialType.System_Char => OpCodes.Conv_U2,
SpecialType.System_Byte => OpCodes.Conv_U1,
_ => throw new Exception($"Cast from {node.Expression} ({castSource.Type}) to {castTarget.Type} is not supported.")
};
AddCilInstruction(ilVar, opcode);
}
else if (conversion.IsExplicit && conversion.IsReference)
{
var opcode = castTarget.Type.TypeKind == TypeKind.TypeParameter ? OpCodes.Unbox_Any : OpCodes.Castclass;
AddCilInstruction(ilVar, opcode, castTarget.Type);
}
else if (conversion.IsImplicit && conversion.IsReference && castSource.Type.TypeKind == TypeKind.TypeParameter)
{
AddCilInstruction(ilVar, OpCodes.Box, Context.TypeResolver.Resolve(castSource.Type));
}
}
public override void VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) => HandleLambdaExpression(node);
public override void VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) => HandleLambdaExpression(node);
public override void VisitRangeExpression(RangeExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitAwaitExpression(AwaitExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitTupleExpression(TupleExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitInterpolatedStringExpression(InterpolatedStringExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitIsPatternExpression(IsPatternExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitThrowExpression(ThrowExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitSwitchExpression(SwitchExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitAnonymousObjectCreationExpression(AnonymousObjectCreationExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitOmittedArraySizeExpression(OmittedArraySizeExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitMakeRefExpression(MakeRefExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitRefTypeExpression(RefTypeExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitRefValueExpression(RefValueExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitCheckedExpression(CheckedExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitDefaultExpression(DefaultExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitTypeOfExpression(TypeOfExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitSizeOfExpression(SizeOfExpressionSyntax node) => LogUnsupportedSyntax(node);
public override void VisitInitializerExpression(InitializerExpressionSyntax node) => LogUnsupportedSyntax(node);
private void HandleLambdaExpression(LambdaExpressionSyntax node)
{
//TODO: Handle static lambdas.
// use the lambda string representation to lookup the variable with the synthetic method definition
var syntheticMethodVariable = Context.DefinitionVariables.GetVariable(node.ToString(), MemberKind.Method);
if (!syntheticMethodVariable.IsValid)
{
// if we fail to resolve the variable it means this is un unsupported scenario (like a lambda that captures context)
LogUnsupportedSyntax(node);
return;
}
AddCilInstruction(ilVar, OpCodes.Ldarg_0);
var exps = CecilDefinitionsFactory.InstantiateDelegate(Context, ilVar, Context.GetTypeInfo(node).ConvertedType, syntheticMethodVariable.VariableName);
AddCecilExpressions(exps);
}
private void StoreTopOfStackInLocalVariableAndLoadItsAddressIfNeeded(ExpressionSyntax node)
{
var invocation = (InvocationExpressionSyntax) node.Ancestors().FirstOrDefault(a => a.IsKind(SyntaxKind.InvocationExpression));
if (invocation == null || invocation.ArgumentList.Arguments.Any(argumentExp => argumentExp.Expression.DescendantNodesAndSelf().Any( exp => exp == node)))
return;
var targetOfInvocationType = Context.SemanticModel.GetTypeInfo(node);
if (targetOfInvocationType.Type?.IsValueType == false)
return;
StoreTopOfStackInLocalVariableAndLoadItsAddress(targetOfInvocationType.Type);
}
private void StoreTopOfStackInLocalVariableAndLoadItsAddress(ITypeSymbol type)
{
var tempLocalName = AddLocalVariableWithResolvedType("tmp", Context.DefinitionVariables.GetLastOf(MemberKind.Method), Context.TypeResolver.Resolve(type));
AddCilInstruction(ilVar, OpCodes.Stloc, tempLocalName);
AddCilInstruction(ilVar, OpCodes.Ldloca_S, tempLocalName);
}
private OpCode LoadOpCodeFor(LiteralExpressionSyntax node)
{
var info = Context.SemanticModel.GetTypeInfo(node);
switch (info.Type.SpecialType)
{
case SpecialType.System_Single:
return OpCodes.Ldc_R4;
case SpecialType.System_Double:
return OpCodes.Ldc_R8;
case SpecialType.System_Int16:
case SpecialType.System_Int32:
return OpCodes.Ldc_I4;
case SpecialType.System_Int64:
return OpCodes.Ldc_I8;
case SpecialType.System_Char:
return OpCodes.Ldc_I4;
case SpecialType.System_Boolean:
return OpCodes.Ldc_I4;
}
throw new ArgumentException($"Literal type {info.Type} not supported.", nameof(node));
}
private OpCode StelemOpCodeFor(ITypeSymbol type)
{
switch (type.SpecialType)
{
case SpecialType.System_Byte: return OpCodes.Stelem_I1;
case SpecialType.System_Int16: return OpCodes.Stelem_I2;
case SpecialType.System_Int32: return OpCodes.Stelem_I4;
case SpecialType.System_Int64: return OpCodes.Stelem_I8;
case SpecialType.System_Single: return OpCodes.Stelem_R4;
case SpecialType.System_Double: return OpCodes.Stelem_R8;
case SpecialType.None: // custom types.
case SpecialType.System_String:
case SpecialType.System_Object: return OpCodes.Stelem_Ref;
}
throw new Exception($"Element type {type.Name} not supported.");
}
/*
* Support for scenario in which a method is being referenced before it has been declared. This can happen for instance in code like:
*
* class C
* {
* void Foo() { Bar(); }
* void Bar() {}
* }
*
* In this case when the first reference to Bar() is found (in method Foo()) the method itself has not been defined yet.
*/
private void EnsureMethodAvailable(string varName, IMethodSymbol method, TypeParameterSyntax[] typeParameters)
{
if (!method.IsDefinedInCurrentType(Context))
return;
var found = Context.DefinitionVariables.GetMethodVariable(method.AsMethodDefinitionVariable());
if (found.IsValid)
return;
MethodDeclarationVisitor.AddMethodDefinition(Context, varName, method.Name, "MethodAttributes.Private", method.ReturnType, method.ReturnsByRef, typeParameters);
Context.DefinitionVariables.RegisterMethod(method.ContainingType.Name, method.Name, method.Parameters.Select(p => p.Type.Name).ToArray(), varName);
}
private void FixCallSite()
{
Context.MoveLineAfter(callFixList.Pop(), Context.CurrentLine);
}
private void PushCall()
{
callFixList.Push(Context.CurrentLine);
}
private void ProcessProperty(SimpleNameSyntax node, IPropertySymbol propertySymbol)
{
EnsurePropertyExists(node, propertySymbol);
var parentMae = node.Parent as MemberAccessExpressionSyntax;
var isAccessOnThisOrObjectCreation = true;
if (parentMae != null)
{
isAccessOnThisOrObjectCreation = parentMae.Expression.IsKind(SyntaxKind.ObjectCreationExpression);
}
// if this is an *unqualified* access we need to load *this*
if (parentMae == null || parentMae.Expression == node)
{
AddCilInstruction(ilVar, OpCodes.Ldarg_0);
}
var parentExp = node.Parent;
if (parentExp.Kind() == SyntaxKind.SimpleAssignmentExpression || parentMae != null && parentMae.Name.Identifier == node.Identifier && parentMae.Parent.IsKind(SyntaxKind.SimpleAssignmentExpression))
{
AddMethodCall(ilVar, propertySymbol.SetMethod, isAccessOnThisOrObjectCreation);
}
else
{
if (propertySymbol.ContainingType.SpecialType == SpecialType.System_Array && propertySymbol.Name == "Length")
{
AddCilInstruction(ilVar, OpCodes.Ldlen);
AddCilInstruction(ilVar, OpCodes.Conv_I4);
}
else if (propertySymbol.ContainingType.SpecialType == SpecialType.System_Array && propertySymbol.Name == "LongLength")
{
AddCilInstruction(ilVar, OpCodes.Ldlen);
AddCilInstruction(ilVar, OpCodes.Conv_I8);
}
else
{
AddMethodCall(ilVar, propertySymbol.GetMethod, isAccessOnThisOrObjectCreation);
StoreTopOfStackInLocalVariableAndLoadItsAddressIfNeeded(node);
}
}
}
private void EnsurePropertyExists(SyntaxNode node, [NotNull] IPropertySymbol propertySymbol)
{
var declaringReference = propertySymbol.DeclaringSyntaxReferences.SingleOrDefault();
if (declaringReference == null)
return;
var propertyDeclaration = (BasePropertyDeclarationSyntax) declaringReference.GetSyntax();
if (propertyDeclaration.Span.Start > node.Span.End)
{
// this is a forward reference, process it...
propertyDeclaration.Accept(new PropertyDeclarationVisitor(Context));
}
}
private void ProcessField(SimpleNameSyntax node, IFieldSymbol fieldSymbol)
{
var fieldDeclarationVariable = EnsureFieldExists(node, fieldSymbol);
var isTargetOfQualifiedAccess = (node.Parent is MemberAccessExpressionSyntax mae) && mae.Name == node;
if (!fieldSymbol.IsStatic && !isTargetOfQualifiedAccess)
AddCilInstruction(ilVar, OpCodes.Ldarg_0);
if (HandleLoadAddress(ilVar, fieldSymbol.Type, (CSharpSyntaxNode) node.Parent, OpCodes.Ldflda, fieldSymbol.Name, MemberKind.Field, fieldSymbol.ContainingType.Name))
{
return;
}
if (fieldSymbol.IsVolatile)
AddCilInstruction(ilVar, OpCodes.Volatile);
AddCilInstruction(ilVar, LoadOpCodeForFieldAccess(fieldSymbol), fieldDeclarationVariable.VariableName);
HandlePotentialDelegateInvocationOn(node, fieldSymbol.Type, ilVar);
}
private OpCode LoadOpCodeForFieldAccess(IFieldSymbol fieldSymbol) => fieldSymbol.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld;
private DefinitionVariable EnsureFieldExists(SimpleNameSyntax node, [NotNull] IFieldSymbol fieldSymbol)
{
var fieldDeclaration = (FieldDeclarationSyntax) fieldSymbol.DeclaringSyntaxReferences.Single().GetSyntax().Parent.Parent;
if (fieldDeclaration.Span.Start > node.Span.End)
{
// this is a forward reference, process it...
fieldDeclaration.Accept(new FieldDeclarationVisitor(Context));
}
var fieldDeclarationVariable = Context.DefinitionVariables.GetVariable(fieldSymbol.Name, MemberKind.Field, fieldSymbol.ContainingType.Name);
if (!fieldDeclarationVariable.IsValid)
throw new Exception($"Could not resolve reference to field: {fieldSymbol.Name}");
return fieldDeclarationVariable;
}
private void ProcessLocalVariable(SimpleNameSyntax localVarSyntax, SymbolInfo varInfo)
{
var symbol = (ILocalSymbol) varInfo.Symbol;
var localVar = (CSharpSyntaxNode) localVarSyntax.Parent;
if (HandleLoadAddress(ilVar, symbol.Type, localVar, OpCodes.Ldloca, symbol.Name, MemberKind.LocalVariable))
{
return;
}
AddCilInstruction(ilVar, OpCodes.Ldloc, Context.DefinitionVariables.GetVariable(symbol.Name, MemberKind.LocalVariable).VariableName);
HandlePotentialDelegateInvocationOn(localVarSyntax, symbol.Type, ilVar);
HandlePotentialFixedLoad(symbol);
HandlePotentialRefLoad(localVarSyntax, symbol);
}
private void HandlePotentialRefLoad(SimpleNameSyntax localVariableNameSyntax, ILocalSymbol symbol)
{
var needsLoadIndirect = false;
var sourceSymbol = Context.SemanticModel.GetSymbolInfo(localVariableNameSyntax).Symbol;
var sourceIsByRef = sourceSymbol.IsByRef();
var returnStatement = localVariableNameSyntax.Ancestors().OfType<ReturnStatementSyntax>().SingleOrDefault();
var argument = localVariableNameSyntax.Ancestors().OfType<ArgumentSyntax>().SingleOrDefault();
var assigment = localVariableNameSyntax.Ancestors().OfType<BinaryExpressionSyntax>().SingleOrDefault(candidate => candidate.IsKind(SyntaxKind.SimpleAssignmentExpression));
if (assigment != null && assigment.Left != localVariableNameSyntax)
{
var targetIsByRef = Context.SemanticModel.GetSymbolInfo(assigment.Left).Symbol.IsByRef();
needsLoadIndirect = (assigment.Right == localVariableNameSyntax && sourceIsByRef && !targetIsByRef) // simple assignment like: nonRef = ref;
|| sourceIsByRef; // complex assignment like: nonRef = ref + 10;
}
else if (argument != null)
{
var parameterSymbol = ParameterSymbolFromArgumentSyntax(argument);
var targetIsByRef = parameterSymbol.IsByRef();
needsLoadIndirect = (parameterSymbol == sourceSymbol && sourceIsByRef && !targetIsByRef) // simple argument like Foo(ref) where the parameter is not a reference.
|| sourceIsByRef; // complex argument like Foo(ref + 1)
}
else if (returnStatement != null)
{
var method = returnStatement.Ancestors().OfType<MethodDeclarationSyntax>().Single();
var methodIsByRef = Context.SemanticModel.GetSymbolInfo(method.ReturnType).Symbol.IsByRef();
needsLoadIndirect = (returnStatement.Expression == localVariableNameSyntax && !methodIsByRef && sourceIsByRef) // simple return like: return ref_var; (method is not by ref)
|| sourceIsByRef; // more complex return like: return ref_var + 1; // in this case we can only be accessing the value whence we need to deference the reference.
}
if (needsLoadIndirect)
AddCilInstruction(ilVar, LoadIndirectOpCodeFor(symbol.Type.SpecialType));
}
private void HandlePotentialFixedLoad(ILocalSymbol symbol)
{
if (!symbol.IsFixed)
return;
AddCilInstruction(ilVar, OpCodes.Conv_U);
}
private void ProcessMethodReference(SimpleNameSyntax node, IMethodSymbol method)
{
var invocationParent = node.Ancestors().OfType<InvocationExpressionSyntax>()
.SingleOrDefault(i => i.Expression == node || i.Expression.ChildNodes().Contains(node));
if (invocationParent != null)
{
ProcessMethodCall(node, method);
return;
}
// this is not an invocation. We need to figure out whether this is an assignment, return, etc
var firstParentNotPartOfName = node.Ancestors().First(a => a.Kind() != SyntaxKind.QualifiedName
&& a.Kind() != SyntaxKind.SimpleMemberAccessExpression
&& a.Kind() != SyntaxKind.EqualsValueClause
&& a.Kind() != SyntaxKind.VariableDeclarator);
if (firstParentNotPartOfName is PrefixUnaryExpressionSyntax unaryPrefix && unaryPrefix.IsKind(SyntaxKind.AddressOfExpression))
{
AddCilInstruction(ilVar, OpCodes.Ldftn, method.MethodResolverExpression(Context));
return;
}
var delegateType = firstParentNotPartOfName switch
{
ArgumentSyntax arg => ((IMethodSymbol) Context.SemanticModel.GetSymbolInfo(arg.Parent.Parent).Symbol).Parameters[arg.FirstAncestorOrSelf<ArgumentListSyntax>().Arguments.IndexOf(arg)].Type,
AssignmentExpressionSyntax assignment => Context.SemanticModel.GetSymbolInfo(assignment.Left).Symbol switch
{
ILocalSymbol local => local.Type,
IParameterSymbol param => param.Type,
IFieldSymbol field => field.Type,
IPropertySymbol prop => prop.Type,
_ => throw new NotSupportedException($"Assignment to {assignment.Left} ({assignment.Kind()}) is not supported.")
},
VariableDeclarationSyntax variableDeclaration => Context.SemanticModel.GetTypeInfo(variableDeclaration.Type).Type,
ReturnStatementSyntax returnStatement => returnStatement.FirstAncestorOrSelf<MemberDeclarationSyntax>() switch
{
MethodDeclarationSyntax md => Context.SemanticModel.GetTypeInfo(md.ReturnType).Type,
_ => throw new NotSupportedException($"Return is not supported.")
},
_ => throw new NotSupportedException($"Referencing method {method} in expression {firstParentNotPartOfName} ({firstParentNotPartOfName.GetType().FullName}) is not supported.")
};
// we have a reference to a method used to initialize a delegate
// and need to load the referenced method token and instantiate the delegate. For instance:
//IL_0002: ldarg.0
//IL_0002: ldftn string Test::M(int32)
//IL_0008: newobj instance void class [System.Private.CoreLib]System.Func`2<int32, string>::.ctor(object, native int)
if (method.IsStatic)
{
AddCilInstruction(ilVar, OpCodes.Ldnull);
}
else if (!node.Parent.IsKind(SyntaxKind.ThisExpression) && node.Parent == firstParentNotPartOfName)
{
AddCilInstruction(ilVar, OpCodes.Ldarg_0);
}
var exps = CecilDefinitionsFactory.InstantiateDelegate(Context, ilVar, delegateType, method.MethodResolverExpression(Context));
AddCecilExpressions(exps);
}
private void ProcessMethodCall(SimpleNameSyntax node, IMethodSymbol method)
{
if (!method.IsStatic && method.IsDefinedInCurrentType(Context) && node.Parent.Kind() == SyntaxKind.InvocationExpression)
{
AddCilInstruction(ilVar, OpCodes.Ldarg_0);
}
//TODO: We need to find the InvocationSyntax that node represents...
EnsureMethodAvailable(Context.Naming.SyntheticVariable(node.Identifier.Text, ElementKind.Method), method.OverriddenMethod ?? method.OriginalDefinition, Array.Empty<TypeParameterSyntax>());
var isAccessOnThis = !node.Parent.IsKind(SyntaxKind.SimpleMemberAccessExpression);
var mae = node.Parent as MemberAccessExpressionSyntax;
if (mae?.Expression.IsKind(SyntaxKind.ObjectCreationExpression) == true)
{
isAccessOnThis = true;
}
AddMethodCall(ilVar, method, isAccessOnThis);
}
private void InjectRequiredConversions(ExpressionSyntax expression, Action loadArrayIntoStack = null)
{
var typeInfo = Context.SemanticModel.GetTypeInfo(expression);
if (typeInfo.Type == null)
return;
var conversion = Context.SemanticModel.GetConversion(expression);
if (conversion.IsImplicit && conversion.IsNumeric)
{
Debug.Assert(typeInfo.ConvertedType != null);
switch (typeInfo.ConvertedType.SpecialType)
{
case SpecialType.System_Single:
AddCilInstruction(ilVar, OpCodes.Conv_R4);
return;
case SpecialType.System_Double:
AddCilInstruction(ilVar, OpCodes.Conv_R8);
return;
case SpecialType.System_Byte:
AddCilInstruction(ilVar, OpCodes.Conv_I1);
return;
case SpecialType.System_Int16:
AddCilInstruction(ilVar, OpCodes.Conv_I2);
return;
case SpecialType.System_Int32:
// byte/char are pushed as Int32 by the runtime
if (typeInfo.Type.SpecialType != SpecialType.System_SByte && typeInfo.Type.SpecialType != SpecialType.System_Byte && typeInfo.Type.SpecialType != SpecialType.System_Char)
AddCilInstruction(ilVar, OpCodes.Conv_I4);
return;
case SpecialType.System_Int64:
var convOpCode = typeInfo.Type.SpecialType == SpecialType.System_Char || typeInfo.Type.SpecialType == SpecialType.System_Byte ? OpCodes.Conv_U8 : OpCodes.Conv_I8;
AddCilInstruction(ilVar, convOpCode);
return;
default:
throw new Exception($"Conversion from {typeInfo.Type} to {typeInfo.ConvertedType} not implemented.");
}
}
if (conversion.IsImplicit && conversion.IsBoxing)
{
AddCilInstruction(ilVar, OpCodes.Box, typeInfo.Type);
}
else if (conversion.IsIdentity && typeInfo.Type.Name == "Index" && loadArrayIntoStack != null)
{
// We are indexing an array/indexer using System.Index; In this case
// we need to convert from System.Index to *int* which is done through
// the method System.Index::GetOffset(int32)
loadArrayIntoStack();
AddCilInstruction(ilVar, OpCodes.Ldlen);
AddCilInstruction(ilVar, OpCodes.Conv_I4);
AddMethodCall(ilVar, (IMethodSymbol) typeInfo.Type.GetMembers().Single(m => m.Name == "GetOffset"));
}
}
private Action<IVisitorContext, string, ITypeSymbol, ITypeSymbol> OperatorHandlerFor(SyntaxToken operatorToken)
{
if (operatorHandlers.ContainsKey(operatorToken.Kind()))
{
return operatorHandlers[operatorToken.Kind()];
}
throw new Exception(string.Format("Operator {0} not supported yet (expression: {1})", operatorToken.ValueText, operatorToken.Parent));
}
/*
* +--> ArgumentList
* |
* /---------\
* n.DoIt(10 + x, y);
* \----/
* |
* +---> Expression: MemberAccessExpression
*
* We do not have a natural order to visit the expression and the argument list:
*
* - If we visit in the order: arguments, expression (which would be the natural order)
* push 10
* push x
* add
* push y
* push n <-- Should be the first
* Call DoIt(Int32, Int32)
*
* - If we visit in the order: expression, arguments
* push n
* Call DoIt(Int32, Int32) <--+
* push 10 |
* push x | Should be here
* add |
* push y |
* <-----------------+
*
* To fix this we visit in the order [exp, args] and move the call operation after visiting the arguments
*/
private void HandleMethodInvocation(SyntaxNode target, SyntaxNode args)
{
var targetTypeInfo = Context.SemanticModel.GetTypeInfo(target).Type;
if (targetTypeInfo?.TypeKind == TypeKind.FunctionPointer)
{
// if *target* is a function pointer, then we'll emmit a calli, which
// expects the stack as : <arg1, arg2, .. argn, function ptr>
Visit(args);
Visit(target);
}
else
{
Visit(target);
PushCall();
Visit(args);
FixCallSite();
}
}
private void HandleIdentifier(SimpleNameSyntax node)
{
var member = Context.SemanticModel.GetSymbolInfo(node);
switch (member.Symbol.Kind)
{
case SymbolKind.Method:
ProcessMethodReference(node, member.Symbol as IMethodSymbol);
break;
case SymbolKind.Parameter:
ProcessParameter(ilVar, node, (IParameterSymbol) member.Symbol);
break;
case SymbolKind.Local:
ProcessLocalVariable(node, member);
break;
case SymbolKind.Field:
ProcessField(node, member.Symbol as IFieldSymbol);
break;
case SymbolKind.Property:
ProcessProperty(node, member.Symbol as IPropertySymbol);
break;
}
}
private void ProcessArrayCreation(ITypeSymbol elementType, InitializerExpressionSyntax initializer)
{
AddCilInstruction(ilVar, OpCodes.Newarr, Context.TypeResolver.Resolve(elementType));
var stelemOpCode = StelemOpCodeFor(elementType);
for (var i = 0; i < initializer?.Expressions.Count; i++)
{
AddCilInstruction(ilVar, OpCodes.Dup);
AddCilInstruction(ilVar, OpCodes.Ldc_I4, i);
initializer.Expressions[i].Accept(this);
var itemType = Context.GetTypeInfo(initializer.Expressions[i]);
if (elementType.IsReferenceType && itemType.Type != null && itemType.Type.IsValueType)
{
AddCilInstruction(ilVar, OpCodes.Box, Context.TypeResolver.Resolve(itemType.Type));
}
AddCilInstruction(ilVar, stelemOpCode);
}
}
}
internal class ElementTypeSymbolResolver : SymbolVisitor<ITypeSymbol>
{
public override ITypeSymbol VisitEvent(IEventSymbol symbol)
{
return symbol.Type.Accept(this);
}
public override ITypeSymbol VisitField(IFieldSymbol symbol)
{
return symbol.Type.Accept(this);
}
public override ITypeSymbol VisitLocal(ILocalSymbol symbol)
{
return symbol.Type.Accept(this);
}
public override ITypeSymbol VisitMethod(IMethodSymbol symbol)
{
return symbol.ReturnType.Accept(this);
}
public override ITypeSymbol VisitProperty(IPropertySymbol symbol)
{
return symbol.Type.Accept(this);
}
public override ITypeSymbol VisitParameter(IParameterSymbol symbol)
{
return symbol.Type.Accept(this);
}
public override ITypeSymbol VisitArrayType(IArrayTypeSymbol symbol)
{
return symbol.ElementType;
}
public override ITypeSymbol VisitNamedType(INamedTypeSymbol symbol)
{
return symbol;
}
}
}
| 46.658833 | 313 | 0.607465 | [
"MIT"
] | adrianoc/cecilifier | Cecilifier.Core/AST/ExpressionVisitor.cs | 57,577 | C# |
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
namespace NMica.Utils.IO
{
[PublicAPI]
public static class TextTasks
{
public static UTF8Encoding UTF8NoBom => new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
public static void WriteAllLines(string path, IEnumerable<string> lines, Encoding encoding = null)
{
WriteAllLines(path, lines.ToArray(), encoding);
}
public static void WriteAllLines(string path, string[] lines, Encoding encoding = null)
{
FileSystemTasks.EnsureExistingParentDirectory(path);
File.WriteAllLines(path, lines, encoding ?? UTF8NoBom);
}
public static void WriteAllText(string path, string content, Encoding encoding = null)
{
FileSystemTasks.EnsureExistingParentDirectory(path);
File.WriteAllText(path, content, encoding ?? UTF8NoBom);
}
public static void WriteAllBytes(string path, byte[] bytes)
{
FileSystemTasks.EnsureExistingParentDirectory(path);
File.WriteAllBytes(path, bytes);
}
public static string ReadAllText(string path, Encoding encoding = null)
{
Assert.FileExists(path);
return File.ReadAllText(path, encoding ?? Encoding.UTF8);
}
public static string[] ReadAllLines(string path, Encoding encoding = null)
{
Assert.FileExists(path);
return File.ReadAllLines(path, encoding ?? Encoding.UTF8);
}
public static byte[] ReadAllBytes(string path)
{
Assert.FileExists(path);
return File.ReadAllBytes(path);
}
}
}
| 32.267857 | 132 | 0.640841 | [
"MIT"
] | NMica/NMica-Utils | src/NMica.Utils/IO/TextTasks.cs | 1,807 | C# |
using System;
using System.Xml;
using HotChocolate.Language;
using HotChocolate.Properties;
#nullable enable
namespace HotChocolate.Types
{
/// <summary>
/// The TimeSpan scalar type represented in two formats:
/// <see cref="TimeSpanFormat.Iso8601"/> and <see cref="TimeSpanFormat.DotNet"/>
/// </summary>
public class TimeSpanType
: ScalarType<TimeSpan, StringValueNode>
{
private readonly TimeSpanFormat _format;
public TimeSpanType()
: this(ScalarNames.TimeSpan, TypeResources.TimeSpanType_Description)
{
}
public TimeSpanType(
TimeSpanFormat format = TimeSpanFormat.Iso8601,
BindingBehavior bind = BindingBehavior.Implicit)
: this(ScalarNames.TimeSpan, TypeResources.TimeSpanType_Description, format, bind)
{
}
public TimeSpanType(
NameString name,
string? description = default,
TimeSpanFormat format = TimeSpanFormat.Iso8601,
BindingBehavior bind = BindingBehavior.Explicit)
: base(name, bind)
{
_format = format;
Description = description;
}
protected override TimeSpan ParseLiteral(StringValueNode valueSyntax)
{
if (TryDeserializeFromString(valueSyntax.Value, _format, out TimeSpan? value) &&
value != null)
{
return value.Value;
}
throw new SerializationException(
TypeResourceHelper.Scalar_Cannot_ParseLiteral(Name, valueSyntax.GetType()),
this);
}
protected override StringValueNode ParseValue(TimeSpan runtimeValue)
{
return _format == TimeSpanFormat.Iso8601
? new StringValueNode(XmlConvert.ToString(runtimeValue))
: new StringValueNode(runtimeValue.ToString("c"));
}
public override IValueNode ParseResult(object? resultValue)
{
if (resultValue is null)
{
return NullValueNode.Default;
}
if (resultValue is string s &&
TryDeserializeFromString(s, _format, out TimeSpan? timeSpan))
{
return ParseValue(timeSpan);
}
if (resultValue is TimeSpan ts)
{
return ParseValue(ts);
}
throw new SerializationException(
TypeResourceHelper.Scalar_Cannot_ParseResult(Name, resultValue.GetType()),
this);
}
public override bool TrySerialize(object? runtimeValue, out object? resultValue)
{
if (runtimeValue is null)
{
resultValue = null;
return true;
}
if (runtimeValue is TimeSpan timeSpan)
{
if (_format == TimeSpanFormat.Iso8601)
{
resultValue = XmlConvert.ToString(timeSpan);
return true;
}
resultValue = timeSpan.ToString("c");
return true;
}
resultValue = null;
return false;
}
public override bool TryDeserialize(object? resultValue, out object? runtimeValue)
{
if (resultValue is null)
{
runtimeValue = null;
return true;
}
if (resultValue is string s &&
TryDeserializeFromString(s, _format, out TimeSpan? timeSpan))
{
runtimeValue = timeSpan;
return true;
}
if (resultValue is TimeSpan ts)
{
runtimeValue = ts;
return true;
}
runtimeValue = null;
return false;
}
private static bool TryDeserializeFromString(
string serialized,
TimeSpanFormat format,
out TimeSpan? value)
{
return format == TimeSpanFormat.Iso8601
? TryDeserializeIso8601(serialized, out value)
: TryDeserializeDotNet(serialized, out value);
}
private static bool TryDeserializeIso8601(string serialized, out TimeSpan? value)
{
try
{
return Iso8601Duration.TryParse(serialized, out value);
}
catch (FormatException)
{
value = null;
return false;
}
}
private static bool TryDeserializeDotNet(string serialized, out TimeSpan? value)
{
if (TimeSpan.TryParse(serialized, out TimeSpan timeSpan))
{
value = timeSpan;
return true;
}
value = null;
return false;
}
}
}
| 29.147059 | 94 | 0.531584 | [
"MIT"
] | Alxandr/hotchocolate | src/HotChocolate/Core/src/Types/Types/Scalars/TimeSpanType.cs | 4,955 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.DataFactory.Latest.Outputs
{
[OutputType]
public sealed class FileServerWriteSettingsResponse
{
/// <summary>
/// The type of copy behavior for copy sink.
/// </summary>
public readonly object? CopyBehavior;
/// <summary>
/// The maximum concurrent connection count for the source data store. Type: integer (or Expression with resultType integer).
/// </summary>
public readonly object? MaxConcurrentConnections;
/// <summary>
/// The write setting type.
/// Expected value is 'FileServerWriteSettings'.
/// </summary>
public readonly string Type;
[OutputConstructor]
private FileServerWriteSettingsResponse(
object? copyBehavior,
object? maxConcurrentConnections,
string type)
{
CopyBehavior = copyBehavior;
MaxConcurrentConnections = maxConcurrentConnections;
Type = type;
}
}
}
| 30.386364 | 133 | 0.640987 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/DataFactory/Latest/Outputs/FileServerWriteSettingsResponse.cs | 1,337 | C# |
/*
* Copyright 2020 Sage Intacct, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "LICENSE" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using Intacct.SDK.Functions.GeneralLedger;
using Intacct.SDK.Functions;
using Intacct.SDK.Tests.Xml;
using Intacct.SDK.Xml;
using Xunit;
namespace Intacct.SDK.Tests.Functions.GeneralLedger
{
public class StatisticalAccountUpdateTest : XmlObjectTestHelper
{
[Fact]
public void GetXmlTest()
{
string expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<function controlid=""unittest"">
<update>
<STATACCOUNT>
<ACCOUNTNO>9000</ACCOUNTNO>
<TITLE>hello world</TITLE>
</STATACCOUNT>
</update>
</function>";
StatisticalAccountUpdate record = new StatisticalAccountUpdate("unittest")
{
AccountNo = "9000",
Title = "hello world"
};
this.CompareXml(expected, record);
}
}
} | 29.529412 | 86 | 0.654714 | [
"Apache-2.0"
] | Intacct/intacct-sdk-net | Intacct.SDK.Tests/Functions/GeneralLedger/StatisticalAccountUpdateTest.cs | 1,508 | 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("ThirdPartySample")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ThirdPartySample")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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("0f9d2c94-aeba-477f-afc4-625bc4e8da5e")]
// 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.972973 | 84 | 0.746619 | [
"Apache-2.0"
] | birbilis/OverrideXml | src/ThirdPartySample/Properties/AssemblyInfo.cs | 1,408 | C# |
using System.IO;
using Netch.Controllers;
using Netch.Models;
using Netch.Servers.VMess.Utils;
namespace Netch.Servers.VLESS
{
public class VLESSController : Guard, IServerController
{
public override string Name { get; protected set; } = "VLESS";
public override string MainFile { get; protected set; } = "v2ray.exe";
public ushort? Socks5LocalPort { get; set; }
public string LocalAddress { get; set; }
public bool Start(Server s, Mode mode)
{
File.WriteAllText("data\\last.json", V2rayConfigUtils.GenerateClientConfig(s, mode));
return StartInstanceAuto("-config ..\\data\\last.json");
}
public override void Stop()
{
StopInstance();
}
}
} | 27.678571 | 97 | 0.623226 | [
"MIT"
] | tonyklose1984/Netch | Netch/Servers/VLESS/VLESSController.cs | 775 | C# |
namespace Demo.ViewModels
{
using System;
using NativeCode.Mobile.Core.Presentation;
using Xamarin.Forms;
public class WebContentViewModel : ViewModel
{
public WebContentViewModel(Uri url)
{
this.Source = new UrlWebViewSource { Url = url.AbsoluteUri };
}
public UrlWebViewSource Source { get; set; }
}
} | 20.888889 | 73 | 0.632979 | [
"Apache-2.0"
] | nativecode-dev/frameworks | src/Demo/Demo/ViewModels/WebContentViewModel.cs | 378 | C# |
using System;
using System.Collections.Generic;
using Contracts;
using KSP.Localization;
using ContractConfigurator;
using ContractConfigurator.Parameters;
namespace Kerbalism.Contracts
{
public class OutsideHeliopauseFactory : ParameterFactory
{
public override ContractParameter Generate(Contract contract)
{
return new OutsideHeliopause();
}
}
public class OutsideHeliopause : VesselParameter
{
protected override string GetParameterTitle()
{
if (!string.IsNullOrEmpty(title)) return title;
var sun = Lib.GetHomeSun();
return "Leave the heliosphere of " + sun.bodyName;
}
protected override bool VesselMeetsCondition(Vessel vessel)
{
if (vessel.mainBody.flightGlobalsIndex != Lib.GetHomeSun().flightGlobalsIndex)
return false;
return !KERBALISM.API.Magnetosphere(vessel);
}
}
}
| 23.486486 | 82 | 0.731876 | [
"Unlicense"
] | Kerbalism/KerbalismContracts | src/KerbalismContracts/ContractConfigurator/OutsideHeliopause.cs | 871 | C# |
using System;
using System.IO;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
namespace Unity.InteractiveTutorials.Tests
{
public class BuildPlayerTests : TestBase
{
static string buildPath
{
get
{
const string buildName = "BuildPlayerTests_Build";
if (Application.platform == RuntimePlatform.OSXEditor)
return buildName + ".app";
return buildName;
}
}
[SetUp]
public void SetUp()
{
Assert.That(File.Exists(buildPath), Is.False, "Existing file at path " + buildPath);
Assert.That(Directory.Exists(buildPath), Is.False, "Existing directory at path " + buildPath);
}
[TearDown]
public void TearDown()
{
if (File.Exists(buildPath))
File.Delete(buildPath);
if (Directory.Exists(buildPath))
Directory.Delete(buildPath, true);
}
static BuildTarget buildTarget
{
get
{
switch (Application.platform)
{
case RuntimePlatform.OSXEditor:
return BuildTarget.StandaloneOSX;
case RuntimePlatform.WindowsEditor:
return BuildTarget.StandaloneWindows;
case RuntimePlatform.LinuxEditor:
return BuildTarget.StandaloneLinux;
default:
throw new ArgumentOutOfRangeException();
}
}
}
[Test]
public void BuildPlayer_Succeeds()
{
var buildPlayerOptions = new BuildPlayerOptions
{
scenes = new[] { GetTestAssetPath("EmptyTestScene.unity") },
locationPathName = buildPath,
targetGroup = BuildTargetGroup.Standalone,
target = buildTarget,
options = BuildOptions.StrictMode,
};
BuildPipeline.BuildPlayer(buildPlayerOptions);
}
}
}
| 28.328947 | 106 | 0.521598 | [
"Unlicense"
] | ameru/karting-microgame-unity | try not to fall off rainbow road/Library/PackageCache/com.unity.learn.iet-framework@0.1.16-preview/Tests/Editor/BuildPlayerTests.cs | 2,153 | C# |
using System;
using System.Net;
using Csla;
using Csla.Security;
using Csla.Serialization;
namespace ClassLibrary
{
[Serializable()]
public class ClassC1 : BusinessBase<ClassC1>
{
private static PropertyInfo<string> AProperty = RegisterProperty(new PropertyInfo<string>("A"));
public string A
{
get { return GetProperty<string>(AProperty); }
set { SetProperty<string>(AProperty, value); }
}
private static PropertyInfo<string> BProperty = RegisterProperty(new PropertyInfo<string>("B"));
public string B
{
get { return GetProperty<string>(BProperty); }
set { SetProperty<string>(BProperty, value); }
}
protected override void AddAuthorizationRules()
{
AuthorizationRules.AllowWrite(AProperty, "Users");
AuthorizationRules.AllowRead(AProperty, "Users");
}
protected static void AddObjectAuthorizationRules()
{
AuthorizationRules.AllowCreate(typeof(ClassC1), "invalid");
AuthorizationRules.AllowEdit(typeof(ClassC1), "invalid");
AuthorizationRules.AllowDelete(typeof(ClassC1), "invalid");
}
}
}
| 28.589744 | 100 | 0.698655 | [
"MIT"
] | angtianqiang/csla | Source/Csla.Silverlight.test/SecurityTest/WindowsAuthentication/SilverlightClassLibrary/ClassC1.cs | 1,117 | C# |
using System;
namespace TrueCraft.Core
{
public class TrueCraftUser
{
public static string AuthServer = "http://truecraft.io";
public string Username { get; set; }
public string SessionId { get; set; }
}
} | 20.333333 | 64 | 0.627049 | [
"MIT"
] | MinecraftSources/TrueCraft | TrueCraft.Core/TrueCraftUser.cs | 246 | 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 SokoolTools.CleanFolders.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SokoolTools.CleanFolders.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap App {
get {
object obj = ResourceManager.GetObject("App", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap collapse_all {
get {
object obj = ResourceManager.GetObject("collapse_all", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Delete {
get {
object obj = ResourceManager.GetObject("Delete", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap expand_all {
get {
object obj = ResourceManager.GetObject("expand_all", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap File {
get {
object obj = ResourceManager.GetObject("File", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Folder {
get {
object obj = ResourceManager.GetObject("Folder", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Log {
get {
object obj = ResourceManager.GetObject("Log", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized string similar to Cancel.
/// </summary>
internal static string MessageBoxButton_Cancel {
get {
return ResourceManager.GetString("MessageBoxButton_Cancel", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dont Save.
/// </summary>
internal static string MessageBoxButton_DontSave {
get {
return ResourceManager.GetString("MessageBoxButton_DontSave", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Save.
/// </summary>
internal static string MessageBoxButton_Save {
get {
return ResourceManager.GetString("MessageBoxButton_Save", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unsaved Changes.
/// </summary>
internal static string MessageBoxCaption_UnsavedChanges {
get {
return ResourceManager.GetString("MessageBoxCaption_UnsavedChanges", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to You have made changes to this {0}. Ok to save changes before proceeding?.
/// </summary>
internal static string MessageBoxText_SaveConfirmation {
get {
return ResourceManager.GetString("MessageBoxText_SaveConfirmation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Open {
get {
object obj = ResourceManager.GetObject("Open", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
}
}
| 39.010582 | 190 | 0.56395 | [
"MIT"
] | sokooltools/CleanFolders | Properties/Resources.Designer.cs | 7,375 | C# |
using Aspose.Slides.Web.Core.Enums;
using Aspose.Slides.Web.Core.Helpers;
using Aspose.Slides.Web.Core.Infrastructure;
using Aspose.Slides.Web.Interfaces.Services;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace Aspose.Slides.Web.Core.Services
{
/// <summary>
/// Implementation of slides protection logic.
/// </summary>
internal sealed class ProtectionService : SlidesServiceBase, IProtectionService
{
/// <summary>
/// Ctor
/// </summary>
/// <param name="logger"></param>
/// <param name="licenseProvider"></param>
public ProtectionService(ILogger<ProtectionService> logger, ILicenseProvider licenseProvider) : base(logger)
{
licenseProvider.SetAsposeLicense(AsposeProducts.Slides);
}
/// <summary>
/// Removes password protection from source file, saves resulted file to out file.
/// Method tries to remove readonly and view protection with specified password.
/// </summary>
/// <param name="sourceFiles">Source slides files to proceed.</param>
/// <param name="outFiles">Output slides files.</param>
/// <param name="password">Password.</param>
/// <param name="cancellationToken">A cancellation token to observe while waiting for the task to complete.</param>
public void Unlock(
IList<string> sourceFiles,
IList<string> outFiles,
string password,
CancellationToken cancellationToken = default
)
{
void UnlockPresentationByIndex(int index)
{
var sourceFile = sourceFiles[index];
var isViewProtected = false;
try
{
using var testPresentation = new Presentation(sourceFile, new LoadOptions { OnlyLoadDocumentProperties = true });
cancellationToken.ThrowIfCancellationRequested();
}
catch (InvalidPasswordException)
{
isViewProtected = true;
}
using var presentation = isViewProtected
? new Presentation(sourceFile, new LoadOptions { Password = password })
: new Presentation(sourceFile);
cancellationToken.ThrowIfCancellationRequested();
presentation.ProtectionManager.EncryptDocumentProperties = false;
presentation.ProtectionManager.RemoveEncryption();
presentation.ProtectionManager.RemoveWriteProtection();
if (presentation.DocumentProperties.ContainsCustomProperty("_MarkAsFinal"))
presentation.DocumentProperties.RemoveCustomProperty("_MarkAsFinal");
cancellationToken.ThrowIfCancellationRequested();
var outFile = outFiles[index];
presentation.Save(outFile, sourceFile.GetSlidesExportSaveFormatBySourceFile());
}
try
{
Parallel.For(0, sourceFiles.Count, UnlockPresentationByIndex);
}
catch (AggregateException ae)
{
foreach (var e in ae.InnerExceptions)
{
throw e;
}
}
}
/// <summary>
/// Asynchronously removes password protection from source file, saves resulted file to out file.
/// Method tries to remove readonly and view protection with specified password.
/// </summary>
/// <param name="sourceFiles">Source slides files to proceed.</param>
/// <param name="outFiles">Output slides files.</param>
/// <param name="password">Password.</param>
/// <param name="cancellationToken">A cancellation token to observe while waiting for the task to complete.</param>
public async Task UnlockAsync(
IList<string> sourceFiles,
IList<string> outFiles,
string password,
CancellationToken cancellationToken = default)
=> await Task.Run(() => Unlock(sourceFiles, outFiles, password, cancellationToken));
/// <summary>
/// Applies protection to source file, saves resulted file to out file.
/// </summary>
/// <param name="sourceFiles">Source slides files to proceed.</param>
/// <param name="outFiles">Output slides files.</param>
/// <param name="markAsReadonly">Mark presentation as read-only.</param>
/// <param name="markAsFinal">Mark presentation as final.</param>
/// <param name="passwordEdit">Password for edit.</param>
/// <param name="passwordView">Password for view.</param>
/// <param name="cancellationToken">A cancellation token to observe while waiting for the task to complete.</param>
public void Lock(
IList<string> sourceFiles,
IList<string> outFiles,
bool markAsReadonly,
bool markAsFinal,
string passwordEdit,
string passwordView,
CancellationToken cancellationToken = default
)
{
void LockPresentationByIndex(int index)
{
var sourceFile = sourceFiles[index];
using var presentation = new Presentation(sourceFile);
cancellationToken.ThrowIfCancellationRequested();
if (!string.IsNullOrEmpty(passwordEdit))
presentation.ProtectionManager.SetWriteProtection(passwordEdit);
if (!string.IsNullOrEmpty(passwordView))
{
presentation.ProtectionManager.EncryptDocumentProperties = true;
presentation.ProtectionManager.Encrypt(passwordView);
}
if (markAsReadonly)
throw new NotImplementedException();
if (markAsFinal)
presentation.DocumentProperties.SetCustomPropertyValue("_MarkAsFinal", true);
cancellationToken.ThrowIfCancellationRequested();
var outFile = outFiles[index];
presentation.Save(outFile, sourceFile.GetSlidesExportSaveFormatBySourceFile());
}
try
{
Parallel.For(0, sourceFiles.Count, LockPresentationByIndex);
}
catch (AggregateException ae)
{
foreach (var e in ae.InnerExceptions)
{
throw e;
}
}
}
/// <summary>
/// Asynchronously applies protection to source file, saves resulted file to out file.
/// If both view and edit passwords are blank, applies to file read-only.
/// </summary>
/// <param name="sourceFiles">Source slides files to proceed.</param>
/// <param name="outFiles">Output slides files.</param>
/// <param name="markAsReadonly">Mark presentation as read-only.</param>
/// <param name="markAsFinal">Mark presentation as final.</param>
/// <param name="passwordEdit">Password for edit.</param>
/// <param name="passwordView">Password for view.</param>
/// <param name="cancellationToken">A cancellation token to observe while waiting for the task to complete.</param>
public async Task LockAsync(
IList<string> sourceFiles,
IList<string> outFiles,
bool markAsReadonly,
bool markAsFinal,
string passwordEdit,
string passwordView,
CancellationToken cancellationToken = default
) =>
await Task.Run(() => Lock(
sourceFiles,
outFiles,
markAsReadonly,
markAsFinal,
passwordEdit,
passwordView,
cancellationToken
));
}
}
| 32.658416 | 119 | 0.721085 | [
"MIT"
] | aspose-slides/Aspose.Slides-for-.NET | Demos/Aspose.Slides.Web.Core/Services/ProtectionService.cs | 6,597 | C# |
// Copyright © 2015 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.md for more information.
namespace Pegasus.Tests.Performance
{
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using NUnit.Framework;
[TestFixture]
[Category("Performance")]
public abstract class PerformanceTestBase
{
private static decimal[] tDistribution = new decimal[]
{
0.00m, 0.00m, 12.71m, 4.30m, 3.18m, 2.78m, 2.57m, 2.45m, 2.36m, 2.31m,
2.26m, 2.23m, 2.20m, 2.18m, 2.16m, 2.14m, 2.13m, 2.12m, 2.11m, 2.10m,
2.09m, 2.09m, 2.08m, 2.07m, 2.07m, 2.06m, 2.06m, 2.06m, 2.05m, 2.05m,
2.05m, 2.04m, 2.04m, 2.04m, 2.03m, 2.03m, 2.03m, 2.03m, 2.03m, 2.02m,
2.02m, 2.02m, 2.02m, 2.02m, 2.02m, 2.02m, 2.01m, 2.01m, 2.01m, 2.01m,
2.01m, 2.01m, 2.01m, 2.01m, 2.01m, 2.00m, 2.00m, 2.00m, 2.00m, 2.00m,
2.00m, 2.00m, 2.00m, 2.00m, 2.00m, 2.00m, 2.00m, 2.00m, 2.00m, 2.00m,
1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.99m,
1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.99m,
1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.99m, 1.98m, 1.98m, 1.98m,
1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m,
1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m,
1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m,
1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m,
1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m,
1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m, 1.98m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m, 1.97m,
1.97m, 1.97m, 1.97m, 1.97m, 1.96m
};
public PerformanceTestBase()
{
this.Methods = (from m in this.GetType().GetMethods()
from e in m.GetCustomAttributes(typeof(EvaluateAttribute), inherit: true).Cast<EvaluateAttribute>()
select new TestCaseData(m)).ToArray();
}
protected TestCaseData[] Methods { get; }
protected TimeSpan TestTargetTime => TimeSpan.FromSeconds(2);
protected TimeSpan WarmupTargetTime => TimeSpan.FromSeconds(0.1);
[TestCaseSource("Methods")]
public void Evaluate(MethodInfo method)
{
var action = MakeAction(this, method);
var measure = new Func<int, RunningStat>(samples =>
{
var runningStat = new RunningStat();
var sw = new Stopwatch();
while (samples-- > 0)
{
sw.Restart();
action();
runningStat.Push((decimal)sw.Elapsed.TotalMilliseconds);
}
return runningStat;
});
var initialTime = measure(1);
var baseTime = measure(1);
var warmupSamples = Math.Max(1, (int)Math.Round(this.WarmupTargetTime.TotalMilliseconds / (double)baseTime.Mean));
var warmupTime = measure(warmupSamples);
var testSamples = Math.Max(30, (int)Math.Round(this.TestTargetTime.TotalMilliseconds / (double)warmupTime.Mean));
var testTime = measure(testSamples);
PublishResults(initialTime.Mean, baseTime.Mean, warmupSamples, warmupTime.Mean, warmupTime.StandardDeviation, testSamples, testTime.Mean, testTime.StandardDeviation);
}
private static string FormatTime(int count, decimal mean, decimal stdDev = 0)
{
string suffix;
decimal rounded;
if (count > 1 && stdDev != 0)
{
var interval = tDistribution[Math.Min(count, tDistribution.Length - 1)] * stdDev;
var intervalScale = GetScale(interval);
suffix = "±" + Math.Round(interval, 3 - intervalScale) + "ms";
var scale = Math.Min(intervalScale, GetScale(mean));
rounded = Math.Round(mean, 3 - scale);
}
else
{
suffix = string.Empty;
rounded = Math.Round(mean, 3 - GetScale(mean));
}
return rounded + "ms" + suffix;
}
private static int GetScale(decimal d)
{
return d == 0 ? 0 : (int)Math.Floor(Math.Log10((double)Math.Abs(d))) + 1;
}
private static Action MakeAction(object fixture, MethodInfo method)
{
return (Action)Expression.Lambda(Expression.Call(Expression.Constant(fixture), method)).Compile();
}
private static void PublishResults(decimal initialTime, decimal baseTime, int warmupSamples, decimal warmupMean, decimal warmupStandardDeviation, int testSamples, decimal testMean, decimal testStandardDeviation)
{
Trace.WriteLine($"initialTime: {FormatTime(1, initialTime)}:");
Trace.WriteLine($"baseTime: {FormatTime(1, baseTime)}:");
Trace.WriteLine($"warmupSamples: {warmupSamples}");
Trace.WriteLine($"warmupMean: {FormatTime(warmupSamples, warmupMean, warmupStandardDeviation)}:");
Trace.WriteLine($"testSamples: {testSamples}");
Trace.WriteLine($"testMean: {FormatTime(testSamples, testMean, testStandardDeviation)}:");
var testName = TestContext.CurrentContext.Test.FullName;
var resultsFolder = Path.Combine(
TestContext.CurrentContext.TestDirectory,
"performance");
var outputPath = Path.Combine(
resultsFolder,
testName + ".csv");
var columns = "date,testSamples,testMean,testStandardDeviation,warmupSamples,warmupMean,warmupStandardDeviation,initialTime,baseTime,machine";
if (File.Exists(outputPath))
{
var lines = File.ReadAllLines(outputPath);
Assume.That(lines.Length, Is.GreaterThanOrEqualTo(1));
Assume.That(lines[0], Is.EqualTo(columns));
}
else
{
if (!Directory.Exists(resultsFolder))
{
Directory.CreateDirectory(resultsFolder);
}
File.WriteAllLines(outputPath, new[]
{
columns
});
}
var data = new[] { testSamples, testMean, testStandardDeviation, warmupSamples, warmupMean, warmupStandardDeviation, initialTime, baseTime }.Select(d => d.ToString(CultureInfo.InvariantCulture)).ToList();
data.Insert(0, DateTime.UtcNow.ToString("O"));
data.Insert(9, Environment.MachineName);
File.AppendAllLines(outputPath, new[]
{
string.Join(",", data),
});
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
protected class EvaluateAttribute : Attribute
{
}
private class RunningStat
{
private int count = 0;
private decimal mean;
private decimal s;
public int Count => this.count;
public decimal Mean => this.count > 0 ? this.mean : 0;
public decimal StandardDeviation => (decimal)Math.Sqrt((double)this.Variance);
public decimal Variance => this.count > 1 ? this.s / (this.count - 1) : 0;
public void Clear()
{
this.count = 0;
}
public void Push(decimal value)
{
this.count++;
if (this.count == 1)
{
this.mean = value;
}
else
{
var a = value - this.mean;
this.mean = this.mean + (value - this.mean) / this.count;
var b = value - this.mean;
this.s += a * b;
}
}
}
}
}
| 44.784232 | 219 | 0.530529 | [
"MIT"
] | david-pfx/Pegasus | Pegasus.Tests/Performance/PerformanceTestBase.cs | 10,797 | C# |
using System;
using System.Collections.Generic;
using Doppelkopf.Controllers;
using Doppelkopf.Models;
namespace Doppelkopf.Interfaces
{
public interface IUserPermissionService
{
// use to check if user has token (check does NOT test if user is named yet)
public bool IsMessageFromTokenizedUser(List<IClientConnectionController> clientConnectionControllers, ClientMessage message);
// use to check if message is from a named user (this INCLUDES being a tokenized user)
public bool IsMessageFromNamedUser(List<User> users, ClientMessage message);
}
}
| 35.588235 | 133 | 0.750413 | [
"MIT"
] | Elypson/Doppelkopf | Doppelkopf/Interfaces/IUserPermissionService.cs | 607 | C# |
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
namespace BizHawk.Emulation.Common
{
/// <summary>
/// This is a generic implementation of IMemoryCallbackSystem
/// that can be used by used by any core
/// </summary>
/// <seealso cref="IMemoryCallbackSystem" />
public class MemoryCallbackSystem : IMemoryCallbackSystem
{
public MemoryCallbackSystem(string[] availableScopes)
{
if (availableScopes == null)
{
availableScopes = new[] { "System Bus" };
}
AvailableScopes = availableScopes;
ExecuteCallbacksAvailable = true;
_reads.CollectionChanged += OnCollectionChanged;
_writes.CollectionChanged += OnCollectionChanged;
_execs.CollectionChanged += OnCollectionChanged;
}
private readonly ObservableCollection<IMemoryCallback> _reads = new ObservableCollection<IMemoryCallback>();
private readonly ObservableCollection<IMemoryCallback> _writes = new ObservableCollection<IMemoryCallback>();
private readonly ObservableCollection<IMemoryCallback> _execs = new ObservableCollection<IMemoryCallback>();
private bool _hasAny;
public bool ExecuteCallbacksAvailable { get; }
public string[] AvailableScopes { get; }
/// <exception cref="InvalidOperationException">scope of <paramref name="callback"/> isn't available</exception>
public void Add(IMemoryCallback callback)
{
if (!AvailableScopes.Contains(callback.Scope))
{
throw new InvalidOperationException($"{callback.Scope} is not currently supported for callbacks");
}
switch (callback.Type)
{
case MemoryCallbackType.Execute:
_execs.Add(callback);
break;
case MemoryCallbackType.Read:
_reads.Add(callback);
break;
case MemoryCallbackType.Write:
_writes.Add(callback);
break;
}
if (UpdateHasVariables())
{
Changes();
}
}
private static void Call(ObservableCollection<IMemoryCallback> cbs, uint addr, uint value, uint flags, string scope)
{
// ReSharper disable once ForCanBeConvertedToForeach
// Intentionally a for loop - https://github.com/TASVideos/BizHawk/issues/1823
for (int i = 0; i < cbs.Count; i++)
{
if (!cbs[i].Address.HasValue || (cbs[i].Scope == scope && cbs[i].Address == (addr & cbs[i].AddressMask)))
{
cbs[i].Callback(addr, value, flags);
}
}
}
public void CallMemoryCallbacks(uint addr, uint value, uint flags, string scope)
{
if (!_hasAny)
{
return;
}
if (HasReads)
{
if ((flags & (uint) MemoryCallbackFlags.AccessRead) != 0)
{
Call(_reads, addr, value, flags, scope);
}
}
if (HasWrites)
{
if ((flags & (uint) MemoryCallbackFlags.AccessWrite) != 0)
{
Call(_writes, addr, value, flags, scope);
}
}
if (HasExecutes)
{
if ((flags & (uint) MemoryCallbackFlags.AccessExecute) != 0)
{
Call(_execs, addr, value, flags, scope);
}
}
}
public bool HasReads { get; private set; }
public bool HasWrites { get; private set; }
public bool HasExecutes { get; private set; }
public bool HasReadsForScope(string scope)
{
return _reads.Any(e => e.Scope == scope);
}
public bool HasWritesForScope(string scope)
{
return _writes.Any(e => e.Scope == scope);
}
public bool HasExecutesForScope(string scope)
{
return _execs.Any(e => e.Scope == scope);
}
private bool UpdateHasVariables()
{
bool hadReads = HasReads;
bool hadWrites = HasWrites;
bool hadExecutes = HasExecutes;
HasReads = _reads.Count > 0;
HasWrites = _writes.Count > 0;
HasExecutes = _execs.Count > 0;
_hasAny = HasReads || HasWrites || HasExecutes;
return (HasReads != hadReads || HasWrites != hadWrites || HasExecutes != hadExecutes);
}
private int RemoveInternal(MemoryCallbackDelegate action)
{
var readsToRemove = _reads.Where(imc => imc.Callback == action).ToList();
var writesToRemove = _writes.Where(imc => imc.Callback == action).ToList();
var execsToRemove = _execs.Where(imc => imc.Callback == action).ToList();
foreach (var read in readsToRemove)
{
_reads.Remove(read);
}
foreach (var write in writesToRemove)
{
_writes.Remove(write);
}
foreach (var exec in execsToRemove)
{
_execs.Remove(exec);
}
return readsToRemove.Count + writesToRemove.Count + execsToRemove.Count;
}
public void Remove(MemoryCallbackDelegate action)
{
if (RemoveInternal(action) > 0)
{
if (UpdateHasVariables())
{
Changes();
}
}
}
public void RemoveAll(IEnumerable<MemoryCallbackDelegate> actions)
{
bool changed = false;
foreach (var action in actions)
{
changed |= RemoveInternal(action) > 0;
}
if (changed)
{
if (UpdateHasVariables())
{
Changes();
}
}
}
public void Clear()
{
// Remove one-by-one to avoid NotifyCollectionChangedAction.Reset events.
for (int i = _reads.Count - 1; i >= 0; i--)
{
_reads.RemoveAt(i);
}
for (int i = _writes.Count - 1; i >= 0; i--)
{
_writes.RemoveAt(i);
}
for (int i = _execs.Count - 1; i >= 0; i--)
{
_execs.RemoveAt(i);
}
if (UpdateHasVariables())
{
Changes();
}
}
public delegate void ActiveChangedEventHandler();
public event ActiveChangedEventHandler ActiveChanged;
public delegate void CallbackAddedEventHandler(IMemoryCallback callback);
public event CallbackAddedEventHandler CallbackAdded;
public delegate void CallbackRemovedEventHandler(IMemoryCallback callback);
public event CallbackRemovedEventHandler CallbackRemoved;
private void Changes()
{
ActiveChanged?.Invoke();
}
public void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
switch (args.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (IMemoryCallback callback in args.NewItems)
{
CallbackAdded?.Invoke(callback);
}
break;
case NotifyCollectionChangedAction.Remove:
foreach (IMemoryCallback callback in args.OldItems)
{
CallbackRemoved?.Invoke(callback);
}
break;
}
}
public IEnumerator<IMemoryCallback> GetEnumerator()
{
foreach (var imc in _reads)
{
yield return imc;
}
foreach (var imc in _writes)
{
yield return imc;
}
foreach (var imc in _execs)
{
yield return imc;
}
}
IEnumerator IEnumerable.GetEnumerator()
{
foreach (var imc in _reads)
{
yield return imc;
}
foreach (var imc in _writes)
{
yield return imc;
}
foreach (var imc in _execs)
{
yield return imc;
}
}
}
public class MemoryCallback : IMemoryCallback
{
public MemoryCallback(string scope, MemoryCallbackType type, string name, MemoryCallbackDelegate callback, uint? address, uint? mask)
{
Type = type;
Name = name;
Callback = callback;
Address = address;
AddressMask = mask ?? 0xFFFFFFFF;
Scope = scope;
}
public MemoryCallbackType Type { get; }
public string Name { get; }
public MemoryCallbackDelegate Callback { get; }
public uint? Address { get; }
public uint? AddressMask { get; }
public string Scope { get; }
}
}
| 23.88959 | 136 | 0.644923 | [
"MIT"
] | Gorialis/BizHawk | BizHawk.Emulation.Common/Base Implementations/MemoryCallbackSystem.cs | 7,575 | C# |
public class Solution {
public int NumDecodings(string s) {
if (string.IsNullOrEmpty(s)) {
return 0;
}
var currMinusTwo = 1;
var currMinusOne = '0' == s[0] ? 0 : 1;
var curr = currMinusOne;
for (var i = 2; s.Length >= i; ++i) {
var oneDigit = s[i - 1] - '0';
var twoDigits = 10 * (s[i - 2] - '0') + (s[i - 1] - '0');
curr = (0 == oneDigit ? 0 : currMinusOne);
curr += (10 <= twoDigits && 26 >= twoDigits ? currMinusTwo : 0);
currMinusTwo = currMinusOne;
currMinusOne = curr;
}
return curr;
}
}
| 27.25 | 76 | 0.458716 | [
"MIT"
] | gurfinkel/leetCode | problems/Decode Ways/numDecodings.cs | 654 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Microsoft.Azure.WebJobs.Script
{
/// <summary>
/// Provides the current HostName for the Function App.
/// <remarks>
/// The environment value for WEBSITE_HOSTNAME is unreliable and shouldn't be used directly. AppService site swaps change
/// the site’s hostname under the covers, and the worker process is NOT recycled (for performance reasons). That means the
/// site will continue to run with the same hostname environment variable, leading to an incorrect host name.
///
/// WAS_DEFAULT_HOSTNAME is a header injected by front end on every request which provides the correct hostname. We check
/// this header on all http requests, and updated the cached hostname value as needed.
/// </remarks>
/// </summary>
public class HostNameProvider
{
private readonly IEnvironment _environment;
private string _hostName;
public HostNameProvider(IEnvironment environment)
{
_environment = environment ?? throw new ArgumentNullException(nameof(environment));
}
public virtual string Value
{
get
{
if (string.IsNullOrEmpty(_hostName))
{
// default to the the value specified in environment
_hostName = _environment.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteHostName);
if (string.IsNullOrEmpty(_hostName))
{
// Linux Dedicated on AppService doesn't have WEBSITE_HOSTNAME
string websiteName = _environment.GetEnvironmentVariable(EnvironmentSettingNames.AzureWebsiteName);
if (!string.IsNullOrEmpty(websiteName))
{
_hostName = $"{websiteName}.azurewebsites.net";
}
}
}
return _hostName;
}
}
public virtual void Synchronize(HttpRequest request, ILogger logger)
{
string hostNameHeaderValue = request.Headers[ScriptConstants.AntaresDefaultHostNameHeader];
if (!string.IsNullOrEmpty(hostNameHeaderValue) &&
string.Compare(Value, hostNameHeaderValue) != 0)
{
logger.LogInformation("HostName updated from '{0}' to '{1}'", Value, hostNameHeaderValue);
_hostName = hostNameHeaderValue;
}
}
internal void Reset()
{
_hostName = null;
}
}
}
| 40.357143 | 126 | 0.611327 | [
"Apache-2.0",
"MIT"
] | Azure/azure-functions-host | src/WebJobs.Script/HostNameProvider.cs | 2,829 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System;
namespace Zuehlke.IdentityProvider.Controllers.Account
{
public class AccountOptions
{
public static bool AllowLocalLogin = true;
public static bool AllowRememberLogin = true;
public static TimeSpan RememberMeLoginDuration = TimeSpan.FromDays(30);
public static bool ShowLogoutPrompt = true;
public static bool AutomaticRedirectAfterSignOut = false;
public static bool WindowsAuthenticationEnabled = false;
// specify the Windows authentication schemes you want to use for authentication
public static readonly string[] WindowsAuthenticationSchemes = new string[] { "Negotiate", "NTLM" };
public static readonly string WindowsAuthenticationDisplayName = "Windows";
public static string InvalidCredentialsErrorMessage = "Invalid username or password";
}
}
| 40.153846 | 108 | 0.738506 | [
"MIT"
] | MicroserviceBasedUi/identity-provider | src/Zuehlke.IdentityProvider/Controllers/Account/AccountOptions.cs | 1,046 | C# |
using EmployeeManagementSystem.SharedKernel;
using System.Collections.Generic;
namespace EmployeeManagementSystem.Models
{
public class Department : BaseEntity
{
public string Name { get; set; }
public List<Employee> Employees { get; set; }
}
}
| 21.230769 | 53 | 0.706522 | [
"MIT"
] | iamkajal/microsofttechday2019 | EmployeeManagementSystem/Models/Department.cs | 278 | C# |
// <copyright file="OtsuThresholder.cs" company="QutEcoacoustics">
// All code in this file and all associated files are the copyright and property of the QUT Ecoacoustics Research Group (formerly MQUTeR, and formerly QUT Bioacoustics Research Group).
// </copyright>
namespace TowseyLibrary
{
using System;
using System.IO;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
/// <summary>
/// Go to following link for info on Otsu threshold
/// http://www.labbookpages.co.uk/software/imgProc/otsuThreshold.html.
/// </summary>
public class OtsuThresholder
{
public class Arguments
{
public FileInfo InputImageFile { get; set; }
public DirectoryInfo OutputDirectory { get; set; }
public FileInfo OutputFileName { get; set; }
public FileInfo SpectrogramConfigPath { get; set; }
public double BgnThreshold { get; set; }
}
/// <summary>
///
/// </summary>
public static void Execute(Arguments arguments)
{
string date = "# DATE AND TIME: " + DateTime.Now;
LoggedConsole.WriteLine("Test of OtsuThresholder class");
LoggedConsole.WriteLine(date);
LoggedConsole.WriteLine();
// Load Source image
Image<Rgb24> srcImage = null;
try
{
srcImage = (Image<Rgb24>)Image.Load(arguments.InputImageFile.FullName);
}
catch (IOException ioE)
{
Console.Error.WriteLine(ioE);
Environment.Exit(1);
}
int width = srcImage.Width;
int height = srcImage.Height;
/*
// Get raw image data
byte[,] M = ConvertColourImageToGreyScaleMatrix((Image<Rgb24>)srcImage);
// Sanity check image
if ((width * height) != (M.GetLength(0) * M.GetLength(1)))
{
Console.Error.WriteLine("Unexpected image data size.");
Environment.Exit(1);
}
// Output Image<Rgb24> info
//Console.WriteLine("Loaded image: '%s', width: %d, height: %d, num bytes: %d\n", filename, width, height, srcData.Length);
byte[] vector = DataTools.Matrix2Array(M);
byte[] outputArray;
// Create Otsu Thresholder
OtsuThresholder thresholder = new OtsuThresholder();
int threshold = thresholder.CalculateThreshold(vector, out outputArray);
byte[,] opByteMatrix = DataTools.Array2Matrix(outputArray, width, height);
*/
byte[,] matrix = ConvertColourImageToGreyScaleMatrix((Image<Rgb24>)srcImage);
double[,] ipMatrix = MatrixTools.ConvertMatrixOfByte2Double(matrix);
GetGlobalOtsuThreshold(ipMatrix, out var opByteMatrix, out var threshold, out var histoImage);
Console.WriteLine("Threshold: {0}", threshold);
Image<Rgb24> opImage = ConvertMatrixToGreyScaleImage(opByteMatrix);
Image<Rgb24>[] imageArray = { srcImage, opImage, histoImage };
var images = ImageTools.CombineImagesVertically(imageArray);
images.Save(arguments.OutputFileName.FullName);
}
// ========================= OtsuTHRESHOLD class proper.
private readonly int[] histData;
private int maxLevelValue;
private int threshold;
/// <summary>
/// Initializes a new instance of the <see cref="OtsuThresholder"/> class.
/// CONSTRUCTOR.
/// </summary>
public OtsuThresholder()
{
this.histData = new int[256];
}
public int[] GetHistData()
{
return this.histData;
}
public int getMaxLevelValue()
{
return this.maxLevelValue;
}
public int getThreshold()
{
return this.threshold;
}
public int CalculateThreshold(byte[] srcData, out byte[] monoData)
{
int ptr;
/*
// Clear histogram data
// Set all values to zero
ptr = 0;
while (ptr < histData.Length) histData[ptr++] = 0;
// Calculate histogram and find the level with the max value
// Note: the max level value isn't required by the Otsu method
ptr = 0;
maxLevelValue = 0;
while (ptr < srcData.Length)
{
int h = 0xFF & srcData[ptr];
histData[h]++;
if (histData[h] > maxLevelValue) maxLevelValue = histData[h];
ptr++;
}
// Total number of pixels
int total = srcData.Length;
float sum = 0;
for (int t = 0; t < 256; t++) sum += t * histData[t];
float sumB = 0;
int wB = 0;
int wF = 0;
float varMax = 0;
threshold = 0;
for (int t = 0; t < 256; t++)
{
wB += histData[t]; // Weight Background
if (wB == 0) continue;
wF = total - wB; // Weight Foreground
if (wF == 0) break;
sumB += (float)(t * histData[t]);
float mB = sumB / wB; // Mean Background
float mF = (sum - sumB) / wF; // Mean Foreground
// Calculate Between Class Variance
float varBetween = (float)wB * (float)wF * (mB - mF) * (mB - mF);
// Check if new maximum found
if (varBetween > varMax)
{
varMax = varBetween;
threshold = t;
}
}
*/
// Total number of pixels
int total = srcData.Length;
this.threshold = this.CalculateThreshold(srcData);
// Apply threshold to create binary image
monoData = new byte[total];
if (monoData != null)
{
ptr = 0;
while (ptr < srcData.Length)
{
monoData[ptr] = (byte)((0xFF & srcData[ptr]) >= this.threshold ? (byte)255 : 0);
ptr++;
}
}
return this.threshold;
} //doThreshold
public int CalculateThreshold(byte[] srcData)
{
int ptr;
// Clear histogram data
// Set all values to zero
ptr = 0;
while (ptr < this.histData.Length)
{
this.histData[ptr++] = 0;
}
// Calculate histogram and find the level with the max value
// Note: the max level value isn't required by the Otsu method
ptr = 0;
this.maxLevelValue = 0;
while (ptr < srcData.Length)
{
int h = 0xFF & srcData[ptr];
this.histData[h]++;
if (this.histData[h] > this.maxLevelValue)
{
this.maxLevelValue = this.histData[h];
}
ptr++;
}
// Total number of pixels
int total = srcData.Length;
float sum = 0;
for (int t = 0; t < 256; t++)
{
sum += t * this.histData[t];
}
float sumB = 0;
int wB = 0;
int wF = 0;
float varMax = 0;
this.threshold = 0;
for (int t = 0; t < 256; t++)
{
wB += this.histData[t]; // Weight Background
if (wB == 0)
{
continue;
}
wF = total - wB; // Weight Foreground
if (wF == 0)
{
break;
}
sumB += t * this.histData[t];
float mB = sumB / wB; // Mean Background
float mF = (sum - sumB) / wF; // Mean Foreground
// Calculate Between Class Variance
float varBetween = wB * (float)wF * (mB - mF) * (mB - mF);
// Check if new maximum found
if (varBetween > varMax)
{
varMax = varBetween;
this.threshold = t;
}
}
return this.threshold;
} //doThreshold
// ================================================= STATIC METHODS =====================================================
public static byte[,] ConvertColourImageToGreyScaleMatrix(Image<Rgb24> image)
{
int width = image.Width;
int height = image.Height;
byte[,] m = new byte[height, width];
for (int r = 0; r < height; r++)
{
for (int c = 0; c < width; c++)
{
var color = image[c, r];
// alpha = imData.data[i + 3];
// https://en.wikipedia.org/wiki/Grayscale
// gray = red*0.2126 + green*0.7152 + blue*.0722;
m[r, c] = (byte)Math.Round((color.R * 0.2126) + (color.G * 0.7152) + (color.B * 0.0722));
}
}
return m;
}
public static Image<Rgb24> ConvertMatrixToGreyScaleImage(byte[,] M)
{
int width = M.GetLength(1);
int height = M.GetLength(0);
var image = new Image<Rgb24>(width, height);
for (int r = 0; r < height; r++)
{
for (int c = 0; c < width; c++)
{
Color color = Color.FromRgb(M[r, c], M[r, c], M[r, c]);
image[c, r] = color;
}
}
return image;
}
public static Image<Rgb24> ConvertMatrixToReversedGreyScaleImage(byte[,] M)
{
int width = M.GetLength(1);
int height = M.GetLength(0);
var image = new Image<Rgb24>(width, height);
for (int r = 0; r < height; r++)
{
for (int c = 0; c < width; c++)
{
var value = (byte)(255 - M[r, c]);
//Color color = Color.FromRgb(value, value, value);
image[c, r] = Color.FromRgb(value, value, value);
}
}
return image;
}
private static Image<Rgb24> CreateHistogramFrame(OtsuThresholder thresholder, int width, int height)
{
width = 256; // histogram is one byte width.
int[] histData = thresholder.GetHistData();
int max = thresholder.getMaxLevelValue();
int threshold = thresholder.getThreshold();
var image = new Image<Rgb24>(width, height);
for (int col = 0; col < width; col++)
{
//int ptr = (numPixels - width) + col;
int val = height * histData[col] / max;
if (col == threshold)
{
for (int i = 0; i < height; i++)
{
image[col, i] = Color.Red;
}
}
else
{
for (int i = 1; i <= val; i++)
{
image[col, height - i] = Color.Black;
}
//histPlotData[ptr] = (byte)((val < i) ? (byte)255 : 0);
}
for (int i = 0; i < height; i++)
{
image[0, i] = Color.Gray;
}
}
return image;
}
public static void GetOtsuThreshold(byte[,] matrix, out byte[,] m2, out int threshold)
{
int width = matrix.GetLength(1);
int height = matrix.GetLength(0);
byte[] vector = DataTools.Matrix2Array(matrix);
// Create Otsu Thresholder
OtsuThresholder thresholder = new OtsuThresholder();
threshold = thresholder.CalculateThreshold(vector, out var outputArray);
m2 = DataTools.Array2Matrix(outputArray, width, height);
}
public static void GetOtsuThreshold(byte[,] matrix, out byte[,] m2, out int threshold, out Image<Rgb24> histogramImage)
{
int width = matrix.GetLength(1);
int height = matrix.GetLength(0);
byte[] vector = DataTools.Matrix2Array(matrix);
// Create Otsu Thresholder
OtsuThresholder thresholder = new OtsuThresholder();
threshold = thresholder.CalculateThreshold(vector, out var outputArray);
m2 = DataTools.Array2Matrix(outputArray, width, height);
histogramImage = CreateHistogramFrame(thresholder, height, 256);
}
public static void GetGlobalOtsuThreshold(double[,] inputMatrix, out byte[,] opByteMatrix, out double opThreshold, out Image<Rgb24> histogramImage)
{
if (inputMatrix == null)
{
throw new ArgumentNullException(nameof(inputMatrix));
}
var normMatrix = MatrixTools.NormaliseInZeroOne(inputMatrix, out var min, out var max);
var byteMatrix = MatrixTools.ConvertMatrixOfDouble2Byte(normMatrix);
GetOtsuThreshold(byteMatrix, out opByteMatrix, out var threshold, out histogramImage);
opThreshold = threshold / (double)byte.MaxValue;
opThreshold = min + (opThreshold * (max - min));
}
/// <summary>
/// </summary>
/// <param name="m">The spectral sonogram passes as matrix of doubles.</param>
public static void DoLocalOtsuThresholding(double[,] m, out byte[,] opByteMatrix)
{
int byteThreshold = 30;
int minPercentileBound = 5;
int maxPercentileBound = 95;
int temporalNh = 15;
int freqBinNh = 15;
int rowCount = m.GetLength(0);
int colCount = m.GetLength(1);
//double[,] normM = MatrixTools.NormaliseInZeroOne(m);
var ipByteMatrix = MatrixTools.ConvertMatrixOfDouble2Byte(m);
var bd1 = DataTools.GetByteDistribution(ipByteMatrix);
opByteMatrix = new byte[rowCount, colCount];
// for all cols i.e. freq bins
for (int col = freqBinNh; col < colCount - freqBinNh; col++)
{
// for all rows i.e. frames
for (int row = temporalNh; row < rowCount - temporalNh; row++)
{
var localMatrix = MatrixTools.Submatrix(ipByteMatrix, row - temporalNh, col - freqBinNh, row + temporalNh, col + freqBinNh);
// debug check for min and max - make sure it worked
int[] bd = DataTools.GetByteDistribution(localMatrix);
int[] histo = Histogram.Histo(localMatrix, out var minIntensity, out var maxIntensity);
int lowerBinBound = Histogram.GetPercentileBin(histo, minPercentileBound);
int upperBinBound = Histogram.GetPercentileBin(histo, maxPercentileBound);
int range = upperBinBound - lowerBinBound;
//normM[row, col] = (upperBinBound - lowerBinBound);
if (range > byteThreshold)
{
var thresholder = new OtsuThresholder();
byte[] vector = DataTools.Matrix2Array(localMatrix);
int threshold = thresholder.CalculateThreshold(vector);
if (localMatrix[temporalNh, freqBinNh] > threshold)
{
opByteMatrix[row, col] = 255;
}
}
}
}
// debug check for min and max - make sure it worked
var bd2 = DataTools.GetByteDistribution(opByteMatrix);
bd2 = null;
}
/*
/// <summary>
/// TEST method for Otsu Thresholder
It does not work in this context.
Paste code back into SandPit.cs file. Enclose within if(true) block to get it working.
/// </summary>
public static void TESTMETHOD_OtsuThresholder()
{
// check that Otsu thresholder is still working
//OtsuThresholder.Execute(null);
//string recordingPath = @"G:\SensorNetworks\WavFiles\LewinsRail\BAC2_20071008-085040.wav";
//string recordingPath = @"C:\SensorNetworks\WavFiles\TestRecordings\NW_NW273_20101013-051200-0514-1515-Brown Cuckoo-dove1.wav";
string recordingPath = @"C:\SensorNetworks\WavFiles\TestRecordings\TOWERB_20110302_202900_22.LSK.F.wav";
var outputPath = @"G:\SensorNetworks\Output\temp\AEDexperiments";
var outputDirectory = new DirectoryInfo(outputPath);
var recording = new AudioRecording(recordingPath);
var recordingDuration = recording.WavReader.Time;
const int frameSize = 1024;
double windowOverlap = 0.0;
//NoiseReductionType noiseReductionType = NoiseReductionType.None;
var noiseReductionType = SNR.KeyToNoiseReductionType("FlattenAndTrim");
//NoiseReductionType noiseReductionType = NoiseReductionType.Standard;
var sonoConfig = new SonogramConfig
{
SourceFName = recording.BaseName,
//set default values - ignore those set by user
WindowSize = frameSize,
WindowOverlap = windowOverlap,
NoiseReductionType = noiseReductionType,
NoiseReductionParameter = 0.0,
};
var aedConfiguration = new Aed.AedConfiguration
{
//AedEventColor = Color.Red;
//AedHitColor = Color.FromRgb(128, AedEventColor),
// This stops AED Wiener filter and noise removal.
NoiseReductionType = noiseReductionType,
IntensityThreshold = 20.0,
SmallAreaThreshold = 100,
};
double[] thresholdLevels = { 20.0 };
//double[] thresholdLevels = {30.0, 25.0, 20.0, 15.0, 10.0, 5.0};
var imageList = new List<Image<Rgb24>>();
foreach (double th in thresholdLevels)
{
aedConfiguration.IntensityThreshold = th;
var sonogram = (BaseSonogram)new SpectrogramStandard(sonoConfig, recording.WavReader);
AcousticEvent[] events = Aed.CallAed(sonogram, aedConfiguration, TimeSpan.Zero, recordingDuration);
LoggedConsole.WriteLine("AED # events: " + events.Length);
//cluster events
//var clusters = AcousticEvent.ClusterEvents(events);
//AcousticEvent.AssignClusterIds(clusters);
// see line 415 of AcousticEvent.cs for drawing the cluster ID into the sonogram image.
var distributionImage = IndexDistributions.DrawImageOfDistribution(sonogram.Data, 300, 100, "Distribution");
// get image of original data matrix
var srcImage = ImageTools.DrawReversedMatrix(sonogram.Data);
srcImage.RotateFlip(RotateFlipType.Rotate270FlipNone);
// get image of global thresholded data matrix
byte[,] opByteMatrix;
double opGlobalThreshold;
Image<Rgb24> histogramImage;
OtsuThresholder.GetGlobalOtsuThreshold(sonogram.Data, out opByteMatrix, out opGlobalThreshold, out histogramImage);
Image<Rgb24> opImageGlobal = OtsuThresholder.ConvertMatrixToReversedGreyScaleImage(opByteMatrix);
opImageGlobal.RotateFlip(RotateFlipType.Rotate270FlipNone);
// get image of local thresholded data matrix
var normalisedMatrix = MatrixTools.NormaliseInZeroOne(sonogram.Data);
OtsuThresholder.DoLocalOtsuThresholding(normalisedMatrix, out opByteMatrix);
// debug check for min and max - make sure it worked
int[] bd = DataTools.GetByteDistribution(opByteMatrix);
//Image<Rgb24> opImageLocal = OtsuThresholder.ConvertMatrixToGreyScaleImage(opByteMatrix);
Image<Rgb24> opImageLocal = OtsuThresholder.ConvertMatrixToReversedGreyScaleImage(opByteMatrix);
opImageLocal.RotateFlip(RotateFlipType.Rotate270FlipNone);
Image<Rgb24>[] imageArray = { srcImage, opImageGlobal, opImageLocal };
Image<Rgb24> images = ImageTools.CombineImagesVertically(imageArray);
var opPath = FilenameHelpers.AnalysisResultPath(outputDirectory, recording.BaseName, "ThresholdExperiment", "png");
images.Save(opPath);
var hits = new double[sonogram.FrameCount, sonogram.Data.GetLength(1)];
// display a variety of debug score arrays
double[] normalisedScores = new double[sonogram.FrameCount];
double normalisedThreshold = 0.5;
//DataTools.Normalise(amplitudeScores, decibelThreshold, out normalisedScores, out normalisedThreshold);
var scorePlot = new Plot("Scores", normalisedScores, normalisedThreshold);
var plots = new List<Plot> { scorePlot };
var image = Recognizers.LitoriaBicolor.DisplayDebugImage(sonogram, events.ToList<AcousticEvent>(),
plots, hits);
//var image = Aed.DrawSonogram(sonogram, events);
using (Graphics gr = Graphics.FromImage(image))
{
gr.DrawImage(distributionImage, new Point(0, 0));
}
imageList.Add(image);
}
var compositeImage = ImageTools.CombineImagesVertically(imageList);
var debugPath = FilenameHelpers.AnalysisResultPath(outputDirectory, recording.BaseName, "AedExperiment", "png");
compositeImage.Save(debugPath);
}
*/
/// <summary>
/// The core of the Otsu algorithm is shown here.
/// The input is an array of bytes, srcData that stores the greyscale image.
///
/// </summary>
//public static double OtsuThreshold(byte[] srcData)
//{
// double threshold = 0;
// int scaleResolution = 256;
// int[] histData = new int[scaleResolution];
// // Calculate histogram
// int ptr = 0;
// while (ptr < srcData.Length)
// {
// int h = 0xFF & srcData[ptr]; // convert grey scale value to an int. Index for histogram.
// histData[h]++;
// ptr++;
// }
// // Total number of pixels
// int total = srcData.Length;
// float sum = 0;
// for (int t = 0; t < scaleResolution; t++)
// sum += t * histData[t];
// float sumB = 0;
// int wB = 0;
// int wF = 0;
// float varMax = 0;
// threshold = 0;
// for (int t = 0; t < scaleResolution; t++)
// {
// wB += histData[t]; // Weight Background
// if (wB == 0) continue;
// wF = total - wB; // Weight Foreground
// if (wF == 0) break;
// sumB += (float)(t * histData[t]);
// float mB = sumB / wB; // Mean Background
// float mF = (sum - sumB) / wF; // Mean Foreground
// // Calculate Between Class Variance
// float varBetween = (float)wB * (float)wF * (mB - mF) * (mB - mF);
// // Check if new maximum found
// if (varBetween > varMax)
// {
// varMax = varBetween;
// threshold = t;
// }
// } // for
// return threshold;
//} // OtsuThreshold()
} // class OtsuThresholder
} | 38.174847 | 184 | 0.506268 | [
"Apache-2.0"
] | QutEcoacoustics/audio-analysis | src/TowseyLibrary/OtsuThresholder.cs | 24,890 | C# |
namespace LuceneFileFinder.Forms
{
partial class IndexManager
{
/// <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.components = new System.ComponentModel.Container();
System.Windows.Forms.ColumnHeader chMOutFolder;
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(IndexManager));
this.tabManager = new System.Windows.Forms.TabControl();
this.tpFile = new System.Windows.Forms.TabPage();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.lblFPaths = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.lblFFiles = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.lblFUpdate = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.lblFCreation = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.panel1 = new System.Windows.Forms.Panel();
this.btnFInAdd = new System.Windows.Forms.Button();
this.btnFInDelete = new System.Windows.Forms.Button();
this.lvwFOut = new System.Windows.Forms.ListView();
this.chFOFolder = new System.Windows.Forms.ColumnHeader();
this.imgIcon = new System.Windows.Forms.ImageList(this.components);
this.lvwFIn = new System.Windows.Forms.ListView();
this.chFIFolder = new System.Windows.Forms.ColumnHeader();
this.panel2 = new System.Windows.Forms.Panel();
this.btnFOutAdd = new System.Windows.Forms.Button();
this.btnFOutDelete = new System.Windows.Forms.Button();
this.tpMP3 = new System.Windows.Forms.TabPage();
this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel();
this.lvwMOut = new System.Windows.Forms.ListView();
this.lvwMIn = new System.Windows.Forms.ListView();
this.chMInFolder = new System.Windows.Forms.ColumnHeader();
this.panel5 = new System.Windows.Forms.Panel();
this.btnMOAdd = new System.Windows.Forms.Button();
this.btnMODelete = new System.Windows.Forms.Button();
this.panel6 = new System.Windows.Forms.Panel();
this.btnMIAdd = new System.Windows.Forms.Button();
this.btnMIDelete = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.lblMPaths = new System.Windows.Forms.Label();
this.label18 = new System.Windows.Forms.Label();
this.lblMFiles = new System.Windows.Forms.Label();
this.label20 = new System.Windows.Forms.Label();
this.lblMUpdate = new System.Windows.Forms.Label();
this.label22 = new System.Windows.Forms.Label();
this.lblMCreation = new System.Windows.Forms.Label();
this.label24 = new System.Windows.Forms.Label();
this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel();
this.panel3 = new System.Windows.Forms.Panel();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.listView3 = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.label9 = new System.Windows.Forms.Label();
this.label10 = new System.Windows.Forms.Label();
this.label11 = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.label15 = new System.Windows.Forms.Label();
this.label16 = new System.Windows.Forms.Label();
this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel();
this.listView4 = new System.Windows.Forms.ListView();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.listView5 = new System.Windows.Forms.ListView();
this.columnHeader3 = new System.Windows.Forms.ColumnHeader();
this.columnHeader4 = new System.Windows.Forms.ColumnHeader();
this.columnHeader5 = new System.Windows.Forms.ColumnHeader();
this.panel4 = new System.Windows.Forms.Panel();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();
this.lblWarning = new System.Windows.Forms.Label();
this.btnCancel = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.toolTip = new System.Windows.Forms.ToolTip(this.components);
chMOutFolder = new System.Windows.Forms.ColumnHeader();
this.tabManager.SuspendLayout();
this.tpFile.SuspendLayout();
this.groupBox1.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.tpMP3.SuspendLayout();
this.tableLayoutPanel4.SuspendLayout();
this.panel5.SuspendLayout();
this.panel6.SuspendLayout();
this.groupBox2.SuspendLayout();
this.tableLayoutPanel2.SuspendLayout();
this.panel3.SuspendLayout();
this.tableLayoutPanel3.SuspendLayout();
this.panel4.SuspendLayout();
this.SuspendLayout();
//
// chMOutFolder
//
chMOutFolder.Text = "排除目录";
chMOutFolder.Width = 312;
//
// tabManager
//
this.tabManager.Controls.Add(this.tpFile);
this.tabManager.Controls.Add(this.tpMP3);
this.tabManager.Location = new System.Drawing.Point(0, 0);
this.tabManager.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.tabManager.Name = "tabManager";
this.tabManager.SelectedIndex = 0;
this.tabManager.Size = new System.Drawing.Size(460, 380);
this.tabManager.TabIndex = 0;
this.tabManager.Selected += new System.Windows.Forms.TabControlEventHandler(this.tabManager_Selected);
//
// tpFile
//
this.tpFile.BackColor = System.Drawing.SystemColors.Control;
this.tpFile.Controls.Add(this.groupBox1);
this.tpFile.Controls.Add(this.tableLayoutPanel1);
this.tpFile.Location = new System.Drawing.Point(4, 26);
this.tpFile.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.tpFile.Name = "tpFile";
this.tpFile.Padding = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.tpFile.Size = new System.Drawing.Size(452, 350);
this.tpFile.TabIndex = 0;
this.tpFile.Text = "文件";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.lblFPaths);
this.groupBox1.Controls.Add(this.label7);
this.groupBox1.Controls.Add(this.lblFFiles);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.lblFUpdate);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.lblFCreation);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Location = new System.Drawing.Point(8, 7);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(429, 70);
this.groupBox1.TabIndex = 7;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "文件索引数据库信息";
//
// lblFPaths
//
this.lblFPaths.AutoSize = true;
this.lblFPaths.Location = new System.Drawing.Point(313, 44);
this.lblFPaths.Name = "lblFPaths";
this.lblFPaths.Size = new System.Drawing.Size(39, 17);
this.lblFPaths.TabIndex = 7;
this.lblFPaths.Text = "1,000";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(238, 44);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(68, 17);
this.label7.TabIndex = 6;
this.label7.Text = "目录总数:";
//
// lblFFiles
//
this.lblFFiles.AutoSize = true;
this.lblFFiles.Location = new System.Drawing.Point(313, 22);
this.lblFFiles.Name = "lblFFiles";
this.lblFFiles.Size = new System.Drawing.Size(46, 17);
this.lblFFiles.TabIndex = 5;
this.lblFFiles.Text = "10,000";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(238, 22);
this.label5.Margin = new System.Windows.Forms.Padding(4);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(68, 17);
this.label5.TabIndex = 4;
this.label5.Text = "文件总数:";
//
// lblFUpdate
//
this.lblFUpdate.AutoSize = true;
this.lblFUpdate.Location = new System.Drawing.Point(82, 44);
this.lblFUpdate.Name = "lblFUpdate";
this.lblFUpdate.Size = new System.Drawing.Size(109, 17);
this.lblFUpdate.TabIndex = 3;
this.lblFUpdate.Text = "2010/04/29 18:00";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(7, 44);
this.label3.Margin = new System.Windows.Forms.Padding(4);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(68, 17);
this.label3.TabIndex = 2;
this.label3.Text = "更新时间:";
//
// lblFCreation
//
this.lblFCreation.AutoSize = true;
this.lblFCreation.Location = new System.Drawing.Point(82, 22);
this.lblFCreation.Name = "lblFCreation";
this.lblFCreation.Size = new System.Drawing.Size(109, 17);
this.lblFCreation.TabIndex = 1;
this.lblFCreation.Text = "2010/04/29 18:00";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(7, 22);
this.label1.Margin = new System.Windows.Forms.Padding(4);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(68, 17);
this.label1.TabIndex = 0;
this.label1.Text = "创建时间:";
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 2;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 80.41958F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 19.58042F));
this.tableLayoutPanel1.Controls.Add(this.panel1, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.lvwFOut, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.lvwFIn, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.panel2, 1, 1);
this.tableLayoutPanel1.Location = new System.Drawing.Point(8, 85);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 2;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50.57471F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 49.42529F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(429, 257);
this.tableLayoutPanel1.TabIndex = 6;
//
// panel1
//
this.panel1.Controls.Add(this.btnFInAdd);
this.panel1.Controls.Add(this.btnFInDelete);
this.panel1.Location = new System.Drawing.Point(347, 3);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(79, 71);
this.panel1.TabIndex = 7;
//
// btnFInAdd
//
this.btnFInAdd.Location = new System.Drawing.Point(0, 0);
this.btnFInAdd.Name = "btnFInAdd";
this.btnFInAdd.Size = new System.Drawing.Size(75, 23);
this.btnFInAdd.TabIndex = 2;
this.btnFInAdd.Text = "添加";
this.btnFInAdd.UseVisualStyleBackColor = true;
this.btnFInAdd.Click += new System.EventHandler(this.btnFInAdd_Click);
//
// btnFInDelete
//
this.btnFInDelete.Location = new System.Drawing.Point(0, 29);
this.btnFInDelete.Name = "btnFInDelete";
this.btnFInDelete.Size = new System.Drawing.Size(75, 23);
this.btnFInDelete.TabIndex = 3;
this.btnFInDelete.Text = "删除";
this.btnFInDelete.UseVisualStyleBackColor = true;
this.btnFInDelete.Click += new System.EventHandler(this.btnFInDelete_Click);
//
// lvwFOut
//
this.lvwFOut.AllowDrop = true;
this.lvwFOut.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.chFOFolder});
this.lvwFOut.Location = new System.Drawing.Point(3, 132);
this.lvwFOut.Name = "lvwFOut";
this.lvwFOut.Size = new System.Drawing.Size(331, 122);
this.lvwFOut.SmallImageList = this.imgIcon;
this.lvwFOut.TabIndex = 1;
this.toolTip.SetToolTip(this.lvwFOut, "使用排除目录会导致父目录上的非目录文件也将会被排除");
this.lvwFOut.UseCompatibleStateImageBehavior = false;
this.lvwFOut.View = System.Windows.Forms.View.Details;
this.lvwFOut.DragDrop += new System.Windows.Forms.DragEventHandler(this.lvwFIn_DragDrop);
this.lvwFOut.DragEnter += new System.Windows.Forms.DragEventHandler(this.lvwFIn_DragEnter);
//
// chFOFolder
//
this.chFOFolder.Text = "排除目录";
this.chFOFolder.Width = 312;
//
// imgIcon
//
this.imgIcon.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
this.imgIcon.ImageSize = new System.Drawing.Size(16, 16);
this.imgIcon.TransparentColor = System.Drawing.Color.Transparent;
//
// lvwFIn
//
this.lvwFIn.AllowDrop = true;
this.lvwFIn.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.chFIFolder});
this.lvwFIn.Location = new System.Drawing.Point(3, 3);
this.lvwFIn.Name = "lvwFIn";
this.lvwFIn.Size = new System.Drawing.Size(331, 123);
this.lvwFIn.SmallImageList = this.imgIcon;
this.lvwFIn.TabIndex = 0;
this.toolTip.SetToolTip(this.lvwFIn, "只包含重要的目录可减少索引时间");
this.lvwFIn.UseCompatibleStateImageBehavior = false;
this.lvwFIn.View = System.Windows.Forms.View.Details;
this.lvwFIn.DragDrop += new System.Windows.Forms.DragEventHandler(this.lvwFIn_DragDrop);
this.lvwFIn.DragEnter += new System.Windows.Forms.DragEventHandler(this.lvwFIn_DragEnter);
//
// chFIFolder
//
this.chFIFolder.Text = "包含目录";
this.chFIFolder.Width = 313;
//
// panel2
//
this.panel2.Controls.Add(this.btnFOutAdd);
this.panel2.Controls.Add(this.btnFOutDelete);
this.panel2.Location = new System.Drawing.Point(347, 132);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(79, 75);
this.panel2.TabIndex = 8;
//
// btnFOutAdd
//
this.btnFOutAdd.Location = new System.Drawing.Point(0, 0);
this.btnFOutAdd.Name = "btnFOutAdd";
this.btnFOutAdd.Size = new System.Drawing.Size(75, 23);
this.btnFOutAdd.TabIndex = 4;
this.btnFOutAdd.Text = "添加";
this.toolTip.SetToolTip(this.btnFOutAdd, "排除的目录必须是包含目录中某项的子目录");
this.btnFOutAdd.UseVisualStyleBackColor = true;
this.btnFOutAdd.Click += new System.EventHandler(this.btnFOutAdd_Click);
//
// btnFOutDelete
//
this.btnFOutDelete.Location = new System.Drawing.Point(0, 29);
this.btnFOutDelete.Name = "btnFOutDelete";
this.btnFOutDelete.Size = new System.Drawing.Size(75, 23);
this.btnFOutDelete.TabIndex = 5;
this.btnFOutDelete.Text = "删除";
this.btnFOutDelete.UseVisualStyleBackColor = true;
this.btnFOutDelete.Click += new System.EventHandler(this.btnFOutDelete_Click);
//
// tpMP3
//
this.tpMP3.BackColor = System.Drawing.SystemColors.Control;
this.tpMP3.Controls.Add(this.tableLayoutPanel4);
this.tpMP3.Controls.Add(this.groupBox2);
this.tpMP3.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.tpMP3.Location = new System.Drawing.Point(4, 26);
this.tpMP3.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.tpMP3.Name = "tpMP3";
this.tpMP3.Padding = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.tpMP3.Size = new System.Drawing.Size(452, 350);
this.tpMP3.TabIndex = 1;
this.tpMP3.Text = "MP3";
//
// tableLayoutPanel4
//
this.tableLayoutPanel4.ColumnCount = 2;
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 80.41958F));
this.tableLayoutPanel4.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 19.58042F));
this.tableLayoutPanel4.Controls.Add(this.lvwMOut, 0, 1);
this.tableLayoutPanel4.Controls.Add(this.lvwMIn, 0, 0);
this.tableLayoutPanel4.Controls.Add(this.panel5, 1, 1);
this.tableLayoutPanel4.Controls.Add(this.panel6, 1, 0);
this.tableLayoutPanel4.Location = new System.Drawing.Point(8, 85);
this.tableLayoutPanel4.Name = "tableLayoutPanel4";
this.tableLayoutPanel4.RowCount = 2;
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50.57471F));
this.tableLayoutPanel4.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 49.42529F));
this.tableLayoutPanel4.Size = new System.Drawing.Size(429, 257);
this.tableLayoutPanel4.TabIndex = 9;
//
// lvwMOut
//
this.lvwMOut.AllowDrop = true;
this.lvwMOut.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
chMOutFolder});
this.lvwMOut.Location = new System.Drawing.Point(3, 132);
this.lvwMOut.Name = "lvwMOut";
this.lvwMOut.Size = new System.Drawing.Size(331, 122);
this.lvwMOut.SmallImageList = this.imgIcon;
this.lvwMOut.TabIndex = 1;
this.toolTip.SetToolTip(this.lvwMOut, "使用排除目录会导致父目录上的非目录文件也将会被排除");
this.lvwMOut.UseCompatibleStateImageBehavior = false;
this.lvwMOut.View = System.Windows.Forms.View.Details;
this.lvwMOut.DragDrop += new System.Windows.Forms.DragEventHandler(this.lvwFIn_DragDrop);
this.lvwMOut.DragEnter += new System.Windows.Forms.DragEventHandler(this.lvwFIn_DragEnter);
//
// lvwMIn
//
this.lvwMIn.AllowDrop = true;
this.lvwMIn.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.chMInFolder});
this.lvwMIn.Location = new System.Drawing.Point(3, 3);
this.lvwMIn.Name = "lvwMIn";
this.lvwMIn.Size = new System.Drawing.Size(331, 123);
this.lvwMIn.SmallImageList = this.imgIcon;
this.lvwMIn.TabIndex = 0;
this.toolTip.SetToolTip(this.lvwMIn, "只包含重要的目录可减少索引时间");
this.lvwMIn.UseCompatibleStateImageBehavior = false;
this.lvwMIn.View = System.Windows.Forms.View.Details;
this.lvwMIn.DragDrop += new System.Windows.Forms.DragEventHandler(this.lvwFIn_DragDrop);
this.lvwMIn.DragEnter += new System.Windows.Forms.DragEventHandler(this.lvwFIn_DragEnter);
//
// chMInFolder
//
this.chMInFolder.Text = "包含目录";
this.chMInFolder.Width = 316;
//
// panel5
//
this.panel5.Controls.Add(this.btnMOAdd);
this.panel5.Controls.Add(this.btnMODelete);
this.panel5.Location = new System.Drawing.Point(347, 132);
this.panel5.Name = "panel5";
this.panel5.Size = new System.Drawing.Size(79, 75);
this.panel5.TabIndex = 8;
//
// btnMOAdd
//
this.btnMOAdd.Location = new System.Drawing.Point(0, 0);
this.btnMOAdd.Name = "btnMOAdd";
this.btnMOAdd.Size = new System.Drawing.Size(75, 23);
this.btnMOAdd.TabIndex = 4;
this.btnMOAdd.Text = "添加";
this.toolTip.SetToolTip(this.btnMOAdd, "排除的目录必须是包含目录中某项的子目录");
this.btnMOAdd.UseVisualStyleBackColor = true;
this.btnMOAdd.Click += new System.EventHandler(this.btnMOAdd_Click);
//
// btnMODelete
//
this.btnMODelete.Location = new System.Drawing.Point(0, 29);
this.btnMODelete.Name = "btnMODelete";
this.btnMODelete.Size = new System.Drawing.Size(75, 23);
this.btnMODelete.TabIndex = 5;
this.btnMODelete.Text = "删除";
this.btnMODelete.UseVisualStyleBackColor = true;
this.btnMODelete.Click += new System.EventHandler(this.btnMODelete_Click);
//
// panel6
//
this.panel6.Controls.Add(this.btnMIAdd);
this.panel6.Controls.Add(this.btnMIDelete);
this.panel6.Location = new System.Drawing.Point(347, 3);
this.panel6.Name = "panel6";
this.panel6.Size = new System.Drawing.Size(79, 75);
this.panel6.TabIndex = 9;
//
// btnMIAdd
//
this.btnMIAdd.Location = new System.Drawing.Point(0, 0);
this.btnMIAdd.Name = "btnMIAdd";
this.btnMIAdd.Size = new System.Drawing.Size(75, 23);
this.btnMIAdd.TabIndex = 4;
this.btnMIAdd.Text = "添加";
this.btnMIAdd.UseVisualStyleBackColor = true;
this.btnMIAdd.Click += new System.EventHandler(this.btnMIAdd_Click);
//
// btnMIDelete
//
this.btnMIDelete.Location = new System.Drawing.Point(0, 29);
this.btnMIDelete.Name = "btnMIDelete";
this.btnMIDelete.Size = new System.Drawing.Size(75, 23);
this.btnMIDelete.TabIndex = 5;
this.btnMIDelete.Text = "删除";
this.btnMIDelete.UseVisualStyleBackColor = true;
this.btnMIDelete.Click += new System.EventHandler(this.btnMIDelete_Click);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.lblMPaths);
this.groupBox2.Controls.Add(this.label18);
this.groupBox2.Controls.Add(this.lblMFiles);
this.groupBox2.Controls.Add(this.label20);
this.groupBox2.Controls.Add(this.lblMUpdate);
this.groupBox2.Controls.Add(this.label22);
this.groupBox2.Controls.Add(this.lblMCreation);
this.groupBox2.Controls.Add(this.label24);
this.groupBox2.Location = new System.Drawing.Point(8, 7);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(429, 70);
this.groupBox2.TabIndex = 8;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "MP3索引数据库信息";
//
// lblMPaths
//
this.lblMPaths.AutoSize = true;
this.lblMPaths.Location = new System.Drawing.Point(313, 44);
this.lblMPaths.Name = "lblMPaths";
this.lblMPaths.Size = new System.Drawing.Size(39, 17);
this.lblMPaths.TabIndex = 7;
this.lblMPaths.Text = "1,000";
//
// label18
//
this.label18.AutoSize = true;
this.label18.Location = new System.Drawing.Point(238, 44);
this.label18.Name = "label18";
this.label18.Size = new System.Drawing.Size(68, 17);
this.label18.TabIndex = 6;
this.label18.Text = "目录总数:";
//
// lblMFiles
//
this.lblMFiles.AutoSize = true;
this.lblMFiles.Location = new System.Drawing.Point(313, 22);
this.lblMFiles.Name = "lblMFiles";
this.lblMFiles.Size = new System.Drawing.Size(46, 17);
this.lblMFiles.TabIndex = 5;
this.lblMFiles.Text = "10,000";
//
// label20
//
this.label20.AutoSize = true;
this.label20.Location = new System.Drawing.Point(238, 22);
this.label20.Margin = new System.Windows.Forms.Padding(4);
this.label20.Name = "label20";
this.label20.Size = new System.Drawing.Size(68, 17);
this.label20.TabIndex = 4;
this.label20.Text = "文件总数:";
//
// lblMUpdate
//
this.lblMUpdate.AutoSize = true;
this.lblMUpdate.Location = new System.Drawing.Point(82, 44);
this.lblMUpdate.Name = "lblMUpdate";
this.lblMUpdate.Size = new System.Drawing.Size(109, 17);
this.lblMUpdate.TabIndex = 3;
this.lblMUpdate.Text = "2010/04/29 18:00";
//
// label22
//
this.label22.AutoSize = true;
this.label22.Location = new System.Drawing.Point(7, 44);
this.label22.Margin = new System.Windows.Forms.Padding(4);
this.label22.Name = "label22";
this.label22.Size = new System.Drawing.Size(68, 17);
this.label22.TabIndex = 2;
this.label22.Text = "更新时间:";
//
// lblMCreation
//
this.lblMCreation.AutoSize = true;
this.lblMCreation.Location = new System.Drawing.Point(82, 22);
this.lblMCreation.Name = "lblMCreation";
this.lblMCreation.Size = new System.Drawing.Size(109, 17);
this.lblMCreation.TabIndex = 1;
this.lblMCreation.Text = "2010/04/29 18:00";
//
// label24
//
this.label24.AutoSize = true;
this.label24.Location = new System.Drawing.Point(7, 22);
this.label24.Margin = new System.Windows.Forms.Padding(4);
this.label24.Name = "label24";
this.label24.Size = new System.Drawing.Size(68, 17);
this.label24.TabIndex = 0;
this.label24.Text = "创建时间:";
//
// tableLayoutPanel2
//
this.tableLayoutPanel2.ColumnCount = 2;
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 80.41958F));
this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 19.58042F));
this.tableLayoutPanel2.Controls.Add(this.panel3, 1, 0);
this.tableLayoutPanel2.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel2.Name = "tableLayoutPanel2";
this.tableLayoutPanel2.RowCount = 1;
this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel2.Size = new System.Drawing.Size(200, 100);
this.tableLayoutPanel2.TabIndex = 0;
//
// panel3
//
this.panel3.Controls.Add(this.button1);
this.panel3.Controls.Add(this.button2);
this.panel3.Location = new System.Drawing.Point(163, 3);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(34, 66);
this.panel3.TabIndex = 7;
//
// button1
//
this.button1.Location = new System.Drawing.Point(0, 3);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 2;
this.button1.Text = "添加";
this.button1.UseVisualStyleBackColor = true;
//
// button2
//
this.button2.Location = new System.Drawing.Point(0, 29);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 3;
this.button2.Text = "删除";
this.button2.UseVisualStyleBackColor = true;
//
// listView3
//
this.listView3.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader1});
this.listView3.Location = new System.Drawing.Point(3, 132);
this.listView3.Name = "listView3";
this.listView3.Size = new System.Drawing.Size(331, 122);
this.listView3.TabIndex = 1;
this.listView3.UseCompatibleStateImageBehavior = false;
this.listView3.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Text = "排除路径";
this.columnHeader1.Width = 312;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(313, 44);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(35, 12);
this.label9.TabIndex = 7;
this.label9.Text = "1,000";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(238, 44);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(65, 12);
this.label10.TabIndex = 6;
this.label10.Text = "目录总数:";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(313, 22);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(41, 12);
this.label11.TabIndex = 5;
this.label11.Text = "10,000";
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(238, 22);
this.label12.Margin = new System.Windows.Forms.Padding(4);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(65, 12);
this.label12.TabIndex = 4;
this.label12.Text = "文件总数:";
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(82, 44);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(101, 12);
this.label13.TabIndex = 3;
this.label13.Text = "2010/04/29 18:00";
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(7, 44);
this.label14.Margin = new System.Windows.Forms.Padding(4);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(65, 12);
this.label14.TabIndex = 2;
this.label14.Text = "更新时间:";
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(82, 22);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(101, 12);
this.label15.TabIndex = 1;
this.label15.Text = "2010/04/29 18:00";
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(7, 22);
this.label16.Margin = new System.Windows.Forms.Padding(4);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(65, 12);
this.label16.TabIndex = 0;
this.label16.Text = "创建时间:";
//
// tableLayoutPanel3
//
this.tableLayoutPanel3.ColumnCount = 2;
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 80.41958F));
this.tableLayoutPanel3.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 19.58042F));
this.tableLayoutPanel3.Controls.Add(this.listView4, 0, 1);
this.tableLayoutPanel3.Controls.Add(this.listView5, 0, 0);
this.tableLayoutPanel3.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel3.Name = "tableLayoutPanel3";
this.tableLayoutPanel3.RowCount = 2;
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel3.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel3.Size = new System.Drawing.Size(200, 100);
this.tableLayoutPanel3.TabIndex = 0;
//
// listView4
//
this.listView4.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader2});
this.listView4.Location = new System.Drawing.Point(3, 23);
this.listView4.Name = "listView4";
this.listView4.Size = new System.Drawing.Size(154, 74);
this.listView4.TabIndex = 1;
this.listView4.UseCompatibleStateImageBehavior = false;
this.listView4.View = System.Windows.Forms.View.Details;
//
// columnHeader2
//
this.columnHeader2.Text = "排除路径";
this.columnHeader2.Width = 312;
//
// listView5
//
this.listView5.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader3,
this.columnHeader4,
this.columnHeader5});
this.listView5.Location = new System.Drawing.Point(3, 3);
this.listView5.Name = "listView5";
this.listView5.Size = new System.Drawing.Size(154, 14);
this.listView5.TabIndex = 0;
this.listView5.UseCompatibleStateImageBehavior = false;
this.listView5.View = System.Windows.Forms.View.Details;
//
// columnHeader3
//
this.columnHeader3.Text = "包含路径";
this.columnHeader3.Width = 174;
//
// columnHeader4
//
this.columnHeader4.Text = "文件数";
this.columnHeader4.Width = 82;
//
// columnHeader5
//
this.columnHeader5.Text = "文件夹数";
this.columnHeader5.Width = 64;
//
// panel4
//
this.panel4.Controls.Add(this.button3);
this.panel4.Controls.Add(this.button4);
this.panel4.Location = new System.Drawing.Point(347, 132);
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size(79, 75);
this.panel4.TabIndex = 8;
//
// button3
//
this.button3.Location = new System.Drawing.Point(0, 0);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(75, 23);
this.button3.TabIndex = 4;
this.button3.Text = "添加";
this.button3.UseVisualStyleBackColor = true;
//
// button4
//
this.button4.Location = new System.Drawing.Point(1, 29);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(75, 23);
this.button4.TabIndex = 5;
this.button4.Text = "删除";
this.button4.UseVisualStyleBackColor = true;
//
// folderBrowserDialog
//
this.folderBrowserDialog.RootFolder = System.Environment.SpecialFolder.MyComputer;
this.folderBrowserDialog.ShowNewFolderButton = false;
//
// lblWarning
//
this.lblWarning.AutoSize = true;
this.lblWarning.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.lblWarning.ForeColor = System.Drawing.Color.OrangeRed;
this.lblWarning.Location = new System.Drawing.Point(24, 388);
this.lblWarning.Name = "lblWarning";
this.lblWarning.Size = new System.Drawing.Size(164, 17);
this.lblWarning.TabIndex = 18;
this.lblWarning.Text = "当前目录为排除目录的子目录";
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(359, 384);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 17;
this.btnCancel.Text = "取消";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnOK
//
this.btnOK.Location = new System.Drawing.Point(271, 384);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 23);
this.btnOK.TabIndex = 16;
this.btnOK.Text = "确定";
this.toolTip.SetToolTip(this.btnOK, "保存设置");
this.btnOK.UseVisualStyleBackColor = true;
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// IndexManager
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.ClientSize = new System.Drawing.Size(460, 413);
this.Controls.Add(this.lblWarning);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.tabManager);
this.DoubleBuffered = true;
this.Font = new System.Drawing.Font("微软雅黑", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
this.MaximizeBox = false;
this.Name = "IndexManager";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "索引管理";
this.TopMost = true;
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.IndexManager_FormClosed);
this.tabManager.ResumeLayout(false);
this.tpFile.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.tableLayoutPanel1.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.tpMP3.ResumeLayout(false);
this.tableLayoutPanel4.ResumeLayout(false);
this.panel5.ResumeLayout(false);
this.panel6.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.tableLayoutPanel2.ResumeLayout(false);
this.panel3.ResumeLayout(false);
this.tableLayoutPanel3.ResumeLayout(false);
this.panel4.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TabControl tabManager;
private System.Windows.Forms.TabPage tpFile;
private System.Windows.Forms.TabPage tpMP3;
private System.Windows.Forms.Button btnFOutDelete;
private System.Windows.Forms.Button btnFOutAdd;
private System.Windows.Forms.Button btnFInDelete;
private System.Windows.Forms.Button btnFInAdd;
private System.Windows.Forms.ListView lvwFOut;
private System.Windows.Forms.ColumnHeader chFOFolder;
private System.Windows.Forms.ListView lvwFIn;
private System.Windows.Forms.ColumnHeader chFIFolder;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label lblFUpdate;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label lblFCreation;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lblFPaths;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label lblFFiles;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Label lblMPaths;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.Label lblMFiles;
private System.Windows.Forms.Label label20;
private System.Windows.Forms.Label lblMUpdate;
private System.Windows.Forms.Label label22;
private System.Windows.Forms.Label lblMCreation;
private System.Windows.Forms.Label label24;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.ListView listView3;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4;
private System.Windows.Forms.ListView lvwMOut;
private System.Windows.Forms.ListView lvwMIn;
private System.Windows.Forms.ColumnHeader chMInFolder;
private System.Windows.Forms.Panel panel5;
private System.Windows.Forms.Button btnMOAdd;
private System.Windows.Forms.Button btnMODelete;
private System.Windows.Forms.Panel panel6;
private System.Windows.Forms.Button btnMIAdd;
private System.Windows.Forms.Button btnMIDelete;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3;
private System.Windows.Forms.ListView listView4;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.ListView listView5;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader4;
private System.Windows.Forms.ColumnHeader columnHeader5;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog;
private System.Windows.Forms.ImageList imgIcon;
private System.Windows.Forms.Label lblWarning;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.ToolTip toolTip;
}
} | 48.884495 | 152 | 0.589765 | [
"MIT"
] | restran/lucene-file-finder | Lucene File Finder/Forms/IndexManager.designer.cs | 47,564 | C# |
using Unity.XRTools.ModuleLoader;
using UnityEditor;
using UnityEditor.MARS;
using UnityEditor.MARS.Simulation.Rendering;
using UnityEngine;
using UnityEngine.Rendering;
namespace Unity.MARS
{
[CustomEditor(typeof(CompositeRenderModuleOptions))]
class CompositeRenderModuleOptionsEditor : Editor
{
CompositeRenderModuleOptionsDrawer m_CompositeRenderModuleOptionsDrawer;
void OnEnable()
{
m_CompositeRenderModuleOptionsDrawer = new CompositeRenderModuleOptionsDrawer(serializedObject);
}
public override void OnInspectorGUI()
{
m_CompositeRenderModuleOptionsDrawer.InspectorGUI(serializedObject);
}
}
class CompositeRenderModuleOptionsDrawer
{
SerializedProperty m_UseFallbackCompositeRenderingProperty;
internal CompositeRenderModuleOptionsDrawer(SerializedObject serializedObject)
{
m_UseFallbackCompositeRenderingProperty = serializedObject.FindProperty("m_UseFallbackCompositeRendering");
}
internal void InspectorGUI(SerializedObject serializedObject)
{
serializedObject.Update();
EditorGUIUtility.labelWidth = MarsEditorGUI.SettingsLabelWidth;
using (new EditorGUI.DisabledScope(Application.isPlaying))
{
using (var changed = new EditorGUI.ChangeCheckScope())
{
using (new EditorGUI.DisabledScope(RenderPipelineManager.currentPipeline != null))
{
EditorGUILayout.PropertyField(m_UseFallbackCompositeRenderingProperty);
}
if (changed.changed)
{
serializedObject.ApplyModifiedProperties();
if (ModuleLoaderCore.instance != null)
ModuleLoaderCore.instance.ReloadModules();
}
}
}
}
}
}
| 32.819672 | 119 | 0.637363 | [
"Apache-2.0"
] | bsides44/MARSGeofencing | MARS geofencing/Library/PackageCache/com.unity.mars@1.3.1/Editor/Scripts/Simulation/CompositeRenderModuleOptionsEditor.cs | 2,004 | C# |
using Cassette.TinyIoC;
using Should;
using Xunit;
namespace Cassette.HtmlTemplates
{
public class HtmlTemplatePipeline_Tests
{
readonly HtmlTemplatePipeline pipeline;
readonly HtmlTemplateBundle bundle;
public HtmlTemplatePipeline_Tests()
{
bundle = new HtmlTemplateBundle("~");
pipeline = new HtmlTemplatePipeline(new TinyIoCContainer());
}
[Fact]
public void WhenProcess_ThenItAssignsInlineHtmlTemplateBundleRenderer()
{
pipeline.Process(bundle);
bundle.Renderer.ShouldBeType<InlineHtmlTemplateBundleRenderer>();
}
[Fact]
public void WhenProcessBundle_ThenHashIsAssigned()
{
pipeline.Process(bundle);
bundle.Hash.ShouldNotBeNull();
}
}
} | 25.852941 | 80 | 0.604096 | [
"MIT"
] | BluewireTechnologies/cassette | src/Cassette.UnitTests/HtmlTemplates/HtmlTemplatePipeline.cs | 881 | C# |
using System.Collections.Generic;
namespace EIP.Common.Entities.Tree
{
/// <summary>
/// Wd树形结构:模块权限
/// </summary>
public class WdTreeEntity
{
public WdTreeEntity()
{
}
public WdTreeEntity(TreeEntity tree)
{
id = tree.id.ToString();
text = tree.name;
value = tree.id.ToString();
url = tree.url;
icon = tree.icon;
if (!string.IsNullOrEmpty(icon))
{
img = string.Format("/Contents/images/icons/{0}.png", icon);
}
}
/// <summary>
/// 标识
/// </summary>
public string id { get; set; }
/// <summary>
/// 显示内容
/// </summary>
public string text { get; set; }
/// <summary>
/// 节点值
/// </summary>
public string value { get; set; }
/// <summary>
/// 图标
/// </summary>
public string icon { get; set; }
/// <summary>
/// 节点是否加载完(默认为True)
/// </summary>
public bool complete
{
get { return true; }
}
/// <summary>
/// 节点是否展开
/// </summary>
public bool isexpand { get; set; }
/// <summary>
/// 点击该节点,跳转的Url地址
/// </summary>
public string url { get; set; }
/// <summary>
/// 当前节点是否存在子节点
/// </summary>
public bool hasChildren
{
get { return (ChildNodes != null && ChildNodes.Count > 0) ? true : false; }
}
/// <summary>
/// 节点子节点
/// </summary>
public IList<WdTreeEntity> ChildNodes { get; set; }
/// <summary>
/// 图片地址
/// </summary>
public string img { get; set; }
}
} | 22.46988 | 87 | 0.42252 | [
"MIT"
] | woshisunzewei/EIP | Common/EIP.Common.Entities/Tree/WdTreeEntity.cs | 2,003 | C# |
using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.XPath;
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Linq;
using System.Threading.Tasks;
namespace GetValidBoosterPacks
{
public class Program
{
public static async Task Main(string[] args)
{
var url = "https://yugipedia.com/wiki/Template:Booster_Packs";
string[] boosterPacks;
using (var dom = await BrowsingContext.New(Configuration.Default.WithDefaultLoader()).OpenAsync(url))
{
var body = dom.Body.GetElementsByClassName("nowraplinks collapsible autocollapse navbox-inner").First();
IEnumerable<IElement> boosterPackRows = body.GetElementsByTagName("ul");
boosterPackRows = boosterPackRows.Take(boosterPackRows.Count() - 1).Skip(1);
boosterPacks = boosterPackRows.SelectMany(element => element.Children).Select(element => element.TextContent.Trim()).ToArray();
}
using (var pipe = new NamedPipeServerStream("GetValidBoosterPacks.Pipe", PipeDirection.Out))
{
pipe.WaitForConnection();
Serializer.Serialize(pipe, boosterPacks);
pipe.WaitForPipeDrain();
pipe.Disconnect();
pipe.Close();
}
}
}
}
| 30.652174 | 143 | 0.621986 | [
"MIT"
] | MeLikeChoco/YuGiOhBot | GetValidBoosterPacks/Program.cs | 1,412 | C# |
using Blazor.EventGridViewer.Core.CustomEventArgs;
using Blazor.EventGridViewer.Core.Models;
using Blazor.EventGridViewer.Services.Interfaces;
using System;
namespace Blazor.EventGridViewer.Services
{
/// <summary>
/// Class used to handle EventGrid Events
/// </summary>
public class EventGridService : IEventGridService
{
/// <inheritdoc/>
public event EventHandler<EventGridEventArgs> EventReceived;
private readonly IAdapter<EventGridEventModel, EventGridViewerEventModel> _eventGridEventModelAdapter;
public EventGridService(IAdapter<EventGridEventModel, EventGridViewerEventModel> eventGridEventModelAdapter)
{
_eventGridEventModelAdapter = eventGridEventModelAdapter;
}
/// <inheritdoc/>
public bool RaiseEventReceivedEvent(EventGridEventModel model)
{
if (string.IsNullOrWhiteSpace(model.EventType) || string.IsNullOrWhiteSpace(model.Subject))
return false;
var eventGridViewerEventModel = _eventGridEventModelAdapter.Convert(model);
EventReceived?.Invoke(this, new EventGridEventArgs(eventGridViewerEventModel));
return true;
}
}
}
| 35.057143 | 116 | 0.713121 | [
"MIT"
] | Azure-Samples/eventgrid-viewer-blazor | src/Blazor.EventGridViewer.Services/EventGridService.cs | 1,229 | C# |
// <auto-generated />
using System;
using Identity.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace Identity.Migrations
{
[DbContext(typeof(AuthDbContext))]
[Migration("20200731073430_InitialCrate")]
partial class InitialCrate
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.6")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("Identity.Areas.Identity.Data.ApplicationUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<string>("FirstName")
.HasColumnType("nvarchar(100)");
b.Property<string>("LastName")
.HasColumnType("nvarchar(100)");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Name")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Identity.Areas.Identity.Data.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Identity.Areas.Identity.Data.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Identity.Areas.Identity.Data.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Identity.Areas.Identity.Data.ApplicationUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.570423 | 125 | 0.468697 | [
"MIT"
] | namchokGithub/AuthSystem | Identity/Migrations/20200731073430_InitialCrate.Designer.cs | 10,672 | C# |
using Microsoft.SqlServer.TransactSql.ScriptDom;
using System.Collections.Generic;
using System.Linq;
namespace SqlServer.Dac.Visitors
{
public class CastCallVisitor : BaseVisitor, IVisitor<CastCall>
{
public IList<CastCall> Statements { get; } = new List<CastCall>();
public int Count { get { return this.Statements.Count; } }
public override void Visit(CastCall node)
{
Statements.Add(node);
}
}
} | 28.3125 | 74 | 0.684327 | [
"MIT"
] | arvindshmicrosoft/SqlServer.Rules | SqlServer.Dac/Visitors/CastCallVisitor.cs | 455 | C# |
/*
* Copyright 2016 Adam Burton (adz21c@gmail.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using GreenPipes;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace Miles.GreenPipes.TransactionContext
{
class TransactionContextSpecification<TContext> : ITransactionContextConfigurator, IPipeSpecification<TContext> where TContext : class, PipeContext
{
public IsolationLevel? HintIsolationLevel { get; set; }
public IEnumerable<ValidationResult> Validate()
{
return Enumerable.Empty<ValidationResult>();
}
public void Apply(IPipeBuilder<TContext> builder)
{
builder.AddFilter(new TransactionContextFilter<TContext>(HintIsolationLevel));
}
}
}
| 34.052632 | 151 | 0.720247 | [
"Apache-2.0"
] | adz21c/Miles | src/Miles.GreenPipes/TransactionContext/TransactionContextSpecification.cs | 1,296 | C# |
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org)
// Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net)
// Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// See the LICENSE.md file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using Stride.Core.Annotations;
namespace Stride.Core.Translation
{
public static class TranslationManager
{
private static readonly Lazy<ITranslationManager> Lazy = new Lazy<ITranslationManager>(() => new TranslationManagerImpl());
/// <summary>
/// Gets the instance of the <see cref="ITranslationManager"/>.
/// </summary>
public static ITranslationManager Instance => Lazy.Value;
/// <summary>
/// Implementation of <see cref="ITranslationManager"/>.
/// </summary>
private sealed class TranslationManagerImpl : ITranslationManager
{
private readonly Dictionary<string, ITranslationProvider> translationProviders = new Dictionary<string, ITranslationProvider>();
/// <inheritdoc />
public CultureInfo CurrentLanguage
{
get => CultureInfo.CurrentUICulture;
set
{
if (Equals(CultureInfo.CurrentUICulture, value))
return;
CultureInfo.CurrentUICulture = CultureInfo.DefaultThreadCurrentUICulture = value;
OnLanguageChanged();
}
}
/// <inheritdoc />
public event EventHandler LanguageChanged;
/// <inheritdoc />
string ITranslationProvider.BaseName => nameof(TranslationManager);
/// <inheritdoc />
public string GetString(string text)
{
return GetString(text, Assembly.GetCallingAssembly());
}
/// <inheritdoc />
public string GetString(string text, Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException(nameof(assembly));
return GetProvider(assembly)?.GetString(text) ?? text;
}
/// <inheritdoc />
public string GetPluralString(string text, string textPlural, long count)
{
return GetPluralString(text, textPlural, count, Assembly.GetCallingAssembly());
}
/// <inheritdoc />
public string GetPluralString(string text, string textPlural, long count, Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException(nameof(assembly));
return GetProvider(assembly)?.GetPluralString(text, textPlural, count) ?? text;
}
/// <inheritdoc />
public string GetParticularString(string context, string text)
{
return GetParticularString(context, text, Assembly.GetCallingAssembly());
}
/// <inheritdoc />
public string GetParticularString(string context, string text, Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException(nameof(assembly));
return GetProvider(assembly)?.GetParticularString(context, text) ?? text;
}
/// <inheritdoc />
public string GetParticularPluralString(string context, string text, string textPlural, long count)
{
return GetParticularPluralString(context, text, textPlural, count, Assembly.GetCallingAssembly());
}
/// <inheritdoc />
public string GetParticularPluralString(string context, string text, string textPlural, long count, Assembly assembly)
{
if (assembly == null) throw new ArgumentNullException(nameof(assembly));
return GetProvider(assembly)?.GetParticularPluralString(context, text, textPlural, count) ?? text;
}
/// <inheritdoc />
public void RegisterProvider(ITranslationProvider provider)
{
if (provider == null) throw new ArgumentNullException(nameof(provider));
translationProviders.Add(provider.BaseName, provider);
}
[CanBeNull]
private ITranslationProvider GetProvider([NotNull] Assembly assembly)
{
translationProviders.TryGetValue(assembly.GetName().Name, out var provider);
return provider;
}
private void OnLanguageChanged()
{
LanguageChanged?.Invoke(this, EventArgs.Empty);
}
}
}
} | 39.495935 | 140 | 0.595513 | [
"MIT"
] | Ethereal77/stride | sources/core/Stride.Core.Translation/TranslationManager.cs | 4,858 | 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 fsx-2018-03-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.FSx.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.FSx.Model.Internal.MarshallTransformations
{
/// <summary>
/// OpenZFSNfsExport Marshaller
/// </summary>
public class OpenZFSNfsExportMarshaller : IRequestMarshaller<OpenZFSNfsExport, JsonMarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="requestObject"></param>
/// <param name="context"></param>
/// <returns></returns>
public void Marshall(OpenZFSNfsExport requestObject, JsonMarshallerContext context)
{
if(requestObject.IsSetClientConfigurations())
{
context.Writer.WritePropertyName("ClientConfigurations");
context.Writer.WriteArrayStart();
foreach(var requestObjectClientConfigurationsListValue in requestObject.ClientConfigurations)
{
context.Writer.WriteObjectStart();
var marshaller = OpenZFSClientConfigurationMarshaller.Instance;
marshaller.Marshall(requestObjectClientConfigurationsListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
}
/// <summary>
/// Singleton Marshaller.
/// </summary>
public readonly static OpenZFSNfsExportMarshaller Instance = new OpenZFSNfsExportMarshaller();
}
} | 35.013889 | 109 | 0.670766 | [
"Apache-2.0"
] | aws/aws-sdk-net | sdk/src/Services/FSx/Generated/Model/Internal/MarshallTransformations/OpenZFSNfsExportMarshaller.cs | 2,521 | C# |
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2015 Daniel Liew
//
// This file is licensed under the 2-Clause BSD license.
// See LICENSE for details.
//------------------------------------------------------------------------------
using Microsoft.Boogie;
using NUnit.Framework;
using Symbooglix;
using System;
namespace SymbooglixLibTests
{
[TestFixture()]
public class ArithmeticCoercion : SymbooglixTest
{
public void Init(string program)
{
this.p = LoadProgramFrom(program);
var solver = GetSolver();
// No constant folding needed so that the ArithmeticCoercion reaches the solver
this.e = GetExecutor(this.p, new DFSStateScheduler(), solver, /*useConstantFolding=*/ false);
}
[Test()]
public void RealToInt()
{
var counter = new TerminationCounter();
Init("programs/RealToInt.bpl");
counter.Connect(e);
e.Run(GetMain(this.p));
checkCounter(counter);
}
[Test()]
public void IntToReal()
{
var counter = new TerminationCounter();
Init("programs/IntToReal.bpl");
counter.Connect(e);
e.Run(GetMain(this.p));
checkCounter(counter);
}
void checkCounter(TerminationCounter counter)
{
Assert.AreEqual(counter.Sucesses, 1);
Assert.AreEqual(counter.FailingAsserts, 0);
}
}
}
| 28.087719 | 105 | 0.510306 | [
"BSD-2-Clause"
] | michael-emmi/symbooglix | src/SymbooglixLibTests/AithmeticCoercion.cs | 1,601 | C# |
namespace HKH.Tools
{
partial class DbSelect
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.lblServerName = new System.Windows.Forms.Label();
this.lblUserName = new System.Windows.Forms.Label();
this.lblPassword = new System.Windows.Forms.Label();
this.tbUserName = new System.Windows.Forms.TextBox();
this.tbPassword = new System.Windows.Forms.TextBox();
this.lblDbName = new System.Windows.Forms.Label();
this.tbDbName = new System.Windows.Forms.TextBox();
this.cbServerName = new System.Windows.Forms.ComboBox();
this.cbDbName = new System.Windows.Forms.ComboBox();
this.btnTest = new System.Windows.Forms.Button();
this.rbWindow = new System.Windows.Forms.RadioButton();
this.rbSQLServer = new System.Windows.Forms.RadioButton();
this.gbLoginModel = new System.Windows.Forms.GroupBox();
this.btnRefresh = new System.Windows.Forms.Button();
this.gbLoginModel.SuspendLayout();
this.SuspendLayout();
//
// lblServerName
//
this.lblServerName.AutoSize = true;
this.lblServerName.Location = new System.Drawing.Point(33, 21);
this.lblServerName.Name = "lblServerName";
this.lblServerName.Size = new System.Drawing.Size(53, 12);
this.lblServerName.TabIndex = 0;
this.lblServerName.Text = "服务器:";
//
// lblUserName
//
this.lblUserName.AutoSize = true;
this.lblUserName.Location = new System.Drawing.Point(29, 74);
this.lblUserName.Name = "lblUserName";
this.lblUserName.Size = new System.Drawing.Size(53, 12);
this.lblUserName.TabIndex = 1;
this.lblUserName.Text = "用户名:";
//
// lblPassword
//
this.lblPassword.AutoSize = true;
this.lblPassword.Location = new System.Drawing.Point(29, 109);
this.lblPassword.Name = "lblPassword";
this.lblPassword.Size = new System.Drawing.Size(53, 12);
this.lblPassword.TabIndex = 2;
this.lblPassword.Text = "密 码:";
//
// tbUserName
//
this.tbUserName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbUserName.Enabled = false;
this.tbUserName.Location = new System.Drawing.Point(82, 74);
this.tbUserName.Name = "tbUserName";
this.tbUserName.Size = new System.Drawing.Size(100, 21);
this.tbUserName.TabIndex = 3;
//
// tbPassword
//
this.tbPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbPassword.Enabled = false;
this.tbPassword.Location = new System.Drawing.Point(82, 106);
this.tbPassword.Name = "tbPassword";
this.tbPassword.PasswordChar = '*';
this.tbPassword.Size = new System.Drawing.Size(100, 21);
this.tbPassword.TabIndex = 4;
//
// lblDbName
//
this.lblDbName.AutoSize = true;
this.lblDbName.Location = new System.Drawing.Point(33, 220);
this.lblDbName.Name = "lblDbName";
this.lblDbName.Size = new System.Drawing.Size(53, 12);
this.lblDbName.TabIndex = 5;
this.lblDbName.Text = "数据库:";
//
// tbDbName
//
this.tbDbName.Location = new System.Drawing.Point(86, 220);
this.tbDbName.Name = "tbDbName";
this.tbDbName.Size = new System.Drawing.Size(100, 21);
this.tbDbName.TabIndex = 6;
//
// cbServerName
//
this.cbServerName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cbServerName.FormattingEnabled = true;
this.cbServerName.Location = new System.Drawing.Point(86, 21);
this.cbServerName.Name = "cbServerName";
this.cbServerName.Size = new System.Drawing.Size(121, 20);
this.cbServerName.TabIndex = 7;
this.cbServerName.DropDown += new System.EventHandler(this.cbServerName_DropDown);
this.cbServerName.SelectedIndexChanged += new System.EventHandler(this.cbServerName_SelectedIndexChanged);
//
// cbDbName
//
this.cbDbName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.cbDbName.FormattingEnabled = true;
this.cbDbName.Location = new System.Drawing.Point(86, 221);
this.cbDbName.Name = "cbDbName";
this.cbDbName.Size = new System.Drawing.Size(121, 20);
this.cbDbName.TabIndex = 8;
this.cbDbName.DropDown += new System.EventHandler(this.cbDbName_DropDown);
//
// btnTest
//
this.btnTest.Location = new System.Drawing.Point(35, 257);
this.btnTest.Name = "btnTest";
this.btnTest.Size = new System.Drawing.Size(75, 23);
this.btnTest.TabIndex = 9;
this.btnTest.Text = "测试连接";
this.btnTest.UseVisualStyleBackColor = true;
this.btnTest.Click += new System.EventHandler(this.btnTest_Click);
//
// rbWindow
//
this.rbWindow.AutoSize = true;
this.rbWindow.Checked = true;
this.rbWindow.Location = new System.Drawing.Point(32, 20);
this.rbWindow.Name = "rbWindow";
this.rbWindow.Size = new System.Drawing.Size(113, 16);
this.rbWindow.TabIndex = 11;
this.rbWindow.TabStop = true;
this.rbWindow.Text = "Windows方式登录";
this.rbWindow.UseVisualStyleBackColor = true;
this.rbWindow.CheckedChanged += new System.EventHandler(this.rbWindow_CheckedChanged);
//
// rbSQLServer
//
this.rbSQLServer.AutoSize = true;
this.rbSQLServer.Location = new System.Drawing.Point(32, 42);
this.rbSQLServer.Name = "rbSQLServer";
this.rbSQLServer.Size = new System.Drawing.Size(131, 16);
this.rbSQLServer.TabIndex = 12;
this.rbSQLServer.TabStop = true;
this.rbSQLServer.Text = "SQL Server方式登录";
this.rbSQLServer.UseVisualStyleBackColor = true;
//
// gbLoginModel
//
this.gbLoginModel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.gbLoginModel.Controls.Add(this.tbPassword);
this.gbLoginModel.Controls.Add(this.rbSQLServer);
this.gbLoginModel.Controls.Add(this.lblUserName);
this.gbLoginModel.Controls.Add(this.rbWindow);
this.gbLoginModel.Controls.Add(this.lblPassword);
this.gbLoginModel.Controls.Add(this.tbUserName);
this.gbLoginModel.Location = new System.Drawing.Point(35, 58);
this.gbLoginModel.Name = "gbLoginModel";
this.gbLoginModel.Size = new System.Drawing.Size(200, 141);
this.gbLoginModel.TabIndex = 13;
this.gbLoginModel.TabStop = false;
this.gbLoginModel.Text = "登录方式";
//
// btnRefresh
//
this.btnRefresh.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnRefresh.Location = new System.Drawing.Point(213, 21);
this.btnRefresh.Name = "btnRefresh";
this.btnRefresh.Size = new System.Drawing.Size(75, 23);
this.btnRefresh.TabIndex = 14;
this.btnRefresh.Text = "刷新";
this.btnRefresh.UseVisualStyleBackColor = true;
this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
//
// DbSelect
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.btnRefresh);
this.Controls.Add(this.gbLoginModel);
this.Controls.Add(this.btnTest);
this.Controls.Add(this.cbDbName);
this.Controls.Add(this.cbServerName);
this.Controls.Add(this.tbDbName);
this.Controls.Add(this.lblDbName);
this.Controls.Add(this.lblServerName);
this.Name = "DbSelect";
this.Size = new System.Drawing.Size(299, 324);
this.gbLoginModel.ResumeLayout(false);
this.gbLoginModel.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label lblServerName;
private System.Windows.Forms.Label lblUserName;
private System.Windows.Forms.Label lblPassword;
private System.Windows.Forms.TextBox tbUserName;
private System.Windows.Forms.TextBox tbPassword;
private System.Windows.Forms.Label lblDbName;
private System.Windows.Forms.TextBox tbDbName;
private System.Windows.Forms.ComboBox cbServerName;
private System.Windows.Forms.ComboBox cbDbName;
private System.Windows.Forms.Button btnTest;
private System.Windows.Forms.RadioButton rbWindow;
private System.Windows.Forms.RadioButton rbSQLServer;
private System.Windows.Forms.GroupBox gbLoginModel;
private System.Windows.Forms.Button btnRefresh;
}
}
| 46.974576 | 158 | 0.589031 | [
"Apache-2.0"
] | JackyLi918/HKH | HKHProjects/HKH.Tools/DbSelect.Designer.cs | 11,304 | C# |
using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
namespace MicroFeel.Yonyou.Api
{
public class Bank
{
///<Summary>
///银行编号
///</Summary>
[JsonPropertyName("code")]
public string Code { get;set; }
///<Summary>
///银行名称
///</Summary>
[JsonPropertyName("name")]
public string Name { get;set; }
}
} | 355 | 355 | 0.659155 | [
"Apache-2.0"
] | microfeel/Yonyou | MicroFeel.Yonyou.OpenApi/Model/Data/Bank.cs | 371 | C# |
namespace MassTransit.Initializers
{
public interface IMessageInitializerFactory<TMessage>
where TMessage : class
{
IMessageInitializer<TMessage> CreateMessageInitializer();
}
} | 25.75 | 65 | 0.728155 | [
"ECL-2.0",
"Apache-2.0"
] | AOrlov/MassTransit | src/MassTransit/Initializers/IMessageInitializerFactory.cs | 208 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Extensibility.ImageEditing;
using OpenLiveWriter.Localization;
using OpenLiveWriter.PostEditor.Commands;
namespace OpenLiveWriter.PostEditor.PostHtmlEditing.ImageEditing.Decorators
{
public class HtmlAlignEditor : ImageDecoratorEditor
{
private IContainer components = null;
private ImagePickerControl imagePickerAlign;
public HtmlAlignEditor(CommandManager commandManager)
{
// This call is required by the Windows Form Designer.
InitializeComponent();
imagePickerAlign.AccessibleName = Res.Get(StringId.Alignment);
imagePickerAlign.Items.AddRange( new object[] {
new AlignmentComboItem(Res.Get(StringId.ImgSBAlignInline), ImgAlignment.NONE, ResourceHelper.LoadAssemblyResourceBitmap(BUTTON_IMAGE_PATH + "WrapTextInlineEnabled.png")),
new AlignmentComboItem(Res.Get(StringId.ImgSBAlignLeft), ImgAlignment.LEFT, ResourceHelper.LoadAssemblyResourceBitmap(BUTTON_IMAGE_PATH + "WrapTextLeftEnabled.png")),
new AlignmentComboItem(Res.Get(StringId.ImgSBAlignRight), ImgAlignment.RIGHT, ResourceHelper.LoadAssemblyResourceBitmap(BUTTON_IMAGE_PATH + "WrapTextRightEnabled.png")),
new AlignmentComboItem(Res.Get(StringId.ImgSBAlignCenter), ImgAlignment.CENTER, ResourceHelper.LoadAssemblyResourceBitmap(BUTTON_IMAGE_PATH + "WrapTextCenterEnabled.png"))
});
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region 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.SuspendLayout();
this.imagePickerAlign = new ImagePickerControl();
this.imagePickerAlign.Name = "imagePickerAlign";
this.imagePickerAlign.Dock = DockStyle.Fill;
this.imagePickerAlign.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.imagePickerAlign.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.imagePickerAlign.IntegralHeight = false;
this.imagePickerAlign.ItemHeight = 29;
this.imagePickerAlign.SelectedIndexChanged += new EventHandler(imagePickerAlign_SelectedIndexChanged);
//
// HtmlAlignEditor
//
this.Controls.Add(this.imagePickerAlign);
this.Name = "HtmlAlignEditor";
this.Size = new System.Drawing.Size(208, 35);
this.ResumeLayout(false);
}
#endregion
protected override void LoadEditor()
{
base.LoadEditor ();
HtmlAlignSettings = new HtmlAlignDecoratorSettings(EditorContext.Settings, EditorContext.ImgElement);
Alignment = HtmlAlignSettings.Alignment;
}
private HtmlAlignDecoratorSettings HtmlAlignSettings;
public override Size GetPreferredSize()
{
return new Size(208, 35);
}
protected override void OnSaveSettings()
{
HtmlAlignSettings.Alignment = Alignment;
base.OnSaveSettings ();
FireAlignmentChanged();
}
public event EventHandler AlignmentChanged;
protected void FireAlignmentChanged()
{
if (AlignmentChanged != null)
AlignmentChanged(this, EventArgs.Empty);
}
public ImgAlignment Alignment
{
get
{
return alignment;
}
private set
{
alignment = value;
switch (value)
{
case ImgAlignment.NONE:
imagePickerAlign.SelectedIndex = 0;
break;
case ImgAlignment.LEFT:
imagePickerAlign.SelectedIndex = 1;
break;
case ImgAlignment.RIGHT:
imagePickerAlign.SelectedIndex = 2;
break;
case ImgAlignment.CENTER:
imagePickerAlign.SelectedIndex = 3;
break;
}
SaveSettingsAndApplyDecorator();
}
}
ImgAlignment alignment;
public const string BUTTON_IMAGE_PATH = "PostHtmlEditing.ImageEditing.Images." ;
private void imagePickerAlign_SelectedIndexChanged(object sender, EventArgs e)
{
AlignmentComboItem selectedAlignment = imagePickerAlign.SelectedItem as AlignmentComboItem;
if (selectedAlignment != null)
Alignment = (ImgAlignment) selectedAlignment.ItemValue;
}
private class AlignmentComboItem : OptionItem, ImagePickerControl.IComboImageItem
{
public AlignmentComboItem(string text, ImgAlignment alignment, Image borderImage) : base(text, alignment)
{
image = borderImage;
}
#region ImageBorderItem Members
public Image Image
{
get
{
return image;
}
}
private Image image;
#endregion
}
}
internal class OptionItem
{
internal string Text;
internal object ItemValue;
public OptionItem(string text, object val)
{
Text = text;
ItemValue = val;
}
public override bool Equals(object obj)
{
if (obj is OptionItem)
{
OptionItem size = (OptionItem)obj;
return size.ItemValue.Equals(ItemValue);
}
return false;
}
public override int GetHashCode()
{
return ItemValue.GetHashCode();
}
public override string ToString()
{
return Text;
}
}
}
| 28.839196 | 187 | 0.696289 | [
"MIT"
] | augustoproiete-forks/OpenLiveWriter--OpenLiveWriter | src/managed/OpenLiveWriter.PostEditor/PostHtmlEditing/ImageEditing/Decorators/HtmlAlignEditor.cs | 5,739 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Nethereum.JsonRpc.UnityClient;
using LeaderboardSolidityContract.Contracts.Leaderboard.ContractDefinition;
using static Timer;
using static PrivateKey;
public class AddHighScore : MonoBehaviour
{
public Button submitButton;
public InputField playerNameInput;
private string txHash;
private bool hasSubmitted = false;
public void OnClick()
{
if (hasSubmitted == true)
{
string url = "https://rinkeby.etherscan.io/tx/" + txHash;
Application.ExternalEval($"window.open(\" {url} \")");
}
else
{
StartCoroutine(AddScore());
}
}
void Update()
{
submitButton.interactable = false;
if (playerNameInput.text != "") submitButton.interactable = true;
if (hasSubmitted == true) submitButton.GetComponentInChildren<Text>().text = "View Transaction";
}
private IEnumerator AddScore()
{
string url = "https://rinkeby.infura.io/v3/fbc0597d7f784931a68acca3eb26f65b";
string fromAddress = "0xcAdf00cB9a90892e1eE28ef1Ec4b00E8241D6957";
string contractAddress = "0x1931d2436288c4489a7849a7eebda6dfb47d63d7";
var transactionTransferRequest = new TransactionSignedUnityRequest(url, PrivateKey.RINKEBY);
var transactionMessage = new AddScoreFunctionBase
{
FromAddress = fromAddress,
// shorten player name
User = playerNameInput.text.Length > 10 ? playerNameInput.text.Substring(0, 10) : playerNameInput.text,
Score = (int)Timer.score,
};
yield return transactionTransferRequest.SignAndSendTransaction(transactionMessage, contractAddress);
txHash = transactionTransferRequest.Result;
hasSubmitted = true;
}
}
| 31.357143 | 109 | 0.736333 | [
"MIT"
] | IPFPS/ipfps | Assets/FPS/Scripts/Ethereum/AddHighScore.cs | 1,758 | C# |
using MO.Common.Geom;
using MO.Common.Lang;
using MO.Content2d.Frame.Controls;
using MO.Design2d.Frame.Common;
using MO.Direct2d.Common;
using MO.Direct2d.Draw;
namespace MO.Design2d.Frame.Controls
{
//============================================================
// <T>控件声明。</T>
//============================================================
public class FUiLabel : FUiDataControl
{
// 类型名称
public static string TYPE_NAME = "Label";
//============================================================
// <T>构造控件。</T>
//============================================================
public FUiLabel(FUiFrameConsole console = null)
: base(console) {
}
//============================================================
// <T>获得资源。</T>
//============================================================
public FRcLabel LabelResource {
get { return _resource as FRcLabel; }
}
//============================================================
// <T>配置处理。</T>
//
// @param args 参数
//============================================================
public override void OnSetup(SUiSetupArgs args) {
base.OnSetup(args);
}
//============================================================
// <T>开始绘制处理。</T>
//
// @param args 参数
//============================================================
public override void OnDrawBegin(SUiDrawArgs args) {
base.OnDrawBegin(args);
// 绘制文本
string label = ControlResource.Label;
SIntSize2 size = ControlResource.Size;
if (!RString.IsEmpty(label)) {
FDxTextFormat labelFormat = _context.DefaultTextFormat;
labelFormat.AlignmentCd = EDxTextAlignment.Leading;
labelFormat.ParagraphAlignmentCd = EDxParagraphAlignment.Center;
_context.Context.DrawText(label, _context.DefaultTextFormat, LabelResource.Font.Color, new SIntRectangle(0, 0, size.Width, size.Height));
}
}
//============================================================
// <T>结束绘制处理。</T>
//
// @param args 参数
//============================================================
public override void OnDrawAfter(SUiDrawArgs args) {
base.OnDrawAfter(args);
}
//============================================================
// <T>释放资源。</T>
//============================================================
public override void OnDispose() {
base.OnDispose();
}
}
}
| 34.355263 | 149 | 0.378782 | [
"Apache-2.0"
] | favedit/MoCross | Tools/2 - Core/MoDesign2d/Frame/Controls/FUiLabel.cs | 2,719 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Medical
{
public class TimelineMatchInfo
{
internal TimelineMatchInfo(Type actionType, String comment, String file)
{
ActionType = actionType;
Comment = comment;
File = file;
}
public Type ActionType { get; private set; }
public String Comment { get; private set; }
public String File { get; private set; }
}
/// <summary>
/// This class is used in static analysis of timelines.
/// </summary>
public abstract class TimelineStaticInfo
{
private List<TimelineMatchInfo> matches = new List<TimelineMatchInfo>();
public void addMatch(Type actionType, String comment, String file)
{
matches.Add(new TimelineMatchInfo(actionType, comment, file));
}
public void clearMatches()
{
matches.Clear();
}
public abstract bool matchesPattern(String check);
public bool HasMatches
{
get
{
return matches.Count > 0;
}
}
public IEnumerable<TimelineMatchInfo> Matches
{
get
{
return matches;
}
}
}
public class ExactMatchStaticInfo : TimelineStaticInfo
{
private String searchPattern;
public ExactMatchStaticInfo(String searchPattern)
{
this.searchPattern = searchPattern;
}
public override bool matchesPattern(String check)
{
if (check != null)
{
return check.Contains(searchPattern);
}
else
{
return check == searchPattern;
}
}
}
public class EndsWithStaticInfo : TimelineStaticInfo
{
private String searchPattern;
public EndsWithStaticInfo(String searchPattern)
{
this.searchPattern = searchPattern;
}
public override bool matchesPattern(String check)
{
if (check != null)
{
return check.EndsWith(searchPattern);
}
else
{
return check == searchPattern;
}
}
}
}
| 23.942308 | 81 | 0.51004 | [
"MIT"
] | AnomalousMedical/Medical | Standalone/Controller/Timeline/TimelineStaticInfo.cs | 2,492 | C# |
using System;
using System.Reactive.Concurrency;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
#if DEBUG
[assembly: InternalsVisibleTo("reactive-extensions-test")]
[assembly: InternalsVisibleTo("reactive-extensions-benchmarks")]
#else
[assembly: InternalsVisibleTo("reactive-extensions-test,PublicKey=" +
"002400000480000094000000060200000024000052534131000400000100010021abffd06f6b96" +
"c263f931fc995e76f6de4c41063813f875b1e6eef6e207000c19d27e576d13c1865418b6158859" +
"c8b9f59037e9d3e1b855ed7a51d99369f64e7a09cd32ba4d3cc97f71546b02e3e542fba8c9de6d" +
"cd9d27c393ae27be179dd4053f6bf8b85e5a4e4792f6606e69a1d4a09a480a81a78107e722b569" +
"bfcca5ba"
)]
[assembly: InternalsVisibleTo("reactive-extensions-benchmarks,PublicKey=" +
"002400000480000094000000060200000024000052534131000400000100010021abffd06f6b96" +
"c263f931fc995e76f6de4c41063813f875b1e6eef6e207000c19d27e576d13c1865418b6158859" +
"c8b9f59037e9d3e1b855ed7a51d99369f64e7a09cd32ba4d3cc97f71546b02e3e542fba8c9de6d" +
"cd9d27c393ae27be179dd4053f6bf8b85e5a4e4792f6606e69a1d4a09a480a81a78107e722b569" +
"bfcca5ba")]
#endif
namespace akarnokd.reactive_extensions
{
/// <summary>
/// Test helper scheduler that executes actions on the current thread
/// sleeping if necessary.
/// </summary>
internal sealed class ImmediateScheduler : IScheduler
{
public DateTimeOffset Now => DateTimeOffset.Now;
internal static readonly IScheduler INSTANCE = new ImmediateScheduler();
public IDisposable Schedule<TState>(TState state, Func<IScheduler, TState, IDisposable> action)
{
return action(this, state);
}
public IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
Task.Delay(dueTime).Wait();
return action(this, state);
}
public IDisposable Schedule<TState>(TState state, DateTimeOffset dueTime, Func<IScheduler, TState, IDisposable> action)
{
var diff = dueTime - Now;
Task.Delay(diff).Wait();
return action(this, state);
}
}
}
| 38.859649 | 127 | 0.749887 | [
"Apache-2.0"
] | akarnokd/reactive-extensions | reactive-extensions/observable/ImmediateScheduler.cs | 2,217 | C# |
namespace Promitor.ResourceDiscovery.Agent.Configuration
{
public class ResourceCollection
{
public string Name { get; set; }
public string Type { get; set; }
public ResourceCriteria Criteria { get; set; } = new ResourceCriteria();
}
} | 30.222222 | 80 | 0.661765 | [
"MIT"
] | tomkerkhove/resource-discovery-sandbox | src/Promitor.ResourceDiscovery.Agent/Configuration/ResourceCollection.cs | 274 | 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.Aiven.Inputs
{
public sealed class ServiceIntegrationDatadogUserConfigDatadogTagArgs : Pulumi.ResourceArgs
{
[Input("comment")]
public Input<string>? Comment { get; set; }
[Input("tag")]
public Input<string>? Tag { get; set; }
public ServiceIntegrationDatadogUserConfigDatadogTagArgs()
{
}
}
}
| 26.807692 | 95 | 0.685796 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-aiven | sdk/dotnet/Inputs/ServiceIntegrationDatadogUserConfigDatadogTagArgs.cs | 697 | 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("client.financial.accountsReceivable.input.paymentApplication")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("client.financial.accountsReceivable.input.paymentApplication")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("7518d00b-1baf-412c-b6d1-d8fe9d2e7087")]
// 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")]
| 40.351351 | 91 | 0.756196 | [
"MIT"
] | CatalinaTechnology/ctAPIClientEXamples | client.financial.accountsReceivable.input.paymentApplication/Properties/AssemblyInfo.cs | 1,496 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Cms.Service.Interface
{
public interface ICompanyService
{
}
}
| 13.454545 | 34 | 0.763514 | [
"MIT"
] | gulizay91/cms | TheMoonStudio.Cms/Cms.Service.Interface/ICompanyService.cs | 150 | 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
#region Usings
using System;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Common;
using DotNetNuke.Modules.HTMLEditorProvider;
#endregion
namespace DotNetNuke.UI.WebControls
{
/// <summary>
/// The DNNRichTextEditControl control provides a standard UI component for editing
/// RichText
/// </summary>
[ToolboxData("<{0}:DNNRichTextEditControl runat=server></{0}:DNNRichTextEditControl>")]
public class DNNRichTextEditControl : TextEditControl
{
private HtmlEditorProvider _richTextEditor;
private TextBox _defaultTextEditor;
protected Control TextEditControl
{
get
{
if (this._richTextEditor != null)
{
return this._richTextEditor.HtmlEditorControl;
}
return this._defaultTextEditor;
}
}
protected string EditorText
{
get
{
if (this._richTextEditor != null)
{
return this._richTextEditor.Text;
}
return this._defaultTextEditor.Text;
}
set
{
if (this._richTextEditor != null)
{
this._richTextEditor.Text = value;
}
else
{
this._defaultTextEditor.Text = value;
}
}
}
protected override void CreateChildControls()
{
if (this.EditMode == PropertyEditorMode.Edit)
{
var pnlEditor = new Panel();
if(string.IsNullOrEmpty(this.CssClass))
{
pnlEditor.CssClass ="dnnLeft";
}
else
{
pnlEditor.CssClass = string.Format("{0} dnnLeft", this.CssClass);
}
this._richTextEditor = HtmlEditorProvider.Instance();
if (this._richTextEditor != null)
{
this._richTextEditor.ControlID = this.ID + "edit";
this._richTextEditor.Initialize();
this._richTextEditor.Height = this.ControlStyle.Height;
this._richTextEditor.Width = this.ControlStyle.Width;
if (this._richTextEditor.Height.IsEmpty)
{
this._richTextEditor.Height = new Unit(250);
}
this._richTextEditor.Width = new Unit(400);
}
else
{
this._defaultTextEditor = new TextBox
{
ID = this.ID + "edit",
Width = this.ControlStyle.Width.IsEmpty ? new Unit(300) : this.ControlStyle.Width,
Height = this.ControlStyle.Height.IsEmpty ? new Unit(250) : this.ControlStyle.Height,
TextMode = TextBoxMode.MultiLine
};
this._defaultTextEditor.Attributes.Add("aria-label", "editor");
}
this.Controls.Clear();
pnlEditor.Controls.Add(this.TextEditControl);
this.Controls.Add(pnlEditor);
}
base.CreateChildControls();
}
public override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
var dataChanged = false;
var presentValue = this.StringValue;
var postedValue = this.EditorText;
if (!presentValue.Equals(postedValue))
{
this.Value = postedValue;
dataChanged = true;
}
return dataChanged;
}
protected override void OnDataChanged(EventArgs e)
{
var strValue = this.RemoveBaseTags(Convert.ToString(this.Value));
var strOldValue = this.RemoveBaseTags(Convert.ToString(this.OldValue));
var args = new PropertyEditorEventArgs(this.Name) { Value = this.Page.Server.HtmlEncode(strValue), OldValue = this.Page.Server.HtmlEncode(strOldValue), StringValue = this.Page.Server.HtmlEncode(this.RemoveBaseTags(this.StringValue)) };
base.OnValueChanged(args);
}
private string RemoveBaseTags(String strInput)
{
return Globals.BaseTagRegex.Replace(strInput, " ");
}
protected override void OnInit(EventArgs e)
{
this.EnsureChildControls();
base.OnInit(e);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.EditMode == PropertyEditorMode.Edit)
{
this.EditorText = this.Page.Server.HtmlDecode(Convert.ToString(this.Value));
}
if (this.Page != null && this.EditMode == PropertyEditorMode.Edit)
{
this.Page.RegisterRequiresPostBack(this);
}
}
protected override void RenderEditMode(HtmlTextWriter writer)
{
this.RenderChildren(writer);
}
protected override void RenderViewMode(HtmlTextWriter writer)
{
string propValue = this.Page.Server.HtmlDecode(Convert.ToString(this.Value));
this.ControlStyle.AddAttributesToRender(writer);
writer.RenderBeginTag(HtmlTextWriterTag.Span);
writer.Write(propValue);
writer.RenderEndTag();
}
}
}
| 34.288136 | 247 | 0.530565 | [
"MIT"
] | MaiklT/Dnn.Platform | DNN Platform/Library/UI/WebControls/PropertyEditor/Edit Controls/DNN Edit Controls/DNNRichTextEditControl.cs | 6,071 | C# |
using LanguageServer.Json;
namespace LanguageServer.Parameters.TextDocument
{
/// <summary>
/// For <c>textDocument/codeAction</c>
/// </summary>
/// <seealso>Spec 3.8.0</seealso>
public class CodeActionResult : Either
{
/// <summary>
/// Defines an implicit conversion of a <see cref="T:LanguageServer.Parameters.TextDocument.Command[]"/> to a <see cref="CodeActionResult"/>
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <seealso>Spec 3.8.0</seealso>
public static implicit operator CodeActionResult(Command[] value)
=> new CodeActionResult(value);
/// <summary>
/// Defines an implicit conversion of a <see cref="T:LanguageServer.Parameters.TextDocument.CodeAction[]"/> to a <see cref="CodeActionResult"/>
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
/// <seealso>Spec 3.8.0</seealso>
public static implicit operator CodeActionResult(CodeAction[] value)
=> new CodeActionResult(value);
/// <summary>
/// Initializes a new instance of <c>CodeActionResult</c> with the specified value.
/// </summary>
/// <param name="value"></param>
/// <seealso>Spec 3.8.0</seealso>
public CodeActionResult(Command[] value)
{
Type = typeof(Command[]);
Value = value;
}
/// <summary>
/// Initializes a new instance of <c>CodeActionResult</c> with the specified value.
/// </summary>
/// <param name="value"></param>
/// <seealso>Spec 3.8.0</seealso>
public CodeActionResult(CodeAction[] value)
{
Type = typeof(CodeAction[]);
Value = value;
}
/// <summary>
/// Returns true if its underlying value is a <see cref="T:LanguageServer.Parameters.TextDocument.Command[]"/>.
/// </summary>
/// <seealso>Spec 3.8.0</seealso>
public bool IsCommandArray => Type == typeof(Command[]);
/// <summary>
/// Returns true if its underlying value is a <see cref="T:LanguageServer.Parameters.TextDocument.CodeAction[]"/>.
/// </summary>
/// <seealso>Spec 3.8.0</seealso>
public bool IsCodeActionArray => Type == typeof(CodeAction[]);
/// <summary>
/// Gets the value of the current object if its underlying value is a <see cref="T:LanguageServer.Parameters.TextDocument.Command[]"/>.
/// </summary>
/// <seealso>Spec 3.8.0</seealso>
public Command[] CommandArray => GetValue<Command[]>();
/// <summary>
/// Gets the value of the current object if its underlying value is a <see cref="T:LanguageServer.Parameters.TextDocument.CodeAction[]"/>.
/// </summary>
/// <seealso>Spec 3.8.0</seealso>
public CodeAction[] CodeActionArray => GetValue<CodeAction[]>();
}
}
| 40.342105 | 152 | 0.568819 | [
"MIT"
] | matarillo/LanguageServerProtocol | LanguageServer/Parameters/TextDocument/CodeActionResult.cs | 3,068 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UniGLTF
{
public struct PosRot
{
public Vector3 Position;
public Quaternion Rotation;
public static PosRot FromGlobalTransform(Transform t)
{
return new PosRot
{
Position = t.position,
Rotation = t.rotation,
};
}
}
public class BlendShape
{
public string Name;
public BlendShape(string name)
{
Name = name;
}
public List<Vector3> Positions = new List<Vector3>();
public List<Vector3> Normals = new List<Vector3>();
public List<Vector3> Tangents = new List<Vector3>();
}
public static class UnityExtensions
{
public static Vector4 ReverseZ(this Vector4 v)
{
return new Vector4(v.x, v.y, -v.z, v.w);
}
public static Vector3 ReverseZ(this Vector3 v)
{
return new Vector3(v.x, v.y, -v.z);
}
[Obsolete]
public static Vector2 ReverseY(this Vector2 v)
{
return new Vector2(v.x, -v.y);
}
public static Vector2 ReverseUV(this Vector2 v)
{
return new Vector2(v.x, 1.0f - v.y);
}
public static Quaternion ReverseZ(this Quaternion q)
{
float angle;
Vector3 axis;
q.ToAngleAxis(out angle, out axis);
return Quaternion.AngleAxis(-angle, ReverseZ(axis));
}
public static Matrix4x4 Matrix4x4FromColumns(Vector4 c0, Vector4 c1, Vector4 c2, Vector4 c3)
{
#if UNITY_2017_1_OR_NEWER
return new Matrix4x4(c0, c1, c2, c3);
#else
var m = default(Matrix4x4);
m.SetColumn(0, c0);
m.SetColumn(1, c1);
m.SetColumn(2, c2);
m.SetColumn(3, c3);
return m;
#endif
}
public static Matrix4x4 Matrix4x4FromRotation(Quaternion q)
{
#if UNITY_2017_1_OR_NEWER
return Matrix4x4.Rotate(q);
#else
var m = default(Matrix4x4);
m.SetTRS(Vector3.zero, q, Vector3.one);
return m;
#endif
}
public static Matrix4x4 ReverseZ(this Matrix4x4 m)
{
m.SetTRS(m.ExtractPosition().ReverseZ(), m.ExtractRotation().ReverseZ(), m.ExtractScale());
return m;
}
public static Matrix4x4 MatrixFromArray(float[] values)
{
var m = new Matrix4x4();
m.m00 = values[0];
m.m10 = values[1];
m.m20 = values[2];
m.m30 = values[3];
m.m01 = values[4];
m.m11 = values[5];
m.m21 = values[6];
m.m31 = values[7];
m.m02 = values[8];
m.m12 = values[9];
m.m22 = values[10];
m.m32 = values[11];
m.m03 = values[12];
m.m13 = values[13];
m.m23 = values[14];
m.m33 = values[15];
return m;
}
// https://forum.unity.com/threads/how-to-assign-matrix4x4-to-transform.121966/
public static Quaternion ExtractRotation(this Matrix4x4 matrix)
{
Vector3 forward;
forward.x = matrix.m02;
forward.y = matrix.m12;
forward.z = matrix.m22;
Vector3 upwards;
upwards.x = matrix.m01;
upwards.y = matrix.m11;
upwards.z = matrix.m21;
return Quaternion.LookRotation(forward, upwards);
}
public static Vector3 ExtractPosition(this Matrix4x4 matrix)
{
Vector3 position;
position.x = matrix.m03;
position.y = matrix.m13;
position.z = matrix.m23;
return position;
}
public static Vector3 ExtractScale(this Matrix4x4 matrix)
{
Vector3 scale;
scale.x = new Vector4(matrix.m00, matrix.m10, matrix.m20, matrix.m30).magnitude;
scale.y = new Vector4(matrix.m01, matrix.m11, matrix.m21, matrix.m31).magnitude;
scale.z = new Vector4(matrix.m02, matrix.m12, matrix.m22, matrix.m32).magnitude;
return scale;
}
public static string RelativePathFrom(this Transform self, Transform root)
{
var path = new List<String>();
for (var current = self; current != null; current = current.parent)
{
if (current == root)
{
return String.Join("/", path.ToArray());
}
path.Insert(0, current.name);
}
throw new Exception("no RelativePath");
}
public static Transform GetChildByName(this Transform self, string childName)
{
foreach (Transform child in self)
{
if (child.name == childName)
{
return child;
}
}
throw new KeyNotFoundException();
}
public static Transform GetFromPath(this Transform self, string path)
{
var current = self;
var splited = path.Split('/');
foreach (var childName in splited)
{
current = current.GetChildByName(childName);
}
return current;
}
public static IEnumerable<Transform> GetChildren(this Transform self)
{
foreach (Transform child in self)
{
yield return child;
}
}
public static IEnumerable<Transform> Traverse(this Transform t)
{
yield return t;
foreach (Transform x in t)
{
foreach (Transform y in x.Traverse())
{
yield return y;
}
}
}
public static Transform FindDescenedant(this Transform t, string name)
{
return t.Traverse().First(x => x.name == name);
}
public static IEnumerable<Transform> Ancestors(this Transform t)
{
yield return t;
if (t.parent != null)
{
foreach (Transform x in t.parent.Ancestors())
{
yield return x;
}
}
}
public static float[] ToArray(this Quaternion q)
{
return new float[] { q.x, q.y, q.z, q.w };
}
public static float[] ToArray(this Vector3 v)
{
return new float[] { v.x, v.y, v.z };
}
public static float[] ToArray(this Vector4 v)
{
return new float[] { v.x, v.y, v.z, v.w };
}
public static float[] ToArray(this Color c)
{
return new float[] { c.r, c.g, c.b, c.a };
}
public static void ReverseZRecursive(this Transform root)
{
var globalMap = root.Traverse().ToDictionary(x => x, x => PosRot.FromGlobalTransform(x));
foreach (var x in root.Traverse())
{
x.position = globalMap[x].Position.ReverseZ();
x.rotation = globalMap[x].Rotation.ReverseZ();
}
}
public static Mesh GetSharedMesh(this Transform t)
{
var meshFilter = t.GetComponent<MeshFilter>();
if (meshFilter != null)
{
return meshFilter.sharedMesh;
}
var skinnedMeshRenderer = t.GetComponent<SkinnedMeshRenderer>();
if (skinnedMeshRenderer != null)
{
return skinnedMeshRenderer.sharedMesh;
}
return null;
}
public static Material[] GetSharedMaterials(this Transform t)
{
var renderer = t.GetComponent<Renderer>();
if (renderer != null)
{
return renderer.sharedMaterials;
}
return new Material[] { };
}
public static bool Has<T>(this Transform transform, T t) where T : Component
{
return transform.GetComponent<T>() == t;
}
public static T GetOrAddComponent<T>(this GameObject go) where T : Component
{
var c = go.GetComponent<T>();
if (c != null)
{
return c;
}
return go.AddComponent<T>();
}
}
}
| 28.557325 | 104 | 0.484778 | [
"MIT"
] | DeanVanGreunen/UniGLTF | Core/Scripts/Extensions/UnityExtensions.cs | 8,969 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DataAccessLayer
{
public interface ISales : IProduct
{
string ORno { get; set; }
string CustomerName { get; set; }
double SubTotal { get; set; }
double Total { get; set; }
double Change { get; set; }
int Quantity { get; set; }
double Cash { get; set; }
string GetMaxOR();
}
}
| 22.5 | 41 | 0.588889 | [
"MIT"
] | kitchanismo/IceCreamShopCSharp | IceCreamShopCSharp/DataAccessLayer/Interface/ISales.cs | 452 | C# |
/*
* The MIT License
*
* Copyright 2019 Palmtree Software.
*
* 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.Linq;
using System.Numerics;
namespace Palmtree.Math.CodeGen.TestData.Plugin.Uint
{
class TestDataRendererPlugin_ToBigInt_UX
: TestDataRendererPluginBase_1_1
{
public TestDataRendererPlugin_ToBigInt_UX()
: base("uint", "test_data_tobigint_ux.xml")
{
}
protected override IEnumerable<TestDataItemContainer> TestDataItems
{
get
{
return (UBigIntDataSource
.Select(p1 =>
{
return (new
{
p1 = (IDataItem)new UBigIntDataItem(p1),
r1 = (IDataItem)new BigIntDataItem(p1),
});
})
.Zip(Enumerable.Range(0, int.MaxValue),
(item, index) => new TestDataItemContainer
{
Index = index,
Param1 = item.p1,
Result1 = item.r1,
}));
}
}
}
}
/*
* END OF FILE
*/ | 34.5 | 80 | 0.580538 | [
"MIT"
] | rougemeilland/Palmtree.Math | Palmtree.Math.CodeGen.TestData/Plugin/Uint/TestDataRendererPlugin_ToBigInt_UX.cs | 2,417 | C# |
using SharpenedMinecraft.Types.Items;
using System;
using System.Collections.Generic;
using System.Text;
namespace SharpenedMinecraft.Types.Blocks
{
public class Tube_coralBlock : Block
{
public override string BlockId => "minecraft:tube_coral";
public override BlockState[] PossibleStates { get; }
public Tube_coralBlock() : base()
{
PossibleStates = new BlockState[]
{
new BlockState(8441, new Dictionary<string, string>
{ }),
};
State = PossibleStates[0];
Drops = new ItemStack[] { new Tube_coralItem() };
}
}
}
| 22.965517 | 67 | 0.588589 | [
"MIT"
] | SharpenedMinecraft/SM1 | Main/Types/Blocks/Tube_coralBlock.cs | 666 | C# |
namespace WordExamplesCS4
{
partial class Example07
{
/// <summary>
/// Erforderliche Designervariable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Verwendete Ressourcen bereinigen.
/// </summary>
/// <param name="disposing">True, wenn verwaltete Ressourcen gelöscht werden sollen; andernfalls False.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Vom Komponenten-Designer generierter Code
/// <summary>
/// Erforderliche Methode für die Designerunterstützung.
/// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Example07));
this.buttonQuitExample = new System.Windows.Forms.Button();
this.labelEventLogHeader = new System.Windows.Forms.Label();
this.textBoxEvents = new System.Windows.Forms.TextBox();
this.textBoxDescription = new System.Windows.Forms.TextBox();
this.buttonStartExample = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// buttonQuitExample
//
this.buttonQuitExample.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.buttonQuitExample.Enabled = false;
this.buttonQuitExample.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.buttonQuitExample.Image = ((System.Drawing.Image)(resources.GetObject("buttonQuitExample.Image")));
this.buttonQuitExample.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.buttonQuitExample.Location = new System.Drawing.Point(29, 54);
this.buttonQuitExample.Name = "buttonQuitExample";
this.buttonQuitExample.Size = new System.Drawing.Size(680, 28);
this.buttonQuitExample.TabIndex = 26;
this.buttonQuitExample.Text = "Quit Word";
this.buttonQuitExample.UseVisualStyleBackColor = true;
this.buttonQuitExample.Click += new System.EventHandler(this.buttonQuitExample_Click);
//
// labelEventLogHeader
//
this.labelEventLogHeader.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.labelEventLogHeader.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.labelEventLogHeader.Location = new System.Drawing.Point(31, 180);
this.labelEventLogHeader.Name = "labelEventLogHeader";
this.labelEventLogHeader.Size = new System.Drawing.Size(679, 22);
this.labelEventLogHeader.TabIndex = 25;
this.labelEventLogHeader.Text = "EventLog";
//
// textBoxEvents
//
this.textBoxEvents.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxEvents.BackColor = System.Drawing.SystemColors.InactiveBorder;
this.textBoxEvents.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBoxEvents.Location = new System.Drawing.Point(30, 205);
this.textBoxEvents.Multiline = true;
this.textBoxEvents.Name = "textBoxEvents";
this.textBoxEvents.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.textBoxEvents.Size = new System.Drawing.Size(679, 80);
this.textBoxEvents.TabIndex = 24;
//
// textBoxDescription
//
this.textBoxDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.textBoxDescription.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.textBoxDescription.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textBoxDescription.Location = new System.Drawing.Point(29, 100);
this.textBoxDescription.Multiline = true;
this.textBoxDescription.Name = "textBoxDescription";
this.textBoxDescription.Size = new System.Drawing.Size(680, 67);
this.textBoxDescription.TabIndex = 23;
this.textBoxDescription.Text = resources.GetString("textBoxDescription.Text");
//
// buttonStartExample
//
this.buttonStartExample.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.buttonStartExample.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.buttonStartExample.Image = ((System.Drawing.Image)(resources.GetObject("buttonStartExample.Image")));
this.buttonStartExample.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.buttonStartExample.Location = new System.Drawing.Point(30, 20);
this.buttonStartExample.Name = "buttonStartExample";
this.buttonStartExample.Size = new System.Drawing.Size(680, 28);
this.buttonStartExample.TabIndex = 22;
this.buttonStartExample.Text = "Start Word";
this.buttonStartExample.UseVisualStyleBackColor = true;
this.buttonStartExample.Click += new System.EventHandler(this.buttonStartExample_Click);
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button1.Image = ((System.Drawing.Image)(resources.GetObject("button1.Image")));
this.button1.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.button1.Location = new System.Drawing.Point(30, 20);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(680, 28);
this.button1.TabIndex = 22;
this.button1.Text = "Start Word";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.buttonStartExample_Click);
//
// button2
//
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.button2.Enabled = false;
this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.button2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.button2.Image = ((System.Drawing.Image)(resources.GetObject("button2.Image")));
this.button2.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.button2.Location = new System.Drawing.Point(29, 54);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(680, 28);
this.button2.TabIndex = 26;
this.button2.Text = "Quit Word";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.buttonQuitExample_Click);
//
// Example07
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.LightSteelBlue;
this.Controls.Add(this.button2);
this.Controls.Add(this.buttonQuitExample);
this.Controls.Add(this.labelEventLogHeader);
this.Controls.Add(this.textBoxEvents);
this.Controls.Add(this.textBoxDescription);
this.Controls.Add(this.button1);
this.Controls.Add(this.buttonStartExample);
this.Name = "Example07";
this.Size = new System.Drawing.Size(739, 304);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button buttonQuitExample;
private System.Windows.Forms.Label labelEventLogHeader;
private System.Windows.Forms.TextBox textBoxEvents;
private System.Windows.Forms.TextBox textBoxDescription;
private System.Windows.Forms.Button buttonStartExample;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
}
}
| 60.109827 | 179 | 0.63535 | [
"MIT"
] | NetOffice/NetOffice | Examples/Word/C#/Standard Examples/WordExamples/Examples/Example07.Designer.cs | 10,405 | C# |
using Newtonsoft.Json;
namespace DataTransferObjects.Vehicle
{
public record IndexVehicleDto([JsonProperty("Name")]string Name);
} | 19.571429 | 69 | 0.781022 | [
"MIT"
] | carpool-team/carpool | src/API/Shared/DataTransferObjects/Vehicle/IndexVehicleDto.cs | 139 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("Clock")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Clock")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// 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")]
| 33.774194 | 84 | 0.7383 | [
"MIT"
] | patrickCode/Mobile | Xamarin/Android/TestOrderApp/Clock/Properties/AssemblyInfo.cs | 1,050 | C# |
using System;
/*
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. Camunda licenses this file to you under the Apache License,
* Version 2.0; you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace org.camunda.bpm.engine.impl.test
{
/// <summary>
/// Base class for the process engine test cases.
///
/// The main reason not to use our own test support classes is that we need to
/// run our test suite with various configurations, e.g. with and without spring,
/// standalone or on a server etc. Those requirements create some complications
/// so we think it's best to use a separate base class. That way it is much easier
/// for us to maintain our own codebase and at the same time provide stability
/// on the test support classes that we offer as part of our api (in org.camunda.bpm.engine.test).
///
/// @author Tom Baeyens
/// @author Joram Barrez
/// </summary>
public class PluggableProcessEngineTestCase : AbstractProcessEngineTestCase
{
protected internal static ProcessEngine cachedProcessEngine;
protected internal override void initializeProcessEngine()
{
processEngine = OrInitializeCachedProcessEngine;
}
private static ProcessEngine OrInitializeCachedProcessEngine
{
get
{
if (cachedProcessEngine == null)
{
try
{
cachedProcessEngine = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("camunda.cfg.xml").buildProcessEngine();
}
catch (Exception ex)
{
if (ex.InnerException != null && ex.InnerException is FileNotFoundException)
{
cachedProcessEngine = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("activiti.cfg.xml").buildProcessEngine();
}
else
{
throw ex;
}
}
}
return cachedProcessEngine;
}
}
public static ProcessEngine ProcessEngine
{
get
{
return OrInitializeCachedProcessEngine;
}
}
}
} | 30.927711 | 141 | 0.728866 | [
"Apache-2.0"
] | luizfbicalho/Camunda.NET | camunda-bpm-platform-net/engine/src/main/java/org/camunda/bpm/engine/impl/test/PluggableProcessEngineTestCase.cs | 2,569 | 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.
#nullable enable
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Storage
{
/// <summary>
/// A service that enables storing and retrieving of information associated with solutions,
/// projects or documents across runtime sessions.
/// </summary>
internal abstract partial class AbstractPersistentStorageService : IChecksummedPersistentStorageService
{
private readonly IPersistentStorageLocationService _locationService;
/// <summary>
/// This lock guards all mutable fields in this type.
/// </summary>
private readonly object _lock = new object();
private ReferenceCountedDisposable<IChecksummedPersistentStorage>? _currentPersistentStorage;
private SolutionId? _currentPersistentStorageSolutionId;
protected AbstractPersistentStorageService(IPersistentStorageLocationService locationService)
=> _locationService = locationService;
protected abstract string GetDatabaseFilePath(string workingFolderPath);
/// <summary>
/// Can throw. If it does, the caller (<see cref="CreatePersistentStorage"/>) will attempt
/// to delete the database and retry opening one more time. If that fails again, the <see
/// cref="NoOpPersistentStorage"/> instance will be used.
/// </summary>
protected abstract IChecksummedPersistentStorage? TryOpenDatabase(Solution solution, string workingFolderPath, string databaseFilePath);
protected abstract bool ShouldDeleteDatabase(Exception exception);
IPersistentStorage IPersistentStorageService.GetStorage(Solution solution)
=> this.GetStorage(solution);
IPersistentStorage IPersistentStorageService2.GetStorage(Solution solution, bool checkBranchId)
=> this.GetStorage(solution, checkBranchId);
public IChecksummedPersistentStorage GetStorage(Solution solution)
=> GetStorage(solution, checkBranchId: true);
public IChecksummedPersistentStorage GetStorage(Solution solution, bool checkBranchId)
{
if (!DatabaseSupported(solution, checkBranchId))
{
return NoOpPersistentStorage.Instance;
}
return GetStorageWorker(solution);
}
internal IChecksummedPersistentStorage GetStorageWorker(Solution solution)
{
lock (_lock)
{
// Do we already have storage for this?
if (solution.Id == _currentPersistentStorageSolutionId)
{
// We do, great. Increment our ref count for our caller. They'll decrement it
// when done with it.
return PersistentStorageReferenceCountedDisposableWrapper.AddReferenceCountToAndCreateWrapper(_currentPersistentStorage!);
}
var workingFolder = _locationService.TryGetStorageLocation(solution);
if (workingFolder == null)
{
return NoOpPersistentStorage.Instance;
}
// If we already had some previous cached service, let's let it start cleaning up
if (_currentPersistentStorage != null)
{
var storageToDispose = _currentPersistentStorage;
// Kick off a task to actually go dispose the previous cached storage instance.
// This will remove the single ref count we ourselves added when we cached the
// instance. Then once all other existing clients who are holding onto this
// instance let go, it will finally get truly disposed.
Task.Run(() => storageToDispose.Dispose());
_currentPersistentStorage = null;
_currentPersistentStorageSolutionId = null;
}
var storage = CreatePersistentStorage(solution, workingFolder);
Contract.ThrowIfNull(storage);
// Create and cache a new storage instance associated with this particular solution.
// It will initially have a ref-count of 1 due to our reference to it.
_currentPersistentStorage = new ReferenceCountedDisposable<IChecksummedPersistentStorage>(storage);
_currentPersistentStorageSolutionId = solution.Id;
// Now increment the reference count and return to our caller. The current ref
// count for this instance will be 2. Until all the callers *and* us decrement
// the refcounts, this instance will not be actually disposed.
return PersistentStorageReferenceCountedDisposableWrapper.AddReferenceCountToAndCreateWrapper(_currentPersistentStorage);
}
}
private static bool DatabaseSupported(Solution solution, bool checkBranchId)
{
if (solution.FilePath == null)
{
return false;
}
if (checkBranchId && solution.BranchId != solution.Workspace.PrimaryBranchId)
{
// we only use database for primary solution. (Ex, forked solution will not use database)
return false;
}
return true;
}
private IChecksummedPersistentStorage CreatePersistentStorage(Solution solution, string workingFolderPath)
{
// Attempt to create the database up to two times. The first time we may encounter
// some sort of issue (like DB corruption). We'll then try to delete the DB and can
// try to create it again. If we can't create it the second time, then there's nothing
// we can do and we have to store things in memory.
return TryCreatePersistentStorage(solution, workingFolderPath) ??
TryCreatePersistentStorage(solution, workingFolderPath) ??
NoOpPersistentStorage.Instance;
}
private IChecksummedPersistentStorage? TryCreatePersistentStorage(
Solution solution,
string workingFolderPath)
{
var databaseFilePath = GetDatabaseFilePath(workingFolderPath);
try
{
return TryOpenDatabase(solution, workingFolderPath, databaseFilePath);
}
catch (Exception ex)
{
StorageDatabaseLogger.LogException(ex);
if (ShouldDeleteDatabase(ex))
{
// this was not a normal exception that we expected during DB open.
// Report this so we can try to address whatever is causing this.
FatalError.ReportWithoutCrash(ex);
IOUtilities.PerformIO(() => Directory.Delete(Path.GetDirectoryName(databaseFilePath), recursive: true));
}
return null;
}
}
private void Shutdown()
{
ReferenceCountedDisposable<IChecksummedPersistentStorage>? storage = null;
lock (_lock)
{
// We will transfer ownership in a thread-safe way out so we can dispose outside the lock
storage = _currentPersistentStorage;
_currentPersistentStorage = null;
_currentPersistentStorageSolutionId = null;
}
if (storage != null)
{
// Dispose storage outside of the lock. Note this only removes our reference count; clients who are still
// using this will still be holding a reference count.
storage.Dispose();
}
}
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
internal readonly struct TestAccessor
{
private readonly AbstractPersistentStorageService _service;
public TestAccessor(AbstractPersistentStorageService service)
=> _service = service;
public void Shutdown()
=> _service.Shutdown();
}
/// <summary>
/// A trivial wrapper that we can hand out for instances from the <see cref="AbstractPersistentStorageService"/>
/// that wraps the underlying <see cref="IPersistentStorage"/> singleton.
/// </summary>
private sealed class PersistentStorageReferenceCountedDisposableWrapper : IChecksummedPersistentStorage
{
private readonly ReferenceCountedDisposable<IChecksummedPersistentStorage> _storage;
private PersistentStorageReferenceCountedDisposableWrapper(ReferenceCountedDisposable<IChecksummedPersistentStorage> storage)
=> _storage = storage;
public static IChecksummedPersistentStorage AddReferenceCountToAndCreateWrapper(ReferenceCountedDisposable<IChecksummedPersistentStorage> storage)
{
// This should only be called from a caller that has a non-null storage that it
// already has a reference on. So .TryAddReference cannot fail.
return new PersistentStorageReferenceCountedDisposableWrapper(storage.TryAddReference() ?? throw ExceptionUtilities.Unreachable);
}
public void Dispose()
=> _storage.Dispose();
public Task<Checksum> ReadChecksumAsync(string name, CancellationToken cancellationToken)
=> _storage.Target.ReadChecksumAsync(name, cancellationToken);
public Task<Checksum> ReadChecksumAsync(Project project, string name, CancellationToken cancellationToken)
=> _storage.Target.ReadChecksumAsync(project, name, cancellationToken);
public Task<Checksum> ReadChecksumAsync(Document document, string name, CancellationToken cancellationToken)
=> _storage.Target.ReadChecksumAsync(document, name, cancellationToken);
public Task<Stream> ReadStreamAsync(string name, CancellationToken cancellationToken)
=> _storage.Target.ReadStreamAsync(name, cancellationToken);
public Task<Stream> ReadStreamAsync(Project project, string name, CancellationToken cancellationToken)
=> _storage.Target.ReadStreamAsync(project, name, cancellationToken);
public Task<Stream> ReadStreamAsync(Document document, string name, CancellationToken cancellationToken)
=> _storage.Target.ReadStreamAsync(document, name, cancellationToken);
public Task<Stream> ReadStreamAsync(string name, Checksum checksum, CancellationToken cancellationToken)
=> _storage.Target.ReadStreamAsync(name, checksum, cancellationToken);
public Task<Stream> ReadStreamAsync(Project project, string name, Checksum checksum, CancellationToken cancellationToken)
=> _storage.Target.ReadStreamAsync(project, name, checksum, cancellationToken);
public Task<Stream> ReadStreamAsync(Document document, string name, Checksum checksum, CancellationToken cancellationToken)
=> _storage.Target.ReadStreamAsync(document, name, checksum, cancellationToken);
public Task<bool> WriteStreamAsync(string name, Stream stream, CancellationToken cancellationToken)
=> _storage.Target.WriteStreamAsync(name, stream, cancellationToken);
public Task<bool> WriteStreamAsync(Project project, string name, Stream stream, CancellationToken cancellationToken)
=> _storage.Target.WriteStreamAsync(project, name, stream, cancellationToken);
public Task<bool> WriteStreamAsync(Document document, string name, Stream stream, CancellationToken cancellationToken)
=> _storage.Target.WriteStreamAsync(document, name, stream, cancellationToken);
public Task<bool> WriteStreamAsync(string name, Stream stream, Checksum checksum, CancellationToken cancellationToken)
=> _storage.Target.WriteStreamAsync(name, stream, checksum, cancellationToken);
public Task<bool> WriteStreamAsync(Project project, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken)
=> _storage.Target.WriteStreamAsync(project, name, stream, checksum, cancellationToken);
public Task<bool> WriteStreamAsync(Document document, string name, Stream stream, Checksum checksum, CancellationToken cancellationToken)
=> _storage.Target.WriteStreamAsync(document, name, stream, checksum, cancellationToken);
}
}
}
| 48.955056 | 158 | 0.661694 | [
"MIT"
] | JavierMatosD/roslyn | src/Workspaces/Core/Portable/Storage/AbstractPersistentStorageService.cs | 13,073 | C# |
//This script is used to make a 3D UI mesh "zoom" in (instead of just appearing, the element
//starts small and then expands to a target size).
using UnityEngine;
using System.Collections; //This allows us to use coroutines
using UnityEngine.UI; //Enable UI items in script
public class VRUIPanel : MonoBehaviour
{
public float appearSpeed = 10f; //The speed that the object will zoom in and out
public Button preSelectedButton; //Which UI button will be the first one selected (this is needed for controller support)
Vector3 initialScale; //Initial scale of the object
Vector3 targetScale; //Target scale of the object
//This will be called when this game object is enabled
void OnEnable()
{
//Record the initial scale of the object
initialScale = transform.localScale;
//Set the scale to zero, making it invisible
transform.localScale = Vector3.zero;
//Set the target scale to its initial scale so it can grow to its original size
targetScale = initialScale;
//Start the Zoom coroutine
StartCoroutine (Zoom ());
}
//This will be called when this game object is disabled
void OnDisable()
{
//Record the initial scale of the object
initialScale = transform.localScale;
//Set the target scale to zero so it can shrink all the way down
targetScale = Vector3.zero;
}
//This Coroutine will scale the game object. Coroutines allow us to break instructions
//up so that they happen over time instead of all at once.
IEnumerator Zoom()
{
//While the game object has not yet reached its target scale...
while (Vector3.Distance (transform.localScale, targetScale) > .01f)
{
//...scale the game object over time using Lerp...
transform.localScale = Vector3.Lerp (transform.localScale, targetScale, appearSpeed * Time.deltaTime);
//...and leave or "pause" this code until the next game frame. Then, start back right here
yield return null;
}
//Once scaling is complete, select the designated button
preSelectedButton.Select ();
}
}
| 36.122807 | 123 | 0.720738 | [
"MIT"
] | duliodenis/unity_vr_roadshow | VikingQuestVR_Start/Assets/Scripts/VRUIPanel.cs | 2,061 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.