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 SettingsModelWPFDemo.ViewModels { using Settings.Interfaces; using SettingsModelWPFDemo.ViewModels.Base.SettingPages; using SettingsModelWPFDemo.ViewModels.SettingPages; using System.Collections.Generic; using System.Collections.ObjectModel; /// <summary> /// Defines an interface that supports commands to be executed on load /// and unload of controls in presentation layer. /// </summary> public interface LoadUnloadCommands { /// <summary> /// Execute this command to acquire resources and compute data for display. /// </summary> void LoadedCommand(); /// <summary> /// Execute this command to free resources and store data /// results from display manipulation. /// </summary> void UnloadedCommand(); } /// <summary> /// Implements a viewmodel that manages a settings view with all its sub-setting pages. /// </summary> public class SettingsPageViewModel : Base.ViewModels.ViewModelBase, LoadUnloadCommands { #region fields private ObservableCollection<SettingsPageBaseViewModel> mPages = null; private SettingsPageBaseViewModel mSelectedPage = null; private bool IsEditingSettings = false; #endregion fields #region constructors public SettingsPageViewModel() { mPages = new ObservableCollection<SettingsPageBaseViewModel>(); } #endregion constructors #region properties /// <summary> /// Gets the collection that contains all settings pages thata re available for manipulation. /// </summary> public ObservableCollection<SettingsPageBaseViewModel> Pages { get { return mPages; } } /// <summary> /// Gets the currently selected settings page. /// </summary> public SettingsPageBaseViewModel SelectedPage { get { return mSelectedPage; } set { if (mSelectedPage != value) { mSelectedPage = value; RaisePropertyChanged(() => SelectedPage); } } } /// <summary> /// Execute to acquire resources and compute data for display. /// </summary> public void LoadedCommand() { Pages.Clear(); LoadData(); } /// <summary> /// Execute this to free resources and store data /// results from display manipulation in model. /// </summary> public void UnloadedCommand() { SaveAllDataToModel(); Pages.Clear(); } #endregion properties #region methods /// <summary> /// Unloads settings data from viewmodel into /// model if data is being edited at time of call. /// </summary> public void SaveDataToModelOnEditing() { if (IsEditingSettings == true) SaveAllDataToModel(); } #region Load Data From Model /// <summary> /// Setup viewmodel for edtiting by initializing /// viewmodels from model data and selecting a default page. /// </summary> private void LoadData() { var settings = GetService<ISettingsManager>(); var List = new List<SettingsPageBaseViewModel>() { new GeneralViewModel(), new AppearanceViewModel(settings.Themes), new AboutViewModel() }; for (int i = 0; i < List.Count; i++) { LoadFromModel(List[i]); Pages.Add(List[i]); } SelectedPage = List[0]; IsEditingSettings = true; } /// <summary> /// Applies the current appearance settings to the view. /// </summary> /// <param name="vm"></param> private void LoadFromModel(SettingsPageBaseViewModel vm) { if (vm != null) { var options = GetService<ISettingsManager>(); vm.ApplyOptionsFromModel(options.Options); } } #endregion Load Data From Model #region Save Data To Model private void SaveAllDataToModel() { foreach (var item in Pages) { SaveToModel(item); } Pages.Clear(); IsEditingSettings = false; } private void SaveToModel(SettingsPageBaseViewModel vm) { if (vm != null) { var options = GetService<ISettingsManager>(); vm.SaveOptionsToModel(options.Options); } } #endregion Save Data To Model #endregion methods } }
28.867816
101
0.539916
[ "MIT" ]
Dirkster99/SettingsModel
1.0/Demos_Tests/SettingsModelWPFDemo/ViewModels/SettingsPageViewModel.cs
5,025
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: MethodRequestBody.cs.tt namespace Microsoft.Graph { using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; /// <summary> /// The type WorkbookFunctionsRandBetweenRequestBody. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class WorkbookFunctionsRandBetweenRequestBody { /// <summary> /// Gets or sets Bottom. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "bottom", Required = Newtonsoft.Json.Required.Default)] public Newtonsoft.Json.Linq.JToken Bottom { get; set; } /// <summary> /// Gets or sets Top. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "top", Required = Newtonsoft.Json.Required.Default)] public Newtonsoft.Json.Linq.JToken Top { get; set; } } }
37.179487
153
0.602759
[ "MIT" ]
DamienTehDemon/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/model/WorkbookFunctionsRandBetweenRequestBody.cs
1,450
C#
using System; using System.Collections.Generic; using System.IO; using GaTech.Chai.FhirIg.Extensions; using GaTech.Chai.Mdi.BundleDocumentMdiToEdrsProfile; using GaTech.Chai.Mdi.BundleMessageToxicologyToMdiProfile; using GaTech.Chai.Mdi.Common; using GaTech.Chai.Mdi.CompositionMditoEdrsProfile; using GaTech.Chai.Mdi.DiagnosticReportToxicologyLabResultToMdiProfile; using GaTech.Chai.Mdi.ListCauseOfDeathPathwayProfile; using GaTech.Chai.Mdi.MessageHeaderToxicologyToMdiProfile; using GaTech.Chai.Mdi.ObservationCauseOfDeathConditionProfile; using GaTech.Chai.Mdi.ObservationConditionContributingToDeathProfile; using GaTech.Chai.Mdi.ObservationDeathDateProfile; using GaTech.Chai.Mdi.ObservationDeathInjuryEventOccurredAtWorkProfile; using GaTech.Chai.Mdi.ObservationDecedentPregnancyProfile; using GaTech.Chai.Mdi.ObservationHowDeathInjuryOccurredProfile; using GaTech.Chai.Mdi.ObservationMannerOfDeathProfile; using GaTech.Chai.Mdi.ObservationTobaccoUseContributedToDeathProfile; using GaTech.Chai.Mdi.ObservationToxicologyLabResultProfile; using GaTech.Chai.Mdi.SpecimenToxicologyLabProfile; using GaTech.Chai.Odh.UsualWorkProfile; using GaTech.Chai.UsCore.LocationProfile; using GaTech.Chai.UsCore.OrganizationProfile; using GaTech.Chai.UsCore.PatientProfile; using GaTech.Chai.UsCore.PractitionerProfile; using Hl7.Fhir.Model; using Hl7.Fhir.Serialization; namespace MdiExample { class Program { static void Main(string[] args) { FhirJsonSerializer serializer = new(new SerializerSettings() { Pretty = true }); string outputPath = "/Users/mc142/Documents/workspace/MMG/cbs-ig-dotnet/MDIout/"; // US Core PatientProfile Patient patient = UsCorePatient.Create(); // Name patient.Name = new List<HumanName> { new HumanName() { Family = "FREEMAN", GivenElement = new List<FhirString> { new FhirString("Alice"), new FhirString("J") } } }; patient.Identifier.Add(new Identifier() { Use = Identifier.IdentifierUse.Usual, Type = new CodeableConcept("http://terminology.hl7.org/CodeSystem/v2-0203", "SS", "Social Security number", "Social Security number"), System = "http://hospital.smarthealthit.org", Value = "987054321" }); // Race patient.UsCorePatient().Race.Category = UsCorePatientRace.RaceCoding.Encode("2106-3", "White"); patient.UsCorePatient().Race.ExtendedRaceCodes = new Coding[] { UsCorePatientRace.RaceCoding.Encode("1010-8", "Apache") }; patient.UsCorePatient().Race.RaceText = "Apache"; // Ethnicity patient.UsCorePatient().Ethnicity.Category = UsCorePatientEthnicity.EthnicityCoding.Encode("2186-5", "Not Hispanic or Latino"); patient.UsCorePatient().Ethnicity.ExtendedEthnicityCodes = new Coding[] { UsCorePatientEthnicity.EthnicityCoding.Encode("2162-6", "Central American Indian") }; patient.UsCorePatient().Ethnicity.EthnicityText = "Not Hispanic or Latino"; // Birth Related patient.BirthDateElement = new Date(1965, 5, 2); patient.UsCorePatient().BirthSex.Extension = new Code("F"); patient.Gender = AdministrativeGender.Female; // Address var address = new Address() { Use = Address.AddressUse.Home, State = "TX", PostalCode = "77018", Country = "USA" }; address.Use = Address.AddressUse.Home; patient.Address.Add(address); // Contact patient.Telecom.AddTelecom(ContactPoint.ContactPointSystem.Phone, ContactPoint.ContactPointUse.Home, "212-867-5309"); patient.Telecom.AddTelecom(ContactPoint.ContactPointSystem.Phone, ContactPoint.ContactPointUse.Home, "212-867-5310"); patient.Telecom.AddTelecom(ContactPoint.ContactPointSystem.Phone, ContactPoint.ContactPointUse.Home, "212-867-5310"); // duplicate entry demo patient.Telecom.AddTelecom(ContactPoint.ContactPointSystem.Email, ContactPoint.ContactPointUse.Work, "mywork@gtri.org"); // Deceased patient.Deceased = new FhirDateTime(2014, 3, 2); // ODH Usual Work Observation Observation usualWorkObservation = OdhUsualWork.Create(); usualWorkObservation.Status = ObservationStatus.Final; usualWorkObservation.Subject = patient.AsReference(); usualWorkObservation.Effective = new Period(new FhirDateTime("2000-06-01"), new FhirDateTime("2021-05-20")); usualWorkObservation.OdhUsualWork().OccupationCdcCensus2010 = new Coding(OdhUsualWork.OccupationCdcCensus2010Oid, "3600", "Nursing, psychiatric, and home health aides"); usualWorkObservation.OdhUsualWork().OccupationCdcOnetSdc2010 = new Coding(OdhUsualWork.OccupationOdhOid, "31-1014.00.007136", "Certified Nursing Assistant (CNA) [Nursing Assistants]"); usualWorkObservation.OdhUsualWork().IndustryCdcCensus2010 = new Coding(OdhUsualWork.IndustryCdcCensus2010Oid, "8270", "Nursing care facilities"); usualWorkObservation.OdhUsualWork().UsualOccupationDuration = 21; // Us Core Practitioner (ME) Practitioner practitioner = UsCorePractitioner.Create(); practitioner.Name = new List<HumanName> { new HumanName() { Use = HumanName.NameUse.Official, Family = "Jones", GivenElement = new List<FhirString> { new FhirString("Sam") }, PrefixElement = new List<FhirString> { new FhirString("Dr") } } }; practitioner.UsCorePractitioner().NPI = "3333445555"; // Cause of Death Condition Observation Observation causeOfDeath1 = ObservationCauseOfDeathCondition.Create(); causeOfDeath1.Status = ObservationStatus.Final; causeOfDeath1.Subject = patient.AsReference(); causeOfDeath1.Performer.Add(practitioner.AsReference()); causeOfDeath1.ObservationCauseOfDeathCondition().Value = new CodeableConcept(null, null, "Fentanyl toxicity"); causeOfDeath1.ObservationCauseOfDeathCondition().IntervalString = "minutes to hours"; Observation causeOfDeath2 = ObservationCauseOfDeathCondition.Create(); causeOfDeath2.Status = ObservationStatus.Final; causeOfDeath2.Subject = patient.AsReference(); causeOfDeath2.Performer.Add(practitioner.AsReference()); causeOfDeath2.ObservationCauseOfDeathCondition().Value = new CodeableConcept(null, null, "Fentanyl toxicity"); causeOfDeath2.ObservationCauseOfDeathCondition().IntervalString = "minutes to hours"; Observation causeOfDeath3 = ObservationCauseOfDeathCondition.Create(); causeOfDeath3.Status = ObservationStatus.Final; causeOfDeath3.Subject = patient.AsReference(); causeOfDeath3.Performer.Add(practitioner.AsReference()); causeOfDeath3.ObservationCauseOfDeathCondition().Value = new CodeableConcept(null, null, "Fentanyl toxicity"); causeOfDeath3.ObservationCauseOfDeathCondition().IntervalString = "minutes to hours"; Observation causeOfDeath4 = ObservationCauseOfDeathCondition.Create(); causeOfDeath4.Status = ObservationStatus.Final; causeOfDeath4.Subject = patient.AsReference(); causeOfDeath4.Performer.Add(practitioner.AsReference()); causeOfDeath4.ObservationCauseOfDeathCondition().Value = new CodeableConcept(null, null, "Fentanyl toxicity"); causeOfDeath4.ObservationCauseOfDeathCondition().IntervalString = "minutes to hours"; Observation causeOfDeath5 = ObservationCauseOfDeathCondition.Create(); causeOfDeath5.Status = ObservationStatus.Final; causeOfDeath5.Subject = patient.AsReference(); causeOfDeath5.Performer.Add(practitioner.AsReference()); causeOfDeath5.ObservationCauseOfDeathCondition().Value = new CodeableConcept(null, null, "Fentanyl toxicity"); causeOfDeath5.ObservationCauseOfDeathCondition().IntervalString = "minutes to hours"; Observation causeOfDeath6 = ObservationCauseOfDeathCondition.Create(); causeOfDeath6.Status = ObservationStatus.Final; causeOfDeath6.Subject = patient.AsReference(); causeOfDeath6.Performer.Add(practitioner.AsReference()); causeOfDeath6.ObservationCauseOfDeathCondition().Value = new CodeableConcept(null, null, "Fentanyl toxicity"); causeOfDeath6.ObservationCauseOfDeathCondition().IntervalString = "minutes to hours"; // Cause of Death Pathway List pathWayList = ListCauseOfDeathPathway.Create(); pathWayList.ListCauseOfDeathPathway().AddCauseOfDeathCondition(causeOfDeath1.AsReference()); pathWayList.ListCauseOfDeathPathway().AddCauseOfDeathCondition(causeOfDeath2.AsReference()); pathWayList.ListCauseOfDeathPathway().AddCauseOfDeathCondition(causeOfDeath3.AsReference()); pathWayList.ListCauseOfDeathPathway().AddCauseOfDeathCondition(causeOfDeath4.AsReference()); pathWayList.ListCauseOfDeathPathway().AddCauseOfDeathCondition(causeOfDeath5.AsReference()); //// // Demo: Total number of causes of death check // pathWayList.ListCauseOfDeathPathway().AddCauseOfDeathCondition(causeOfDeath6.AsReference()); pathWayList.Subject = patient.AsReference(); pathWayList.Source = practitioner.AsReference(); // Condition Contributing to Death Observation conditionContributingToDeath = ObservationConditionContributingToDeath.Create(); conditionContributingToDeath.Status = ObservationStatus.Final; conditionContributingToDeath.Subject = patient.AsReference(); conditionContributingToDeath.Performer.Add(practitioner.AsReference()); conditionContributingToDeath.ObservationConditionContributingToDeath().Value = new CodeableConcept(null, null, "Hypertensive heart disease"); // Location Death Location deathLocation = UsCoreLocation.Create(); deathLocation.Identifier.Add(new Identifier("http://www.acme.org/location", "29")); deathLocation.Status = Location.LocationStatus.Active; deathLocation.Name = "Atlanta GA Death Location - Freeman"; deathLocation.Address = new Address() { Use = Address.AddressUse.Home, Type = Address.AddressType.Physical, Line = new List<string>{ "400 Windstream Street" }, City = "Atlanta", District = "Fulton County", State = "GA", Country = "USA" }; // Observation Death Date Observation observationDeathDate = ObservationDeathDate.Create(); observationDeathDate.Subject = patient.AsReference(); observationDeathDate.Effective = new FhirDateTime("2022-01-08T15:30:00-05:00"); observationDeathDate.Value = new FhirDateTime("2022-01-08T14:04:00-05:00"); observationDeathDate.ObservationDeathDate().DateAndTimePronouncedDead = new FhirDateTime("2022-01-08T15:30:00-05:00"); observationDeathDate.ObservationDeathDate().ObservationLocation = deathLocation.AsReference(); observationDeathDate.Method = MdiCodeSystem.Exact; // Observation Death Injury/Event Occurred at Work Observation observationInjuryEventWork = ObservationDeathInjuryEventOccurredAtWork.Create(); observationInjuryEventWork.Status = ObservationStatus.Final; observationInjuryEventWork.Subject = patient.AsReference(); observationInjuryEventWork.Value = MdiVsYesNoNotApplicable.No; // Observation Death How Death Injury Occurred Observation observationHowDeathInjuryOccurred = ObservationHowDeathInjuryOccurred.Create(); observationHowDeathInjuryOccurred.Status = ObservationStatus.Final; observationHowDeathInjuryOccurred.Subject = patient.AsReference(); observationHowDeathInjuryOccurred.Effective = new FhirDateTime("2018-02-19T16:48:06-05:00"); observationHowDeathInjuryOccurred.Performer.Add(practitioner.AsReference()); observationHowDeathInjuryOccurred.Value = new FhirString("Ingested counterfeit medication"); // Observation Manner of Death Observation observationMannerOfDeath = ObservationMannerOfDeath.Create(); observationMannerOfDeath.Subject = patient.AsReference(); observationMannerOfDeath.Performer.Add(patient.AsReference()); observationMannerOfDeath.Value = MdiVsMannerOfDeath.AccidentalDeath; // Observation Decedent Pregnancy Observation observationDecedentPregnancy = ObservationDecedentPregnancy.Create(); observationDecedentPregnancy.Subject = patient.AsReference(); observationDecedentPregnancy.Value = MdiVsDeathPregnancyStatus.NA; // Observation Tobacco Use Contributed To Death Observation observationTobaccoUseContributedToDeath = ObservationTobaccoUseContributedToDeath.Create(); observationTobaccoUseContributedToDeath.Subject = patient.AsReference(); observationTobaccoUseContributedToDeath.Value = MdiVsContributoryTobaccoUse.No; //// // Composition of MDI to EDRS document Composition composition = CompositionMdiToEdrs.Create(); // Demo: Tracking numbers - one with library. the other for custom type composition.CompositionMdiToEdrs().MdiCaseNumber = "Case1234"; //// // demo: custom tracking number //Extension ext = new Extension() { Url = "http://hl7.org/fhir/us/mdi/StructureDefinition/Extension-tracking-number" }; //ext.Value = new Identifier() { Type = new CodeableConcept("http://terminology.hl7.org/CodeSystem/v2-0203", "BCT"), Value = "ME21-113" }; //composition.Extension.AddOrUpdateExtension(ext); composition.Identifier = new Identifier() { Value = "a03eab8c-11e8-4d0c-ad2a-b385395e27de" }; composition.Status = CompositionStatus.Final; composition.Subject = patient.AsReference(); composition.DateElement = new FhirDateTime("2022-02-20"); composition.Author = new List<ResourceReference> { practitioner.AsReference() }; composition.Title = "MDI to EDRS Composition"; composition.CompositionMdiToEdrs().Demographics = new Composition.SectionComponent() { Entry = new List<ResourceReference> { usualWorkObservation.AsReference() } }; composition.CompositionMdiToEdrs().Circumstances = new Composition.SectionComponent() { Entry = new List<ResourceReference> { deathLocation.AsReference(), observationInjuryEventWork.AsReference(), observationTobaccoUseContributedToDeath.AsReference(), observationDecedentPregnancy.AsReference() } }; composition.CompositionMdiToEdrs().Jurisdiction = new Composition.SectionComponent() { Entry = new List<ResourceReference> { observationDeathDate.AsReference() } }; composition.CompositionMdiToEdrs().CauseManner = new Composition.SectionComponent() { Entry = new List<ResourceReference> { pathWayList.AsReference(), conditionContributingToDeath.AsReference(), observationMannerOfDeath.AsReference(), observationHowDeathInjuryOccurred.AsReference() } }; composition.CompositionMdiToEdrs().MedicalHistory = new Composition.SectionComponent() { EmptyReason = new CodeableConcept("http://terminology.hl7.org/CodeSystem/list-empty-reason", "unavailable", "Unavailable", "Decedent's medical history not available"), Text = new Narrative() { Status = Narrative.NarrativeStatus.Additional, Div = "<div xmlns=\"http://www.w3.org/1999/xhtml\">\n <p>No Medical History information</p>\n </div>" } }; //// // Document Bundle Bundle MdiDocument = BundleDocumentMdiToEdrs.Create(); MdiDocument.Identifier = new Identifier("urn:ietf:rfc:3986", "urn:uuid:933dde44f7664b03a20b6324f23986c0"); MdiDocument.TimestampElement = Instant.Now(); MdiDocument.AddResourceEntry(composition, composition.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(patient, patient.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(practitioner, practitioner.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(usualWorkObservation, usualWorkObservation.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(deathLocation, deathLocation.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(observationInjuryEventWork, observationInjuryEventWork.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(observationTobaccoUseContributedToDeath, observationTobaccoUseContributedToDeath.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(observationDecedentPregnancy, observationDecedentPregnancy.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(observationDeathDate, observationDeathDate.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(pathWayList, pathWayList.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(causeOfDeath1, causeOfDeath1.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(causeOfDeath2, causeOfDeath2.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(causeOfDeath3, causeOfDeath3.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(causeOfDeath4, causeOfDeath4.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(causeOfDeath5, causeOfDeath5.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(conditionContributingToDeath, conditionContributingToDeath.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(observationMannerOfDeath, observationMannerOfDeath.AsReference().Url.ToString()); MdiDocument.AddResourceEntry(observationHowDeathInjuryOccurred, observationHowDeathInjuryOccurred.AsReference().Url.ToString()); string output = serializer.SerializeToString(MdiDocument); File.WriteAllText(outputPath + "MDItoEDRS_Document.json", output); Console.WriteLine(output); /////////////////////////// Toxicology Lab Report /////////////////////////////// // Specimen for Toxicology Specimen specimenBlood = SpecimenToxicologyLab.Create(); specimenBlood.Subject = patient.AsReference(); specimenBlood.AccessionIdentifier = new Identifier("http://lab.acme.org/specimens/2021", "X352356"); specimenBlood.Status = Specimen.SpecimenStatus.Available; specimenBlood.Type = new CodeableConcept("http://snomed.info/sct", "258580003", "Whole blood sample (specimen)", "Whole blood sample (specimen)"); specimenBlood.ReceivedTimeElement = new FhirDateTime("2021-12-03T16:00:00Z"); specimenBlood.Collection = new Specimen.CollectionComponent() { Collected = new FhirDateTime("2021-12-03T11:00:00Z"), BodySite = new CodeableConcept("http://snomed.info/sct", "83419000", "Femoral vein structure (body structure)", null) }; specimenBlood.Container.Add(new Specimen.ContainerComponent() { Description = "10mL GT tube", Type = new CodeableConcept("http://snomed.info/sct", "702287009", "Non - evacuated blood collection tube, potassium oxalate / sodium fluoride(physical object)", "GT tube"), SpecimenQuantity = new Quantity() { Value = 20, Unit = "ml" } }); Specimen specimenUrine = SpecimenToxicologyLab.Create(); specimenUrine.Subject = patient.AsReference(); specimenUrine.AccessionIdentifier = new Identifier("http://lab.acme.org/specimens/2021", "ZZZ352356"); specimenUrine.Status = Specimen.SpecimenStatus.Available; specimenUrine.Type = new CodeableConcept("http://snomed.info/sct", "122575003", "Urine specimen (specimen)", "Urine specimen (specimen)"); specimenUrine.ReceivedTimeElement = new FhirDateTime("2021-12-03T16:00:00Z"); specimenUrine.Collection = new Specimen.CollectionComponent() { Collected = new FhirDateTime("2021-12-03T11:00:00Z"), BodySite = new CodeableConcept("http://snomed.info/sct", "83419000", "Femoral vein structure (body structure)", null) }; specimenUrine.Container.Add(new Specimen.ContainerComponent() { Description = "10mL RT tube", SpecimenQuantity = new Quantity() { Value = 5, Unit = "ml" } }); Specimen specimenVitreousHumor = SpecimenToxicologyLab.Create(); specimenVitreousHumor.Subject = patient.AsReference(); specimenVitreousHumor.AccessionIdentifier = new Identifier("http://lab.acme.org/specimens/2021", "XXX352356"); specimenVitreousHumor.Status = Specimen.SpecimenStatus.Available; specimenVitreousHumor.Type = new CodeableConcept("http://snomed.info/sct", "258438000", "Vitreous humor sample (specimen)", "Vitreous humor sample (specimen)"); specimenVitreousHumor.ReceivedTimeElement = new FhirDateTime("2021-12-03T16:00:00Z"); specimenVitreousHumor.Collection = new Specimen.CollectionComponent() { Collected = new FhirDateTime("2021-12-03T11:00:00Z"), BodySite = new CodeableConcept("http://snomed.info/sct", "83419000", "Femoral vein structure (body structure)", null) }; specimenVitreousHumor.Container.Add(new Specimen.ContainerComponent() { Description = "10mL RT tube", SpecimenQuantity = new Quantity() { Value = 3, Unit = "ml" } }); Specimen specimenBile = SpecimenToxicologyLab.Create(); specimenBile.Subject = patient.AsReference(); specimenBile.AccessionIdentifier = new Identifier("http://lab.acme.org/specimens/2021", "OO352356"); specimenBile.Status = Specimen.SpecimenStatus.Available; specimenBile.Type = new CodeableConcept("http://snomed.info/sct", "119341000", "Bile specimen (specimen)", "Bile specimen (specimen)"); specimenBile.ReceivedTimeElement = new FhirDateTime("2021-12-03T16:00:00Z"); specimenBile.Container.Add(new Specimen.ContainerComponent() { Description = "3mL sample of bile specimen", SpecimenQuantity = new Quantity() { Value = 3, Unit = "ml" } }); Specimen specimenLiver = SpecimenToxicologyLab.Create(); specimenLiver.Subject = patient.AsReference(); specimenLiver.AccessionIdentifier = new Identifier("http://lab.acme.org/specimens/2021", "DD352356"); specimenLiver.Status = Specimen.SpecimenStatus.Available; specimenLiver.Type = new CodeableConcept("http://snomed.info/sct", "119379005", "Tissue specimen from liver (specimen)", "Tissue specimen from liver (specimen)"); specimenLiver.ReceivedTimeElement = new FhirDateTime("2021-12-03T16:00:00Z"); specimenLiver.Container.Add(new Specimen.ContainerComponent() { Description = "5mL sample of liver specimen", SpecimenQuantity = new Quantity() { Value = 5, Unit = "ml" } }); Specimen specimenStomachContents = SpecimenToxicologyLab.Create(); specimenStomachContents.Subject = patient.AsReference(); specimenStomachContents.AccessionIdentifier = new Identifier("http://lab.acme.org/specimens/2021", "MM352356"); specimenStomachContents.Status = Specimen.SpecimenStatus.Available; specimenStomachContents.Type = new CodeableConcept("http://snomed.info/sct", "258580003", "Specimen from stomach (specimen)", "Specimen from stomach (specimen)"); specimenStomachContents.ReceivedTimeElement = new FhirDateTime("2021-12-03T16:00:00Z"); specimenStomachContents.Collection = new Specimen.CollectionComponent() { Collected = new FhirDateTime("2021-12-03T11:00:00Z"), BodySite = new CodeableConcept("http://snomed.info/sct", "83419000", "Femoral vein structure (body structure)", null) }; specimenStomachContents.Container.Add(new Specimen.ContainerComponent() { Description = "60mL sample of stomach contents specimen", SpecimenQuantity = new Quantity() { Value = 60, Unit = "ml" } }); // Toxicology Lab Results to MDI Observation toxLabResultEthanolBlood = ObservationToxicologyLabResult.Create(); toxLabResultEthanolBlood.Status = ObservationStatus.Final; toxLabResultEthanolBlood.Code = new CodeableConcept("http://loinc.org", "56478-1", "Ethanol [Mass/volume] in Blood by Gas chromatography", "Ethanol [Mass/volume] in Blood by Gas chromatography"); toxLabResultEthanolBlood.Subject = patient.AsReference(); toxLabResultEthanolBlood.Effective = new FhirDateTime("2021-12-03"); toxLabResultEthanolBlood.Value = new Quantity() { Value = new Decimal(0.145), Unit = "g/dL", System = "http://unitsofmeasure.org" }; toxLabResultEthanolBlood.Specimen = specimenBlood.AsReference(); Observation toxLabResult4anppBlood = ObservationToxicologyLabResult.Create(); toxLabResult4anppBlood.Status = ObservationStatus.Final; toxLabResult4anppBlood.Code = new CodeableConcept("http://loinc.org", "11072-6", "Despropionylfentanyl [Mass/volume] in Serum or Plasma", "Despropionylfentanyl [Mass/volume] in Serum or Plasma"); toxLabResult4anppBlood.Subject = patient.AsReference(); toxLabResult4anppBlood.Effective = new FhirDateTime("2021-12-03"); toxLabResult4anppBlood.Value = new FhirBoolean(true); toxLabResult4anppBlood.Specimen = specimenBlood.AsReference(); Observation toxLabResultAcetylfentanylBlood = ObservationToxicologyLabResult.Create(); toxLabResultAcetylfentanylBlood.Status = ObservationStatus.Final; toxLabResultAcetylfentanylBlood.Code = new CodeableConcept("http://loinc.org", "86223-5", "Acetyl norfentanyl [Mass/volume] in Serum, Plasma or Blood by Confirmatory method", "Acetyl norfentanyl [Mass/volume] in Serum, Plasma or Blood by Confirmatory method"); toxLabResultAcetylfentanylBlood.Subject = patient.AsReference(); toxLabResultAcetylfentanylBlood.Effective = new FhirDateTime("2021-12-03"); toxLabResultAcetylfentanylBlood.Value = new Quantity() { Value = 2, Unit = "ng/mL", System = "http://unitsofmeasure.org" }; toxLabResultAcetylfentanylBlood.Specimen = specimenBlood.AsReference(); Observation toxLabResultFentanylBlood = ObservationToxicologyLabResult.Create(); toxLabResultFentanylBlood.Status = ObservationStatus.Final; toxLabResultFentanylBlood.Code = new CodeableConcept("http://loinc.org", "73938-3", "fentaNYL [Mass/volume] in Blood by Confirmatory method", "fentaNYL [Mass/volume] in Blood by Confirmatory method"); toxLabResultFentanylBlood.Subject = patient.AsReference(); toxLabResultFentanylBlood.Effective = new FhirDateTime("2021-12-03"); toxLabResultFentanylBlood.Value = new Quantity() { Value = 23, Unit = "ng/mL", System = "http://unitsofmeasure.org" }; toxLabResultFentanylBlood.Specimen = specimenBlood.AsReference(); Observation toxLabResultEthanolUrine = ObservationToxicologyLabResult.Create(); toxLabResultEthanolUrine.Status = ObservationStatus.Final; toxLabResultEthanolUrine.Code = new CodeableConcept("http://loinc.org", "46983-3", "Ethanol [Mass/volume] in Urine by Confirmatory method", "Ethanol [Mass/volume] in Urine by Confirmatory method"); toxLabResultEthanolUrine.Subject = patient.AsReference(); toxLabResultEthanolUrine.Effective = new FhirDateTime("2021-12-03"); toxLabResultEthanolUrine.Value = new Quantity() { Value = new Decimal(0.16), Unit = "g/dL", System = "http://unitsofmeasure.org" }; toxLabResultEthanolUrine.Specimen = specimenUrine.AsReference(); Observation toxLabResult4anppUrine = ObservationToxicologyLabResult.Create(); toxLabResult4anppUrine.Status = ObservationStatus.Final; toxLabResult4anppUrine.Code = new CodeableConcept("http://loinc.org", "11072-6", "Despropionylfentanyl [Mass/volume] in Serum or Plasma", "Despropionylfentanyl [Mass/volume] in Serum or Plasma"); toxLabResult4anppUrine.Subject = patient.AsReference(); toxLabResult4anppUrine.Effective = new FhirDateTime("2021-12-03"); toxLabResult4anppUrine.Value = new FhirBoolean(true); toxLabResult4anppUrine.Specimen = specimenUrine.AsReference(); Observation toxLabResultAcetylfentanylUrine = ObservationToxicologyLabResult.Create(); toxLabResultAcetylfentanylUrine.Status = ObservationStatus.Final; toxLabResultAcetylfentanylUrine.Code = new CodeableConcept("http://loinc.org", "74810-3", "Acetyl fentanyl [Presence] in Urine by Confirmatory method", "Acetyl fentanyl [Presence] in Urine by Confirmatory method"); toxLabResultAcetylfentanylUrine.Subject = patient.AsReference(); toxLabResultAcetylfentanylUrine.Effective = new FhirDateTime("2021-12-03"); toxLabResultAcetylfentanylUrine.Value = new FhirBoolean(true); toxLabResultAcetylfentanylUrine.Specimen = specimenUrine.AsReference(); Observation toxLabResultFentanylUrine = ObservationToxicologyLabResult.Create(); toxLabResultFentanylUrine.Status = ObservationStatus.Final; toxLabResultFentanylUrine.Code = new CodeableConcept("http://loinc.org", "11235-9", "fentaNYL [Presence] in Urine", "fentaNYL [Presence] in Urine"); toxLabResultFentanylUrine.Subject = patient.AsReference(); toxLabResultFentanylUrine.Effective = new FhirDateTime("2021-12-03"); toxLabResultFentanylUrine.Value = new FhirBoolean(true); toxLabResultFentanylUrine.Specimen = specimenUrine.AsReference(); Observation toxLabResultNorfentanylUrine = ObservationToxicologyLabResult.Create(); toxLabResultNorfentanylUrine.Status = ObservationStatus.Final; toxLabResultNorfentanylUrine.Code = new CodeableConcept("http://loinc.org", "43199-9", "Norfentanyl [Presence] in Urine", "Norfentanyl [Presence] in Urine"); toxLabResultNorfentanylUrine.Subject = patient.AsReference(); toxLabResultNorfentanylUrine.Effective = new FhirDateTime("2021-12-03"); toxLabResultNorfentanylUrine.Value = new FhirBoolean(true); toxLabResultNorfentanylUrine.Specimen = specimenUrine.AsReference(); Observation toxLabResultXylazineUrine = ObservationToxicologyLabResult.Create(); toxLabResultXylazineUrine.Status = ObservationStatus.Final; toxLabResultXylazineUrine.Code = new CodeableConcept("http://loinc.org", "12327-3", "Ketamine [Presence] in Urine", "Ketamine [Presence] in Urine"); toxLabResultXylazineUrine.Subject = patient.AsReference(); toxLabResultXylazineUrine.Effective = new FhirDateTime("2021-12-03"); toxLabResultXylazineUrine.Value = new FhirBoolean(true); toxLabResultXylazineUrine.Specimen = specimenUrine.AsReference(); Observation toxLabResultEthanolVitreousHumor = ObservationToxicologyLabResult.Create(); toxLabResultEthanolVitreousHumor.Status = ObservationStatus.Final; toxLabResultEthanolVitreousHumor.Code = new CodeableConcept("http://loinc.org", "12465-1", "Ethanol [Mass/volume] in Vitreous fluid", "Ethanol [Mass/volume] in Vitreous fluid"); toxLabResultEthanolVitreousHumor.Subject = patient.AsReference(); toxLabResultEthanolVitreousHumor.Effective = new FhirDateTime("2021-12-03"); toxLabResultEthanolVitreousHumor.Value = new Quantity() { Value = new Decimal(0.133), Unit = "g/dL", System = "http://unitsofmeasure.org" }; toxLabResultEthanolVitreousHumor.Specimen = specimenVitreousHumor.AsReference(); // Us Core Practitioner (Tox Lab) Practitioner practitionerToxLab = UsCorePractitioner.Create(); practitionerToxLab.Name = new List<HumanName> { new HumanName() { Use = HumanName.NameUse.Official, Family = "Goldberger", GivenElement = new List<FhirString> { new FhirString("Bruce") }, PrefixElement = new List<FhirString> { new FhirString("Dr") } } }; practitionerToxLab.UsCorePractitioner().NPI = "555667777"; // Us Core Lab Organization Organization organizationLab = UsCoreOrganization.Create(); organizationLab.Identifier.AddOrUpdateIdentifier(UsCoreOrganization.NPISystem, "111223333"); organizationLab.Active = true; organizationLab.Type.Add(new CodeableConcept("http://terminology.hl7.org/CodeSystem/organization-type", "prov", "Healthcare Provider", null)); organizationLab.Name = "UF Health Pathology Labs, Forensic Toxicology Laboratory"; organizationLab.Telecom.AddTelecom(ContactPoint.ContactPointSystem.Phone, ContactPoint.ContactPointUse.Work, "(352) 265-9900"); organizationLab.Address.Add(new Address() { Line = new List<String> { "4800 SW 35th Drive" }, City = "Gainesville", State = "FL", PostalCode = "32608", Country = "USA" }); // Us Core Diagnostic Report for Tox Lab Results DiagnosticReport diagnosticReport = DiagnosticReportToxicologyLabResultToMdi.Create(); diagnosticReport.DiagnosticReportToxicologyLabResultToMdi().ToxCaseNumber = ("http://uf-path-labs.org/fhir/lab-cases", "R21-01578"); diagnosticReport.Identifier.GetIdentifier(MdiCodeSystem.ToxLabCaseNumber.Coding[0]).Assigner = organizationLab.AsReference(); diagnosticReport.Status = DiagnosticReport.DiagnosticReportStatus.Final; diagnosticReport.Code = new CodeableConcept("http://loinc.org", "81273-5", "fentaNYL and Norfentanyl panel - Specimen", null); diagnosticReport.Subject = patient.AsReference(); if (patient.Name != null) { diagnosticReport.Subject.Display = patient.Name[0].Family + ", " + patient.Name[0].GivenElement[0]; } diagnosticReport.Effective = new FhirDateTime("2021-12-03T11:00:00Z"); diagnosticReport.IssuedElement = new Instant() { Value = new FhirDateTime("2022-01-05T11:00:00Z").ToDateTimeOffset(new TimeSpan()) }; diagnosticReport.Performer.Add(practitionerToxLab.AsReference()); diagnosticReport.Specimen.Add(specimenBlood.AsReference(specimenBlood.Type.Text)); diagnosticReport.Specimen.Add(specimenUrine.AsReference(specimenUrine.Type.Text)); diagnosticReport.Specimen.Add(specimenVitreousHumor.AsReference(specimenVitreousHumor.Type.Text)); diagnosticReport.Specimen.Add(specimenBile.AsReference(specimenBile.Type.Text)); diagnosticReport.Specimen.Add(specimenLiver.AsReference(specimenLiver.Type.Text)); diagnosticReport.Specimen.Add(specimenStomachContents.AsReference(specimenStomachContents.Type.Text)); diagnosticReport.Result.Add(toxLabResultEthanolBlood.AsReference(toxLabResultEthanolBlood.Code.Text)); diagnosticReport.Result.Add(toxLabResult4anppBlood.AsReference(toxLabResult4anppBlood.Code.Text)); diagnosticReport.Result.Add(toxLabResultAcetylfentanylBlood.AsReference(toxLabResultAcetylfentanylBlood.Code.Text)); diagnosticReport.Result.Add(toxLabResultFentanylBlood.AsReference(toxLabResultFentanylBlood.Code.Text)); diagnosticReport.Result.Add(toxLabResultEthanolUrine.AsReference(toxLabResultEthanolUrine.Code.Text)); diagnosticReport.Result.Add(toxLabResult4anppUrine.AsReference(toxLabResult4anppUrine.Code.Text)); diagnosticReport.Result.Add(toxLabResultAcetylfentanylUrine.AsReference(toxLabResultAcetylfentanylUrine.Code.Text)); diagnosticReport.Result.Add(toxLabResultFentanylUrine.AsReference(toxLabResultFentanylUrine.Code.Text)); diagnosticReport.Result.Add(toxLabResultNorfentanylUrine.AsReference(toxLabResultNorfentanylUrine.Code.Text)); diagnosticReport.Result.Add(toxLabResultXylazineUrine.AsReference(toxLabResultXylazineUrine.Code.Text)); diagnosticReport.Result.Add(toxLabResultEthanolVitreousHumor.AsReference(toxLabResultEthanolVitreousHumor.Code.Text)); MessageHeader messageHeader = MessageHeaderToxicologyToMdi.Create(); messageHeader.Source = new MessageHeader.MessageSourceComponent() { Name = "University of Florida Pathology Labs, Forensic Toxicology Laboratory", Software = "MS Access", Version = "1.2.3", Contact = new ContactPoint(ContactPoint.ContactPointSystem.Phone, null, "+1 (555) 123 4567"), Endpoint = "http://uf.org/access/endpoint/1" }; messageHeader.Focus.Add(diagnosticReport.AsReference()); // Tox Report Bundle Bundle bundleMessageToxToMDI = BundleMessageToxicologyToMdi.Create(); bundleMessageToxToMDI.Identifier = new Identifier("urn:ietf:rfc:3986", "urn:uuid:683dde44f7664b03a20b6324f23986d9"); bundleMessageToxToMDI.AddResourceEntry(messageHeader, messageHeader.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(diagnosticReport, diagnosticReport.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(patient, patient.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(practitionerToxLab, practitionerToxLab.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(organizationLab, organizationLab.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(specimenBlood, specimenBlood.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(specimenUrine, specimenUrine.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(specimenVitreousHumor, specimenVitreousHumor.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(specimenBile, specimenBile.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(specimenLiver, specimenLiver.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(specimenStomachContents, specimenStomachContents.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(toxLabResultEthanolBlood, toxLabResultEthanolBlood.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(toxLabResult4anppBlood, toxLabResult4anppBlood.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(toxLabResultAcetylfentanylBlood, toxLabResultAcetylfentanylBlood.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(toxLabResultFentanylBlood, toxLabResultFentanylBlood.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(toxLabResultEthanolUrine, toxLabResultEthanolUrine.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(toxLabResult4anppUrine, toxLabResult4anppUrine.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(toxLabResultAcetylfentanylUrine, toxLabResultAcetylfentanylUrine.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(toxLabResultFentanylUrine, toxLabResultFentanylUrine.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(toxLabResultNorfentanylUrine, toxLabResultNorfentanylUrine.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(toxLabResultXylazineUrine, toxLabResultXylazineUrine.AsReference().Url.ToString()); bundleMessageToxToMDI.AddResourceEntry(toxLabResultEthanolVitreousHumor, toxLabResultEthanolVitreousHumor.AsReference().Url.ToString()); output = serializer.SerializeToString(bundleMessageToxToMDI); File.WriteAllText(outputPath + "ToxToCMS_Message.json", output); Console.WriteLine(output); } } }
84.825263
473
0.723444
[ "Apache-2.0" ]
mmg-fhir-ig/cbs-ig-dotnet
src/MdiExample/Program.cs
40,294
C#
using System.Collections.Generic; using ET; namespace Client.Event { public struct GuildApplicationChanged : IEventHandle { public IReadOnlyList<ApplicationInfo> ApplicationInfos; public GuildApplicationChanged(List<ApplicationInfo> list) { ApplicationInfos = list.AsReadOnly(); } } }
24.428571
66
0.687135
[ "MIT" ]
Noname-Studio/ET
Unity/Assets/Scripts/Client/Event/GuildApplicationChanged.cs
344
C#
namespace SWB_Base { public struct ScreenShake { public float Length; public float Speed; public float Size; public float Rotation; } }
13.454545
26
0.722973
[ "Apache-2.0" ]
kidfearless/kfgo
code/swb_base/structures/ScreenShake.cs
150
C#
// <auto-generated /> using System; using InventoryManager.EntityFramework; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace InventoryManager.EntityFramework.Migrations { [DbContext(typeof(InventoryManagerDbContext))] partial class InventoryManagerDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "5.0.0"); modelBuilder.Entity("InventoryManager.Domain.Models.Item", b => { b.Property<Guid>("id") .ValueGeneratedOnAdd() .HasColumnType("TEXT"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("TEXT"); b.HasKey("id"); b.ToTable("Items"); b.HasDiscriminator<string>("Discriminator").HasValue("Item"); }); modelBuilder.Entity("InventoryManager.Domain.Models.StorableItem", b => { b.HasBaseType("InventoryManager.Domain.Models.Item"); b.Property<Guid?>("Containerid") .HasColumnType("TEXT"); b.HasIndex("Containerid"); b.HasDiscriminator().HasValue("StorableItem"); }); modelBuilder.Entity("InventoryManager.Domain.Models.Container", b => { b.HasBaseType("InventoryManager.Domain.Models.StorableItem"); b.Property<bool>("IsRootContainer") .HasColumnType("INTEGER"); b.Property<double>("MaximumCarryWeight") .HasColumnType("REAL"); b.Property<string>("NickName") .IsRequired() .HasColumnType("TEXT"); b.HasDiscriminator().HasValue("Container"); }); modelBuilder.Entity("InventoryManager.Domain.Models.StorableItem", b => { b.HasOne("InventoryManager.Domain.Models.Container", null) .WithMany("Inventory") .HasForeignKey("Containerid"); }); modelBuilder.Entity("InventoryManager.Domain.Models.Container", b => { b.Navigation("Inventory"); }); #pragma warning restore 612, 618 } } }
34.1
83
0.527493
[ "MIT" ]
Pat02/InventoryManager
InventoryManager.EntityFramework/Migrations/InventoryManagerDbContextModelSnapshot.cs
2,730
C#
using System.Linq; using System.Threading.Tasks; using AElf.ContractTestKit; using AElf.CSharp.Core.Extension; using AElf.Kernel; using AElf.Sdk.CSharp; using AElf.Types; using Shouldly; using Xunit; namespace AElf.Contracts.Vote { public partial class VoteTests { [Fact] public async Task VoteContract_Register_Again_Test() { var votingItem = await RegisterVotingItemAsync(10, 4, true, DefaultSender, 10); var transactionResult = (await VoteContractStub.Register.SendWithExceptionAsync(new VotingRegisterInput { // Basically same as previous one. TotalSnapshotNumber = votingItem.TotalSnapshotNumber, StartTimestamp = votingItem.StartTimestamp, EndTimestamp = votingItem.EndTimestamp, Options = {votingItem.Options}, AcceptedCurrency = votingItem.AcceptedCurrency, IsLockToken = votingItem.IsLockToken })).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.ShouldContain("Voting item already exists"); } [Fact] public async Task VoteContract_Register_CurrencyNotSupportVoting_Test() { var startTime = TimestampHelper.GetUtcNow(); var input = new VotingRegisterInput { TotalSnapshotNumber = 5, EndTimestamp = startTime.AddDays(100), StartTimestamp = startTime, Options = { GenerateOptions(3) }, AcceptedCurrency = "USDT", IsLockToken = true }; var transactionResult = (await VoteContractStub.Register.SendWithExceptionAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.Contains("Claimed accepted token is not available for voting").ShouldBeTrue(); } [Fact] public async Task VoteContract_Vote_NotSuccess_Test() { //did not find related vote event { var input = new VoteInput { VotingItemId = HashHelper.ComputeFrom("hash") }; var transactionResult = (await VoteContractStub.Vote.SendWithExceptionAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.Contains("Voting item not found").ShouldBeTrue(); } //without such option { var votingItem = await RegisterVotingItemAsync(100, 4, true, DefaultSender, 2); var input = new VoteInput { VotingItemId = votingItem.VotingItemId, Option = "Somebody" }; var otherKeyPair = Accounts[1].KeyPair; var otherVoteStub = GetVoteContractTester(otherKeyPair); var transactionResult = (await otherVoteStub.Vote.SendWithExceptionAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.ShouldContain($"Option {input.Option} not found"); } //not enough token { var votingItemId = await RegisterVotingItemAsync(100, 4, true, DefaultSender, 2); var input = new VoteInput { VotingItemId = votingItemId.VotingItemId, Option = votingItemId.Options.First(), Amount = 2000_000_000_00000000L }; var otherKeyPair = Accounts[1].KeyPair; var otherVoteStub = GetVoteContractTester(otherKeyPair); var transactionResult = (await otherVoteStub.Vote.SendWithExceptionAsync(input)).TransactionResult; transactionResult.Status.ShouldBe(TransactionResultStatus.Failed); transactionResult.Error.ShouldContain("Insufficient balance"); } } } }
40.513761
118
0.579257
[ "MIT" ]
AElfProject/AElf
test/AElf.Contracts.Vote.Tests/GQL/BasicTests.cs
4,416
C#
using System; using Rv = TIBCO.Rendezvous; namespace Messaging.TibcoRv { public static class Extensions { public static void Dispose(this Rv.Listener listener) { if (listener == null) return; try { listener.Destroy(); } catch { // Dispose methods must not throw exceptions } GC.SuppressFinalize(listener); // RV does not do this, so we have to } public static void Dispose(this Rv.Transport transport) { if (transport == null) return; try { transport.Destroy(); } catch { // Dispose methods must not throw exceptions } GC.SuppressFinalize(transport); // RV does not do this, so we have to } } }
23.170732
82
0.463158
[ "Apache-2.0" ]
SammyEnigma/Messaging
Messaging.TibcoRv/Extensions.cs
952
C#
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.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace TaxCalculatorForm { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private double grossIncome; private double totalDeductions; private TaxCalculator taxCalculator; public MainWindow() { InitializeComponent(); grossIncome = 0; totalDeductions = 0; standardDeductionRadioButton.IsChecked = true; UpdateTaxSummary(); } private void Button_Click(object sender, RoutedEventArgs e) { grossIncome += Convert.ToDouble(incomeTextBox.Text); grossIncomeLabel.Content = $"Gross Income: ${grossIncome}"; UpdateTaxSummary(); } private void standardDeductionButton_Checked(object sender, RoutedEventArgs e) { totalDeductions = 12200; UpdateTotalDeductionsLabel(); } private void itemizeDeductionsButton_Checked(object sender, RoutedEventArgs e) { totalDeductions = 0; UpdateTotalDeductionsLabel(); } private void Button_Click_1(object sender, RoutedEventArgs e) { totalDeductions += Convert.ToDouble(deductionsTextBox.Text); UpdateTotalDeductionsLabel(); } private void UpdateTotalDeductionsLabel() { totalDeductionsLabel.Content = $"Total Deductions: ${totalDeductions}"; UpdateTaxSummary(); } private void UpdateTaxSummary() { taxCalculator = new TaxCalculator(grossIncome, totalDeductions); taxSummary.Content = ""; taxSummary.Content +=($"Taxes owed at 10%: ${taxCalculator.TaxesOwedAt10Percent}{Environment.NewLine}"); taxSummary.Content +=($"Taxes owed at 12%: ${taxCalculator.TaxesOwedAt12Percent}{Environment.NewLine}"); taxSummary.Content +=($"Taxes owed at 22%: ${taxCalculator.TaxesOwedAt22Percent}{Environment.NewLine}"); taxSummary.Content +=($"Taxes owed at 24%: ${taxCalculator.TaxesOwedAt24Percent}{Environment.NewLine}"); taxSummary.Content +=($"Taxes owed at 32%: ${taxCalculator.TaxesOwedAt32Percent}{Environment.NewLine}"); taxSummary.Content +=($"Taxes owed at 35%: ${taxCalculator.TaxesOwedAt35Percent}{Environment.NewLine}"); taxSummary.Content +=($"Taxes owed at 37%: ${taxCalculator.TaxesOwedAt37Percent}{Environment.NewLine}"); taxSummary.Content +=($"Total taxes owed: ${taxCalculator.TotalTaxesOwed}{Environment.NewLine}"); taxSummary.Content +=($"Taxes as percetnage of gross income: {taxCalculator.TaxesAsPercentageOfGrossIncome}%{Environment.NewLine}"); taxSummary.Content +=($"Taxes as percetnage of adjusted gross income: {taxCalculator.TaxesAsPercentageOfAGI}%{Environment.NewLine}"); } } }
39.188235
145
0.663164
[ "MIT" ]
EricCharnesky/CIS297-Winter2020
TaxCalculatorForm/TaxCalculatorForm/MainWindow.xaml.cs
3,333
C#
namespace TrabalhoEngenhariaFinanceiro { partial class BuscaFornecedor { /// <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(); this.label1 = new System.Windows.Forms.Label(); this.tb_NomeForn = new System.Windows.Forms.TextBox(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.idForn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.nome = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.fornecedorBindingSource = new System.Windows.Forms.BindingSource(this.components); this.bancoFinanceiroDataSet2 = new TrabalhoEngenhariaFinanceiro.BancoFinanceiroDataSet2(); this.btn_Sair = new System.Windows.Forms.Button(); this.fornecedorTableAdapter = new TrabalhoEngenhariaFinanceiro.BancoFinanceiroDataSet2TableAdapters.FornecedorTableAdapter(); this.btn_Selecionar = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.fornecedorBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.bancoFinanceiroDataSet2)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 34); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(38, 13); this.label1.TabIndex = 0; this.label1.Text = "Nome:"; // // tb_NomeForn // this.tb_NomeForn.Location = new System.Drawing.Point(56, 31); this.tb_NomeForn.Name = "tb_NomeForn"; this.tb_NomeForn.Size = new System.Drawing.Size(305, 20); this.tb_NomeForn.TabIndex = 1; this.tb_NomeForn.TextChanged += new System.EventHandler(this.tb_NomeForn_TextChanged); // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToDeleteRows = false; this.dataGridView1.AutoGenerateColumns = false; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.idForn, this.nome}); this.dataGridView1.DataSource = this.fornecedorBindingSource; this.dataGridView1.Location = new System.Drawing.Point(12, 60); this.dataGridView1.MultiSelect = false; this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.ReadOnly = true; this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView1.Size = new System.Drawing.Size(349, 290); this.dataGridView1.TabIndex = 2; this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellContentClick); // // idForn // this.idForn.DataPropertyName = "IdForn"; this.idForn.HeaderText = "IdForn"; this.idForn.Name = "idForn"; this.idForn.ReadOnly = true; // // nome // this.nome.DataPropertyName = "nome"; this.nome.HeaderText = "nome"; this.nome.Name = "nome"; this.nome.ReadOnly = true; this.nome.Width = 200; // // fornecedorBindingSource // this.fornecedorBindingSource.DataMember = "Fornecedor"; this.fornecedorBindingSource.DataSource = this.bancoFinanceiroDataSet2; // // bancoFinanceiroDataSet2 // this.bancoFinanceiroDataSet2.DataSetName = "BancoFinanceiroDataSet2"; this.bancoFinanceiroDataSet2.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // btn_Sair // this.btn_Sair.Location = new System.Drawing.Point(296, 356); this.btn_Sair.Name = "btn_Sair"; this.btn_Sair.Size = new System.Drawing.Size(75, 23); this.btn_Sair.TabIndex = 4; this.btn_Sair.Text = "&Sair"; this.btn_Sair.UseVisualStyleBackColor = true; this.btn_Sair.Click += new System.EventHandler(this.btn_Sair_Click); // // fornecedorTableAdapter // this.fornecedorTableAdapter.ClearBeforeFill = true; // // btn_Selecionar // this.btn_Selecionar.Location = new System.Drawing.Point(215, 356); this.btn_Selecionar.Name = "btn_Selecionar"; this.btn_Selecionar.Size = new System.Drawing.Size(75, 23); this.btn_Selecionar.TabIndex = 5; this.btn_Selecionar.Text = "&Selecionar"; this.btn_Selecionar.UseVisualStyleBackColor = true; this.btn_Selecionar.Click += new System.EventHandler(this.btn_Selecionar_Click); // // BuscaFornecedor // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(383, 391); this.Controls.Add(this.btn_Selecionar); this.Controls.Add(this.btn_Sair); this.Controls.Add(this.dataGridView1); this.Controls.Add(this.tb_NomeForn); this.Controls.Add(this.label1); this.Name = "BuscaFornecedor"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "BuscaFornecedor"; this.Load += new System.EventHandler(this.BuscaFornecedor_Load); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.fornecedorBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.bancoFinanceiroDataSet2)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox tb_NomeForn; private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.Button btn_Sair; private BancoFinanceiroDataSet2 bancoFinanceiroDataSet2; private System.Windows.Forms.BindingSource fornecedorBindingSource; private BancoFinanceiroDataSet2TableAdapters.FornecedorTableAdapter fornecedorTableAdapter; private System.Windows.Forms.Button btn_Selecionar; private System.Windows.Forms.DataGridViewTextBoxColumn idForn; private System.Windows.Forms.DataGridViewTextBoxColumn nome; } }
48.185629
142
0.624581
[ "MIT" ]
biancabarbosa23/Sistema-Financeiro
TrabalhoEngenhariaFinanceiro/BuscaFornecedor.Designer.cs
8,049
C#
using FluentValidation.Results; using MultiTenant.SaaS.DatabaseTenancy.Pattern.Sample.Domain.Commands; using MultiTenant.SaaS.DatabaseTenancy.Pattern.Sample.Domain.Validators; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace DomainTests.Validators { public class SubscribeCommandValidatorTest { private SubscribeCommandValidator validator; public SubscribeCommandValidatorTest() { this.validator = new SubscribeCommandValidator(); } [Fact] public async Task Fails_When_CorrelationId_Is_Empty() { SubscribeCommand command = new SubscribeCommand() { CorrelationId = Guid.Empty, Id = Guid.NewGuid(), Amount = 100.00m, }; ValidationResult expected = new ValidationResult(); ValidationFailure failure = new ValidationFailure("CorrelationId", "CorrelationId is required"); expected.Errors.Add(failure); ValidationResult result = await this.validator.ValidateAsync(command).ConfigureAwait(false); Assert.NotNull(result); Assert.NotNull(result.Errors); Assert.False(result.IsValid); Assert.True(result.Errors.Count > 0); Assert.Equal(expected.Errors.First().ErrorMessage, result.Errors.First().ErrorMessage); } [Fact] public async Task Fails_When_UserId_Is_Empty() { SubscribeCommand command = new SubscribeCommand() { CorrelationId = Guid.NewGuid(), Id = Guid.Empty, }; ValidationResult expected = new ValidationResult(); ValidationFailure failure = new ValidationFailure("UserId", "UserId is required"); expected.Errors.Add(failure); ValidationResult result = await this.validator.ValidateAsync(command).ConfigureAwait(false); Assert.NotNull(result); Assert.NotNull(result.Errors); Assert.False(result.IsValid); Assert.True(result.Errors.Count > 0); Assert.Equal(expected.Errors.First().ErrorMessage, result.Errors.First().ErrorMessage); } [Fact] public async Task Fails_When_Amount_IsNot_Positive() { SubscribeCommand command = new SubscribeCommand() { CorrelationId = Guid.NewGuid(), Id = Guid.NewGuid(), Amount = 0.0m }; ValidationResult expected = new ValidationResult(); ValidationFailure failure = new ValidationFailure("Amount", "Amount must be greater than zero"); expected.Errors.Add(failure); ValidationResult result = await this.validator.ValidateAsync(command).ConfigureAwait(false); Assert.NotNull(result); Assert.NotNull(result.Errors); Assert.False(result.IsValid); Assert.True(result.Errors.Count > 0); Assert.Equal(expected.Errors.First().ErrorMessage, result.Errors.First().ErrorMessage); } [Fact] public async Task Passes() { SubscribeCommand command = new SubscribeCommand() { CorrelationId = Guid.NewGuid(), Id = Guid.NewGuid(), Amount = 100.00m, }; ValidationResult result = await this.validator.ValidateAsync(command).ConfigureAwait(false); Assert.NotNull(result); Assert.NotNull(result.Errors); Assert.True(result.Errors.Count == 0); Assert.True(result.IsValid); } } }
35.590909
109
0.592337
[ "Apache-2.0" ]
AmjadHossainRahat/Multi-Tenant-SaaS-Database-Tenancy-Pattern
test/DomainTests/Validators/SubscribeCommandValidatorTest.cs
3,917
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using NeoCA.Persistence; namespace NeoCA.Persistence.Migrations.MySQL { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.10") .HasAnnotation("Relational:MaxIdentifierLength", 64); modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("FriendlyName") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("Xml") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.HasKey("Id"); b.ToTable("DataProtectionKeys"); }); modelBuilder.Entity("NeoCA.Domain.Entities.Category", b => { b.Property<Guid>("CategoryId") .ValueGeneratedOnAdd() .HasColumnType("char(36)"); b.Property<string>("CreatedBy") .HasColumnType("varchar(450)"); b.Property<DateTime>("CreatedDate") .HasColumnType("datetime(6)"); b.Property<string>("LastModifiedBy") .HasColumnType("varchar(450)"); b.Property<DateTime?>("LastModifiedDate") .HasColumnType("datetime(6)"); b.Property<string>("Name") .IsRequired() .HasColumnType("varchar(50)"); b.HasKey("CategoryId"); b.ToTable("Categories"); b.HasData( new { CategoryId = new Guid("b0788d2f-8003-43c1-92a4-edc76a7c5dde"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Name = "Concerts" }, new { CategoryId = new Guid("6313179f-7837-473a-a4d5-a5571b43e6a6"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Name = "Musicals" }, new { CategoryId = new Guid("bf3f3002-7e53-441e-8b76-f6280be284aa"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Name = "Plays" }, new { CategoryId = new Guid("fe98f549-e790-4e9f-aa16-18c2292a2ee9"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Name = "Conferences" }); }); modelBuilder.Entity("NeoCA.Domain.Entities.Event", b => { b.Property<Guid>("EventId") .ValueGeneratedOnAdd() .HasColumnType("char(36)"); b.Property<string>("Artist") .IsRequired() .HasColumnType("varchar(50)"); b.Property<Guid>("CategoryId") .HasColumnType("char(36)"); b.Property<string>("CreatedBy") .HasColumnType("varchar(450)"); b.Property<DateTime>("CreatedDate") .HasColumnType("datetime(6)"); b.Property<DateTime>("Date") .HasColumnType("datetime(6)"); b.Property<string>("Description") .IsRequired() .HasColumnType("varchar(500)"); b.Property<string>("ImageUrl") .IsRequired() .HasColumnType("varchar(200)"); b.Property<string>("LastModifiedBy") .HasColumnType("varchar(450)"); b.Property<DateTime?>("LastModifiedDate") .HasColumnType("datetime(6)"); b.Property<string>("Name") .IsRequired() .HasColumnType("varchar(50)"); b.Property<int>("Price") .HasColumnType("int"); b.HasKey("EventId"); b.HasIndex("CategoryId"); b.ToTable("Events"); b.HasData( new { EventId = new Guid("ee272f8b-6096-4cb6-8625-bb4bb2d89e8b"), Artist = "John Egbert", CategoryId = new Guid("b0788d2f-8003-43c1-92a4-edc76a7c5dde"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Date = new DateTime(2022, 8, 21, 12, 39, 21, 338, DateTimeKind.Local).AddTicks(4712), Description = "Join John for his farwell tour across 15 continents. John really needs no introduction since he has already mesmerized the world with his banjo.", ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/GloboTicket/banjo.jpg", Name = "John Egbert Live", Price = 65 }, new { EventId = new Guid("3448d5a4-0f72-4dd7-bf15-c14a46b26c00"), Artist = "Michael Johnson", CategoryId = new Guid("b0788d2f-8003-43c1-92a4-edc76a7c5dde"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Date = new DateTime(2022, 11, 21, 12, 39, 21, 339, DateTimeKind.Local).AddTicks(7526), Description = "Michael Johnson doesn't need an introduction. His 25 concert across the globe last year were seen by thousands. Can we add you to the list?", ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/GloboTicket/michael.jpg", Name = "The State of Affairs: Michael Live!", Price = 85 }, new { EventId = new Guid("b419a7ca-3321-4f38-be8e-4d7b6a529319"), Artist = "DJ 'The Mike'", CategoryId = new Guid("b0788d2f-8003-43c1-92a4-edc76a7c5dde"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Date = new DateTime(2022, 6, 21, 12, 39, 21, 339, DateTimeKind.Local).AddTicks(7651), Description = "DJs from all over the world will compete in this epic battle for eternal fame.", ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/GloboTicket/dj.jpg", Name = "Clash of the DJs", Price = 85 }, new { EventId = new Guid("62787623-4c52-43fe-b0c9-b7044fb5929b"), Artist = "Manuel Santinonisi", CategoryId = new Guid("b0788d2f-8003-43c1-92a4-edc76a7c5dde"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Date = new DateTime(2022, 6, 21, 12, 39, 21, 339, DateTimeKind.Local).AddTicks(7682), Description = "Get on the hype of Spanish Guitar concerts with Manuel.", ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/GloboTicket/guitar.jpg", Name = "Spanish guitar hits with Manuel", Price = 25 }, new { EventId = new Guid("1babd057-e980-4cb3-9cd2-7fdd9e525668"), Artist = "Many", CategoryId = new Guid("fe98f549-e790-4e9f-aa16-18c2292a2ee9"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Date = new DateTime(2022, 12, 21, 12, 39, 21, 339, DateTimeKind.Local).AddTicks(7708), Description = "The best tech conference in the world", ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/GloboTicket/conf.jpg", Name = "Techorama 2021", Price = 400 }, new { EventId = new Guid("adc42c09-08c1-4d2c-9f96-2d15bb1af299"), Artist = "Nick Sailor", CategoryId = new Guid("6313179f-7837-473a-a4d5-a5571b43e6a6"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), Date = new DateTime(2022, 10, 21, 12, 39, 21, 339, DateTimeKind.Local).AddTicks(7741), Description = "The critics are over the moon and so will you after you've watched this sing and dance extravaganza written by Nick Sailor, the man from 'My dad and sister'.", ImageUrl = "https://gillcleerenpluralsight.blob.core.windows.net/files/GloboTicket/musical.jpg", Name = "To the Moon and Back", Price = 135 }); }); modelBuilder.Entity("NeoCA.Domain.Entities.Message", b => { b.Property<Guid>("MessageId") .ValueGeneratedOnAdd() .HasColumnType("char(36)"); b.Property<string>("Code") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("Language") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("MessageContent") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("Type") .IsRequired() .HasColumnType("longtext CHARACTER SET utf8mb4"); b.HasKey("MessageId"); b.ToTable("Messages"); b.HasData( new { MessageId = new Guid("253c75d5-32af-4dbf-ab63-1af449bde7bd"), Code = "1", Language = "en", MessageContent = "{PropertyName} is required.", Type = "Error" }, new { MessageId = new Guid("ed0cc6b6-11f4-4512-a441-625941917502"), Code = "2", Language = "en", MessageContent = "{PropertyName} must not exceed {MaxLength} characters.", Type = "Error" }, new { MessageId = new Guid("fafe649a-3e2a-4153-8fd8-9dcd0b87e6d8"), Code = "3", Language = "en", MessageContent = "An event with the same name and date already exists.", Type = "Error" }); }); modelBuilder.Entity("NeoCA.Domain.Entities.Order", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnName("OrderId") .HasColumnType("char(36)"); b.Property<string>("CreatedBy") .HasColumnType("varchar(450)"); b.Property<DateTime>("CreatedDate") .HasColumnType("datetime(6)"); b.Property<string>("LastModifiedBy") .HasColumnType("varchar(450)"); b.Property<DateTime?>("LastModifiedDate") .HasColumnType("datetime(6)"); b.Property<bool>("OrderPaid") .HasColumnType("tinyint(1)"); b.Property<DateTime>("OrderPlaced") .HasColumnType("datetime(6)"); b.Property<int>("OrderTotal") .HasColumnType("int"); b.Property<Guid>("UserId") .HasColumnType("char(36)"); b.HasKey("Id"); b.ToTable("Orders"); b.HasData( new { Id = new Guid("7e94bc5b-71a5-4c8c-bc3b-71bb7976237e"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), OrderPaid = true, OrderPlaced = new DateTime(2022, 2, 21, 12, 39, 21, 339, DateTimeKind.Local).AddTicks(9124), OrderTotal = 400, UserId = new Guid("a441eb40-9636-4ee6-be49-a66c5ec1330b") }, new { Id = new Guid("86d3a045-b42d-4854-8150-d6a374948b6e"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), OrderPaid = true, OrderPlaced = new DateTime(2022, 2, 21, 12, 39, 21, 340, DateTimeKind.Local).AddTicks(11), OrderTotal = 135, UserId = new Guid("ac3cfaf5-34fd-4e4d-bc04-ad1083ddc340") }, new { Id = new Guid("771cca4b-066c-4ac7-b3df-4d12837fe7e0"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), OrderPaid = true, OrderPlaced = new DateTime(2022, 2, 21, 12, 39, 21, 340, DateTimeKind.Local).AddTicks(63), OrderTotal = 85, UserId = new Guid("d97a15fc-0d32-41c6-9ddf-62f0735c4c1c") }, new { Id = new Guid("3dcb3ea0-80b1-4781-b5c0-4d85c41e55a6"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), OrderPaid = true, OrderPlaced = new DateTime(2022, 2, 21, 12, 39, 21, 340, DateTimeKind.Local).AddTicks(86), OrderTotal = 245, UserId = new Guid("4ad901be-f447-46dd-bcf7-dbe401afa203") }, new { Id = new Guid("e6a2679c-79a3-4ef1-a478-6f4c91b405b6"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), OrderPaid = true, OrderPlaced = new DateTime(2022, 2, 21, 12, 39, 21, 340, DateTimeKind.Local).AddTicks(110), OrderTotal = 142, UserId = new Guid("7aeb2c01-fe8e-4b84-a5ba-330bdf950f5c") }, new { Id = new Guid("f5a6a3a0-4227-4973-abb5-a63fbe725923"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), OrderPaid = true, OrderPlaced = new DateTime(2022, 2, 21, 12, 39, 21, 340, DateTimeKind.Local).AddTicks(137), OrderTotal = 40, UserId = new Guid("f5a6a3a0-4227-4973-abb5-a63fbe725923") }, new { Id = new Guid("ba0eb0ef-b69b-46fd-b8e2-41b4178ae7cb"), CreatedDate = new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified), OrderPaid = true, OrderPlaced = new DateTime(2022, 2, 21, 12, 39, 21, 340, DateTimeKind.Local).AddTicks(159), OrderTotal = 116, UserId = new Guid("7aeb2c01-fe8e-4b84-a5ba-330bdf950f5c") }); }); modelBuilder.Entity("NeoCA.Domain.Entities.Event", b => { b.HasOne("NeoCA.Domain.Entities.Category", "Category") .WithMany("Events") .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
48.952255
202
0.434679
[ "Apache-2.0" ]
NeoSOFT-Technologies/netcore-template
Content/src/Infrastructure/NeoCA.Persistence/Migrations/MySQL/ApplicationDbContextModelSnapshot.cs
18,457
C#
using Bogus; using ProductsODataApiDemo.Models; using System.Collections.Generic; using System.Globalization; namespace ProductsODataApiDemo.Data { public static class DataGenerator { public static IEnumerable<Product> GetProducts(int count = 50) { Faker<Product> productFaker = new Faker<Product>() .RuleFor(p => p.Id, f => f.Random.Guid().ToString("N")) .RuleFor(p => p.Name, f => f.Commerce.ProductName()) .RuleFor(p => p.Price, f => decimal.Parse(f.Commerce.Price(), CultureInfo.InvariantCulture)) .RuleFor(p => p.Quantity, f => f.Random.Number(0, 200)) .RuleFor(p => p.ProducedBy, f => f.Company.CompanyName()); return productFaker.Generate(count); } } }
33.5
108
0.604478
[ "MIT" ]
cecilphillip/aspnetcore-web-services
src/ProductsODataApiDemo/Data/DataGenerator.cs
806
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TipsOnWorld : MonoBehaviour { public GameObject tipsPrefab; public RectTransform rootCanvas; RectTransform rect; GameObject tips; bool isClose = false; private void Awake() { tips = Instantiate(tipsPrefab, transform.position, Quaternion.identity, rootCanvas); tips.GetComponent<RectTransform>().localPosition = Vector3.zero; rect = tips.GetComponent<RectTransform>(); } private void LateUpdate() { if (!isClose) { if (Game.IsInFrontOfCamera(transform.position)) { tips.SetActive(true); rect.anchoredPosition = UIPosition.WorldToUI(transform.position, rootCanvas); } else { tips.SetActive(false); } } } public void CloseTips() { isClose = true; tips.SetActive(false); } }
20.959184
93
0.583252
[ "MIT" ]
kevin41307/Hello4
Hello4/Assets/Scripts/TipsOnWorld.cs
1,029
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _09.Holidays_Between { class Program { static void Main(string[] args) { var startDate = DateTime.ParseExact(Console.ReadLine(), "d.M.yyyy", CultureInfo.InvariantCulture); var endDate = DateTime.ParseExact(Console.ReadLine(), "d.M.yyyy", CultureInfo.InvariantCulture); var holidaysCount = 0; for (var date = startDate; date <= endDate; date = date.AddDays(1)) { if (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday) holidaysCount++; } Console.WriteLine(holidaysCount); } } }
27.83871
79
0.581692
[ "MIT" ]
spiderbait90/Step-By-Step-In-C-Sharp
Programming Fundamentals/Methods And Debugging/09. Holidays Between/Program.cs
865
C#
namespace SqlQueryBuilder.Utils; internal static class EnumerableExtensions { public static IEnumerable<T> Prepend<T>(this IEnumerable<T> source, params T[] items) => items.Concat(source); public static IReadOnlyDictionary<TKey?, TValue> ToDictionaryWithNullableKey<TSource, TKey, TValue>( this IEnumerable<TSource> source, Func<TSource, TKey?> keySelector, Func<TSource, TValue> valueSelector, IEqualityComparer<TKey?>? equalityComparer = null) where TKey : notnull { var keyValuePairs = source .Select(item => KeyValuePair.Create(keySelector(item), valueSelector(item))) .ToList(); return new DictionaryWithNullableKey<TKey, TValue>(keyValuePairs, equalityComparer); } }
38.95
92
0.690629
[ "MIT" ]
GennadyGS/SqlQueryBuilder
SqlQueryBuilder/Utils/EnumerableExtensions.cs
781
C#
// *********************************************************************** // Assembly : MPT.CSI.API // Author : Mark Thomas // Created : 06-16-2017 // // Last Modified By : Mark Thomas // Last Modified On : 06-16-2017 // *********************************************************************** // <copyright file="eAreaThicknessType.cs" company=""> // Copyright © 2017 // </copyright> // <summary></summary> // *********************************************************************** namespace MPT.CSI.Serialize.Models.Helpers.Definitions.Sections.AreaSections { /// <summary> /// Thickness types avilable for aera elements in the application. /// </summary> public enum eAreaThicknessType { /// <summary> /// No thickness overwrite. /// </summary> NoOverwrites = 0, /// <summary> /// UserCoordinateSystemNames defined thickness overwrites specified by joint patte. /// </summary> OverwriteByJointPattern = 1, /// <summary> /// UserCoordinateSystemNames defined thickness overwrites specified by point. /// </summary> OverwriteByPoint = 2 } }
32.351351
92
0.491228
[ "MIT" ]
MarkPThomas/MPT.Net
MPT/CSI/API/MPT.CSI.Serialize/Models/Helpers/Definitions/Sections/AreaSections/eAreaThicknessType.cs
1,200
C#
using System; using System.Threading; using Android.App; using Android.Content; using Android.OS; using Android.Util; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Graphics; using Android.Graphics.Drawables; using Android.Graphics.Drawables.Shapes; using Android.Animation; using Java.Nio; using System.IO; namespace ActionComponents { /// <summary> /// The <c>HSVImage</c> class creates the HSV images to present in the <c>ACColorCube</c> and <c>ACHueBar</c> based /// on the current Hue, Saturation and Value properties. /// </summary> public class HSVImage { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="T:ActionComponents.HSVImage"/> class. /// </summary> public HSVImage() { } #endregion #region Static Methods /// <summary> /// Pin the specified minValue, value and maxValue. /// </summary> /// <param name="minValue">Minimum value.</param> /// <param name="value">Value.</param> /// <param name="maxValue">Max value.</param> public static float Pin(float minValue, float value, float maxValue) { if (minValue > value) return minValue; else if (maxValue < value) return maxValue; else return value; } /// <summary> /// Blend the specified value and percent. /// </summary> /// <param name="value">Value.</param> /// <param name="percentIn255">Percent in 255.</param> public static Byte Blend(Byte value, Byte percentIn255) { return (Byte)((int)value * percentIn255 / 255); } /// <summary> /// Saturations the brightness square image. /// </summary> /// <returns>The brightness square image.</returns> /// <param name="hue">Hue.</param> public static Bitmap SaturationBrightnessSquareImage(float hue) { // Calculate metrics int w = 256, h = 256; int bytesPerRow = w * 4; int bitmapByteCount = bytesPerRow * h; int bytesPerPixel = bytesPerRow / w; // Create pixel buffer var RGBImage = new int[w * h]; // Precompute RGB values HSVColor hsv = new HSVColor(hue * 360.0f, 1f, 1f); RGBColor hueRGB = hsv.RGB; Byte r_s = (Byte)((1.0f - hueRGB.Red) * 255); Byte g_s = (Byte)((1.0f - hueRGB.Green) * 255); Byte b_s = (Byte)((1.0f - hueRGB.Blue) * 255); // Create storage for color manipulation Byte r_hs = 0, g_hs = 0, b_hs = 0; Byte max = 255, x = 0, y = 0; // Poke color cube into graphics space for (int s = 0; s <= 255; ++s) { // Create row color r_hs = (Byte)(max - Blend((Byte)s, r_s)); g_hs = (Byte)(max - Blend((Byte)s, g_s)); b_hs = (Byte)(max - Blend((Byte)s, b_s)); // Process each column on this row for (int v = 0; v <=255; ++v) { // Get byte index var index = (v * 256) + s; // Insert color at current x,y location y = (Byte)(max - v); var pixel = new Color(Blend(y, r_hs), Blend(y, g_hs), Blend(y, b_hs)); RGBImage[index] = (int)pixel; } } // Return results Bitmap createdBitmap = Bitmap.CreateBitmap(RGBImage, w, h, Bitmap.Config.Argb8888); return createdBitmap; } /// <summary> /// Hues the bar image. /// </summary> /// <returns>The bar image.</returns> /// <param name="index">Index.</param> /// <param name="hsv">Hsv.</param> public static Bitmap HueBarImage(ACHueBarComponentIndex index, HSVColor hsv) { // Calculate metrics int w = 256, h = 50; int bytesPerRow = w * 4; int bitmapByteCount = bytesPerRow * h; int bytesPerPixel = bytesPerRow / w; // Create pixel buffer var RGBImage = new int[w * h]; // Create storage for color manipulation int byteIndex = 0; RGBColor rgb; HSVColor hsvAdjusted; // Draw color bar for (int x = 0; x < 256; ++x) { // Calculate byte index byteIndex = (x * bytesPerPixel); // Calculate new color space switch (index) { case ACHueBarComponentIndex.ComponentIndexHue: hsv.Hue = (float)x / 255f; break; case ACHueBarComponentIndex.ComponentIndexSaturation: hsv.Saturation = (float)x / 255f; break; case ACHueBarComponentIndex.ComponentIndexBrightness: hsv.Value = (float)x / 255f; break; } // Adjust color space hsvAdjusted = new HSVColor(hsv.Hue * 360.0f, hsv.Saturation, hsv.Value); rgb = hsvAdjusted.RGB; // Make color var pixel = new Color((Byte)(rgb.Red * 255f), (Byte)(rgb.Green * 255f), (Byte)(rgb.Blue * 255f)); // Insert color for (int y = 0; y < 50; ++y) { // Build index var n = (y * 256) + x; RGBImage[n] = (int)pixel; } } // Return results Bitmap createdBitmap = Bitmap.CreateBitmap(RGBImage, w, h, Bitmap.Config.Argb8888); return createdBitmap; } #endregion } }
26.355556
116
0.631535
[ "MIT" ]
Appracatappra/ActionComponents
Android/ActionComponentExplorer/ActionComponents/ActionColorPicker/HSVImage.cs
4,746
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using HoloToolkit.Unity.UX; using UnityEngine; namespace HoloToolkit.Unity.InputModule { [RequireComponent(typeof(DistorterGravity))] [RequireComponent(typeof(LineBase))] [RequireComponent(typeof(LineRendererBase))] public class PointerLine : BaseControllerPointer { [Header("Colors")] [SerializeField] [GradientDefault(GradientDefaultAttribute.ColorEnum.Blue, GradientDefaultAttribute.ColorEnum.White, 1f, 0.25f)] protected Gradient LineColorSelected; [SerializeField] [GradientDefault(GradientDefaultAttribute.ColorEnum.Blue, GradientDefaultAttribute.ColorEnum.White, 1f, 0.5f)] protected Gradient LineColorValid; [SerializeField] [GradientDefault(GradientDefaultAttribute.ColorEnum.Gray, GradientDefaultAttribute.ColorEnum.White, 1f, 0.5f)] protected Gradient LineColorNoTarget; [Range(5, 100)] [SerializeField] protected int LineCastResolution = 25; [SerializeField] protected LineBase LineBase; [SerializeField] [Tooltip("If no line renderers are specified, this array will be auto-populated on startup.")] protected LineRendererBase[] LineRenderers; protected DistorterGravity DistorterGravity; /// <summary> /// Line pointer stays inactive until it's attached to a controller. /// </summary> public bool InteractionEnabled { get { #if UNITY_WSA && UNITY_2017_2_OR_NEWER return ControllerInfo != null; #else return false; #endif } } protected override void OnEnable() { base.OnEnable(); LineBase = GetComponent<LineBase>(); DistorterGravity = GetComponent<DistorterGravity>(); LineBase.AddDistorter(DistorterGravity); if (LineRenderers == null || LineRenderers.Length == 0) { LineRenderers = LineBase.GetComponentsInChildren<LineRendererBase>(); } LineBase.enabled = false; } public void UpdateRenderedLine(RayStep[] lines, PointerResult result, bool selectPressed, float extent) { if (LineBase == null) { return; } Gradient lineColor = LineColorNoTarget; if (InteractionEnabled) { LineBase.enabled = true; // If we hit something if (result.End.Object != null) { lineColor = LineColorValid; LineBase.LastPoint = result.End.Point; } else { LineBase.LastPoint = RayStep.GetPointByDistance(lines, extent); } if (selectPressed) { lineColor = LineColorSelected; } } else { LineBase.enabled = false; } for (int i = 0; i < LineRenderers.Length; i++) { LineRenderers[i].LineColor = lineColor; } } } }
30.953704
119
0.580018
[ "CC0-1.0" ]
AGM-GR/In-Game
Assets/HoloToolkit/Input/Scripts/Utilities/PointerLine.cs
3,345
C#
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; namespace TsTimeline { [TemplatePart(Name="PART_THUMB", Type=typeof(Thumb))] public class TriggerClip : ClipBase { public static readonly DependencyProperty ValueProperty = DepProp.Register<TriggerClip, double>( nameof(Value), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnValueChanged); public double Value { get => (double) GetValue(ValueProperty); set => SetValue(ValueProperty, value); } private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if(d is TriggerClip t) t.UpdateThumb(); } protected override void OnScaleChanged() { this.UpdateThumb(); } public override void OnApplyTemplate() { base.OnApplyTemplate(); TryGetThumb(out _); } private void Thumb_OnDragDelta(Vector vector) { if (IsReadOnly) return; var change = Math.Ceiling(vector.X * (1.0d / Scale) - 0.5d); // 右側のクランプ if (Value + change >= ActualWidth * (1.0d / Scale)) { change = ActualWidth * (1.0d / Scale) - Value; } // 左側のクランプ else if (Value + change<= 0) { change = -Value; } Value += change; } private Thumb _thumb; private bool TryGetThumb(out Thumb thumb) { if (_thumb != null) { thumb = _thumb; return true; } _thumb = thumb = this.GetTemplateChild("PART_THUMB") as Thumb; if (thumb != null) { var eventBinder = new ThumbDragToMousePointConverter(thumb,OnMouseDownSelectedChanged); eventBinder.BindDragDelta(Thumb_OnDragDelta); Loaded += (s, e) => { UpdateThumb(); }; } return _thumb != null; } private void UpdateThumb() { if (TryGetThumb(out var thumb)) { Canvas.SetLeft(thumb, Value * Scale - thumb.ActualWidth / 2); } } } }
27.752688
120
0.501356
[ "MIT" ]
p4j4dyxcry/TsTimeline
TsTimeline/TriggerClip.cs
2,611
C#
//////////////////////////////////////////////////////////////////////////// // // This file is part of RTIMULibCS // // Copyright (c) 2015, richards-tech, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using PiSHat.Sensors; namespace NetBridge.Linux { public class ImuSensorData : SensorData { public bool GyroBiasValid { get; set; } public bool MagCalValid { get; set; } } }
37.452381
88
0.643357
[ "MIT" ]
samnium/IoTWork.NetBridge
Net/Pi.SHat.RTIMULib.Console/ImuSensorData.cs
1,573
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 dataexchange-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.DataExchange.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DataExchange.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DeleteAsset operation /// </summary> public class DeleteAssetResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DeleteAssetResponse response = new DeleteAssetResponse(); return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("AccessDeniedException")) { return AccessDeniedExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ConflictException")) { return ConflictExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServerException")) { return InternalServerExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFoundException")) { return ResourceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException")) { return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException")) { return ValidationExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonDataExchangeException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); } private static DeleteAssetResponseUnmarshaller _instance = new DeleteAssetResponseUnmarshaller(); internal static DeleteAssetResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteAssetResponseUnmarshaller Instance { get { return _instance; } } } }
41.302521
196
0.633774
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/DataExchange/Generated/Model/Internal/MarshallTransformations/DeleteAssetResponseUnmarshaller.cs
4,915
C#
namespace P03_SalesDatabase.Data { public static class DataValidations { public static class Product { public const int MaxNameLength = 50; public const int MaxDescriptionLength = 250; } public static class Customer { public const int MaxNameLength = 100; public const int MaxEmailLength = 80; } public static class Store { public const int MaxNameLength = 80; } } }
22.347826
56
0.560311
[ "MIT" ]
stanislavstoyanov99/SoftUni-Software-Engineering
DB-with-C#/Labs-And-Homeworks/Entity Framework Core/05. Code-First - Exercise/03SalesDatabase/Data/DataValidations.cs
516
C#
using System; using System.Collections.Generic; using System.Text; namespace Microsoft.NetMicroFramework.Tools.MFDeployTool.Engine { internal class CRC { private CRC() { } // // CRC 32 table for use under ZModem protocol, IEEE 802 // G(x) = x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1 // static UInt32[] c_CRCTable = { 0x00000000, 0x04C11DB7, 0x09823B6E, 0x0D4326D9, 0x130476DC, 0x17C56B6B, 0x1A864DB2, 0x1E475005, 0x2608EDB8, 0x22C9F00F, 0x2F8AD6D6, 0x2B4BCB61, 0x350C9B64, 0x31CD86D3, 0x3C8EA00A, 0x384FBDBD, 0x4C11DB70, 0x48D0C6C7, 0x4593E01E, 0x4152FDA9, 0x5F15ADAC, 0x5BD4B01B, 0x569796C2, 0x52568B75, 0x6A1936C8, 0x6ED82B7F, 0x639B0DA6, 0x675A1011, 0x791D4014, 0x7DDC5DA3, 0x709F7B7A, 0x745E66CD, 0x9823B6E0, 0x9CE2AB57, 0x91A18D8E, 0x95609039, 0x8B27C03C, 0x8FE6DD8B, 0x82A5FB52, 0x8664E6E5, 0xBE2B5B58, 0xBAEA46EF, 0xB7A96036, 0xB3687D81, 0xAD2F2D84, 0xA9EE3033, 0xA4AD16EA, 0xA06C0B5D, 0xD4326D90, 0xD0F37027, 0xDDB056FE, 0xD9714B49, 0xC7361B4C, 0xC3F706FB, 0xCEB42022, 0xCA753D95, 0xF23A8028, 0xF6FB9D9F, 0xFBB8BB46, 0xFF79A6F1, 0xE13EF6F4, 0xE5FFEB43, 0xE8BCCD9A, 0xEC7DD02D, 0x34867077, 0x30476DC0, 0x3D044B19, 0x39C556AE, 0x278206AB, 0x23431B1C, 0x2E003DC5, 0x2AC12072, 0x128E9DCF, 0x164F8078, 0x1B0CA6A1, 0x1FCDBB16, 0x018AEB13, 0x054BF6A4, 0x0808D07D, 0x0CC9CDCA, 0x7897AB07, 0x7C56B6B0, 0x71159069, 0x75D48DDE, 0x6B93DDDB, 0x6F52C06C, 0x6211E6B5, 0x66D0FB02, 0x5E9F46BF, 0x5A5E5B08, 0x571D7DD1, 0x53DC6066, 0x4D9B3063, 0x495A2DD4, 0x44190B0D, 0x40D816BA, 0xACA5C697, 0xA864DB20, 0xA527FDF9, 0xA1E6E04E, 0xBFA1B04B, 0xBB60ADFC, 0xB6238B25, 0xB2E29692, 0x8AAD2B2F, 0x8E6C3698, 0x832F1041, 0x87EE0DF6, 0x99A95DF3, 0x9D684044, 0x902B669D, 0x94EA7B2A, 0xE0B41DE7, 0xE4750050, 0xE9362689, 0xEDF73B3E, 0xF3B06B3B, 0xF771768C, 0xFA325055, 0xFEF34DE2, 0xC6BCF05F, 0xC27DEDE8, 0xCF3ECB31, 0xCBFFD686, 0xD5B88683, 0xD1799B34, 0xDC3ABDED, 0xD8FBA05A, 0x690CE0EE, 0x6DCDFD59, 0x608EDB80, 0x644FC637, 0x7A089632, 0x7EC98B85, 0x738AAD5C, 0x774BB0EB, 0x4F040D56, 0x4BC510E1, 0x46863638, 0x42472B8F, 0x5C007B8A, 0x58C1663D, 0x558240E4, 0x51435D53, 0x251D3B9E, 0x21DC2629, 0x2C9F00F0, 0x285E1D47, 0x36194D42, 0x32D850F5, 0x3F9B762C, 0x3B5A6B9B, 0x0315D626, 0x07D4CB91, 0x0A97ED48, 0x0E56F0FF, 0x1011A0FA, 0x14D0BD4D, 0x19939B94, 0x1D528623, 0xF12F560E, 0xF5EE4BB9, 0xF8AD6D60, 0xFC6C70D7, 0xE22B20D2, 0xE6EA3D65, 0xEBA91BBC, 0xEF68060B, 0xD727BBB6, 0xD3E6A601, 0xDEA580D8, 0xDA649D6F, 0xC423CD6A, 0xC0E2D0DD, 0xCDA1F604, 0xC960EBB3, 0xBD3E8D7E, 0xB9FF90C9, 0xB4BCB610, 0xB07DABA7, 0xAE3AFBA2, 0xAAFBE615, 0xA7B8C0CC, 0xA379DD7B, 0x9B3660C6, 0x9FF77D71, 0x92B45BA8, 0x9675461F, 0x8832161A, 0x8CF30BAD, 0x81B02D74, 0x857130C3, 0x5D8A9099, 0x594B8D2E, 0x5408ABF7, 0x50C9B640, 0x4E8EE645, 0x4A4FFBF2, 0x470CDD2B, 0x43CDC09C, 0x7B827D21, 0x7F436096, 0x7200464F, 0x76C15BF8, 0x68860BFD, 0x6C47164A, 0x61043093, 0x65C52D24, 0x119B4BE9, 0x155A565E, 0x18197087, 0x1CD86D30, 0x029F3D35, 0x065E2082, 0x0B1D065B, 0x0FDC1BEC, 0x3793A651, 0x3352BBE6, 0x3E119D3F, 0x3AD08088, 0x2497D08D, 0x2056CD3A, 0x2D15EBE3, 0x29D4F654, 0xC5A92679, 0xC1683BCE, 0xCC2B1D17, 0xC8EA00A0, 0xD6AD50A5, 0xD26C4D12, 0xDF2F6BCB, 0xDBEE767C, 0xE3A1CBC1, 0xE760D676, 0xEA23F0AF, 0xEEE2ED18, 0xF0A5BD1D, 0xF464A0AA, 0xF9278673, 0xFDE69BC4, 0x89B8FD09, 0x8D79E0BE, 0x803AC667, 0x84FBDBD0, 0x9ABC8BD5, 0x9E7D9662, 0x933EB0BB, 0x97FFAD0C, 0xAFB010B1, 0xAB710D06, 0xA6322BDF, 0xA2F33668, 0xBCB4666D, 0xB8757BDA, 0xB5365D03, 0xB1F740B4, }; internal static UInt32 ComputeCRC( byte[] rgBlock, int index, int nLength, UInt32 crc ) { while(nLength-- > 0) { crc = c_CRCTable[((crc >> 24) ^ (rgBlock[index++])) & 0xFF] ^ (crc << 8); } return crc; } } }
66.4375
108
0.688852
[ "Apache-2.0" ]
AustinWise/Netduino-Micro-Framework
Framework/Tools/MFDeploy/Library/MFCRC.cs
4,252
C#
using ExtractorSharp.Component; using ExtractorSharp.Core.Composition; using ExtractorSharp.Core.Config; namespace ExtractorSharp.View.SettingPane { public partial class RulerPane : AbstractSettingPane { public RulerPane(IConnector connector) : base(connector) { InitializeComponent(); } public override void Initialize() { displayCrosshairBox.Checked = Config["RulerCrosshair"].Boolean; displaySpanBox.Checked = Config["RulerSpan"].Boolean; } public override void Save() { Config["RulerCrosshair"] = new ConfigValue(displayCrosshairBox.Checked); Config["RulerSpan"] = new ConfigValue(displaySpanBox.Checked); } } }
35
84
0.67619
[ "MIT" ]
Kritsu/ExtractorSharp
ExtractorSharp/View/SettingPane/RulerPane.cs
737
C#
using UnityEngine; using IsoTools.Internal; namespace IsoTools { public struct IsoRaycastHit { public IsoCollider collider { get; private set; } public float distance { get; private set; } public Vector3 normal { get; private set; } public Vector3 point { get; private set; } public IsoRigidbody rigidbody { get; private set; } public IsoRaycastHit(RaycastHit hit_info) : this() { collider = IsoUtils.IsoConvertCollider(hit_info.collider); distance = hit_info.distance; normal = hit_info.normal; point = hit_info.point; rigidbody = IsoUtils.IsoConvertRigidbody(hit_info.rigidbody); } } } // namespace IsoTools
30.954545
64
0.697504
[ "MIT" ]
CaaporaGames/Caapora2.5D
Assets/Caapora/Scripts/Vendor/IsoTools/Scripts/IsoRaycastHit.cs
683
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Test.Hosting { /// <summary> /// Target for the Distributed Test Step /// </summary> public enum UiaDistributedStepTarget { /// <summary> /// Runs out of proc to the avalon app and is given an Automation Element /// </summary> AutomationElement, /// <summary> /// Run in proc of the Avalon App and is given the UIElement /// </summary> UiElement } }
26.6
81
0.630075
[ "MIT" ]
batzen/wpf-test
src/Test/Common/Code/Microsoft/Test/Hosting/UiaDistributedStepTarget.cs
665
C#
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Web.Http; using CustomService.Model; namespace CustomService.Controllers { public class SimpleWepApiController : ApiController { [Route("api/books")] public IEnumerable<Book> GetBooks() { return new[] { new Book { Title = "The Book : " + Request.GetDependencyScope().GetType().FullName } }; } [Route("api/books/exception")] [HttpGet] public IEnumerable<Book> ThrowException() { var state = ErrorHandlingReporter.GetState( Request, GlobalConfiguration.Configuration); var builder = new StringBuilder(); foreach (var msg in state) { builder.AppendLine(msg); } throw new Exception("intentional exception\n\n" + builder); } } }
26.974359
100
0.527567
[ "MIT" ]
kevinobee/SSC.AggregateService
src/CustomService.Sample/Controllers/SimpleWepApiController.cs
1,054
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Azure.Messaging.EventHubs.Primitives { /// <summary> /// Deals with the interaction with the chosen storage service. It's able to create checkpoints and /// list/claim ownership. /// </summary> /// internal abstract class StorageManager { /// <summary> /// Retrieves a complete ownership list from the chosen storage service. /// </summary> /// /// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param> /// <param name="eventHubName">The name of the specific Event Hub the ownership are associated with, relative to the Event Hubs namespace that contains it.</param> /// <param name="consumerGroup">The name of the consumer group the ownership are associated with.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>An enumerable containing all the existing ownership for the associated Event Hub and consumer group.</returns> /// public abstract Task<IEnumerable<EventProcessorPartitionOwnership>> ListOwnershipAsync(string fullyQualifiedNamespace, string eventHubName, string consumerGroup, CancellationToken cancellationToken); /// <summary> /// Attempts to claim ownership of partitions for processing. /// </summary> /// /// <param name="partitionOwnership">An enumerable containing all the ownership to claim.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>An enumerable containing the successfully claimed ownership instances.</returns> /// public abstract Task<IEnumerable<EventProcessorPartitionOwnership>> ClaimOwnershipAsync(IEnumerable<EventProcessorPartitionOwnership> partitionOwnership, CancellationToken cancellationToken); /// <summary> /// Retrieves a complete checkpoints list from the chosen storage service. /// </summary> /// /// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace the ownership are associated with. This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param> /// <param name="eventHubName">The name of the specific Event Hub the ownership are associated with, relative to the Event Hubs namespace that contains it.</param> /// <param name="consumerGroup">The name of the consumer group the ownership are associated with.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>An enumerable containing all the existing checkpoints for the associated Event Hub and consumer group.</returns> /// public abstract Task<IEnumerable<EventProcessorCheckpoint>> ListCheckpointsAsync(string fullyQualifiedNamespace, string eventHubName, string consumerGroup, CancellationToken cancellationToken); /// <summary> /// Updates the checkpoint using the given information for the associated partition and consumer group in the chosen storage service. /// </summary> /// /// <param name="checkpoint">The checkpoint containing the information to be stored.</param> /// <param name="eventData">The event to use as the basis for the checkpoint's starting position.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// public abstract Task UpdateCheckpointAsync(EventProcessorCheckpoint checkpoint, EventData eventData, CancellationToken cancellationToken); } }
65.88
213
0.601093
[ "MIT" ]
AbelHu/azure-sdk-for-net
sdk/eventhub/Azure.Messaging.EventHubs.Shared/src/Processor/StorageManager.cs
4,943
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace SimpleCalculator { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
22.391304
65
0.615534
[ "MIT" ]
Anuren/hell
C#/SimpleCalculator/Program.cs
517
C#
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: SampleSterling.SampleSterlingPublic File: MainWindow.xaml.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace SampleSterling { using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows; using Ecng.Common; using Ecng.Xaml; using MoreLinq; using StockSharp.BusinessEntities; using StockSharp.Sterling; using StockSharp.Logging; using StockSharp.Xaml; using StockSharp.Localization; using StockSharp.Messages; public partial class MainWindow { public static MainWindow Instance { get; private set; } public static readonly DependencyProperty IsConnectedProperty = DependencyProperty.Register("IsConnected", typeof(bool), typeof(MainWindow), new PropertyMetadata(default(bool))); public bool IsConnected { get { return (bool)GetValue(IsConnectedProperty); } set { SetValue(IsConnectedProperty, value); } } public SterlingTrader Trader { get; private set; } private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow(); private readonly OrdersWindow _ordersWindow = new OrdersWindow(); private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow(); private readonly StopOrdersWindow _stopOrdersWindow = new StopOrdersWindow(); private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow(); private readonly NewsWindow _newsWindow = new NewsWindow(); private readonly LogManager _logManager = new LogManager(); public MainWindow() { Instance = this; InitializeComponent(); Title = Title.Put("Sterling"); Closing += OnClosing; _ordersWindow.MakeHideable(); _securitiesWindow.MakeHideable(); _stopOrdersWindow.MakeHideable(); _portfoliosWindow.MakeHideable(); _myTradesWindow.MakeHideable(); _newsWindow.MakeHideable(); var guiListener = new GuiLogListener(LogControl); //guiListener.Filters.Add(msg => msg.Level > LogLevels.Debug); _logManager.Listeners.Add(guiListener); _logManager.Listeners.Add(new FileLogListener("sterling") { LogDirectory = "Logs" }); Application.Current.MainWindow = this; } private void OnClosing(object sender, CancelEventArgs cancelEventArgs) { Properties.Settings.Default.Save(); _ordersWindow.DeleteHideable(); _securitiesWindow.DeleteHideable(); _stopOrdersWindow.DeleteHideable(); _portfoliosWindow.DeleteHideable(); _myTradesWindow.DeleteHideable(); _newsWindow.DeleteHideable(); _securitiesWindow.Close(); _stopOrdersWindow.Close(); _ordersWindow.Close(); _portfoliosWindow.Close(); _myTradesWindow.Close(); _newsWindow.Close(); if (Trader != null) Trader.Dispose(); } private void ConnectClick(object sender, RoutedEventArgs e) { if (!IsConnected) { if (Trader == null) { // create connector Trader = new SterlingTrader { LogLevel = LogLevels.Debug }; _logManager.Sources.Add(Trader); // subscribe on connection successfully event Trader.Connected += () => { this.GuiAsync(() => OnConnectionChanged(true)); AddSecurities(); Trader.RegisterNews(); }; // subscribe on connection error event Trader.ConnectionError += error => this.GuiAsync(() => { OnConnectionChanged(Trader.ConnectionState == ConnectionStates.Connected); MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959); }); Trader.Disconnected += () => this.GuiAsync(() => OnConnectionChanged(false)); // subscribe on error event Trader.Error += error => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955)); // subscribe on error of market data subscription event Trader.MarketDataSubscriptionFailed += (security, type, error) => this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(type, security))); Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities); Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades); Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders); Trader.NewStopOrders += orders => this.GuiAsync(() => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders)); Trader.NewPortfolios += portfolios => { // subscribe on portfolio updates portfolios.ForEach(Trader.RegisterPortfolio); _portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios); }; Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions); // subscribe on error of order registration event Trader.OrdersRegisterFailed += OrdersFailed; // subscribe on error of order cancelling event Trader.OrdersCancelFailed += OrdersFailed; // subscribe on error of stop-order registration event Trader.StopOrdersRegisterFailed += OrdersFailed; // subscribe on error of stop-order cancelling event Trader.StopOrdersCancelFailed += OrdersFailed; Trader.NewNews += news => _newsWindow.NewsPanel.NewsGrid.News.Add(news); // set market data provider _securitiesWindow.SecurityPicker.MarketDataProvider = Trader; // set news provider _newsWindow.NewsPanel.NewsProvider = Trader; } Trader.Connect(); } else { Trader.Disconnect(); } } private void OnConnectionChanged(bool isConnected) { IsConnected = isConnected; ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect; } private void OrdersFailed(IEnumerable<OrderFail> fails) { this.GuiAsync(() => { foreach (var fail in fails) { var msg = fail.Error.ToString(); MessageBox.Show(this, msg, LocalizedStrings.Str2960); } }); } private static void ShowOrHide(Window window) { if (window == null) throw new ArgumentNullException(nameof(window)); if (window.Visibility == Visibility.Visible) window.Hide(); else window.Show(); } private void ShowMyTradesClick(object sender, RoutedEventArgs e) { ShowOrHide(_myTradesWindow); } private void ShowSecuritiesClick(object sender, RoutedEventArgs e) { ShowOrHide(_securitiesWindow); } private void ShowPortfoliosClick(object sender, RoutedEventArgs e) { ShowOrHide(_portfoliosWindow); } private void ShowOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_ordersWindow); } private void ShowStopOrdersClick(object sender, RoutedEventArgs e) { ShowOrHide(_stopOrdersWindow); } private void ShowNewsClick(object sender, RoutedEventArgs e) { ShowOrHide(_newsWindow); } private void AddSecurities() { Trader.SendOutMessage(new SecurityMessage { SecurityId = new SecurityId { SecurityCode = "AAPL", BoardCode = "BATS", }, Name = "AAPL", SecurityType = SecurityTypes.Stock, }); Trader.SendOutMessage(new SecurityMessage { SecurityId = new SecurityId { SecurityCode = "AAPL", BoardCode = "All", }, Name = "AAPL", SecurityType = SecurityTypes.Stock, }); Trader.SendOutMessage(new SecurityMessage { SecurityId = new SecurityId { SecurityCode = "IBM", BoardCode = "BATS", }, Name = "IBM", SecurityType = SecurityTypes.Stock, }); Trader.SendOutMessage(new SecurityMessage { SecurityId = new SecurityId { SecurityCode = "IBM", BoardCode = "All", }, Name = "IBM", SecurityType = SecurityTypes.Stock, }); } } }
28.498258
123
0.694095
[ "Apache-2.0" ]
andriisydor/stocksharp
Samples/Sterling/SampleSterling/MainWindow.xaml.cs
8,179
C#
/* * MIT License * * Copyright (c) 2020 plexdata.de * * 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 NUnit.Framework; using Plexdata.FileChecksum.Internals.Algorithms; using System; using System.Security.Cryptography; namespace Plexdata.FileChecksum.Tests.Internals.Algorithms { [TestFixture] [TestOf(typeof(Sha512ChecksumCalculator))] public class Sha512ChecksumCalculatorTests { [Test] [TestCase(null, typeof(SHA512Managed))] [TestCase("", typeof(SHA512Managed))] [TestCase(" ", typeof(SHA512Managed))] [TestCase("SHA512", typeof(SHA512Managed))] [TestCase("System.Security.Cryptography.SHA512Cng", typeof(SHA512Cng))] [TestCase("System.Security.Cryptography.SHA512Managed", typeof(SHA512Managed))] [TestCase("System.Security.Cryptography.SHA512CryptoServiceProvider", typeof(SHA512CryptoServiceProvider))] public void Sha512Checksum_SupportedAlgorithmName_AlgorithmInstanceAsExpected(String algorithm, Type expected) { Sha512ChecksumCalculator actual = new Sha512ChecksumCalculator(algorithm); Assert.That(actual.Algorithm, Is.InstanceOf(expected)); } [Test] [TestCase("some-algorithm-name")] public void Sha512Checksum_UnsupportedAlgorithmName_ThrowsInvalidOperationException(String algorithm) { Assert.That(() => new Sha512ChecksumCalculator(algorithm), Throws.InstanceOf<InvalidOperationException>()); } } }
42.79661
119
0.740594
[ "MIT" ]
akesseler/Plexdata.FileChecksum
code/src/Plexdata.FileChecksum.Analyzer.Tests/Internals/Algorithms/Sha512ChecksumCalculatorTests.cs
2,527
C#
// // Copyright © 2012 - 2013 Nauck IT KG http://www.nauck-it.de // // Author: // Daniel Nauck <d.nauck(at)nauck-it.de> // // 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 Portable.Licensing; using ServiceStack.ServiceHost; namespace License.Manager.Core.ServiceModel { [Route("/licenses/{Id}", "PUT, DELETE, OPTIONS")] [Route("/products/{ProductId}/licenses/{Id}", "PUT, DELETE, OPTIONS")] [Route("/customers/{CustomerId}/licenses/{Id}", "PUT, DELETE, OPTIONS")] public class UpdateLicense : IReturn<LicenseDto> { public int Id { get; set; } public LicenseType LicenseType { get; set; } public int Quantity { get; set; } public DateTime? Expiration { get; set; } public int CustomerId { get; set; } public int ProductId { get; set; } public Dictionary<string, string> ProductFeatures { get; set; } public Dictionary<string, string> AdditionalAttributes { get; set; } public string Description { get; set; } } }
43.833333
76
0.706274
[ "MIT" ]
NetworKKnighT/License.Manager
src/License.Manager.Core/ServiceModel/UpdateLicense.cs
2,107
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Microsoft.Azure.Sentinel.Analytics.Management.AnalyticsManagement.Contracts.Model.ARM; using Microsoft.Azure.Sentinel.Analytics.Management.AnalyticsManagement.Contracts.Model.ARM.ModelValidation; using Microsoft.Azure.Sentinel.Analytics.Management.AnalyticsTemplatesService.Interface.ModelValidations; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Microsoft.Azure.Sentinel.Analytics.Management.AnalyticsTemplatesService.Interface.Model { [PeriodGreaterThanOrEqualFrequency] [FrequencyLimitationForLongPeriodQuery] [NewEntityMappings] public class ScheduledTemplateInternalModel : QueryBasedTemplateInternalModel { [JsonProperty("requiredDataConnectors", Required = Required.Always)] public override List<DataConnectorInternalModel> RequiredDataConnectors { get; set; } [JsonProperty("queryFrequency", Required = Required.Always)] [JsonConverter(typeof(ScheduledTemplateTimeSpanConverter))] [RangeTimeSpanIsoFormat("00:05:00", "14.00:00:00")] public TimeSpan QueryFrequency { get; set; } [JsonProperty("queryPeriod", Required = Required.Always)] [JsonConverter(typeof(ScheduledTemplateTimeSpanConverter))] [RangeTimeSpanIsoFormat("00:05:00", "14.00:00:00")] public TimeSpan QueryPeriod { get; set; } [JsonProperty("triggerOperator", Required = Required.Always)] [JsonConverter(typeof(ScheduledTemplateTriggerOperatorConverter))] public AlertTriggerOperator TriggerOperator { get; set; } [JsonProperty("triggerThreshold", Required = Required.Always)] [Range(0, 10000)] public int TriggerThreshold { get; set; } [JsonProperty("eventGroupingSettings", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)] public EventGroupingSettings EventGroupingSettings { get; set; } [JsonProperty("kind", Required = Required.Always)] public override AlertRuleKind Kind { get; } = AlertRuleKind.Scheduled; } public enum AlertTriggerOperator { GreaterThan, LessThan, Equal, NotEqual } }
42.566038
122
0.739805
[ "MIT" ]
Accelerynt-Security/Azure-Sentinel
.script/tests/detectionTemplateSchemaValidation/Models/ScheduledTemplateInternalModel.cs
2,258
C#
namespace Microsoft.Maui.Graphics.Controls { public class CupertinoCheckBoxDrawable : ViewDrawable<ICheckBox>, ICheckBoxDrawable { const string CupertinoCheckBoxMark = "M4.78246 10.9434C5.03441 10.9434 5.23363 10.832 5.37426 10.6152L10.9114 1.89648C11.0168 1.72656 11.0579 1.59766 11.0579 1.46289C11.0579 1.14062 10.8469 0.929688 10.5246 0.929688C10.2903 0.929688 10.1614 1.00586 10.0207 1.22852L4.75902 9.61328L2.02855 6.03906C1.88207 5.83398 1.73559 5.75195 1.52465 5.75195C1.19066 5.75195 0.962149 5.98047 0.962149 6.30273C0.962149 6.4375 1.02074 6.58984 1.13207 6.73047L4.17309 10.6035C4.34887 10.832 4.53051 10.9434 4.78246 10.9434Z"; public void DrawBackground(ICanvas canvas, RectangleF dirtyRect, ICheckBox checkBox) { canvas.SaveState(); float size = 24f; var x = dirtyRect.X; var y = dirtyRect.Y; if (checkBox.IsChecked) { Color fillColor = checkBox.IsEnabled ? Cupertino.Color.SystemColor.Light.Blue.ToColor() : Cupertino.Color.SystemGray.Light.InactiveGray.ToColor(); if (checkBox.Foreground is SolidPaint solidPaint) fillColor = solidPaint.Color; canvas.FillColor = fillColor; canvas.FillEllipse(x, y, size, size); } else { var strokeWidth = 2; canvas.StrokeSize = strokeWidth; canvas.StrokeColor = checkBox.IsEnabled ? Cupertino.Color.SystemColor.Light.Blue.ToColor() : Cupertino.Color.SystemGray.Light.InactiveGray.ToColor(); canvas.DrawEllipse(x + strokeWidth / 2, y + strokeWidth / 2, size - strokeWidth, size - strokeWidth); } canvas.RestoreState(); } public void DrawMark(ICanvas canvas, RectangleF dirtyRect, ICheckBox checkBox) { if (checkBox.IsChecked) { canvas.SaveState(); canvas.Translate(6, 6); var vBuilder = new PathBuilder(); var path = vBuilder.BuildPath(CupertinoCheckBoxMark); canvas.StrokeColor = Cupertino.Color.Fill.Light.WhiteAlt.ToColor(); canvas.DrawPath(path); canvas.RestoreState(); } } public void DrawText(ICanvas canvas, RectangleF dirtyRect, ICheckBox checkBox) { } public override Size GetDesiredSize(IView view, double widthConstraint, double heightConstraint) => new Size(widthConstraint, 24f); } }
40.046154
516
0.617749
[ "MIT" ]
LowerAI/Microsoft.Maui.Graphics.Controls
src/GraphicsControls/Handlers/CheckBox/CupertinoCheckBoxDrawable.cs
2,605
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using Topshelf; namespace RoombaService { class Program { static void Main(string[] args) { HostFactory.Run(x => { x.Service<RoombaService>(); x.RunAsLocalSystem(); x.SetDescription(ConfigurationManager.AppSettings["Description"]); x.SetDisplayName(ConfigurationManager.AppSettings["DisplayName"]); x.SetServiceName(ConfigurationManager.AppSettings["ServiceName"]); x.StartAutomatically(); }); } } }
26.307692
82
0.596491
[ "MIT" ]
xin2015/Roomba
RoombaService/Program.cs
686
C#
using Newtonsoft.Json; namespace StamAcasa.Common.Models { public class AnswerModel { [JsonProperty("id")] public long Id { get; set; } [JsonProperty("questionText")] public string QuestionText { get; set; } [JsonProperty("answer", NullValueHandling = NullValueHandling.Ignore)] public string Answer { get; set; } } }
23.8125
78
0.627297
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
code4romania/covid-19-jurnal-medical
backend/src/StamAcasa.Common/Models/AnswerModel.cs
383
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AbstractVehicules { class Voiture : Vehicule { public Voiture(int _AnneeModele, double _Prix) : base(_AnneeModele, _Prix) { } public override void Demarrer() { Console.WriteLine("La voiture démarre ...."); } public override void Accelerer() { Console.WriteLine("La voiture accélère ..."); } public override string ToString() { return "Voiture_ " + base.ToString(); } } }
22.206897
82
0.579193
[ "MIT" ]
berhu/Git_Projet_C_sharp
TPFraction/AbstractVehicules/Voiture.cs
649
C#
using System.Web.Mvc; namespace StructuredLogging.WebApi { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
21.5
80
0.662791
[ "Apache-2.0" ]
PSneijder/StructuredLogging
StructuredLogging.WebApi/App_Start/FilterConfig.cs
260
C#
using FluentValidation; using MediatR; namespace CQRSAndMediatrWithFluentValidationSampleApplication.Product.Pipeline { public class ValidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse> { private readonly IEnumerable<IValidator<TRequest>> _validators; public ValidationBehaviour(IEnumerable<IValidator<TRequest>> validators) { _validators = validators; } public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) { if (_validators.Any()) { var failures = _validators .Select(v => v.Validate(request)) .SelectMany(result => result.Errors) .Where(error => error != null) .ToList(); if (failures.Any()) { throw new ValidationException("Validation exception", failures); } } return await next(); ; } } }
31.27027
98
0.57822
[ "MIT" ]
marcelmedina/PlayGoKids
2022-04-04/CQRSAndMediatrWithFluentValidationSample/CQRSAndMediatrWithFluentValidationSampleApplication/Product/Pipeline/ValidationBehaviour.cs
1,159
C#
using System; using System.Threading.Tasks; using HotChocolate.Execution.Configuration; using Snapshooter.Xunit; using Xunit; namespace HotChocolate.Execution.Errors { public class ErrorHandlerTests { [Fact] public async Task AddFuncErrorFilter() { // arrange ISchema schema = Schema.Create("type Query { foo: String }", c => c.BindResolver( ctx => { throw new Exception("Foo"); }).To("Query", "foo")); var options = new QueryExecutionOptions { IncludeExceptionDetails = false }; IQueryExecutor executor = schema.MakeExecutable(builder => builder.UseDefaultPipeline(options) .AddErrorFilter(error => error.WithCode("Foo123"))); // act IExecutionResult result = await executor.ExecuteAsync("{ foo }"); // assert result.MatchSnapshot(o => o.IgnoreField("Errors[0].Exception")); } [Fact] public async Task FilterOnlyNullRefExceptions() { // arrange ISchema schema = Schema.Create( "type Query { foo: String bar: String }", c => { // will be handled by the default filter logic c.BindResolver( ctx => { throw new Exception("Foo"); }).To("Query", "foo"); // will be handled by the custom filter logic c.BindResolver( ctx => { throw new NullReferenceException("Foo"); }).To("Query", "bar"); }); var options = new QueryExecutionOptions { IncludeExceptionDetails = false, ExecutionTimeout = TimeSpan.FromMinutes(10) }; IQueryExecutor executor = schema.MakeExecutable(builder => builder.UseDefaultPipeline(options) .AddErrorFilter(error => { if (error.Exception is NullReferenceException) { return error.WithCode("NullRef"); } return error; })); // act IExecutionResult result = await executor.ExecuteAsync("{ foo bar }"); // assert result.MatchSnapshot(o => o.IgnoreField("Errors[0].Exception") .IgnoreField("Errors[1].Exception")); } [Fact] public async Task AddClassErrorFilter() { // arrange ISchema schema = Schema.Create("type Query { foo: String }", c => c.BindResolver( ctx => { throw new Exception("Foo"); }).To("Query", "foo")); var options = new QueryExecutionOptions { IncludeExceptionDetails = false }; IQueryExecutor executor = schema.MakeExecutable(builder => builder.UseDefaultPipeline(options) .AddErrorFilter<DummyErrorFilter>()); // act IExecutionResult result = await executor.ExecuteAsync("{ foo }"); // assert result.MatchSnapshot(o => o.IgnoreField("Errors[0].Exception")); } [Fact] public async Task AddClassErrorFilterWithFactory() { // arrange ISchema schema = Schema.Create("type Query { foo: String }", c => c.BindResolver( ctx => { throw new Exception("Foo"); }).To("Query", "foo")); var options = new QueryExecutionOptions { IncludeExceptionDetails = false }; IQueryExecutor executor = schema.MakeExecutable(builder => builder.UseDefaultPipeline(options) .AddErrorFilter(s => new DummyErrorFilter())); // act IExecutionResult result = await executor.ExecuteAsync("{ foo }"); // assert result.MatchSnapshot(o => o.IgnoreField("Errors[0].Exception")); } public class DummyErrorFilter : IErrorFilter { public IError OnError(IError error) { return error.WithCode("Foo123"); } } } }
31.294872
77
0.455961
[ "MIT" ]
Asshiah/hotchocolate
src/HotChocolate/Core/test/Core.Tests/Execution/Errors/ErrorHandlerTests.cs
4,884
C#
// Copyright (c) Drew Noakes and contributors. All Rights Reserved. Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Diagnostics.CodeAnalysis; namespace MetadataExtractor.Formats.Jpeg { /// <summary>Provides human-readable string versions of the tags stored in a JpegDirectory.</summary> /// <remarks> /// Provides human-readable string versions of the tags stored in a JpegDirectory. /// Thanks to Darrell Silver (www.darrellsilver.com) for the initial version of this class. /// </remarks> /// <author>Drew Noakes https://drewnoakes.com</author> [SuppressMessage("ReSharper", "MemberCanBePrivate.Global")] public sealed class JpegDescriptor : TagDescriptor<JpegDirectory> { public JpegDescriptor(JpegDirectory directory) : base(directory) { } public override string? GetDescription(int tagType) { return tagType switch { JpegDirectory.TagCompressionType => GetImageCompressionTypeDescription(), JpegDirectory.TagComponentData1 => GetComponentDataDescription(0), JpegDirectory.TagComponentData2 => GetComponentDataDescription(1), JpegDirectory.TagComponentData3 => GetComponentDataDescription(2), JpegDirectory.TagComponentData4 => GetComponentDataDescription(3), JpegDirectory.TagDataPrecision => GetDataPrecisionDescription(), JpegDirectory.TagImageHeight => GetImageHeightDescription(), JpegDirectory.TagImageWidth => GetImageWidthDescription(), _ => base.GetDescription(tagType), }; } public string? GetImageCompressionTypeDescription() { return GetIndexedDescription(JpegDirectory.TagCompressionType, "Baseline", "Extended sequential, Huffman", "Progressive, Huffman", "Lossless, Huffman", null, // no 4 "Differential sequential, Huffman", "Differential progressive, Huffman", "Differential lossless, Huffman", "Reserved for JPEG extensions", "Extended sequential, arithmetic", "Progressive, arithmetic", "Lossless, arithmetic", null, // no 12 "Differential sequential, arithmetic", "Differential progressive, arithmetic", "Differential lossless, arithmetic"); } public string? GetImageWidthDescription() { var value = Directory.GetString(JpegDirectory.TagImageWidth); return value == null ? null : value + " pixels"; } public string? GetImageHeightDescription() { var value = Directory.GetString(JpegDirectory.TagImageHeight); return value == null ? null : value + " pixels"; } public string? GetDataPrecisionDescription() { var value = Directory.GetString(JpegDirectory.TagDataPrecision); return value == null ? null : value + " bits"; } public string? GetComponentDataDescription(int componentNumber) { var value = Directory.GetComponent(componentNumber); if (value == null) return null; return $"{value.Name} component: {value}"; } } }
39.111111
172
0.611364
[ "Apache-2.0" ]
GwG422/metadata-extractor-dotnet
MetadataExtractor/Formats/Jpeg/JpegDescriptor.cs
3,520
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SimpleWebApp { public partial class _Default { } }
24.111111
81
0.407834
[ "MIT" ]
tlaothong/lab-swp-ws-kiatnakin
LabWs1/SimpleWebApp/Default.aspx.designer.cs
436
C#
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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.Security; namespace Alphaleonis.Win32.Filesystem { public static partial class Directory { /// <summary>[AlphaFS] Returns the volume information, root information, or both for the specified path.</summary> /// <returns>The volume information, root information, or both for the specified path, or <c>null</c> if <paramref name="path"/> path does not contain root directory information.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="NotSupportedException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The path of a file or directory.</param> [SecurityCritical] public static string GetDirectoryRootTransacted(KernelTransaction transaction, string path) { return GetDirectoryRootCore(transaction, path, PathFormat.RelativePath); } /// <summary>[AlphaFS] Returns the volume information, root information, or both for the specified path.</summary> /// <returns>The volume information, root information, or both for the specified path, or <c>null</c> if <paramref name="path"/> path does not contain root directory information.</returns> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="NotSupportedException"/> /// <param name="transaction">The transaction.</param> /// <param name="path">The path of a file or directory.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public static string GetDirectoryRootTransacted(KernelTransaction transaction, string path, PathFormat pathFormat) { return GetDirectoryRootCore(transaction, path, pathFormat); } } }
52.87931
194
0.716009
[ "MIT" ]
DamirAinullin/AlphaFS
src/AlphaFS/Filesystem/Directory Class/Directory.GetDirectoryRootTransacted.cs
3,067
C#
namespace BetfairClient.Models.Betting { /// <summary> /// Betfair documentation: https://docs.developer.betfair.com/display/1smk3cen4v3lu3yomq5qye0ni/Betting+Type+Definitions#BettingTypeDefinitions-CompetitionResult /// </summary> public class CompetitionResult { public Competition Competition { get; set; } public int MarketCount { get; set; } public string CompetitionRegion { get; set; } } }
32.214286
169
0.694013
[ "MIT" ]
tiagojsrios/betfair-client-csharp
src/BetfairClient/BetfairClient.Models/Betting/CompetitionResult.cs
453
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using System.Collections; using NetOffice; namespace NetOffice.ExcelApi { ///<summary> /// DispatchInterface UsedObjects /// SupportByVersion Excel, 10,11,12,14,15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff838263.aspx ///</summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class UsedObjects : COMObject ,IEnumerable<object> { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(UsedObjects); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public UsedObjects(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public UsedObjects(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public UsedObjects(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public UsedObjects(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public UsedObjects(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public UsedObjects() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public UsedObjects(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff834638.aspx /// </summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] public NetOffice.ExcelApi.Application Application { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Application", paramsArray); NetOffice.ExcelApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.ExcelApi.Application.LateBindingApiWrapperType) as NetOffice.ExcelApi.Application; return newObject; } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff194474.aspx /// </summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] public NetOffice.ExcelApi.Enums.XlCreator Creator { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Creator", paramsArray); int intReturnItem = NetRuntimeSystem.Convert.ToInt32(returnItem); return (NetOffice.ExcelApi.Enums.XlCreator)intReturnItem; } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff834461.aspx /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] public object Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff840938.aspx /// </summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] public Int32 Count { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Count", paramsArray); return NetRuntimeSystem.Convert.ToInt32(returnItem); } } /// <summary> /// SupportByVersion Excel 10, 11, 12, 14, 15 /// Get /// Unknown COM Proxy /// </summary> /// <param name="index">object Index</param> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item")] public object this[object index] { get { object[] paramsArray = Invoker.ValidateParamsArray(index); object returnItem = Invoker.PropertyGet(this, "_Default", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } #endregion #region Methods #endregion #region IEnumerable<object> Member /// <summary> /// SupportByVersionAttribute Excel, 10,11,12,14,15 /// </summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] public IEnumerator<object> GetEnumerator() { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (object item in innerEnumerator) yield return item; } #endregion #region IEnumerable Members /// <summary> /// SupportByVersionAttribute Excel, 10,11,12,14,15 /// </summary> [SupportByVersionAttribute("Excel", 10,11,12,14,15)] IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator() { return NetOffice.Utils.GetProxyEnumeratorAsProperty(this); } #endregion #pragma warning restore } }
33.270642
194
0.674066
[ "MIT" ]
NetOffice/NetOffice
Source/Excel/DispatchInterfaces/UsedObjects.cs
7,253
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 Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Serilog; using Serilog.Events; using Serilog.Sinks.SystemConsole.Themes; using System; using System.IO; using System.Linq; namespace Cirno.Identity { public class Program { public static IConfiguration Configuration { get; } = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true) .AddEnvironmentVariables() .Build(); public static int Main(string[] args) { // Configuration can be specified by appsettings.json (https://github.com/serilog/serilog-settings-configuration) Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(Configuration) .CreateLogger(); try { CreateWebHostBuilder(args).Build().Run(); return 0; } catch (Exception ex) { Log.Fatal(ex, "Host terminated unexpectedly"); return 1; } finally { Log.CloseAndFlush(); } } public static IWebHostBuilder CreateWebHostBuilder(string[] args) { return WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { // Call other providers here and call AddCommandLine last. config.AddCommandLine(args); }) .UseStartup<Startup>() .UseSerilog(); } } }
33.460317
139
0.601044
[ "MIT" ]
Sparin/Cirno
src/Cirno.Identity/Program.cs
2,110
C#
namespace Khala.EventSourcing { using System.Threading; /// <summary> /// Provides interfaces to manage event publishing. /// </summary> public interface IEventPublisher { /// <summary> /// Starts to publish pending events for all aggregates having events not published yet. /// </summary> /// <param name="cancellationToken">A <see cref="CancellationToken"/> to observe while waiting for the task to complete.</param> void EnqueueAll(CancellationToken cancellationToken = default); } }
32.764706
136
0.662478
[ "MIT" ]
ReactiveArchitecture/RA.EventSourcing
source/Khala.EventSourcing.Abstraction/EventSourcing/IEventPublisher.cs
559
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BULogic { public class ProgramLogic { private static Chains _chains; private static Groceries _items; private static int _lockNumber = 0; private static ICollection<Task> _tasksToWait; public static void InitChains() { _chains = new Chains(); _items = new Groceries(); _tasksToWait = new List<Task>(); } public static List<string> GetGroceries(string typeProducts) { return _items.GetGroceries(typeProducts); } public static void AddGrociery(string itemName, double itemCapacity) { _tasksToWait.Add(Task.Run(() => { _items.AddItem(itemName, itemCapacity); _chains.AddItem(itemName); } )); } public static Task<string[]> GetChainsName() { return Task.Run(() => _chains.GetChainsName()); } public static Task<ItemsInChain> GetChainInfo(string chain) { return Task.Run(() => { Task.WaitAll(_tasksToWait.ToArray()); _tasksToWait.Clear(); var result = new ItemsInChain(); var items = _items.GetAllItems(); var chainInfo = _chains.GetChainInfo(chain, items); for (var i = 0; (i < 3) && (i < chainInfo.Count); i++) result.CheapestList.Add(chainInfo[i]); Parallel.For(3, chainInfo.Count, i => result.ExpensiveList.Add(chainInfo[i])); return result; }); } public static void ChangeGrocieryCount(string itemName, double capacity) { _items.ChangeCapcity(itemName, capacity); } public static void ClearGrocieries() { _items.Clear(); } public static Task<Dictionary<string, bool>> GetAllChains() { return Task.Run(() => _chains.GetChainNamesAndAvailability()); } public static void ChangeChainsBool(Dictionary<string, bool> chainsDictonary) { _chains.SetChains(chainsDictonary); } public static Task<double> GetItemCapacity(string itemName) { return Task.Run(() => _items.GetGroceryCapacity(itemName)); } public static Task<string[]> GetCategoriesOfItems() { return Task.Run(() => _items.GetCategories()); } public static Task<List<double>> GetSumsOfChains() { return Task.Run(() => { Task.WaitAll(_tasksToWait.ToArray()); _tasksToWait.Clear(); var items = _items.GetAllItems(); return _chains.GetSum(items); }); } } }
30.57
95
0.519464
[ "MIT" ]
dannyk360/LABS
UIPriceCompare/BULogic/ProgramLogic.cs
3,059
C#
using LineBotKit.Client.Response; using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; namespace LineBotKit.Client.Request { internal class LinePostFormUrlEncodedRequest<T> : LineClientRequestBase { private const string LineDefaultResponseType = "application/x-www-form-urlencoded"; public LinePostFormUrlEncodedRequest(LineClientBase client, string path) : base(client, path, HttpMethod.Post) { } public Task<LineClientResult<T>> Execute(object body, CancellationToken cancellationToken = default(CancellationToken)) { return base.Execute<T>(body, cancellationToken); } protected override void BuildBodyContent(HttpRequestMessage message, object body) { if (Params.Count > 0) { message.Content = new FormUrlEncodedContent(Params); } } protected override Task<Uri> BuildUri(string url, List<KeyValuePair<string, string>> queryParams) { return base.BuildUri(url, null); } } }
30.631579
127
0.671821
[ "Apache-2.0" ]
holmes2136/LineBotKit
src/LineBotKit.Client/Request/LinePostFormUrlEncodedRequest.cs
1,166
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace TJAPlayer3 { /// <summary> /// CDTXStyleExtractor determines if there is a session notation, and if there is then /// it returns a sheet of music clipped according to the specified player Side. /// /// The process operates as follows: /// 1. Break the string up into top-level sections of the following types: /// a) STYLE Single /// b) STYLE Double/Couple /// c) STYLE unrecognized /// d) non-STYLE /// 2. Within the top-level sections, break each up into sub-sections of the following types: /// a) sheet START P1 /// b) sheet START P2 /// c) sheet START bare /// d) sheet START unrecognized /// e) non-sheet /// 3. For the current seqNo, rank the found sheets /// using a per-seqNo set of rankings for each /// relevant section/subsection combination. /// 4. Determine the best-ranked sheet /// 5. Remove sheets other than the best-ranked /// 6. Remove top-level STYLE-type sections which no longer contain a sheet /// 7. From supported STYLE-type sections, remove non-sheet subsections beyond /// the selected sheet, to reduce risk of incorrect command processing. /// 8. Reassemble the string /// </summary> public static class CDTXStyleExtractor { private const RegexOptions StyleExtractorRegexOptions = RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline; private const string StylePrefixRegexPattern = @"^STYLE\s*:\s*"; private const string SheetStartPrefixRegexPattern = @"^#START"; private static readonly string StyleSingleSectionRegexMatchPattern = $"{StylePrefixRegexPattern}(?:Single|1)"; private static readonly string StyleDoubleSectionRegexMatchPattern = $"{StylePrefixRegexPattern}(?:Double|Couple|2)"; private static readonly string StyleUnrecognizedSectionRegexMatchPattern = $"{StylePrefixRegexPattern}"; private static readonly string SheetStartBareRegexMatchPattern = $"{SheetStartPrefixRegexPattern}$"; private static readonly string SheetStartP1RegexMatchPattern = $"{SheetStartPrefixRegexPattern}\\s*P1"; private static readonly string SheetStartP2RegexMatchPattern = $"{SheetStartPrefixRegexPattern}\\s*P2"; private static readonly string SheetStartUnrecognizedRegexMatchPattern = $"{SheetStartPrefixRegexPattern}.*$"; private static readonly Regex SectionSplitRegex = new Regex($"(?={StylePrefixRegexPattern})", StyleExtractorRegexOptions); private static readonly Regex SubSectionSplitRegex = new Regex($"(?={SheetStartPrefixRegexPattern})|(?<=#END\\n)", StyleExtractorRegexOptions); private static readonly Regex StyleSingleSectionMatchRegex = new Regex(StyleSingleSectionRegexMatchPattern, StyleExtractorRegexOptions); private static readonly Regex StyleDoubleSectionMatchRegex = new Regex(StyleDoubleSectionRegexMatchPattern, StyleExtractorRegexOptions); private static readonly Regex StyleUnrecognizedSectionMatchRegex = new Regex(StyleUnrecognizedSectionRegexMatchPattern, StyleExtractorRegexOptions); private static readonly Regex SheetStartPrefixMatchRegex = new Regex(SheetStartPrefixRegexPattern, StyleExtractorRegexOptions); private static readonly Regex SheetStartBareMatchRegex = new Regex(SheetStartBareRegexMatchPattern, StyleExtractorRegexOptions); private static readonly Regex SheetStartP1MatchRegex = new Regex(SheetStartP1RegexMatchPattern, StyleExtractorRegexOptions); private static readonly Regex SheetStartP2MatchRegex = new Regex(SheetStartP2RegexMatchPattern, StyleExtractorRegexOptions); private static readonly Regex SheetStartUnrecognizedMatchRegex = new Regex(SheetStartUnrecognizedRegexMatchPattern, StyleExtractorRegexOptions); private static readonly SectionKindAndSubSectionKind StyleSingleAndSheetStartBare = new SectionKindAndSubSectionKind(SectionKind.StyleSingle, SubSectionKind.SheetStartBare); private static readonly SectionKindAndSubSectionKind StyleSingleAndSheetStartP1 = new SectionKindAndSubSectionKind(SectionKind.StyleSingle, SubSectionKind.SheetStartP1); private static readonly SectionKindAndSubSectionKind StyleSingleAndSheetStartP2 = new SectionKindAndSubSectionKind(SectionKind.StyleSingle, SubSectionKind.SheetStartP2); private static readonly SectionKindAndSubSectionKind StyleSingleAndSheetStartUnrecognized = new SectionKindAndSubSectionKind(SectionKind.StyleSingle, SubSectionKind.SheetStartUnrecognized); private static readonly SectionKindAndSubSectionKind StyleDoubleAndSheetStartBare = new SectionKindAndSubSectionKind(SectionKind.StyleDouble, SubSectionKind.SheetStartBare); private static readonly SectionKindAndSubSectionKind StyleDoubleAndSheetStartP1 = new SectionKindAndSubSectionKind(SectionKind.StyleDouble, SubSectionKind.SheetStartP1); private static readonly SectionKindAndSubSectionKind StyleDoubleAndSheetStartP2 = new SectionKindAndSubSectionKind(SectionKind.StyleDouble, SubSectionKind.SheetStartP2); private static readonly SectionKindAndSubSectionKind StyleDoubleAndSheetStartUnrecognized = new SectionKindAndSubSectionKind(SectionKind.StyleDouble, SubSectionKind.SheetStartUnrecognized); private static readonly SectionKindAndSubSectionKind StyleUnrecognizedAndSheetStartBare = new SectionKindAndSubSectionKind(SectionKind.StyleUnrecognized, SubSectionKind.SheetStartBare); private static readonly SectionKindAndSubSectionKind StyleUnrecognizedAndSheetStartP1 = new SectionKindAndSubSectionKind(SectionKind.StyleUnrecognized, SubSectionKind.SheetStartP1); private static readonly SectionKindAndSubSectionKind StyleUnrecognizedAndSheetStartP2 = new SectionKindAndSubSectionKind(SectionKind.StyleUnrecognized, SubSectionKind.SheetStartP2); private static readonly SectionKindAndSubSectionKind StyleUnrecognizedAndSheetStartUnrecognized = new SectionKindAndSubSectionKind(SectionKind.StyleUnrecognized, SubSectionKind.SheetStartUnrecognized); private static readonly SectionKindAndSubSectionKind NonStyleAndSheetStartBare = new SectionKindAndSubSectionKind(SectionKind.NonStyle, SubSectionKind.SheetStartBare); private static readonly SectionKindAndSubSectionKind NonStyleAndSheetStartP1 = new SectionKindAndSubSectionKind(SectionKind.NonStyle, SubSectionKind.SheetStartP1); private static readonly SectionKindAndSubSectionKind NonStyleAndSheetStartP2 = new SectionKindAndSubSectionKind(SectionKind.NonStyle, SubSectionKind.SheetStartP2); private static readonly SectionKindAndSubSectionKind NonStyleAndSheetStartUnrecognized = new SectionKindAndSubSectionKind(SectionKind.NonStyle, SubSectionKind.SheetStartUnrecognized); private static readonly IDictionary<SectionKindAndSubSectionKind, int>[] SeqNoSheetRanksBySectionKindAndSubSectionKind = { // seqNo 0 new Dictionary<SectionKindAndSubSectionKind, int> { [StyleSingleAndSheetStartBare] = 1, [StyleSingleAndSheetStartP1] = 2, [StyleSingleAndSheetStartUnrecognized] = 3, [NonStyleAndSheetStartBare] = 4, [NonStyleAndSheetStartP1] = 5, [NonStyleAndSheetStartUnrecognized] = 6, [StyleUnrecognizedAndSheetStartBare] = 7, [StyleUnrecognizedAndSheetStartUnrecognized] = 8, [StyleUnrecognizedAndSheetStartP1] = 9, [StyleDoubleAndSheetStartP1] = 10, [StyleDoubleAndSheetStartBare] = 11, [StyleDoubleAndSheetStartUnrecognized] = 12, [StyleSingleAndSheetStartP2] = 13, [NonStyleAndSheetStartP2] = 14, [StyleUnrecognizedAndSheetStartP2] = 15, [StyleDoubleAndSheetStartP2] = 16, }, // seqNo 1 new Dictionary<SectionKindAndSubSectionKind, int> { [StyleDoubleAndSheetStartP1] = 1, [StyleUnrecognizedAndSheetStartP1] = 2, [NonStyleAndSheetStartP1] = 3, [StyleSingleAndSheetStartP1] = 4, [StyleDoubleAndSheetStartBare] = 5, [StyleDoubleAndSheetStartUnrecognized] = 6, [StyleUnrecognizedAndSheetStartBare] = 7, [StyleUnrecognizedAndSheetStartUnrecognized] = 8, [StyleSingleAndSheetStartBare] = 9, [StyleSingleAndSheetStartUnrecognized] = 10, [NonStyleAndSheetStartBare] = 11, [NonStyleAndSheetStartUnrecognized] = 12, [StyleDoubleAndSheetStartP2] = 13, [StyleUnrecognizedAndSheetStartP2] = 14, [NonStyleAndSheetStartP2] = 15, [StyleSingleAndSheetStartP2] = 16, }, // seqNo 2 new Dictionary<SectionKindAndSubSectionKind, int> { [StyleDoubleAndSheetStartP2] = 1, [StyleUnrecognizedAndSheetStartP2] = 2, [NonStyleAndSheetStartP2] = 3, [StyleSingleAndSheetStartP2] = 4, [StyleDoubleAndSheetStartUnrecognized] = 5, [StyleDoubleAndSheetStartBare] = 6, [StyleUnrecognizedAndSheetStartUnrecognized] = 7, [StyleUnrecognizedAndSheetStartBare] = 8, [StyleSingleAndSheetStartUnrecognized] = 9, [StyleSingleAndSheetStartBare] = 10, [NonStyleAndSheetStartUnrecognized] = 11, [NonStyleAndSheetStartBare] = 12, [StyleDoubleAndSheetStartP1] = 13, [StyleUnrecognizedAndSheetStartP1] = 14, [NonStyleAndSheetStartP1] = 15, [StyleSingleAndSheetStartP1] = 16, }, }; public static string tセッション譜面がある(string strTJA, int seqNo, string strFilenameの絶対パス) { void TraceError(string subMessage) { Trace.TraceError(FormatTraceMessage(subMessage)); } string FormatTraceMessage(string subMessage) { return $"{nameof(CDTXStyleExtractor)} {subMessage} (seqNo={seqNo}, {strFilenameの絶対パス})"; } //入力された譜面がnullでないかチェック。 if (string.IsNullOrEmpty(strTJA)) { TraceError("is returning its input value early due to null or empty strTJA."); return strTJA; } // 1. Break the string up into top-level sections of the following types: // a) STYLE Single // b) STYLE Double/Couple // c) STYLE unrecognized // d) non-STYLE var sections = GetSections(strTJA); // 2. Within the top-level sections, break each up into sub-sections of the following types: // a) sheet START P1 // b) sheet START P2 // c) sheet START bare // d) sheet START unrecognized // e) non-sheet SubdivideSectionsIntoSubSections(sections); // 3. For the current seqNo, rank the found sheets // using a per-seqNo set of rankings for each // relevant section/subsection combination. RankSheets(seqNo, sections); // 4. Determine the best-ranked sheet int bestRank; try { bestRank = GetBestRank(sections); } catch (Exception) { TraceError("is returning its input value early due to an inability to determine the best rank. This can occur if a course contains no #START."); return strTJA; } // 5. Remove sheets other than the best-ranked RemoveSheetsOtherThanTheBestRanked(sections, bestRank); // 6. Remove top-level STYLE-type sections which no longer contain a sheet RemoveRecognizedStyleSectionsWithoutSheets(sections); // 7. From supported STYLE-type sections, remove non-sheet subsections beyond // the selected sheet, to reduce risk of incorrect command processing. RemoveStyleSectionSubSectionsBeyondTheSelectedSheet(sections); // 8. Reassemble the string return Reassemble(sections); } // 1. Break the string up into top-level sections of the following types: // a) STYLE Single // b) STYLE Double/Couple // c) STYLE unrecognized // d) non-STYLE private static List<Section> GetSections(string strTJA) { return SectionSplitRegex .Split(strTJA) .Select(o => new Section(GetSectionKind(o), o)) .ToList(); } private static SectionKind GetSectionKind(string section) { if (StyleSingleSectionMatchRegex.IsMatch(section)) { return SectionKind.StyleSingle; } if (StyleDoubleSectionMatchRegex.IsMatch(section)) { return SectionKind.StyleDouble; } if (StyleUnrecognizedSectionMatchRegex.IsMatch(section)) { return SectionKind.StyleUnrecognized; } return SectionKind.NonStyle; } private enum SectionKind { StyleSingle, StyleDouble, StyleUnrecognized, NonStyle } private sealed class Section { public readonly SectionKind SectionKind; public readonly string OriginalRawValue; public List<SubSection> SubSections; public Section(SectionKind sectionKind, string originalRawValue) { SectionKind = sectionKind; OriginalRawValue = originalRawValue; } } // 2. Within the top-level sections, break each up into sub-sections of the following types: // a) sheet START P1 // b) sheet START P2 // c) sheet START bare // d) sheet START unrecognized // e) non-sheet private static void SubdivideSectionsIntoSubSections(IEnumerable<Section> sections) { foreach (var section in sections) { section.SubSections = SubSectionSplitRegex .Split(section.OriginalRawValue) .Select(o => new SubSection(GetSubsectionKind(o), o)) .ToList(); } } private static SubSectionKind GetSubsectionKind(string subsection) { if (SheetStartPrefixMatchRegex.IsMatch(subsection)) { if (SheetStartBareMatchRegex.IsMatch(subsection)) { return SubSectionKind.SheetStartBare; } if (SheetStartP1MatchRegex.IsMatch(subsection)) { return SubSectionKind.SheetStartP1; } if (SheetStartP2MatchRegex.IsMatch(subsection)) { return SubSectionKind.SheetStartP2; } if (SheetStartUnrecognizedMatchRegex.IsMatch(subsection)) { return SubSectionKind.SheetStartUnrecognized; } } return SubSectionKind.NonSheet; } private enum SubSectionKind { SheetStartP1, SheetStartP2, SheetStartBare, SheetStartUnrecognized, NonSheet } private sealed class SubSection { public readonly SubSectionKind SubSectionKind; public readonly string OriginalRawValue; public int Rank; public SubSection(SubSectionKind subSectionKind, string originalRawValue) { SubSectionKind = subSectionKind; OriginalRawValue = originalRawValue; } } // 3. For the current seqNo, rank the found sheets // using a per-seqNo set of rankings for each // relevant section/subsection combination. private static void RankSheets(int seqNo, IList<Section> sections) { var sheetRanksBySectionKindAndSubSectionKind = SeqNoSheetRanksBySectionKindAndSubSectionKind[seqNo]; foreach (var section in sections) { var sectionKind = section.SectionKind; foreach (var subSection in section.SubSections) { var subSectionKind = subSection.SubSectionKind; if (subSectionKind == SubSectionKind.NonSheet) { continue; } var sectionKindAndSubSectionKind = new SectionKindAndSubSectionKind( sectionKind, subSectionKind); subSection.Rank = sheetRanksBySectionKindAndSubSectionKind[sectionKindAndSubSectionKind]; } } } private sealed class SectionKindAndSubSectionKind : IEquatable<SectionKindAndSubSectionKind> { public readonly SectionKind SectionKind; public readonly SubSectionKind SubSectionKind; public SectionKindAndSubSectionKind(SectionKind sectionKind, SubSectionKind subSectionKind) { SectionKind = sectionKind; SubSectionKind = subSectionKind; } public bool Equals(SectionKindAndSubSectionKind other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return SectionKind == other.SectionKind && SubSectionKind == other.SubSectionKind; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is SectionKindAndSubSectionKind other && Equals(other); } public override int GetHashCode() { unchecked { return ((int) SectionKind * 397) ^ (int) SubSectionKind; } } public static bool operator ==(SectionKindAndSubSectionKind left, SectionKindAndSubSectionKind right) { return Equals(left, right); } public static bool operator !=(SectionKindAndSubSectionKind left, SectionKindAndSubSectionKind right) { return !Equals(left, right); } } // 4. Determine the best-ranked sheet private static int GetBestRank(IList<Section> sections) { return sections .SelectMany(o => o.SubSections) .Where(o => o.SubSectionKind != SubSectionKind.NonSheet) .Select(o => o.Rank) .Min(); } // 5. Remove sheets other than the best-ranked private static void RemoveSheetsOtherThanTheBestRanked(IList<Section> sections, int bestRank) { // We can safely remove based on > bestRank because the subsection types // which are never removed always have a Rank value of 0. foreach (var section in sections) { section.SubSections.RemoveAll(o => o.Rank > bestRank); } // If there was a tie for the best sheet, // take the first and remove the rest. var extraBestRankedSheets = new HashSet<SubSection>(sections .SelectMany(o => o.SubSections) .Where(o => o.Rank == bestRank) .Skip(1)); foreach (var section in sections) { section.SubSections.RemoveAll(extraBestRankedSheets.Contains); } } // 6. Remove top-level STYLE-type sections which no longer contain a sheet private static void RemoveRecognizedStyleSectionsWithoutSheets(List<Section> sections) { // Note that we dare not remove SectionKind.StyleUnrecognized instances without sheets. // The reason is because there are plenty of .tja files with weird STYLE: header values // and which are located very early in the file. Removing those sections would remove // important information, and was one of the problems with the years-old splitting code // which was replaced in late summer 2018 and which is now being overhauled in early fall 2018. sections.RemoveAll(o => (o.SectionKind == SectionKind.StyleSingle || o.SectionKind == SectionKind.StyleDouble) && o.SubSections.Count(subSection => subSection.SubSectionKind == SubSectionKind.NonSheet) == o.SubSections.Count); } // 7. From supported STYLE-type sections, remove non-sheet subsections beyond // the selected sheet, to reduce risk of incorrect command processing. private static void RemoveStyleSectionSubSectionsBeyondTheSelectedSheet(List<Section> sections) { foreach (var section in sections) { if (section.SectionKind == SectionKind.StyleSingle || section.SectionKind == SectionKind.StyleDouble) { var subSections = section.SubSections; var lastIndex = subSections.FindIndex(o => o.SubSectionKind != SubSectionKind.NonSheet); var removalIndex = lastIndex + 1; if (lastIndex != -1 && removalIndex < subSections.Count) { subSections.RemoveRange(removalIndex, subSections.Count - removalIndex); } } } } // 8. Reassemble the string private static string Reassemble(List<Section> sections) { var sb = new StringBuilder(); foreach (var section in sections) { foreach (var subSection in section.SubSections) { sb.Append(subSection.OriginalRawValue); } } return sb.ToString(); } } }
36.236264
151
0.731766
[ "MIT" ]
FAKEYJSNPI/TJAPlayer3-f
TJAPlayer3-f/src/Songs/CDTXStyleExtractor.cs
19,861
C#
using System; using System.Runtime.InteropServices; using ElmSharp; using EEntry = ElmSharp.Entry; namespace Microsoft.Maui.Controls.Compatibility.Platform.Tizen { internal static class EntryExtensions { internal static InputPanelReturnKeyType ToInputPanelReturnKeyType(this ReturnType returnType) { switch (returnType) { case ReturnType.Go: return InputPanelReturnKeyType.Go; case ReturnType.Next: return InputPanelReturnKeyType.Next; case ReturnType.Send: return InputPanelReturnKeyType.Send; case ReturnType.Search: return InputPanelReturnKeyType.Search; case ReturnType.Done: return InputPanelReturnKeyType.Done; case ReturnType.Default: return InputPanelReturnKeyType.Default; default: throw new System.NotImplementedException($"ReturnType {returnType} not supported"); } } public static void GetSelectRegion(this EEntry entry, out int start, out int end) { elm_entry_select_region_get(entry.RealHandle, out start, out end); } [DllImport("libelementary.so.1")] static extern void elm_entry_select_region_get(IntPtr obj, out int start, out int end); } }
29.589744
95
0.762565
[ "MIT" ]
10088/maui
src/Compatibility/Core/src/Tizen/Extensions/EntryExtensions.cs
1,154
C#
// // // THIS FILE HAS BEEN GENERATED. DO NOT MODIFY. // using System; using System.Collections.Generic; using byps; namespace byps.test.api.srvr { public sealed class BRequest_ClientIF_incrementInt : BMethodRequest, BSerializable { #region Execute public override int getRemoteId() { return 2049072174; } public override void execute(BRemote __byps__remote, BAsyncResultIF<Object> __byps__asyncResult) { // checkpoint byps.gen.cs.GenApiClass:429 try { ClientIF __byps__remoteT = (ClientIF)__byps__remote; BAsyncResultSendMethod<int> __byps__outerResult = new BAsyncResultSendMethod<int>(__byps__asyncResult, new byps.test.api.BResult_5()); __byps__remoteT.IncrementInt(aValue, BAsyncResultHelper.ToDelegate(__byps__outerResult)); } catch (Exception e) { __byps__asyncResult.setAsyncResult(0, e); } } #endregion #region Fields internal int aValue; #endregion public static readonly long serialVersionUID = 1685952420L; } // end class } // end namespace
24.302326
142
0.733971
[ "MIT" ]
markusessigde/byps
csharp/bypstest-ser/src-ser/byps/test/api/srvr/BRequest_ClientIF_incrementInt.cs
1,047
C#
namespace PatternPal.Tests.TestClasses.ClassChecks { public class Class5 : EClass5 { } public class EClass5 : E1Class5 { } public class E1Class5 : IClass5 { } public interface IClass5 { } }
12.736842
51
0.595041
[ "MIT" ]
PatternPal/PatternPal
PatternPal/PatternPal.Tests/TestClasses/ClassChecks/Class5.cs
244
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using Azure.Core; using Azure.ResourceManager.Models; namespace Azure.ResourceManager.Sql.Models { /// <summary> Represents the activity on an elastic pool. </summary> public partial class ElasticPoolActivity : Resource { /// <summary> Initializes a new instance of ElasticPoolActivity. </summary> public ElasticPoolActivity() { } /// <summary> Initializes a new instance of ElasticPoolActivity. </summary> /// <param name="id"> The id. </param> /// <param name="name"> The name. </param> /// <param name="type"> The type. </param> /// <param name="location"> The geo-location where the resource lives. </param> /// <param name="endTime"> The time the operation finished (ISO8601 format). </param> /// <param name="errorCode"> The error code if available. </param> /// <param name="errorMessage"> The error message if available. </param> /// <param name="errorSeverity"> The error severity if available. </param> /// <param name="operation"> The operation name. </param> /// <param name="operationId"> The unique operation ID. </param> /// <param name="percentComplete"> The percentage complete if available. </param> /// <param name="requestedDatabaseDtuMax"> The requested max DTU per database if available. </param> /// <param name="requestedDatabaseDtuMin"> The requested min DTU per database if available. </param> /// <param name="requestedDtu"> The requested DTU for the pool if available. </param> /// <param name="requestedElasticPoolName"> The requested name for the elastic pool if available. </param> /// <param name="requestedStorageLimitInGB"> The requested storage limit for the pool in GB if available. </param> /// <param name="elasticPoolName"> The name of the elastic pool. </param> /// <param name="serverName"> The name of the server the elastic pool is in. </param> /// <param name="startTime"> The time the operation started (ISO8601 format). </param> /// <param name="state"> The current state of the operation. </param> /// <param name="requestedStorageLimitInMB"> The requested storage limit in MB. </param> /// <param name="requestedDatabaseDtuGuarantee"> The requested per database DTU guarantee. </param> /// <param name="requestedDatabaseDtuCap"> The requested per database DTU cap. </param> /// <param name="requestedDtuGuarantee"> The requested DTU guarantee. </param> internal ElasticPoolActivity(ResourceIdentifier id, string name, ResourceType type, string location, DateTimeOffset? endTime, int? errorCode, string errorMessage, int? errorSeverity, string operation, Guid? operationId, int? percentComplete, int? requestedDatabaseDtuMax, int? requestedDatabaseDtuMin, int? requestedDtu, string requestedElasticPoolName, long? requestedStorageLimitInGB, string elasticPoolName, string serverName, DateTimeOffset? startTime, string state, int? requestedStorageLimitInMB, int? requestedDatabaseDtuGuarantee, int? requestedDatabaseDtuCap, int? requestedDtuGuarantee) : base(id, name, type) { Location = location; EndTime = endTime; ErrorCode = errorCode; ErrorMessage = errorMessage; ErrorSeverity = errorSeverity; Operation = operation; OperationId = operationId; PercentComplete = percentComplete; RequestedDatabaseDtuMax = requestedDatabaseDtuMax; RequestedDatabaseDtuMin = requestedDatabaseDtuMin; RequestedDtu = requestedDtu; RequestedElasticPoolName = requestedElasticPoolName; RequestedStorageLimitInGB = requestedStorageLimitInGB; ElasticPoolName = elasticPoolName; ServerName = serverName; StartTime = startTime; State = state; RequestedStorageLimitInMB = requestedStorageLimitInMB; RequestedDatabaseDtuGuarantee = requestedDatabaseDtuGuarantee; RequestedDatabaseDtuCap = requestedDatabaseDtuCap; RequestedDtuGuarantee = requestedDtuGuarantee; } /// <summary> The geo-location where the resource lives. </summary> public string Location { get; set; } /// <summary> The time the operation finished (ISO8601 format). </summary> public DateTimeOffset? EndTime { get; } /// <summary> The error code if available. </summary> public int? ErrorCode { get; } /// <summary> The error message if available. </summary> public string ErrorMessage { get; } /// <summary> The error severity if available. </summary> public int? ErrorSeverity { get; } /// <summary> The operation name. </summary> public string Operation { get; } /// <summary> The unique operation ID. </summary> public Guid? OperationId { get; } /// <summary> The percentage complete if available. </summary> public int? PercentComplete { get; } /// <summary> The requested max DTU per database if available. </summary> public int? RequestedDatabaseDtuMax { get; } /// <summary> The requested min DTU per database if available. </summary> public int? RequestedDatabaseDtuMin { get; } /// <summary> The requested DTU for the pool if available. </summary> public int? RequestedDtu { get; } /// <summary> The requested name for the elastic pool if available. </summary> public string RequestedElasticPoolName { get; } /// <summary> The requested storage limit for the pool in GB if available. </summary> public long? RequestedStorageLimitInGB { get; } /// <summary> The name of the elastic pool. </summary> public string ElasticPoolName { get; } /// <summary> The name of the server the elastic pool is in. </summary> public string ServerName { get; } /// <summary> The time the operation started (ISO8601 format). </summary> public DateTimeOffset? StartTime { get; } /// <summary> The current state of the operation. </summary> public string State { get; } /// <summary> The requested storage limit in MB. </summary> public int? RequestedStorageLimitInMB { get; } /// <summary> The requested per database DTU guarantee. </summary> public int? RequestedDatabaseDtuGuarantee { get; } /// <summary> The requested per database DTU cap. </summary> public int? RequestedDatabaseDtuCap { get; } /// <summary> The requested DTU guarantee. </summary> public int? RequestedDtuGuarantee { get; } } }
59.439655
627
0.662364
[ "MIT" ]
AhmedLeithy/azure-sdk-for-net
sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Models/ElasticPoolActivity.cs
6,895
C#
/* * Copyright 2010-2013 OBS.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 * * * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace OBS.S3.Model { /// <summary>Tag /// </summary> public class Tag { private string key; private string value; /// <summary> /// Name of the tag. /// /// </summary> public string Key { get { return this.key; } set { this.key = value; } } // Check to see if Key property is set internal bool IsSetKey() { return this.key != null; } /// <summary> /// Value of the tag. /// /// </summary> public string Value { get { return this.value; } set { this.value = value; } } // Check to see if Value property is set internal bool IsSetValue() { return this.value != null; } } }
24.171875
76
0.561086
[ "Apache-2.0" ]
huaweicloud/huaweicloud-sdk-net-dis
DotNet/eSDK_OBS_API/OBS.S3/Model/Tag.cs
1,547
C#
namespace CH01_Books { internal class Book { public string Title { get; init; } public string Author { get; init; } } }
16.555556
43
0.57047
[ "MIT" ]
PacktPublishing/C-9-and-.NET-5-High-Performance
CH01/CH01_Books/CH01_Books/Book.cs
151
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.IO { internal abstract class LowLevelTextWriter { public abstract void Write(char c); public abstract void Write(String s); } }
25.076923
101
0.708589
[ "MIT" ]
690486439/corefx
src/System.Runtime.Extensions/src/System/IO/LowLevelTextWriter.cs
326
C#
#if USE_UNI_LUA using LuaAPI = UniLua.Lua; using RealStatePtr = UniLua.ILuaState; using LuaCSFunction = UniLua.CSharpFunctionDelegate; #else using LuaAPI = XLua.LuaDLL.Lua; using RealStatePtr = System.IntPtr; using LuaCSFunction = XLua.LuaDLL.lua_CSFunction; #endif using XLua; using System.Collections.Generic; namespace XLua.CSObjectWrap { using Utils = XLua.Utils; public class XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapFairyGUIGRootWrapWrapWrapWrapWrap { public static void __Register(RealStatePtr L) { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); System.Type type = typeof(XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapFairyGUIGRootWrapWrapWrapWrap); Utils.BeginObjectRegister(type, L, translator, 0, 0, 0, 0); Utils.EndObjectRegister(type, L, translator, null, null, null, null, null); Utils.BeginClassRegister(type, L, __CreateInstance, 2, 0, 0); Utils.RegisterFunc(L, Utils.CLS_IDX, "__Register", _m___Register_xlua_st_); Utils.EndClassRegister(type, L, translator); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int __CreateInstance(RealStatePtr L) { try { ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L); if(LuaAPI.lua_gettop(L) == 1) { XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapFairyGUIGRootWrapWrapWrapWrap gen_ret = new XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapFairyGUIGRootWrapWrapWrapWrap(); translator.Push(L, gen_ret); return 1; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } return LuaAPI.luaL_error(L, "invalid arguments to XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapFairyGUIGRootWrapWrapWrapWrap constructor!"); } [MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] static int _m___Register_xlua_st_(RealStatePtr L) { try { { System.IntPtr _L = LuaAPI.lua_touserdata(L, 1); XLua.CSObjectWrap.XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapFairyGUIGRootWrapWrapWrapWrap.__Register( _L ); return 0; } } catch(System.Exception gen_e) { return LuaAPI.luaL_error(L, "c# exception:" + gen_e); } } } }
26.518182
213
0.605417
[ "MIT" ]
zxsean/DCET
Unity/Assets/Model/XLua/Gen/XLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapXLuaCSObjectWrapFairyGUIGRootWrapWrapWrapWrapWrap.cs
2,919
C#
using System; using System.Text.RegularExpressions; namespace KSPPluginFramework { /// <summary>Represents a time interval.</summary> public class KSPTimeSpan : IFormattable { //Shortcut to the Calendar Type private CalendarTypeEnum CalType { get { return KSPDateStructure.CalendarType; } } //Descriptors of Timespan - uses UT as the Root value /// <summary>Gets the years component of the time interval represented by the current KSPPluginFramework.KSPTimeSpan structure</summary> /// <returns> /// <para>Returns 0 if the <see cref="KSPDateStructure.CalendarType"/> == <see cref="CalendarTypeEnum.Earth"/></para> /// <para>otherwise</para> /// Returns the year component of this instance. The return value can be positive or negative. /// </returns> public Int32 Years { get { if (CalType != CalendarTypeEnum.Earth) { return (Int32)(UT / KSPDateStructure.SecondsPerYear); } else { return 0; } } } /// <summary>Gets the days component of the time interval represented by the current KSPPluginFramework.KSPTimeSpan structure.</summary> /// <returns> /// <para>Returns Total Number of Days for the current component if the <see cref="KSPDateStructure.CalendarType"/> == <see cref="CalendarTypeEnum.Earth"/></para> /// <para>otherwise</para> /// The day component of the current KSPPluginFramework.KSPTimeSpan structure. The return value ranges between +/- <see cref="KSPDateStructure.DaysPerYear"/> /// </returns> public Int32 Days { get { if (CalType != CalendarTypeEnum.Earth) { return (Int32)(UT / KSPDateStructure.SecondsPerDay % KSPDateStructure.DaysPerYear); } else { return (Int32)(UT / KSPDateStructure.SecondsPerDay); } } } /// <summary>Gets the hours component of the time interval represented by the current KSPPluginFramework.KSPTimeSpan structure.</summary> /// <returns>The hour component of the current KSPPluginFramework.KSPTimeSpan structure. The return value ranges between +/- <see cref="KSPDateStructure.HoursPerDay"/></returns> public int Hours { get { return (Int32)(UT / KSPDateStructure.SecondsPerHour % KSPDateStructure.HoursPerDay); } } /// <summary>Gets the minutes component of the time interval represented by the current KSPPluginFramework.KSPTimeSpan structure.</summary> /// <returns> /// The minute component of the current KSPPluginFramework.KSPTimeSpan structure. The return value ranges between +/- <see cref="KSPDateStructure.MinutesPerHour"/> /// </returns> public int Minutes { get { return (Int32)UT / KSPDateStructure.SecondsPerMinute % KSPDateStructure.MinutesPerHour; } } /// <summary>Gets the seconds component of the time interval represented by the current KSPPluginFramework.KSPTimeSpan structure.</summary> /// <returns> /// The second component of the current KSPPluginFramework.KSPTimeSpan structure. The return value ranges between +/- <see cref="KSPDateStructure.SecondsPerMinute"/> /// </returns> public int Seconds { get { return (Int32)UT % KSPDateStructure.SecondsPerMinute; } } /// <summary>Gets the milliseconds component of the time interval represented by the current KSPPluginFramework.KSPTimeSpan structure.</summary> /// <returns>The millisecond component of the current KSPPluginFramework.KSPTimeSpan structure. The return value ranges from -999 through 999.</returns> public int Milliseconds { get { return (Int32)(Math.Round(UT - Math.Floor(UT), 3) * 1000); } } /// <summary>Replaces the normal "Ticks" function. This is Seconds of UT</summary> /// <returns>The number of seconds of game UT in this instance</returns> public Double UT { get; set; } #region Constructors //public KSPTimeSpan() //{ // UT = 0; //} /// <summary>Initializes a new KSPPluginFramework.KSPTimeSpan to a specified number of hours, minutes, and seconds.</summary> /// <param name="hours">Number of hours.</param> /// <param name="minutes">Number of minutes.</param> /// <param name="seconds">Number of seconds.</param> public KSPTimeSpan(int hours, int minutes, int seconds) { UT = new KSPTimeSpan(0, hours, minutes, seconds, 0).UT; } /// <summary>Initializes a new KSPPluginFramework.KSPTimeSpan to a specified number of days, hours, minutes, and seconds.</summary> /// <param name="days">Number of days.</param> /// <param name="hours">Number of hours.</param> /// <param name="minutes">Number of minutes.</param> /// <param name="seconds">Number of seconds.</param> public KSPTimeSpan(String days, String hours, String minutes, String seconds) { UT = new KSPTimeSpan(Convert.ToInt32(days), Convert.ToInt32(hours), Convert.ToInt32(minutes), Convert.ToInt32(seconds), 0).UT; } /// <summary>Initializes a new KSPPluginFramework.KSPTimeSpan to a specified number of days, hours, minutes, and seconds.</summary> /// <param name="days">Number of days.</param> /// <param name="hours">Number of hours.</param> /// <param name="minutes">Number of minutes.</param> /// <param name="seconds">Number of seconds.</param> public KSPTimeSpan(int days, int hours, int minutes, int seconds) { UT = new KSPTimeSpan(days, hours, minutes, seconds, 0).UT; } /// <summary>Initializes a new KSPPluginFramework.KSPTimeSpan to a specified number of days, hours, minutes, seconds, and milliseconds.</summary> /// <param name="days">Number of days.</param> /// <param name="hours">Number of hours.</param> /// <param name="minutes">Number of minutes.</param> /// <param name="seconds">Number of seconds.</param> /// <param name="milliseconds">Number of milliseconds.</param> public KSPTimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) { UT = days * KSPDateStructure.SecondsPerDay + hours * KSPDateStructure.SecondsPerHour + minutes * KSPDateStructure.SecondsPerMinute + seconds + (Double)milliseconds / 1000; } /// <summary>Initialises a new KSPPluginFramework.KSPTimeSpan to the specified number of seconds of Game UT</summary> /// <param name="ut">a time period expressed in seconds</param> public KSPTimeSpan(Double ut) { UT = ut; } #endregion #region Calculated Properties /// <summary>Gets the value of the current KSPPluginFramework.KSPTimeSpan structure expressed in whole and fractional milliseconds.</summary> /// <returns>The total number of milliseconds represented by this instance.</returns> public Double TotalMilliseconds { get { return UT * 1000; } } /// <summary>Gets the value of the current KSPPluginFramework.KSPTimeSpan structure expressed in whole and fractional seconds.</summary> /// <returns>The total number of seconds represented by this instance.</returns> public Double TotalSeconds { get { return UT; } } /// <summary>Gets the value of the current KSPPluginFramework.KSPTimeSpan structure expressed in whole and fractional minutes.</summary> /// <returns>The total number of minutes represented by this instance.</returns> public Double TotalMinutes { get { return UT / KSPDateStructure.SecondsPerMinute; } } /// <summary>Gets the value of the current KSPPluginFramework.KSPTimeSpan structure expressed in whole and fractional hours.</summary> /// <returns>The total number of hours represented by this instance.</returns> public Double TotalHours { get { return UT / KSPDateStructure.SecondsPerHour; } } /// <summary>Gets the value of the current KSPPluginFramework.KSPTimeSpan structure expressed in whole and fractional days.</summary> /// <returns>The total number of days represented by this instance.</returns> public Double TotalDays { get { return UT / KSPDateStructure.SecondsPerDay; } } #endregion #region String Formatter /// <summary>Generates some standard Templated versions of output</summary> /// <param name="TimeSpanFormat">Enum of some common formats</param> /// <returns>A string that represents the value of this instance.</returns> public String ToStringStandard(TimeSpanStringFormatsEnum TimeSpanFormat, Int32 Precision = 6) { double absUT = Math.Abs(UT); switch (TimeSpanFormat) { case TimeSpanStringFormatsEnum.TimeAsUT: return (UT < 0 ? "+ " : "") + string.Format("{0:N0}s", absUT); case TimeSpanStringFormatsEnum.KSPFormat: return ToString(Precision); case TimeSpanStringFormatsEnum.DateTimeFormat: return ToDateTimeString(Precision); case TimeSpanStringFormatsEnum.IntervalLong: if (KSPDateStructure.UseStockDateFormatters) { return (UT < 0 ? "+ " : "") + KSPUtil.dateTimeFormatter.PrintDateDelta(absUT, false, false, false) + ", " + KSPUtil.dateTimeFormatter.PrintTimeStampCompact(absUT, false, false); } return ToString((UT < 0?"+ ":"") + "y Year\\s, d Da\\y\\s, hh:mm:ss"); case TimeSpanStringFormatsEnum.IntervalLongTrimYears: if (KSPDateStructure.UseStockDateFormatters) { return (UT < 0 ? "+ " : "") + KSPUtil.dateTimeFormatter.PrintDateDelta(absUT, false, false, false) + ", " + KSPUtil.dateTimeFormatter.PrintTimeStampCompact(absUT, false, false); } return ToString((UT < 0 ? "+ " : "") + "y Year\\s, d Da\\y\\s, hh:mm:ss").Replace("0 Years, ", ""); case TimeSpanStringFormatsEnum.DateTimeFormatLong: if (KSPDateStructure.UseStockDateFormatters) { return (UT < 0 ? "+ " : "") + KSPUtil.dateTimeFormatter.PrintDateDeltaCompact(absUT, true, true, true); } String strFormat = ""; if (Years > 0) strFormat += "y\\y"; if (Days > 0) strFormat += (strFormat.EndsWith("y") ? ", " : "") + "d\\d"; if (strFormat != "") strFormat += " "; strFormat += "hh:mm:ss"; if (UT < 0) strFormat = "+ " + strFormat; return ToString(strFormat); default: return ToString(); } } /// <summary>Returns the string representation of the value of this instance.</summary> /// <returns>A string that represents the value of this instance.</returns> public override String ToString() { return ToString(3); } /// <summary>Returns the string representation of the value of this instance.</summary> /// <param name="Precision">How many parts of the timespan to return (of year, Day, hour, minute, second)</param> /// <returns>A string that represents the value of this instance.</returns> public String ToString(Int32 Precision) { if (KSPDateStructure.UseStockDateFormatters) { return (UT < 0 ? "+ " : "") + KSPUtil.dateTimeFormatter.PrintTime(Math.Abs(UT), Precision, false); } Int32 Displayed = 0; String format = ""; if (UT < 0) format += "+"; if (CalType != CalendarTypeEnum.Earth) { if ((Years != 0) && Displayed < Precision) { format = "y\\y,"; Displayed++; } } if ((Days != 0 || format.EndsWith(",")) && Displayed < Precision) { format += (format == "" ? "" : " ") + "d\\d,"; Displayed++; } if ((Hours != 0 || format.EndsWith(",")) && Displayed < Precision) { format += (format == "" ? "" : " ") + "h\\h,"; Displayed++; } if ((Minutes != 0 || format.EndsWith(",")) && Displayed < Precision) { format += (format == "" ? "" : " ") + "m\\m,"; Displayed++; } if (Displayed < Precision) { format += (format == "" ? "" : " ") + "s\\s,"; Displayed++; } format = format.TrimEnd(','); return ToString(format, null); } /// <summary>Returns the string representation of the value of this instance.</summary> /// <param name="Precision">How many parts of the timespan to return (of year, Day, hour, minute, second)</param> /// <returns>A string that represents the value of this instance.</returns> public String ToDateTimeString(Int32 Precision) { if (KSPDateStructure.UseStockDateFormatters) { string returnValue = ""; double UTAbs = Math.Abs(UT); if (UTAbs > KSPDateStructure.SecondsPerDay) { returnValue = KSPUtil.dateTimeFormatter.PrintDateDeltaCompact(UTAbs, false, false, false) + ", "; } returnValue += KSPUtil.dateTimeFormatter.PrintTimeStampCompact(UTAbs, false, false); int precCounter = 0,returnLength = returnValue.Length; for (int i = 0; i < returnLength; i++) { if (returnValue[i] == ',' || returnValue[i] == ':') precCounter++; if (precCounter > (Precision - 1)) { returnLength = i; break; } } if(returnLength < returnValue.Length) { returnValue = returnValue.Substring(0, returnLength); } return (UT < 0 ? "+ " : "") + returnValue; } Int32 Displayed = 0; String format = ""; if (UT < 0) format += "+ "; if (CalType != CalendarTypeEnum.Earth) { if ((Years != 0) && Displayed < Precision) { format = "y\\y,"; Displayed++; } } if ((Days != 0 || format.EndsWith(",")) && Displayed < Precision) { format += (format == "" ? "" : " ") + "d\\d,"; Displayed++; } if ((Hours != 0 || format.EndsWith(",")) && Displayed < Precision) { format += (format == "" ? "" : " ") + "hh:"; Displayed++; } if (Displayed < Precision) { format += "mm:"; Displayed++; } if (Displayed < Precision) { format += "ss"; Displayed++; } format = format.TrimEnd(',').TrimEnd(':'); return ToString(format, null); } /// <summary>Returns the string representation of the value of this instance.</summary> /// <param name="format">Format string using the usual characters to interpret custom datetime - as per standard Timespan custom formats</param> /// <returns>A string that represents the value of this instance.</returns> public String ToString(String format) { return ToString(format, null); } /// <summary>Returns the string representation of the value of this instance.</summary> /// <param name="format">Format string using the usual characters to interpret custom datetime - as per standard Timespan custom formats</param> /// <returns>A string that represents the value of this instance.</returns> public String ToString(String format, IFormatProvider provider) { //parse and replace the format stuff MatchCollection matches = Regex.Matches(format, "([a-zA-z])\\1{0,}"); for (int i = matches.Count - 1; i >= 0; i--) { Match m = matches[i]; Int32 mIndex = m.Index, mLength = m.Length; if (mIndex > 0 && format[m.Index - 1] == '\\') { if (m.Length == 1) continue; else { mIndex++; mLength--; } } switch (m.Value[0]) { case 'y': format = format.Substring(0, mIndex) + Math.Abs(Years).ToString("D" + mLength) + format.Substring(mIndex + mLength); break; case 'd': format = format.Substring(0, mIndex) + Math.Abs(Days).ToString("D" + mLength) + format.Substring(mIndex + mLength); break; case 'h': format = format.Substring(0, mIndex) + Math.Abs(Hours).ToString("D" + mLength.Clamp(1, KSPDateStructure.HoursPerDay.ToString().Length)) + format.Substring(mIndex + mLength); break; case 'm': format = format.Substring(0, mIndex) + Math.Abs(Minutes).ToString("D" + mLength.Clamp(1, KSPDateStructure.MinutesPerHour.ToString().Length)) + format.Substring(mIndex + mLength); break; case 's': format = format.Substring(0, mIndex) + Math.Abs(Seconds).ToString("D" + mLength.Clamp(1, KSPDateStructure.SecondsPerMinute.ToString().Length)) + format.Substring(mIndex + mLength); break; default: break; } } //Now strip out the \ , but not multiple \\ format = Regex.Replace(format, "\\\\(?=[a-z])", ""); return format; //if (KSPDateStructure.CalendarType == CalendarTypeEnum.Earth) // return String.Format(format, _EarthDateTime); //else // return String.Format(format, this); //"TEST"; } #endregion #region Instance Methods #region Mathematic Methods /// <summary>Returns a new KSPPluginFramework.KSPTimeSpan object whose value is the sum of the specified KSPPluginFramework.KSPTimeSpan object and this instance.</summary> /// <param name="value">A KSPPluginFramework.KSPTimeSpan.</param> /// <returns>A new object that represents the value of this instance plus the value of the timespan supplied.</returns> public KSPTimeSpan Add(KSPTimeSpan value) { return new KSPTimeSpan(UT + value.UT); } /// <summary>Returns a new KSPPluginFramework.KSPTimeSpan object whose value is the absolute value of the current KSPPluginFramework.KSPTimeSpan object.</summary> /// <returns>A new object whose value is the absolute value of the current KSPPluginFramework.KSPTimeSpan object.</returns> public KSPTimeSpan Duration() { return new KSPTimeSpan(Math.Abs(UT)); } /// <summary>Returns a new KSPPluginFramework.KSPTimeSpan object whose value is the negated value of this instance.</summary> /// <returns>A new object with the same numeric value as this instance, but with the opposite sign.</returns> public KSPTimeSpan Negate() { return new KSPTimeSpan(UT*-1); } #endregion #region Comparison Methods /// <summary>Compares this instance to a specified KSPPluginFramework.KSPTimeSpan object and returns an integer that indicates whether this instance is shorter than, equal to, or longer than the KSPPluginFramework.KSPTimeSpan object.</summary> /// <param name="value">A KSPPluginFramework.KSPTimeSpan object to compare to this instance.</param> /// <returns>A signed number indicating the relative values of this instance and value.Value Description A negative integer This instance is shorter than value. Zero This instance is equal to value. A positive integer This instance is longer than value.</returns> public Int32 CompareTo(KSPTimeSpan value) { return KSPTimeSpan.Compare(this, value); } /// <summary>Value Condition -1 This instance is shorter than value. 0 This instance is equal to value. 1 This instance is longer than value.-or- value is null.</summary> /// <param name="value">An object to compare, or null.</param> /// <returns>Value Condition -1 This instance is shorter than value. 0 This instance is equal to value. 1 This instance is longer than value.-or- value is null.</returns> public Int32 CompareTo(System.Object value) { if (value == null) return 1; return this.CompareTo((KSPTimeSpan)value); } /// <summary>Returns a value indicating whether this instance is equal to a specified KSPPluginFramework.KSPTimeSpan object.</summary> /// <param name="value">An KSPPluginFramework.KSPTimeSpan object to compare with this instance.</param> /// <returns>true if obj represents the same time interval as this instance; otherwise, false.</returns> public Boolean Equals(KSPTimeSpan value) { return KSPTimeSpan.Equals(this, value); } /// <summary>Returns a value indicating whether this instance is equal to a specified object.</summary> /// <param name="value">An object to compare with this instance</param> /// <returns>true if value is a KSPPluginFramework.KSPTimeSpan object that represents the same time interval as the current KSPPluginFramework.KSPTimeSpan structure; otherwise, false.</returns> public override bool Equals(System.Object value) { return (value.GetType() == this.GetType()) && this.Equals((KSPTimeSpan)value); } #endregion /// <summary>Returns a hash code for this instance.</summary> /// <returns>A 32-bit signed integer hash code.</returns> public override int GetHashCode() { return UT.GetHashCode(); } #endregion #region Static Methods /// <summary>Compares two KSPPluginFramework.KSPTimeSpan values and returns an integer that indicates whether the first value is shorter than, equal to, or longer than the second value.</summary> /// <param name="t1">A KSPPluginFramework.KSPTimeSpan.</param> /// <param name="t2">A KSPPluginFramework.KSPTimeSpan.</param> /// <returns>Value Condition -1 t1 is shorter than t20 t1 is equal to t21 t1 is longer than t2</returns> public static Int32 Compare(KSPTimeSpan t1, KSPTimeSpan t2) { if (t1.UT < t2.UT) return -1; else if (t1.UT > t2.UT) return 1; else return 0; } /// <summary>Returns a value indicating whether two specified instances of KSPPluginFramework.KSPTimeSpan are equal.</summary> /// <param name="t1">A KSPPluginFramework.KSPTimeSpan.</param> /// <param name="t2">A TimeSpan.</param> /// <returns>true if the values of t1 and t2 are equal; otherwise, false.</returns> public static Boolean Equals(KSPTimeSpan t1, KSPTimeSpan t2) { return t1.UT == t2.UT; } /// <summary>Returns a KSPPluginFramework.KSPTimeSpan that represents a specified number of days, where the specification is accurate to the nearest millisecond.</summary> /// <param name="value">A number of days, accurate to the nearest millisecond.</param> /// <returns>A KSPPluginFramework.KSPTimeSpan that represents value.</returns> public static KSPTimeSpan FromDays(Double value) { return new KSPTimeSpan(value * KSPDateStructure.SecondsPerDay); } /// <summary>Returns a KSPPluginFramework.KSPTimeSpan that represents a specified number of hours, where the specification is accurate to the nearest millisecond.</summary> /// <param name="value">A number of hours, accurate to the nearest millisecond.</param> /// <returns>A KSPPluginFramework.KSPTimeSpan that represents value.</returns> public static KSPTimeSpan FromHours(Double value) { return new KSPTimeSpan(value * KSPDateStructure.SecondsPerHour); } /// <summary>Returns a KSPPluginFramework.KSPTimeSpan that represents a specified number of minutes, where the specification is accurate to the nearest millisecond.</summary> /// <param name="value">A number of minutes, accurate to the nearest millisecond.</param> /// <returns>A KSPPluginFramework.KSPTimeSpan that represents value.</returns> public static KSPTimeSpan FromMinutes(Double value) { return new KSPTimeSpan(value * KSPDateStructure.SecondsPerMinute); } /// <summary>Returns a KSPPluginFramework.KSPTimeSpan that represents a specified number of seconds, where the specification is accurate to the nearest millisecond.</summary> /// <param name="value">A number of seconds, accurate to the nearest millisecond.</param> /// <returns>A KSPPluginFramework.KSPTimeSpan that represents value.</returns> public static KSPTimeSpan FromSeconds(Double value) { return new KSPTimeSpan(value); } /// <summary>Returns a KSPPluginFramework.KSPTimeSpan that represents a specified number of milliseconds.</summary> /// <param name="value">A number of milliseconds.</param> /// <returns>A KSPPluginFramework.KSPTimeSpan that represents value.</returns> public static KSPTimeSpan FromMilliseconds(Double value) { return new KSPTimeSpan(value / 1000); } #endregion #region Operators /// <summary>Subtracts a specified KSPPluginFramework.KSPTimeSpan from another specified KSPPluginFramework.KSPTimeSpan.</summary> /// <param name="t1"> A KSPPluginFramework.KSPTimeSpan.</param> /// <param name="t2"> A TimeSpan.</param> /// <returns>A TimeSpan whose value is the result of the value of t1 minus the value of t2.</returns> public static KSPTimeSpan operator -(KSPTimeSpan t1, KSPTimeSpan t2) { return new KSPTimeSpan(t1.UT - t2.UT); } /// <summary>Returns a KSPPluginFramework.KSPTimeSpan whose value is the negated value of the specified instance.</summary> /// <param name="t">A KSPPluginFramework.KSPTimeSpan.</param> /// <returns>A KSPPluginFramework.KSPTimeSpan with the same numeric value as this instance, but the opposite sign.</returns> public static KSPTimeSpan operator -(KSPTimeSpan t) { return new KSPTimeSpan(t.UT).Negate(); } /// <summary>Adds two specified KSPPluginFramework.KSPTimeSpan instances.</summary> /// <param name="t1">A KSPPluginFramework.KSPTimeSpan.</param> /// <param name="t2">A KSPPluginFramework.KSPTimeSpan.</param> /// <returns>A KSPPluginFramework.KSPTimeSpan whose value is the sum of the values of t1 and t2.</returns> public static KSPTimeSpan operator +(KSPTimeSpan t1, KSPTimeSpan t2) { return new KSPTimeSpan(t1.UT + t2.UT); } /// <summary>Returns the specified instance of KSPPluginFramework.KSPTimeSpan.</summary> /// <param name="t">A KSPPluginFramework.KSPTimeSpan.</param> /// <returns>Returns t.</returns> public static KSPTimeSpan operator +(KSPTimeSpan t) { return new KSPTimeSpan(t.UT); } /// <summary>Indicates whether two KSPPluginFramework.KSPTimeSpan instances are not equal.</summary> /// <param name="t1">A KSPPluginFramework.KSPTimeSpan.</param> /// <param name="t2">A TimeSpan.</param> /// <returns>true if the values of t1 and t2 are not equal; otherwise, false.</returns> public static Boolean operator !=(KSPTimeSpan t1, KSPTimeSpan t2) { return !(t1 == t2); } /// <summary>Indicates whether two KSPPluginFramework.KSPTimeSpan instances are equal.</summary> /// <param name="t1">A KSPPluginFramework.KSPTimeSpan.</param> /// <param name="t2">A TimeSpan.</param> /// <returns>true if the values of t1 and t2 are equal; otherwise, false.</returns> public static Boolean operator ==(KSPTimeSpan t1, KSPTimeSpan t2) { if (object.ReferenceEquals(t1, t2)) { // handles if both are null as well as object identity return true; } //handles if one is null and not the other if ((object)t1 == null || (object)t2 == null) { return false; } //now compares return t1.UT == t2.UT; } /// <summary>Indicates whether a specified KSPPluginFramework.KSPTimeSpan is less than another specified KSPPluginFramework.KSPTimeSpan.</summary> /// <param name="t1">A KSPPluginFramework.KSPTimeSpan.</param> /// <param name="t2">A TimeSpan.</param> /// <returns>true if the value of t1 is less than the value of t2; otherwise, false.</returns> public static Boolean operator <=(KSPTimeSpan t1, KSPTimeSpan t2) { return t1.CompareTo(t2) <= 0; } /// <summary>Indicates whether a specified KSPPluginFramework.KSPTimeSpan is less than or equal to another specified KSPPluginFramework.KSPTimeSpan.</summary> /// <param name="t1">A KSPPluginFramework.KSPTimeSpan.</param> /// <param name="t2">A TimeSpan.</param> /// <returns>true if the value of t1 is less than or equal to the value of t2; otherwise, false.</returns> public static Boolean operator <(KSPTimeSpan t1, KSPTimeSpan t2) { return t1.CompareTo(t2) < 0; } /// <summary>Indicates whether a specified KSPPluginFramework.KSPTimeSpan is greater than or equal to another specified KSPPluginFramework.KSPTimeSpan.</summary> /// <param name="t1">A KSPPluginFramework.KSPTimeSpan.</param> /// <param name="t2">A TimeSpan.</param> /// <returns>true if the value of t1 is greater than or equal to the value of t2; otherwise, false.</returns> public static Boolean operator >=(KSPTimeSpan t1, KSPTimeSpan t2) { return t1.CompareTo(t2) >= 0; } /// <summary>Indicates whether a specified KSPPluginFramework.KSPTimeSpan is greater than another specified KSPPluginFramework.KSPTimeSpan.</summary> /// <param name="t1">A KSPPluginFramework.KSPTimeSpan.</param> /// <param name="t2">A TimeSpan.</param> /// <returns>true if the value of t1 is greater than the value of t2; otherwise, false.</returns> public static Boolean operator >(KSPTimeSpan t1, KSPTimeSpan t2) { return t1.CompareTo(t2) > 0; } #endregion } /// <summary> /// Enum of standardised outputs for Timespans as strings /// </summary> public enum TimeSpanStringFormatsEnum { TimeAsUT, KSPFormat, DateTimeFormatLong, IntervalLong, IntervalLongTrimYears, DateTimeFormat, } }
50.003072
271
0.594495
[ "MIT" ]
net-lisias-kspu/KerbalAlarmClock
Source/KerbalAlarmClock/FrameworkExt/KSPTimeSpan.cs
32,554
C#
namespace Fortis.Model.Fields { public interface ITextFieldWrapper : IFieldWrapper<string> { } }
14.428571
59
0.762376
[ "MIT" ]
Fortis-Collection/fortis
src/Fortis/Model/Fields/ITextFieldWrapper.cs
103
C#
using DgBar.Domain.Entities; using DgBar.Domain.Interfaces; using DgBar.Domain.ViewModels; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DgBar.API.Controllers { [Route("api/[controller]")] [ApiController] public class OrderController : ControllerBase { private readonly IOrderManageService _OrderManageService; public OrderController(IOrderManageService orderManageService) { _OrderManageService = orderManageService; } /// <summary> /// Returns all items registered in the menu. /// </summary> /// <returns> The list of menu items.</returns> [HttpGet("Menu")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public ActionResult<SheetOrderViewModel> GetMenu() { var _menu = _OrderManageService.GetItensMenu(); if (_menu != null) { return Ok(_menu); } else { return NoContent(); } } /// <summary> /// This method registers an item in the order; /// </summary> /// <param name="order"> menu item id, order number id</param> /// <returns>the registration of the menu in the order</returns> [HttpPost("ResgistryOrder")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public ActionResult<SheetOrderViewModel> RegistryOrder([FromBody] SheetOrderViewModel order) { var _sheetOrder = _OrderManageService.RegistryOrder(order.IdOrder, order.IdMenu); SheetOrderViewModel _sheetOrderViewModel = new SheetOrderViewModel(_sheetOrder); if (_sheetOrderViewModel != null) { return Ok(_sheetOrderViewModel); } else { return NoContent(); } } /// <summary> /// This method generates a note with: items, discount and total values; /// </summary> /// <param name="order">Order number id.</param> /// <returns>A note </returns> [HttpPost("GenerateNote")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public ActionResult<OrderViewModel> GenerateNote([FromBody] OrderViewModel order) { var _note = _OrderManageService.GenerateNote(order.Id); if (_note != null) { return Ok(_note); } else { return NoContent(); } } /// <summary> /// This method resets all records in the database. /// </summary> /// <param name="id">order id</param> /// <returns>Response 200, with message or error.</returns> [HttpDelete("ResetOrder/{id}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status500InternalServerError)] public ActionResult ResetOrder(int id) { var result = _OrderManageService.ResetOrder(id); if (result) { //return StatusCode(418); return Ok("Deletado com sucesso!"); } else { return NoContent(); } } } }
32.8
100
0.59375
[ "MIT" ]
marianohtl/TesteDgBar
Backend/DgBar.API/Controllers/OrderController.cs
3,938
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.Rds.Model.V20140815 { public class ModifyDampPolicyResponse : AcsResponse { private string requestId; private string policyId; private string policyName; public string RequestId { get { return requestId; } set { requestId = value; } } public string PolicyId { get { return policyId; } set { policyId = value; } } public string PolicyName { get { return policyName; } set { policyName = value; } } } }
20.774648
64
0.656949
[ "Apache-2.0" ]
sdk-team/aliyun-openapi-net-sdk
aliyun-net-sdk-rds/Rds/Model/V20140815/ModifyDampPolicyResponse.cs
1,475
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Data; using System.Windows; using System.Drawing; using System.Windows.Media.Imaging; using System.Windows.Interop; using QuickZip.Tools; using System.Diagnostics; using System.IO; using System.Drawing.Imaging; namespace QuickZip.Converters { [ValueConversion(typeof(Bitmap), typeof(BitmapImage))] public class BitmapToBitmapImageConverter : IValueConverter { public static BitmapToBitmapImageConverter Instance = new BitmapToBitmapImageConverter(); //[System.Runtime.InteropServices.DllImport("gdi32.dll")] //public static extern bool DeleteObject(IntPtr hObject); //public static BitmapSource loadBitmap(Bitmap source) //{ // IntPtr hBitmap = source.GetHbitmap(); // //Memory Leak fixes, for more info : http://social.msdn.microsoft.com/forums/en-US/wpf/thread/edcf2482-b931-4939-9415-15b3515ddac6/ // try // { // BitmapSource retVal = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, // BitmapSizeOptions.FromEmptyOptions()); // if (retVal.CanFreeze) // retVal.Freeze(); // else if (Debugger.IsAttached) // Debugger.Break(); // return retVal; // } // catch // { // return new BitmapImage(); // } // finally // { // DeleteObject(hBitmap); // } //} public static BitmapSource loadBitmap(Bitmap source) { if (source == null) source = new Bitmap(1, 1); else source = new Bitmap(source); MemoryStream ms = new MemoryStream(); lock (source) source.Save(ms, ImageFormat.Png); ms.Position = 0; BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = ms; bi.EndInit(); bi.Freeze(); return bi; } #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { Bitmap bitmap = value.TryConvertTo<Bitmap>(); if (bitmap != null) return loadBitmap(bitmap); return null; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } }
33.809524
146
0.557394
[ "MIT" ]
chengming0916/FileExplorer
src/FileExplorer2/app/QuickZip.UserControls/Tools/Converter/BitmapToBitmapImage.cs
2,842
C#
using System.IO; using Newtonsoft.Json; using Tasks.OctopusDeploy.CrossProjectRelease.Take.Configuration; using Tasks.OctopusDeploy.CrossProjectRelease.Take.Domain.Models; namespace Tasks.OctopusDeploy.CrossProjectRelease.Take.Services { public class SnapshotWriter : IWriteSnapshots { private static readonly JsonSerializer Serializer; private readonly ISnapshotWriterConfiguration _configuration; static SnapshotWriter() { var settings = new JsonSerializerSettings { Formatting = Formatting.Indented }; Serializer = JsonSerializer.Create(settings); } public SnapshotWriter(ISnapshotWriterConfiguration configuration) { _configuration = configuration; } public void Write(Snapshot snapshot) { using (var writer = File.CreateText(_configuration.FileName)) { Serializer.Serialize(writer, snapshot); } } } }
28.833333
73
0.648362
[ "MIT" ]
corker/Tasks.OctopusDeploy.CrossProjectRelease.Take
Tasks.OctopusDeploy.CrossProjectRelease.Take/Services/SnapshotWriter.cs
1,038
C#
using System; public class TwitchUser { public TwitchUser( string userId, string username, string displayName, string color, bool isBroadcaster, bool isModerator, bool isSubscriber, bool isVip) { if (string.IsNullOrEmpty(username)) throw new ArgumentNullException(nameof(username)); Username = username.StartsWith("@") ? username.Substring(1) : username; UserId = userId; DisplayName = displayName; Color = color; IsBroadcaster = isBroadcaster; IsModerator = isModerator; IsSubscriber = isSubscriber; IsVip = isVip; } public string Username { get; } public string UserId { get; } public string DisplayName { get; } public string Color { get; } public bool IsBroadcaster { get; } public bool IsModerator { get; } public bool IsSubscriber { get; } public bool IsVip { get; } }
28.147059
94
0.6186
[ "MIT" ]
haycc/BabyYoda
src/BabyYodaClient/Assets/Scripts/Network/PacketHandlers/Models/TwitchUser.cs
959
C#
using System; using System.Collections.Generic; namespace ScriptCs.Contracts { public interface IModuleConfiguration : IServiceOverrides<IModuleConfiguration> { bool Cache { get; } string ScriptName { get; } bool IsRepl { get; } LogLevel LogLevel { get; } bool Debug { get; } IDictionary<Type, object> Overrides { get; } } }
18.666667
83
0.627551
[ "Apache-2.0" ]
BlackFrog1/scriptcs
src/ScriptCs.Contracts/IModuleConfiguration.cs
394
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.IO; using System.Linq; using System.Text; using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.Language.Extensions; namespace RazorPageGenerator { public class Program { public static int Main(string[] args) { if (args == null || args.Length < 1) { Console.WriteLine("Invalid argument(s)."); Console.WriteLine(@"Usage: dotnet razorpagegenerator <root-namespace-of-views> [path] Examples: dotnet razorpagegenerator Microsoft.AspNetCore.Diagnostics.RazorViews - processes all views in ""Views"" subfolders of the current directory dotnet razorpagegenerator Microsoft.AspNetCore.Diagnostics.RazorViews c:\project - processes all views in ""Views"" subfolders of c:\project directory "); return 1; } var rootNamespace = args[0]; var targetProjectDirectory = args.Length > 1 ? args[1] : Directory.GetCurrentDirectory(); var projectEngine = CreateProjectEngine(rootNamespace, targetProjectDirectory); var results = MainCore(projectEngine, targetProjectDirectory); foreach (var result in results) { File.WriteAllText(result.FilePath, result.GeneratedCode); } Console.WriteLine(); Console.WriteLine($"{results.Count} files successfully generated."); Console.WriteLine(); return 0; } public static RazorProjectEngine CreateProjectEngine(string rootNamespace, string targetProjectDirectory, Action<RazorProjectEngineBuilder> configure = null) { var fileSystem = RazorProjectFileSystem.Create(targetProjectDirectory); var projectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, fileSystem, builder => { builder .SetNamespace(rootNamespace) .SetBaseType("Microsoft.Extensions.RazorViews.BaseView") .ConfigureClass((document, @class) => { @class.ClassName = Path.GetFileNameWithoutExtension(document.Source.FilePath); @class.Modifiers.Clear(); @class.Modifiers.Add("internal"); }); FunctionsDirective.Register(builder); InheritsDirective.Register(builder); SectionDirective.Register(builder); builder.Features.Add(new SuppressChecksumOptionsFeature()); builder.Features.Add(new SuppressMetadataAttributesFeature()); if (configure != null) { configure(builder); } builder.AddDefaultImports(@" @using System @using System.Threading.Tasks "); }); return projectEngine; } public static IList<RazorPageGeneratorResult> MainCore(RazorProjectEngine projectEngine, string targetProjectDirectory) { var viewDirectories = Directory.EnumerateDirectories(targetProjectDirectory, "Views", SearchOption.AllDirectories); var fileCount = 0; var results = new List<RazorPageGeneratorResult>(); foreach (var viewDir in viewDirectories) { Console.WriteLine(); Console.WriteLine(" Generating code files for views in {0}", viewDir); var viewDirPath = viewDir.Substring(targetProjectDirectory.Length).Replace('\\', '/'); var cshtmlFiles = projectEngine.FileSystem.EnumerateItems(viewDirPath); if (!cshtmlFiles.Any()) { Console.WriteLine(" No .cshtml files were found."); continue; } foreach (var item in cshtmlFiles) { Console.WriteLine(" Generating code file for view {0}...", item.FileName); results.Add(GenerateCodeFile(projectEngine, item)); Console.WriteLine(" Done!"); fileCount++; } } return results; } private static RazorPageGeneratorResult GenerateCodeFile(RazorProjectEngine projectEngine, RazorProjectItem projectItem) { var projectItemWrapper = new FileSystemRazorProjectItemWrapper(projectItem); var codeDocument = projectEngine.Process(projectItemWrapper); var cSharpDocument = codeDocument.GetCSharpDocument(); if (cSharpDocument.Diagnostics.Any()) { var diagnostics = string.Join(Environment.NewLine, cSharpDocument.Diagnostics); Console.WriteLine($"One or more parse errors encountered. This will not prevent the generator from continuing: {Environment.NewLine}{diagnostics}."); } var generatedCodeFilePath = Path.ChangeExtension(projectItem.PhysicalPath, ".Designer.cs"); return new RazorPageGeneratorResult { FilePath = generatedCodeFilePath, GeneratedCode = cSharpDocument.GeneratedCode, }; } private class SuppressChecksumOptionsFeature : RazorEngineFeatureBase, IConfigureRazorCodeGenerationOptionsFeature { public int Order { get; set; } public void Configure(RazorCodeGenerationOptionsBuilder options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } options.SuppressChecksum = true; } } private class SuppressMetadataAttributesFeature : RazorEngineFeatureBase, IConfigureRazorCodeGenerationOptionsFeature { public int Order { get; set; } public void Configure(RazorCodeGenerationOptionsBuilder options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } options.SuppressMetadataAttributes = true; } } private class FileSystemRazorProjectItemWrapper : RazorProjectItem { private readonly RazorProjectItem _source; public FileSystemRazorProjectItemWrapper(RazorProjectItem item) { _source = item; } public override string BasePath => _source.BasePath; public override string FilePath => _source.FilePath; // Mask the full name since we don't want a developer's local file paths to be commited. public override string PhysicalPath => _source.FileName; public override bool Exists => _source.Exists; public override Stream Read() { var processedContent = ProcessFileIncludes(); return new MemoryStream(Encoding.UTF8.GetBytes(processedContent)); } private string ProcessFileIncludes() { var basePath = System.IO.Path.GetDirectoryName(_source.PhysicalPath); var cshtmlContent = File.ReadAllText(_source.PhysicalPath); var startMatch = "<%$ include: "; var endMatch = " %>"; var startIndex = 0; while (startIndex < cshtmlContent.Length) { startIndex = cshtmlContent.IndexOf(startMatch, startIndex); if (startIndex == -1) { break; } var endIndex = cshtmlContent.IndexOf(endMatch, startIndex); if (endIndex == -1) { throw new InvalidOperationException($"Invalid include file format in {_source.PhysicalPath}. Usage example: <%$ include: ErrorPage.js %>"); } var includeFileName = cshtmlContent.Substring(startIndex + startMatch.Length, endIndex - (startIndex + startMatch.Length)); Console.WriteLine(" Inlining file {0}", includeFileName); var includeFileContent = File.ReadAllText(System.IO.Path.Combine(basePath, includeFileName)); cshtmlContent = cshtmlContent.Substring(0, startIndex) + includeFileContent + cshtmlContent.Substring(endIndex + endMatch.Length); startIndex = startIndex + includeFileContent.Length; } return cshtmlContent; } } } }
40.853881
165
0.587795
[ "Apache-2.0" ]
AmadeusW/Razor
src/RazorPageGenerator/Program.cs
8,947
C#
using System; using System.Collections.Generic; using UnityEngine; namespace KERBALISM { public class SunShieldingPartData { public double distance = 1.0; public double thickness = 1.0; public SunShieldingPartData(double distance, double thickness) { this.distance = distance; this.thickness = thickness; } public SunShieldingPartData(ConfigNode node) { distance = Lib.ConfigValue<double>(node, "distance", 1.0); thickness = Lib.ConfigValue<double>(node, "thickness", 1.0); } public void Save(ConfigNode node) { node.AddValue("distance", distance); node.AddValue("thickness", thickness); } } public class VesselHabitatInfo { public Dictionary<uint, List<SunShieldingPartData>> habitatShieldings = new Dictionary<uint, List<SunShieldingPartData>>(); private int habitatIndex = -1; private List<Habitat> habitats; public double MaxPressure => maxPressure; private double maxPressure; public VesselHabitatInfo(ConfigNode node) { if (node == null) return; maxPressure = Lib.ConfigValue(node, "maxPressure", 1.0); if (!node.HasNode("sspi")) return; foreach (var n in node.GetNode("sspi").GetNodes()) { uint partId = uint.Parse(n.name); List<SunShieldingPartData> sspiList = new List<SunShieldingPartData>(); foreach (var p in n.GetNodes()) { sspiList.Add(new SunShieldingPartData(p)); } habitatShieldings[partId] = sspiList; } } internal void Save(ConfigNode node) { node.AddValue("maxPressure", maxPressure); var sspiNode = node.AddNode("sspi"); foreach (var entry in habitatShieldings) { var n = sspiNode.AddNode(entry.Key.ToString()); for (var i = 0; i < entry.Value.Count; i++) { entry.Value[i].Save(n.AddNode(i.ToString())); } } } private void RaytraceToSun(Part habitat) { if (!Features.Radiation) return; var habitatPosition = habitat.transform.position; var vd = habitat.vessel.KerbalismData(); List<SunShieldingPartData> sunShieldingParts = new List<SunShieldingPartData>(); Ray r = new Ray(habitatPosition, vd.EnvMainSun.Direction); var hits = Physics.RaycastAll(r, 200); foreach (var hit in hits) { if (hit.collider != null && hit.collider.gameObject != null) { Part blockingPart = Part.GetComponentUpwards<Part>(hit.collider.gameObject); if (blockingPart == null || blockingPart == habitat) continue; var mass = blockingPart.mass + blockingPart.GetResourceMass(); mass *= 1000; // KSP masses are in tons // divide part mass by the mass of aluminium (2699 kg/m³), cubic root of that // gives a very rough approximation of the thickness, assuming it's a cube. // So a 40.000 kg fuel tank would be equivalent to 2.45m aluminium. var thickness = Math.Pow(mass / 2699.0, 1.0 / 3.0); sunShieldingParts.Add(new SunShieldingPartData(hit.distance, thickness)); } } // sort by distance, in reverse sunShieldingParts.Sort((a, b) => b.distance.CompareTo(a.distance)); habitatShieldings[habitat.flightID] = sunShieldingParts; } public double AverageHabitatRadiation(double radiation) { if (habitatShieldings.Count < 1) return radiation; var result = 0.0; foreach (var shieldingPartsList in habitatShieldings.Values) { var remainingRadiation = radiation; foreach (var shieldingInfo in shieldingPartsList) { // for a 500 keV gamma ray, halfing thickness for aluminium is 3.05cm. But... // Solar energetic particles (SEP) are high-energy particles coming from the Sun. // They consist of protons, electrons and HZE ions with energy ranging from a few tens of keV // to many GeV (the fastest particles can approach the speed of light, as in a // "ground-level event"). This is why they are such a big problem for interplanetary space travel. // We just assume a big halfing thickness for that kind of ionized radiation. var halfingThickness = 1.0; // halfing factor h = part thickness / halfing thickness // remaining radiation = radiation / (2^h) // However, what you loose in particle radiation you gain in gamma radiation (Bremsstrahlung) var bremsstrahlung = remainingRadiation / Math.Pow(2, shieldingInfo.thickness / halfingThickness); remainingRadiation -= bremsstrahlung; result += Radiation.DistanceRadiation(bremsstrahlung, shieldingInfo.distance); } result += remainingRadiation; } return result / habitatShieldings.Count; } internal void Update(Vessel v) { if (v == null || !v.loaded) return; if (habitats == null) { habitats = Lib.FindModules<Habitat>(v); maxPressure = 1.0; foreach (var habitat in habitats) maxPressure = Math.Min(maxPressure, habitat.max_pressure); } if (!Features.Radiation || habitats.Count == 0) return; // always do EVAs if (v.isEVA) { RaytraceToSun(v.rootPart); return; } if (habitatIndex < 0) { // first run, do them all foreach (var habitat in habitats) RaytraceToSun(habitat.part); habitatIndex = 0; } else { // only do one habitat at a time to preserve some performance // and check that part still exists if (habitats[habitatIndex].part == null) habitats.RemoveAt(habitatIndex); else RaytraceToSun(habitats[habitatIndex].part); habitatIndex = (habitatIndex + 1) % habitats.Count; } } } }
29.668421
126
0.662941
[ "Unlicense" ]
LianCastro/Kerbalism
src/Kerbalism/Database/VesselHabitatInfo.cs
5,451
C#
using fa19projectgroup16.Models; using fa19projectgroup16.DAL; using System.Collections.Generic; using System; using System.Linq; using Microsoft.Extensions.DependencyInjection; namespace fa19projectgroup16.Seeding { public static class SeedAccounts { private static AppUser GetAppUser(AppDbContext _context, string email){ AppUser user = _context.Users .Where(a => a.Email == email) .FirstOrDefault(); return user; } public static void SeedAllAccounts(IServiceProvider service) { AppDbContext db = service.GetRequiredService<AppDbContext>(); List<Account> Accounts = new List<Account>(); List<StockPortfolio> portfolios = new List<StockPortfolio>(); List<IRAAccount> IRAAccounts = new List<IRAAccount>(); StockPortfolio a1 = new StockPortfolio() { Balance = 0m, AccountName = "Shan's Stock", AccountType = AccountType.Stock, AccountNumber = 1000000000, AppUser = GetAppUser(db, "Dixon@aool.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a1); Account a2 = new Account() { Balance = 40035.5m, AccountName = "William's Savings", AccountType = AccountType.Savings, AccountNumber = 1000000001, AppUser = GetAppUser(db, "willsheff@email.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a2); Account a3 = new Account() { Balance = 39779.49m, AccountName = "Gregory's Checking", AccountType = AccountType.Checking, AccountNumber = 1000000002, AppUser = GetAppUser(db, "smartinmartin.Martin@aool.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a3); Account a4 = new Account() { Balance = 47277.33m, AccountName = "Allen's Checking", AccountType = AccountType.Checking, AccountNumber = 1000000003, AppUser = GetAppUser(db, "avelasco@yaho.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a4); Account a5 = new Account() { Balance = 70812.15m, AccountName = "Reagan's Checking", AccountType = AccountType.Checking, AccountNumber = 1000000004, AppUser = GetAppUser(db, "rwood@voyager.net"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a5); Account a6 = new Account() { Balance = 21901.97m, AccountName = "Kelly's Savings", AccountType = AccountType.Savings, AccountNumber = 1000000005, AppUser = GetAppUser(db, "nelson.Kelly@aool.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a6); Account a7 = new Account() { Balance = 70480.99m, AccountName = "Eryn's Checking", AccountType = AccountType.Checking, AccountNumber = 1000000006, AppUser = GetAppUser(db, "erynrice@aool.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a7); Account a8 = new Account() { Balance = 7916.4m, AccountName = "Jake's Savings", AccountType = AccountType.Savings, AccountNumber = 1000000007, AppUser = GetAppUser(db, "westj@pioneer.net"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a8); StockPortfolio a9 = new StockPortfolio() { Balance = 0m, AccountName = "Michelle's Stock", AccountType = AccountType.Stock, AccountNumber = 1000000008, AppUser = GetAppUser(db, "mb@aool.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a9); Account a10 = new Account() { Balance = 69576.83m, AccountName = "Jeffrey's Savings", AccountType = AccountType.Savings, AccountNumber = 1000000009, AppUser = GetAppUser(db, "jeff@ggmail.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a10); StockPortfolio a11 = new StockPortfolio() { Balance = 0m, AccountName = "Kelly's Stock", AccountType = AccountType.Stock, AccountNumber = 1000000010, AppUser = GetAppUser(db, "nelson.Kelly@aool.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a11); Account a12 = new Account() { Balance = 30279.33m, AccountName = "Eryn's Checking 2", AccountType = AccountType.Checking, AccountNumber = 1000000011, AppUser = GetAppUser(db, "erynrice@aool.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a12); IRAAccount a13 = new IRAAccount() { Balance = 5000m, AccountName = "Jennifer's IRA", AccountType = AccountType.IRA, AccountNumber = 1000000012, AppUser = GetAppUser(db, "mackcloud@pimpdaddy.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a13); Account a14 = new Account() { Balance = 11958.08m, AccountName = "Sarah's Savings", AccountType = AccountType.Savings, AccountNumber = 1000000013, AppUser = GetAppUser(db, "ss34@ggmail.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a14); Account a15 = new Account() { Balance = 72990.47m, AccountName = "Jeremy's Savings", AccountType = AccountType.Savings, AccountNumber = 1000000014, AppUser = GetAppUser(db, "tanner@ggmail.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a15); Account a16 = new Account() { Balance = 7417.2m, AccountName = "Elizabeth's Savings", AccountType = AccountType.Savings, AccountNumber = 1000000015, AppUser = GetAppUser(db, "liz@ggmail.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a16); IRAAccount a17 = new IRAAccount() { Balance = 5000m, AccountName = "Allen's IRA", AccountType = AccountType.IRA, AccountNumber = 1000000016, AppUser = GetAppUser(db, "ra@aoo.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a17); StockPortfolio a18 = new StockPortfolio() { Balance = 0m, AccountName = "John's Stock", AccountType = AccountType.Stock, AccountNumber = 1000000017, AppUser = GetAppUser(db, "johnsmith187@aool.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a18); Account a19 = new Account() { Balance = 1642.82m, AccountName = "Clarence's Savings", AccountType = AccountType.Savings, AccountNumber = 1000000018, AppUser = GetAppUser(db, "mclarence@aool.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a19); Account a20 = new Account() { Balance = 84421.45m, AccountName = "Sarah's Checking", AccountType = AccountType.Checking, AccountNumber = 1000000019, AppUser = GetAppUser(db, "ss34@ggmail.com"), Date = new DateTime(2016, 1, 1), Is_Active = true }; Accounts.Add(a20); foreach (Account account in Accounts) { db.Add(account); db.SaveChanges(); } } } }
25.59854
73
0.642002
[ "MIT" ]
jdalamo/K-Project
Seeding/SeedAccounts.cs
7,014
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; namespace CustomKerningSample { public partial class App : Application { public App () { InitializeComponent(); MainPage = new CustomKerningSample.MainPage(); } protected override void OnStart () { // Handle when your app starts } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
15.228571
49
0.690432
[ "MIT" ]
rdelrosario/CustomKerningSample
CustomKerningSample/CustomKerningSample/App.xaml.cs
535
C#
namespace CentrumAkcji { partial class Form1 { /// <summary> /// Wymagana zmienna projektanta. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Wyczyść wszystkie używane zasoby. /// </summary> /// <param name="disposing">prawda, jeżeli zarządzane zasoby powinny zostać zlikwidowane; Fałsz w przeciwnym wypadku.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Kod generowany przez Projektanta formularzy systemu Windows /// <summary> /// Metoda wymagana do obsługi projektanta — nie należy modyfikować /// jej zawartości w edytorze kodu. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.label1 = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); this.label1.Location = new System.Drawing.Point(176, 97); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(166, 25); this.label1.TabIndex = 0; this.label1.Text = "Test Aero Glass"; // // pictureBox1 // this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(239, 165); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(484, 237); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox1.TabIndex = 1; this.pictureBox1.TabStop = false; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "Centrum akcji"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.PictureBox pictureBox1; } }
41.151899
172
0.578899
[ "MIT" ]
ProgramistaZpolski/Aeroglasstest
Form1.Designer.cs
3,266
C#
/****************************************************************************** Copyright (c) 2015 Koray Kiyakoglu http://www.swarm2d.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ using Swarm2D.Library; namespace Swarm2D.Cluster { public class GetChildMessage : ClusterObjectMessage { public string Name { get; private set; } public GetChildMessage() { } public GetChildMessage(string name) { Name = name; } protected override void OnSerialize(IDataWriter writer) { writer.WriteUnicodeString(Name); } protected override void OnDeserialize(IDataReader reader) { Name = reader.ReadUnicodeString(); } } }
34.396226
79
0.659901
[ "MIT" ]
kiyakkoray/Swarm2D
Source/Swarm2D.Cluster/Messages/GetChildMessage.cs
1,823
C#
using System; using System.Collections.Generic; using Hedwig.Validations; namespace Hedwig.Models { public class EnrollmentFamilyDeterminationDTO { public int Id { get; set; } public int? NumberOfPeople { get; set; } public decimal? Income { get; set; } public DateTime? DeterminationDate { get; set; } public int FamilyId { get; set; } public List<ValidationError> ValidationErrors { get; set; } } }
24.529412
61
0.729017
[ "CC0-1.0" ]
ctoec/ecis-experimental
src/Hedwig/Models/FamilyDetermination/EnrollmentFamilyDeterminationDTO.cs
417
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from shared/minwindef.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public static partial class Windows { [NativeTypeName("#define STRICT 1")] public const int STRICT = 1; [NativeTypeName("#define MAX_PATH 260")] public const int MAX_PATH = 260; [NativeTypeName("#define FALSE 0")] public const int FALSE = 0; [NativeTypeName("#define TRUE 1")] public const int TRUE = 1; } }
30.73913
145
0.670438
[ "MIT" ]
DaZombieKiller/terrafx.interop.windows
sources/Interop/Windows/shared/minwindef/Windows.cs
709
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace R2RTest { /// <summary> /// Compiles assemblies using the Cross-Platform AOT compiler /// </summary> class CrossgenRunner : CompilerRunner { public override CompilerIndex Index => CompilerIndex.Crossgen; protected override string CompilerRelativePath => "."; protected override string CompilerFileName => "crossgen".AppendOSExeSuffix(); protected override string CompilerPath { get { return _options.CrossgenPath != null ? _options.CrossgenPath.FullName : base.CompilerPath; } } public CrossgenRunner(BuildOptions options, IEnumerable<string> referencePaths) : base(options, referencePaths) { } protected override ProcessParameters ExecutionProcess(IEnumerable<string> modules, IEnumerable<string> folders, bool noEtw) { ProcessParameters processParameters = base.ExecutionProcess(modules, folders, noEtw); processParameters.EnvironmentOverrides["COMPLUS_ReadyToRun"] = "1"; processParameters.EnvironmentOverrides["COMPLUS_NoGuiOnAssert"] = "1"; return processParameters; } protected override IEnumerable<string> BuildCommandLineArguments(IEnumerable<string> assemblyFileNames, string outputFileName) { if (assemblyFileNames.Count() > 1) { throw new NotImplementedException($@"Crossgen1 doesn't support composite build mode for compiling multiple input assemblies: {string.Join("; ", assemblyFileNames)}"); } // The file to compile yield return "/in"; yield return assemblyFileNames.First(); // Output yield return "/out"; yield return outputFileName; if (_options.LargeBubble && Path.GetFileNameWithoutExtension(assemblyFileNames.First()) != "System.Private.CoreLib") { // There seems to be a bug in Crossgen on Linux we don't intend to fix - // it crashes when trying to compile S.P.C in large version bubble mode. yield return "/largeversionbubble"; } yield return "/platform_assemblies_paths"; HashSet<string> paths = new HashSet<string>(); foreach (string assemblyFileName in assemblyFileNames) { paths.Add(Path.GetDirectoryName(assemblyFileName)); } paths.UnionWith(_referenceFolders); yield return paths.ConcatenatePaths(); } } }
37.371795
182
0.641509
[ "MIT" ]
06needhamt/runtime
src/coreclr/src/tools/r2rtest/CrossgenRunner.cs
2,915
C#
using UnityEngine; public class ClydeBehavior : BaseEnemyAIBehavior { public override EnemyType EnemyType => EnemyType.Clyde; readonly ICollectiblesManagerModel collectiblesManager; readonly IClydeSettings settings; readonly int sqrChaseDistance; public ClydeBehavior ( IMapModel map, IPathFinder pathFinder, IRandomProvider randomProvider, IClydeSettings settings, ICollectiblesManagerModel collectiblesManager ) : base(map, pathFinder, randomProvider, settings) { this.collectiblesManager = collectiblesManager; this.settings = settings; sqrChaseDistance = settings.DisableChaseDistance * settings.DisableChaseDistance; } public override Vector2Int[] GetAction (Vector2Int position, EnemyAIMode mode, IActorModel target) { float ratio = collectiblesManager.CollectedCount / (float)collectiblesManager.TotalCollectibles; if (ratio < settings.CollectedRequirementRatio) { Vector2Int randomPos = new Vector2Int(position.x + Random.Range(-3, 4), position.y); return FindPath( position, GetValidPositionCloseTo(randomPos, x => x == Tile.EnemySpawn) ); } return mode switch { EnemyAIMode.Scatter => GetDefaultScatterAction(position, target), EnemyAIMode.Chase => GetChaseAction(position, target), EnemyAIMode.Frightened => GetDefaultFrightenedAction(position, target), EnemyAIMode.Dead => GetDefaultDeadAction(position, target), _ => throw new System.NotImplementedException() }; } Vector2Int[] GetChaseAction (Vector2Int position, IActorModel target) { if ((target.Position - position).sqrMagnitude > sqrChaseDistance) return FindPath(position, target.Position); return GetDefaultScatterAction(position, target); } }
34.508772
102
0.674631
[ "MIT" ]
AAulicino/pacman-mvc
Assets/Scripts/MVC/Model/Core/Actor/Enemy/AI/Behaviors/ClydeBehavior.cs
1,967
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("CSharpFeatures.FastStringCreation")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("CSharpFeatures.FastStringCreation")] [assembly: System.Reflection.AssemblyTitleAttribute("CSharpFeatures.FastStringCreation")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
44
91
0.667984
[ "MIT" ]
joaokucera/csharp-features
src/CSharpFeatures.FastStringCreation/obj/Release/net6.0/CSharpFeatures.FastStringCreation.AssemblyInfo.cs
1,012
C#
/* * LeagueClient * * 7.23.209.3517 * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Text; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations; namespace LeagueClientApi.Model { /// <summary> /// LolMatchHistoryRecentlyPlayedSummoner /// </summary> [DataContract] public partial class LolMatchHistoryRecentlyPlayedSummoner : IEquatable<LolMatchHistoryRecentlyPlayedSummoner>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="LolMatchHistoryRecentlyPlayedSummoner" /> class. /// </summary> /// <param name="ChampionId">ChampionId.</param> /// <param name="GameCreationDate">GameCreationDate.</param> /// <param name="GameId">GameId.</param> /// <param name="SummonerId">SummonerId.</param> /// <param name="SummonerName">SummonerName.</param> /// <param name="TeamId">TeamId.</param> public LolMatchHistoryRecentlyPlayedSummoner(long? ChampionId = default(long?), string GameCreationDate = default(string), long? GameId = default(long?), long? SummonerId = default(long?), string SummonerName = default(string), long? TeamId = default(long?)) { this.ChampionId = ChampionId; this.GameCreationDate = GameCreationDate; this.GameId = GameId; this.SummonerId = SummonerId; this.SummonerName = SummonerName; this.TeamId = TeamId; } /// <summary> /// Gets or Sets ChampionId /// </summary> [DataMember(Name="championId", EmitDefaultValue=false)] public long? ChampionId { get; set; } /// <summary> /// Gets or Sets GameCreationDate /// </summary> [DataMember(Name="gameCreationDate", EmitDefaultValue=false)] public string GameCreationDate { get; set; } /// <summary> /// Gets or Sets GameId /// </summary> [DataMember(Name="gameId", EmitDefaultValue=false)] public long? GameId { get; set; } /// <summary> /// Gets or Sets SummonerId /// </summary> [DataMember(Name="summonerId", EmitDefaultValue=false)] public long? SummonerId { get; set; } /// <summary> /// Gets or Sets SummonerName /// </summary> [DataMember(Name="summonerName", EmitDefaultValue=false)] public string SummonerName { get; set; } /// <summary> /// Gets or Sets TeamId /// </summary> [DataMember(Name="teamId", EmitDefaultValue=false)] public long? TeamId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class LolMatchHistoryRecentlyPlayedSummoner {\n"); sb.Append(" ChampionId: ").Append(ChampionId).Append("\n"); sb.Append(" GameCreationDate: ").Append(GameCreationDate).Append("\n"); sb.Append(" GameId: ").Append(GameId).Append("\n"); sb.Append(" SummonerId: ").Append(SummonerId).Append("\n"); sb.Append(" SummonerName: ").Append(SummonerName).Append("\n"); sb.Append(" TeamId: ").Append(TeamId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as LolMatchHistoryRecentlyPlayedSummoner); } /// <summary> /// Returns true if LolMatchHistoryRecentlyPlayedSummoner instances are equal /// </summary> /// <param name="other">Instance of LolMatchHistoryRecentlyPlayedSummoner to be compared</param> /// <returns>Boolean</returns> public bool Equals(LolMatchHistoryRecentlyPlayedSummoner other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.ChampionId == other.ChampionId || this.ChampionId != null && this.ChampionId.Equals(other.ChampionId) ) && ( this.GameCreationDate == other.GameCreationDate || this.GameCreationDate != null && this.GameCreationDate.Equals(other.GameCreationDate) ) && ( this.GameId == other.GameId || this.GameId != null && this.GameId.Equals(other.GameId) ) && ( this.SummonerId == other.SummonerId || this.SummonerId != null && this.SummonerId.Equals(other.SummonerId) ) && ( this.SummonerName == other.SummonerName || this.SummonerName != null && this.SummonerName.Equals(other.SummonerName) ) && ( this.TeamId == other.TeamId || this.TeamId != null && this.TeamId.Equals(other.TeamId) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.ChampionId != null) hash = hash * 59 + this.ChampionId.GetHashCode(); if (this.GameCreationDate != null) hash = hash * 59 + this.GameCreationDate.GetHashCode(); if (this.GameId != null) hash = hash * 59 + this.GameId.GetHashCode(); if (this.SummonerId != null) hash = hash * 59 + this.SummonerId.GetHashCode(); if (this.SummonerName != null) hash = hash * 59 + this.SummonerName.GetHashCode(); if (this.TeamId != null) hash = hash * 59 + this.TeamId.GetHashCode(); return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
37.743842
266
0.546594
[ "MIT" ]
wildbook/LeagueClientApi
Model/LolMatchHistoryRecentlyPlayedSummoner.cs
7,662
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.EntityFrameworkCore.Metadata { /// <summary> /// <para> /// Indicates whether an element in the <see cref="IMutableModel" /> was specified explicitly /// using the fluent API in <see cref="DbContext.OnModelCreating" />, through use of a /// .NET attribute (data annotation), or by convention via the EF Core model building conventions. /// </para> /// <para> /// This type is typically used by database providers (and other extensions). It is generally /// not used in application code. /// </para> /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-conventions">Model building conventions</see> for more information. /// </remarks> public enum ConfigurationSource { /// <summary> /// Indicates that the model element was explicitly specified using the fluent API in /// <see cref="DbContext.OnModelCreating" />. /// </summary> Explicit, /// <summary> /// Indicates that the model element was specified through use of a .NET attribute (data annotation). /// </summary> DataAnnotation, /// <summary> /// Indicates that the model element was specified by convention via the EF Core model building conventions. /// </summary> Convention } }
40.25641
121
0.610191
[ "MIT" ]
CameronAavik/efcore
src/EFCore/Metadata/ConfigurationSource.cs
1,570
C#
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.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Bushtail_Sports.View { /// <summary> /// Interaktionslogik für UC_Home.xaml /// </summary> public partial class UC_BotSetup : UserControl { public UC_BotSetup() { InitializeComponent(); } } }
22.275862
50
0.719814
[ "MIT" ]
Lamiput/Bushtail-Sports
Bushtail-Sports/View/UC_BotSetup.xaml.cs
649
C#
namespace ClearHl7.Codes.V250 { /// <summary> /// HL7 Version 2 Table 0550 - Body Parts. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0550</remarks> public enum CodeBodyParts { /// <summary> /// ACET - Acetabulum. /// </summary> Acetabulum, /// <summary> /// ACHIL - Achilles. /// </summary> Achilles, /// <summary> /// ADB - Abdomen. /// </summary> Abdomen, /// <summary> /// ADE - Adenoids. /// </summary> Adenoids, /// <summary> /// ADR - Adrenal. /// </summary> Adrenal, /// <summary> /// AMN - Amniotic fluid. /// </summary> AmnioticFluid, /// <summary> /// AMS - Amniotic Sac. /// </summary> AmnioticSac, /// <summary> /// ANAL - Anal. /// </summary> Anal, /// <summary> /// ANKL - Ankle. /// </summary> Ankle, /// <summary> /// ANTEC - Antecubital. /// </summary> Antecubital, /// <summary> /// ANTECF - Antecubital Fossa. /// </summary> AntecubitalFossa, /// <summary> /// ANTR - Antrum. /// </summary> Antrum, /// <summary> /// ANUS - Anus. /// </summary> Anus, /// <summary> /// AORTA - Aorta. /// </summary> Aorta, /// <summary> /// APDX - Appendix. /// </summary> Appendix, /// <summary> /// AR - Aortic Rim. /// </summary> AorticRim, /// <summary> /// AREO - Areola. /// </summary> Areola, /// <summary> /// ARM - Arm. /// </summary> Arm, /// <summary> /// ARTE - Artery. /// </summary> Artery, /// <summary> /// ASCIT - Ascites. /// </summary> Ascites, /// <summary> /// ASCT - Ascitic Fluid. /// </summary> AsciticFluid, /// <summary> /// ATR - Atrium. /// </summary> Atrium, /// <summary> /// AURI - Auricular. /// </summary> Auricular, /// <summary> /// AV - Aortic Valve. /// </summary> AorticValve, /// <summary> /// AXI - Axilla. /// </summary> Axilla, /// <summary> /// BACK - Back. /// </summary> Back, /// <summary> /// BARTD - Bartholin Duct. /// </summary> BartholinDuct, /// <summary> /// BARTG - Bartholin Gland. /// </summary> BartholinGland, /// <summary> /// BCYS - Brain Cyst Fluid. /// </summary> BrainCystFluid, /// <summary> /// BDY - Body, Whole. /// </summary> BodyWhole, /// <summary> /// BID - Bile Duct. /// </summary> BileDuct, /// <summary> /// BIFL - Bile fluid. /// </summary> BileFluid, /// <summary> /// BLAD - Bladder. /// </summary> Bladder, /// <summary> /// BLD - Blood, Whole. /// </summary> BloodWhole, /// <summary> /// BLDA - Blood, Arterial. /// </summary> BloodArterial, /// <summary> /// BLDC - Blood, Capillary. /// </summary> BloodCapillary, /// <summary> /// BLDV - Blood, Venous. /// </summary> BloodVenous, /// <summary> /// BLOOD - Blood. /// </summary> Blood, /// <summary> /// BMAR - Bone marrow. /// </summary> BoneMarrow, /// <summary> /// BON - Bone. /// </summary> Bone, /// <summary> /// BOWEL - Bowel. /// </summary> Bowel, /// <summary> /// BOWLA - Bowel, Large. /// </summary> BowelLarge, /// <summary> /// BOWSM - Bowel, Small. /// </summary> BowelSmall, /// <summary> /// BPH - Basophils. /// </summary> Basophils, /// <summary> /// BRA - Brachial. /// </summary> Brachial, /// <summary> /// BRAIN - Brain. /// </summary> Brain, /// <summary> /// BRO - Bronchial. /// </summary> Bronchial, /// <summary> /// BROCH - Bronchiole/Bronchiolar. /// </summary> BronchioleBronchiolar, /// <summary> /// BRONC - Bronchus/Bronchial. /// </summary> BronchusBronchial, /// <summary> /// BROW - Eyebrow. /// </summary> Eyebrow, /// <summary> /// BRST - Breast. /// </summary> Breast, /// <summary> /// BRSTFL - Breast fluid. /// </summary> BreastFluid, /// <summary> /// BRTGF - Bartholin Gland Fluid. /// </summary> BartholinGlandFluid, /// <summary> /// BRV - Broviac. /// </summary> Broviac, /// <summary> /// BUCCA - Buccal. /// </summary> Buccal, /// <summary> /// BURSA - Bursa. /// </summary> Bursa, /// <summary> /// BURSF - Bursa Fluid. /// </summary> BursaFluid, /// <summary> /// BUTT - Buttocks. /// </summary> Buttocks, /// <summary> /// CALF - Calf. /// </summary> Calf, /// <summary> /// CANAL - Canal. /// </summary> Canal, /// <summary> /// CANLI - Canaliculis. /// </summary> Canaliculis, /// <summary> /// CANTH - Canthus. /// </summary> Canthus, /// <summary> /// CARO - Carotid. /// </summary> Carotid, /// <summary> /// CARP - Carpal. /// </summary> Carpal, /// <summary> /// CAVIT - Cavity. /// </summary> Cavity, /// <summary> /// CBLD - Blood, Cord. /// </summary> BloodCord, /// <summary> /// CDM - Cardiac Muscle. /// </summary> CardiacMuscle, /// <summary> /// CDUCT - Common Duct. /// </summary> CommonDuct, /// <summary> /// CECUM - Cecum/Cecal. /// </summary> CecumCecal, /// <summary> /// CERVUT - Cervix/Uterus. /// </summary> CervixUterus, /// <summary> /// CHE - Cavity, Chest. /// </summary> CavityChest, /// <summary> /// CHEEK - Cheek. /// </summary> Cheek, /// <summary> /// CHES - Chest. /// </summary> Chest, /// <summary> /// CHEST - Chest Tube. /// </summary> ChestTube, /// <summary> /// CHIN - Chin. /// </summary> Chin, /// <summary> /// CIRCU - Circumcision Site. /// </summary> CircumcisionSite, /// <summary> /// CLAVI - Clavicle/Clavicular. /// </summary> ClavicleClavicular, /// <summary> /// CLIT - Clitoris. /// </summary> Clitoris, /// <summary> /// CLITO - Clitoral. /// </summary> Clitoral, /// <summary> /// CNL - Cannula. /// </summary> Cannula, /// <summary> /// COCCG - Coccygeal. /// </summary> Coccygeal, /// <summary> /// COCCY - Coccyx. /// </summary> Coccyx, /// <summary> /// COLON - Colon. /// </summary> Colon, /// <summary> /// COLOS - Colostomy. /// </summary> Colostomy, /// <summary> /// CONJ - Conjunctiva. /// </summary> Conjunctiva, /// <summary> /// COR - Cord. /// </summary> Cord, /// <summary> /// CORAL - Coral. /// </summary> Coral, /// <summary> /// CORD - Cord Blood. /// </summary> CordBlood, /// <summary> /// CORN - Cornea. /// </summary> Cornea, /// <summary> /// COS - Colostomy Stoma. /// </summary> ColostomyStoma, /// <summary> /// CRANE - Cranium, ethmoid. /// </summary> CraniumEthmoid, /// <summary> /// CRANF - Cranium, frontal. /// </summary> CraniumFrontal, /// <summary> /// CRANO - Cranium, occipital. /// </summary> CraniumOccipital, /// <summary> /// CRANP - Cranium, parietal. /// </summary> CraniumParietal, /// <summary> /// CRANS - Cranium, sphenoid. /// </summary> CraniumSphenoid, /// <summary> /// CRANT - Cranium, temporal. /// </summary> CraniumTemporal, /// <summary> /// CSF - Cerebral Spinal Fluid. /// </summary> CerebralSpinalFluid, /// <summary> /// CUBIT - Cubitus. /// </summary> Cubitus, /// <summary> /// CUFF - Cuff. /// </summary> Cuff, /// <summary> /// CULD - Cul De Sac. /// </summary> CulDeSac, /// <summary> /// CULDO - Culdocentesis. /// </summary> Culdocentesis, /// <summary> /// CVX - Cervix. /// </summary> Cervix, /// <summary> /// DELT - Deltoid. /// </summary> Deltoid, /// <summary> /// DEN - Dental Gingiva. /// </summary> DentalGingiva, /// <summary> /// DENTA - Dental. /// </summary> Dental, /// <summary> /// DIAF - Dialysis Fluid. /// </summary> DialysisFluid, /// <summary> /// DIGIT - Digit. /// </summary> Digit, /// <summary> /// DISC - Disc. /// </summary> Disc, /// <summary> /// DORS - Dorsum/Dorsal. /// </summary> DorsumDorsal, /// <summary> /// DPH - Diaphragm. /// </summary> Diaphragm, /// <summary> /// DUFL - Duodenal Fluid. /// </summary> DuodenalFluid, /// <summary> /// DUODE - Duodenum/Duodenal. /// </summary> DuodenumDuodenal, /// <summary> /// DUR - Dura. /// </summary> Dura, /// <summary> /// EAR - Ear. /// </summary> Ear, /// <summary> /// EARBI - Ear bone, incus. /// </summary> EarBoneIncus, /// <summary> /// EARBM - Ear bone, malleus. /// </summary> EarBoneMalleus, /// <summary> /// EARBS - Ear bone,stapes. /// </summary> EarBoneStapes, /// <summary> /// EARLO - Ear Lobe. /// </summary> EarLobe, /// <summary> /// EC - Endocervical. /// </summary> Endocervical, /// <summary> /// ELBOW - Elbow. /// </summary> Elbow, /// <summary> /// ELBOWJ - Elbow Joint. /// </summary> ElbowJoint, /// <summary> /// ENDC - Endocardium. /// </summary> Endocardium, /// <summary> /// ENDM - Endometrium. /// </summary> Endometrium, /// <summary> /// EOLPH - endolpthamitis. /// </summary> Endolpthamitis, /// <summary> /// EOS - Eosinophils. /// </summary> Eosinophils, /// <summary> /// EPD - Epididymis. /// </summary> Epididymis, /// <summary> /// EPICA - Epicardial. /// </summary> Epicardial, /// <summary> /// EPICM - Epicardium. /// </summary> Epicardium, /// <summary> /// EPIDU - Epidural. /// </summary> Epidural, /// <summary> /// EPIGL - Epiglottis. /// </summary> Epiglottis, /// <summary> /// ESO - Esophagus. /// </summary> Esophagus, /// <summary> /// ESOPG - Esophageal. /// </summary> Esophageal, /// <summary> /// ET - Endotracheal. /// </summary> Endotracheal, /// <summary> /// ETHMO - Ethmoid. /// </summary> Ethmoid, /// <summary> /// EUR - Endourethral. /// </summary> Endourethral, /// <summary> /// EYE - Eye. /// </summary> Eye, /// <summary> /// EYELI - Eyelid. /// </summary> Eyelid, /// <summary> /// FACE - Face. /// </summary> Face, /// <summary> /// FALLT - Fallopian Tube. /// </summary> FallopianTube, /// <summary> /// FBINC - Facial bone, inferior nasal concha. /// </summary> FacialBoneInferiorNasalConcha, /// <summary> /// FBLAC - Facial bone, lacrimal. /// </summary> FacialBoneLacrimal, /// <summary> /// FBMAX - Facial bone, maxilla. /// </summary> FacialBoneMaxilla, /// <summary> /// FBNAS - Facial bone, nasal. /// </summary> FacialBoneNasal, /// <summary> /// FBPAL - Facial bone, palatine. /// </summary> FacialBonePalatine, /// <summary> /// FBVOM - Facial bone, vomer. /// </summary> FacialBoneVomer, /// <summary> /// FBZYG - Facial bone, zygomatic. /// </summary> FacialBoneZygomatic, /// <summary> /// FEMOR - Femoral. /// </summary> Femoral, /// <summary> /// FEMUR - Femur. /// </summary> Femur, /// <summary> /// FET - Fetus. /// </summary> Fetus, /// <summary> /// FIBU - Fibula. /// </summary> Fibula, /// <summary> /// FING - Finger. /// </summary> Finger, /// <summary> /// FINGN - Finger Nail. /// </summary> FingerNail, /// <summary> /// FMH - Femoral Head. /// </summary> FemoralHead, /// <summary> /// FOL - Follicle. /// </summary> Follicle, /// <summary> /// FOOT - Foot. /// </summary> Foot, /// <summary> /// FOREA - Forearm. /// </summary> Forearm, /// <summary> /// FOREH - Forehead. /// </summary> Forehead, /// <summary> /// FORES - Foreskin. /// </summary> Foreskin, /// <summary> /// FOURC - Fourchette. /// </summary> Fourchette, /// <summary> /// GB - Gall Bladder. /// </summary> GallBladder, /// <summary> /// GEN - Genital. /// </summary> Genital, /// <summary> /// GENC - Genital Cervix. /// </summary> GenitalCervix, /// <summary> /// GENL - Genital Lochia. /// </summary> GenitalLochia, /// <summary> /// GL - Genital Lesion. /// </summary> GenitalLesion, /// <summary> /// GLAND - Gland. /// </summary> Gland, /// <summary> /// GLANS - Glans. /// </summary> Glans, /// <summary> /// GLUT - Gluteus. /// </summary> Gluteus, /// <summary> /// GLUTE - Gluteal. /// </summary> Gluteal, /// <summary> /// GLUTM - Gluteus Medius. /// </summary> GluteusMedius, /// <summary> /// GROIN - Groin. /// </summary> Groin, /// <summary> /// GUM - Gum. /// </summary> Gum, /// <summary> /// GVU - Genital - Vulva. /// </summary> GenitalVulva, /// <summary> /// HAL - Hallux. /// </summary> Hallux, /// <summary> /// HAND - Hand. /// </summary> Hand, /// <summary> /// HAR - Hair. /// </summary> Hair, /// <summary> /// HART - Heart. /// </summary> Heart, /// <summary> /// HEAD - Head. /// </summary> Head, /// <summary> /// HEEL - Heel. /// </summary> Heel, /// <summary> /// HEM - Hemorrhoid. /// </summary> Hemorrhoid, /// <summary> /// HIP - Hip. /// </summary> Hip, /// <summary> /// HIPJ - Hip Joint. /// </summary> HipJoint, /// <summary> /// HUMER - Humerus. /// </summary> Humerus, /// <summary> /// HV - Heart Valve. /// </summary> HeartValve, /// <summary> /// HVB - Heart Valve, Bicuspid. /// </summary> HeartValveBicuspid, /// <summary> /// HVT - Heart Valve, Tricuspid. /// </summary> HeartValveTricuspid, /// <summary> /// HYMEN - Hymen. /// </summary> Hymen, /// <summary> /// ICX - Intracervical. /// </summary> Intracervical, /// <summary> /// ILC - Ileal Conduit. /// </summary> IlealConduit, /// <summary> /// ILCON - Ilical Conduit. /// </summary> IlicalConduit, /// <summary> /// ILCR - Iliac Crest. /// </summary> IliacCrest, /// <summary> /// ILE - Ileal Loop. /// </summary> IlealLoop, /// <summary> /// ILEOS - Ileostomy. /// </summary> Ileostomy, /// <summary> /// ILEUM - Ileum. /// </summary> Ileum, /// <summary> /// ILIAC - Iliac. /// </summary> Iliac, /// <summary> /// INASA - Intranasal. /// </summary> Intranasal, /// <summary> /// INGUI - Inguinal. /// </summary> Inguinal, /// <summary> /// INSTL - Intestine, Large. /// </summary> IntestineLarge, /// <summary> /// INSTS - Intestine, Small. /// </summary> IntestineSmall, /// <summary> /// INT - Intestine. /// </summary> Intestine, /// <summary> /// INTRO - Introitus. /// </summary> Introitus, /// <summary> /// INTRU - Intrauterine. /// </summary> Intrauterine, /// <summary> /// ISCHI - Ischium. /// </summary> Ischium, /// <summary> /// ISH - Loop, Ishial. /// </summary> LoopIshial, /// <summary> /// JAW - Jaw. /// </summary> Jaw, /// <summary> /// JUGE - Jugular, External. /// </summary> JugularExternal, /// <summary> /// JUGI - Jugular, Internal. /// </summary> JugularInternal, /// <summary> /// KIDN - Kidney. /// </summary> KidneyDeprecated, /// <summary> /// KNEE - Knee. /// </summary> Knee, /// <summary> /// KNEEF - Knee Fluid. /// </summary> KneeFluid, /// <summary> /// KNEEJ - Knee Joint. /// </summary> KneeJoint, /// <summary> /// LABIA - Labia. /// </summary> Labia, /// <summary> /// LABMA - Labia Majora. /// </summary> LabiaMajora, /// <summary> /// LABMI - Labia Minora. /// </summary> LabiaMinora, /// <summary> /// LACRI - Lacrimal. /// </summary> Lacrimal, /// <summary> /// LAM - Lamella. /// </summary> Lamella, /// <summary> /// LARYN - Larynx. /// </summary> Larynx, /// <summary> /// LEG - Leg. /// </summary> Leg, /// <summary> /// LENS - Lens. /// </summary> Lens, /// <summary> /// LING - Lingual. /// </summary> Lingual, /// <summary> /// LINGU - Lingula. /// </summary> Lingula, /// <summary> /// LIP - Lip. /// </summary> Lip, /// <summary> /// LIVER - Liver. /// </summary> Liver, /// <summary> /// LMN - Lumen. /// </summary> Lumen, /// <summary> /// LN - Lymph Node. /// </summary> LymphNode, /// <summary> /// LNG - Lymph Node, Groin. /// </summary> LymphNodeGroin, /// <summary> /// LOBE - Lobe. /// </summary> Lobe, /// <summary> /// LOCH - Lochia. /// </summary> Lochia, /// <summary> /// LUMBA - Lumbar. /// </summary> Lumbar, /// <summary> /// LUNG - Lung. /// </summary> Lung, /// <summary> /// LYM - Lymphocytes. /// </summary> Lymphocytes, /// <summary> /// MAC - Macrophages. /// </summary> Macrophages, /// <summary> /// MALLE - Malleolus. /// </summary> Malleolus, /// <summary> /// MANDI - Mandible/Mandibular. /// </summary> MandibleMandibular, /// <summary> /// MAR - Marrow. /// </summary> Marrow, /// <summary> /// MAST - Mastoid. /// </summary> Mastoid, /// <summary> /// MAXIL - Maxilla/Maxillary. /// </summary> MaxillaMaxillary, /// <summary> /// MAXS - Maxillary Sinus. /// </summary> MaxillarySinus, /// <summary> /// MEATU - Meatus. /// </summary> Meatus, /// <summary> /// MEC - Meconium. /// </summary> Meconium, /// <summary> /// MEDST - Mediastinum. /// </summary> Mediastinum, /// <summary> /// MEDU - Medullary. /// </summary> Medullary, /// <summary> /// METAC - Metacarpal. /// </summary> Metacarpal, /// <summary> /// METAT - Metatarsal. /// </summary> Metatarsal, /// <summary> /// MILK - Milk, Breast. /// </summary> MilkBreast, /// <summary> /// MITRL - Mitral Valve. /// </summary> MitralValve, /// <summary> /// MOLAR - Molar. /// </summary> Molar, /// <summary> /// MONSU - Mons Ureteris. /// </summary> MonsUreteris, /// <summary> /// MONSV - Mons Veneris(Mons Pubis). /// </summary> MonsVenerisMonsPubis, /// <summary> /// MOU - Membrane. /// </summary> Membrane, /// <summary> /// MOUTH - Mouth. /// </summary> Mouth, /// <summary> /// MP - Mons Pubis. /// </summary> MonsPubis, /// <summary> /// MPB - Meninges. /// </summary> Meninges, /// <summary> /// MRSA2 - Mrsa:. /// </summary> Mrsa, /// <summary> /// MYO - Myocardium. /// </summary> Myocardium, /// <summary> /// NAIL - Nail. /// </summary> Nail, /// <summary> /// NAILB - Nail Bed. /// </summary> NailBed, /// <summary> /// NAILF - Nail, Finger. /// </summary> NailFinger, /// <summary> /// NAILT - Nail, Toe. /// </summary> NailToe, /// <summary> /// NARES - Nares. /// </summary> Nares, /// <summary> /// NASL - Nasal. /// </summary> Nasal, /// <summary> /// NAVEL - Navel. /// </summary> Navel, /// <summary> /// NECK - Neck. /// </summary> Neck, /// <summary> /// NERVE - Nerve. /// </summary> Nerve, /// <summary> /// NIPPL - Nipple. /// </summary> Nipple, /// <summary> /// NLACR - Nasolacrimal. /// </summary> Nasolacrimal, /// <summary> /// NOS - Nose (Nasal Passage). /// </summary> NoseNasalPassage, /// <summary> /// NOSE - Nose/Nose(outside). /// </summary> NoseNoseOutside, /// <summary> /// NOSTR - Nostril. /// </summary> Nostril, /// <summary> /// NP - Nasopharyngeal/Nasopharynx. /// </summary> NasopharyngealNasopharynx, /// <summary> /// NSS - Nasal Septum. /// </summary> NasalSeptum, /// <summary> /// NTRAC - Nasotracheal. /// </summary> Nasotracheal, /// <summary> /// OCCIP - Occipital. /// </summary> Occipital, /// <summary> /// OLECR - Olecranon. /// </summary> Olecranon, /// <summary> /// OMEN - Omentum. /// </summary> Omentum, /// <summary> /// ORBIT - Orbit/Orbital. /// </summary> OrbitOrbital, /// <summary> /// ORO - Oropharynx. /// </summary> Oropharynx, /// <summary> /// OSCOX - Os coxa (pelvic girdle). /// </summary> OsCoxaPelvicGirdle, /// <summary> /// OVARY - Ovary. /// </summary> Ovary, /// <summary> /// PAFL - Pancreatic Fluid. /// </summary> PancreaticFluid, /// <summary> /// PALAT - Palate. /// </summary> Palate, /// <summary> /// PALM - Palm. /// </summary> Palm, /// <summary> /// PANAL - Perianal/Perirectal. /// </summary> PerianalPerirectal, /// <summary> /// PANCR - Pancreas. /// </summary> Pancreas, /// <summary> /// PARAT - Paratracheal. /// </summary> Paratracheal, /// <summary> /// PARIE - Parietal. /// </summary> Parietal, /// <summary> /// PARON - Paronychia. /// </summary> Paronychia, /// <summary> /// PAROT - Parotid/Parotid Gland. /// </summary> ParotidParotidGland, /// <summary> /// PAS - Parasternal. /// </summary> Parasternal, /// <summary> /// PATEL - Patella. /// </summary> Patella, /// <summary> /// PCARD - Pericardium. /// </summary> Pericardium, /// <summary> /// PCLIT - Periclitoral. /// </summary> Periclitoral, /// <summary> /// PELV - Pelvis. /// </summary> Pelvis, /// <summary> /// PENIS - Penis. /// </summary> Penis, /// <summary> /// PENSH - Penile Shaft. /// </summary> PenileShaft, /// <summary> /// PER - Peritoneal. /// </summary> Peritoneal, /// <summary> /// PERI - Pericardial Fluid. /// </summary> PericardialFluid, /// <summary> /// PERIH - Perihepatic. /// </summary> Perihepatic, /// <summary> /// PERIN - Perineal Abscess. /// </summary> PerinealAbscess, /// <summary> /// PERIS - Perisplenic. /// </summary> Perisplenic, /// <summary> /// PERIT - Peritoneum. /// </summary> Peritoneum, /// <summary> /// PERIU - Periurethal. /// </summary> Periurethal, /// <summary> /// PERIV - Perivesicular. /// </summary> Perivesicular, /// <summary> /// PERRA - Perirectal. /// </summary> Perirectal, /// <summary> /// PERT - Peritoneal Fluid. /// </summary> PeritonealFluid, /// <summary> /// PHALA - Phalanyx. /// </summary> Phalanyx, /// <summary> /// PILO - Pilonidal. /// </summary> Pilonidal, /// <summary> /// PINNA - Pinna. /// </summary> Pinna, /// <summary> /// PLACF - Placenta (Fetal Side). /// </summary> PlacentaFetalSide, /// <summary> /// PLACM - Placenta (Maternal Side). /// </summary> PlacentaMaternalSide, /// <summary> /// PLANT - Plantar. /// </summary> Plantar, /// <summary> /// PLATH - Palate, Hard. /// </summary> PalateHard, /// <summary> /// PLATS - Palate, Soft. /// </summary> PalateSoft, /// <summary> /// PLC - Placenta. /// </summary> Placenta, /// <summary> /// PLEU - Pleural Fluid. /// </summary> PleuralFluid, /// <summary> /// PLEUR - Pleura. /// </summary> Pleura, /// <summary> /// PLR - Pleural Fluid (Thoracentesis Fld). /// </summary> PleuralFluidThoracentesisFld, /// <summary> /// PNEAL - Perineal. /// </summary> Perineal, /// <summary> /// PNEPH - Perinephric. /// </summary> Perinephric, /// <summary> /// PNM - Perineum. /// </summary> Perineum, /// <summary> /// POPLI - Popliteal. /// </summary> Popliteal, /// <summary> /// PORBI - Periorbital. /// </summary> Periorbital, /// <summary> /// PREAU - Preauricular. /// </summary> Preauricular, /// <summary> /// PRERE - Prerenal. /// </summary> Prerenal, /// <summary> /// PROS - Prostatic Fluid. /// </summary> ProstaticFluid, /// <summary> /// PRST - Prostate Gland. /// </summary> ProstateGland, /// <summary> /// PTONS - Peritonsillar. /// </summary> Peritonsillar, /// <summary> /// PUBIC - Pubic. /// </summary> Pubic, /// <summary> /// PUL - Pulmonary Artery. /// </summary> PulmonaryArtery, /// <summary> /// RADI - Radial. /// </summary> Radial, /// <summary> /// RADIUS - Radius. /// </summary> Radius, /// <summary> /// RBC - Red Blood Cells. /// </summary> RedBloodCells, /// <summary> /// RECTL - Rectal. /// </summary> Rectal, /// <summary> /// RECTU - Rectum. /// </summary> Rectum, /// <summary> /// RENL - Renal. /// </summary> Renal, /// <summary> /// RIB - Rib. /// </summary> Rib, /// <summary> /// RNP - Renal Pelvis. /// </summary> RenalPelvis, /// <summary> /// RPERI - Retroperitoneal. /// </summary> Retroperitoneal, /// <summary> /// SAC - Uterine Cul/De/Sac. /// </summary> UterineCulDeSac, /// <summary> /// SACIL - Sacroiliac. /// </summary> Sacroiliac, /// <summary> /// SACRA - Sacral. /// </summary> Sacral, /// <summary> /// SACRO - Sacrococcygeal. /// </summary> Sacrococcygeal, /// <summary> /// SACRU - Sacrum. /// </summary> Sacrum, /// <summary> /// SALGL - Salivary Gland. /// </summary> SalivaryGland, /// <summary> /// SCALP - Scalp. /// </summary> Scalp, /// <summary> /// SCAPU - Scapula/Scapular. /// </summary> ScapulaScapular, /// <summary> /// SCLAV - Supraclavicle/Supraclavicular. /// </summary> SupraclavicleSupraclavicular, /// <summary> /// SCLER - Sclera. /// </summary> Sclera, /// <summary> /// SCLV - Sub Clavian. /// </summary> SubClavian, /// <summary> /// SCROT - Scrotum/Scrotal. /// </summary> ScrotumScrotal, /// <summary> /// SDP - Subdiaphramatic. /// </summary> Subdiaphramatic, /// <summary> /// SEM - Seminal Fluid. /// </summary> SeminalFluid, /// <summary> /// SEMN - Semen. /// </summary> Semen, /// <summary> /// SEPTU - Septum/Septal. /// </summary> SeptumSeptal, /// <summary> /// SEROM - Seroma. /// </summary> Seroma, /// <summary> /// SGF - Subgaleal Fluid. /// </summary> SubgalealFluid, /// <summary> /// SHIN - Shin. /// </summary> Shin, /// <summary> /// SHOL - Shoulder. /// </summary> Shoulder, /// <summary> /// SHOLJ - Sholder Joint. /// </summary> SholderJoint, /// <summary> /// SIGMO - Sigmoid. /// </summary> Sigmoid, /// <summary> /// SINUS - Sinus. /// </summary> Sinus, /// <summary> /// SKENE - Skene's Gland. /// </summary> SkenesGland, /// <summary> /// SKM - Skeletal Muscle. /// </summary> SkeletalMuscle, /// <summary> /// SKULL - Skull. /// </summary> Skull, /// <summary> /// SOLE - Sole. /// </summary> Sole, /// <summary> /// SPCOR - Spinal Cord. /// </summary> SpinalCord, /// <summary> /// SPHEN - Sphenoid. /// </summary> Sphenoid, /// <summary> /// SPLN - Spleen. /// </summary> Spleen, /// <summary> /// SPRM - Spermatozoa. /// </summary> Spermatozoa, /// <summary> /// SPX - Supra Cervical. /// </summary> SupraCervical, /// <summary> /// STER - Sternum/Sternal. /// </summary> SternumSternal, /// <summary> /// STOM - Stoma. /// </summary> Stoma, /// <summary> /// STOMA - Stomach. /// </summary> Stomach, /// <summary> /// STOOLL - Liquid Stool. /// </summary> LiquidStool, /// <summary> /// STUMP - Stump. /// </summary> Stump, /// <summary> /// SUB - Subdural. /// </summary> Subdural, /// <summary> /// SUBD - Subdural Fluid. /// </summary> SubduralFluid, /// <summary> /// SUBM - Submandibular. /// </summary> Submandibular, /// <summary> /// SUBME - Submental. /// </summary> Submental, /// <summary> /// SUBPH - Subphrenic. /// </summary> Subphrenic, /// <summary> /// SUBX - Submaxillary. /// </summary> Submaxillary, /// <summary> /// SUPB - Suprapubic Specimen. /// </summary> SuprapubicSpecimen, /// <summary> /// SUPRA - Suprapubic. /// </summary> Suprapubic, /// <summary> /// SWT - Sweat. /// </summary> Sweat, /// <summary> /// SWTG - Sweat Gland. /// </summary> SweatGland, /// <summary> /// SYN - Synovial Fluid. /// </summary> SynovialFluid, /// <summary> /// SYNOL - Synovial. /// </summary> Synovial, /// <summary> /// SYNOV - Synovium. /// </summary> Synovium, /// <summary> /// TARS - Tarsal. /// </summary> Tarsal, /// <summary> /// TBRON - Transbronchial. /// </summary> Transbronchial, /// <summary> /// TCN - Transcarina Asp. /// </summary> TranscarinaAsp, /// <summary> /// TDUCT - Tear Duct. /// </summary> TearDuct, /// <summary> /// TEAR - Tears. /// </summary> Tears, /// <summary> /// TEMPL - Temple. /// </summary> Temple, /// <summary> /// TEMPO - Temporal. /// </summary> Temporal, /// <summary> /// TESTI - Testicle(Testis). /// </summary> TesticleTestis, /// <summary> /// THIGH - Thigh. /// </summary> Thigh, /// <summary> /// THM - Thymus. /// </summary> Thymus, /// <summary> /// THORA - Thorax/Thoracic/Thoracentesis. /// </summary> ThoraxThoracicThoracentesis, /// <summary> /// THRB - Throat. /// </summary> Throat, /// <summary> /// THUMB - Thumb. /// </summary> Thumb, /// <summary> /// THYRD - Thyroid. /// </summary> Thyroid, /// <summary> /// TIBIA - Tibia. /// </summary> Tibia, /// <summary> /// TML - Temporal Lobe. /// </summary> TemporalLobe, /// <summary> /// TNL - Thumbnail. /// </summary> Thumbnail, /// <summary> /// TOE - Toe. /// </summary> Toe, /// <summary> /// TOEN - Toe Nail. /// </summary> ToeNail, /// <summary> /// TONG - Tongue. /// </summary> Tongue, /// <summary> /// TONS - Tonsil. /// </summary> Tonsil, /// <summary> /// TOOTH - Tooth. /// </summary> Tooth, /// <summary> /// TRCHE - Trachea/Tracheal. /// </summary> TracheaTracheal, /// <summary> /// TSK - Tooth Socket. /// </summary> ToothSocket, /// <summary> /// ULNA - Ulna/Ulnar. /// </summary> UlnaUlnar, /// <summary> /// UMB - Umbilical Blood. /// </summary> UmbilicalBlood, /// <summary> /// UMBL - Umbilicus/Umbilical. /// </summary> UmbilicusUmbilical, /// <summary> /// URET - Ureter. /// </summary> Ureter, /// <summary> /// URTH - Urethra. /// </summary> Urethra, /// <summary> /// USTOM - Stoma, Urinary. /// </summary> StomaUrinary, /// <summary> /// UTER - Uterus. /// </summary> Uterus, /// <summary> /// UTERI - Uterine. /// </summary> Uterine, /// <summary> /// VAGIN - Vagina/Vaginal. /// </summary> VaginaVaginal, /// <summary> /// VAL - Valve. /// </summary> Valve, /// <summary> /// VAS - Vas Deferens. /// </summary> VasDeferens, /// <summary> /// VASTL - Vastus Lateralis. /// </summary> VastusLateralis, /// <summary> /// VAULT - Vault. /// </summary> Vault, /// <summary> /// VCSF - Ventricular CSF. /// </summary> VentricularCsf, /// <summary> /// VCUFF - Vaginal Cuff. /// </summary> VaginalCuff, /// <summary> /// VEIN - Vein. /// </summary> Vein, /// <summary> /// VENTG - Ventragluteal. /// </summary> Ventragluteal, /// <summary> /// VERMI - Vermis Cerebelli. /// </summary> VermisCerebelli, /// <summary> /// VERTC - Vertebra, cervical. /// </summary> VertebraCervical, /// <summary> /// VERTL - Vertebra, lumbar. /// </summary> VertebraLumbar, /// <summary> /// VERTT - Vertebra, thoracic. /// </summary> VertebraThoracic, /// <summary> /// VESCL - Vesicular. /// </summary> Vesicular, /// <summary> /// VESFLD - Vesicular Fluid. /// </summary> VesicularFluid, /// <summary> /// VESI - Vesicle. /// </summary> Vesicle, /// <summary> /// VESTI - Vestibule(Genital). /// </summary> VestibuleGenital, /// <summary> /// VGV - Vaginal Vault. /// </summary> VaginalVault, /// <summary> /// VITR - Vitreous Fluid. /// </summary> VitreousFluid, /// <summary> /// VOC - Vocal Cord. /// </summary> VocalCord, /// <summary> /// VULVA - Vulva. /// </summary> Vulva, /// <summary> /// WBC - Leukocytes. /// </summary> Leukocytes, /// <summary> /// WRIST - Wrist. /// </summary> Wrist, /// <summary> /// - External Jugular. /// </summary> ExternalJugular } }
19.413933
59
0.386702
[ "MIT" ]
kamlesh-microsoft/clear-hl7-net
src/ClearHl7.Codes/V250/CodeBodyParts.cs
43,198
C#
using System; using System.Collections.Generic; using System.Linq; namespace Day4_ReposeRecord { public class GuardRecordProcessor { public GuardRecordProcessor(string[] rawData) { AllActions = new List<GuardAction>(); GuardRecords = initGuardRecords(rawData); } public List<GuardRecord> GuardRecords { get; set; } public List<GuardAction> AllActions { get; set; } public GuardRecord SleepiestGuard() { //Find guard that sleeps the most GuardRecords.Sort((x, y) => x.Stats.MinutesAsleep.CompareTo(y.Stats.MinutesAsleep)); var sleepyGuard = GuardRecords.Last(); return sleepyGuard; } public GuardRecord ConsistentSleepyGuard() { //Find guard that sleeps at the same time the most often GuardRecords.Sort((x, y) => x.Stats.TopMinuteAsleepCount.CompareTo(y.Stats.TopMinuteAsleepCount)); var consistentSleepyGuard = GuardRecords.Last(); return consistentSleepyGuard; } private List<GuardRecord> initGuardRecords(string[] data) { foreach (var rawGRecord in data) { //our timestamp is between a left and right bracket var tStart = rawGRecord.IndexOf('['); var tEnd = rawGRecord.IndexOf(']'); var tStmp = rawGRecord.Substring(tStart + 1, tEnd - tStart - 1); //Everything after the timestamp var otherData = rawGRecord.Substring(tEnd + 1, rawGRecord.Length - tEnd - 1); //If the rest of the data contains a pound sign, the record is being shift record if (otherData.Contains('#')) { var guardId = otherData.Split(' ').First(x => x.StartsWith("#")); var newAction = new GuardAction(tStmp, GuardActionType.BeginShift).GetSetGuard(guardId); AllActions.Add(newAction); } if (otherData.Contains("falls asleep")) { var newAction = new GuardAction(tStmp, GuardActionType.FallAsleep); AllActions.Add(newAction); } else if (otherData.Contains("wakes up")) { var newAction = new GuardAction(tStmp, GuardActionType.WakeUp); AllActions.Add(newAction); } } //Sort our action list AllActions.Sort((x, y) => DateTime.Compare(x.TimeStamp, y.TimeStamp)); //Run through the list and set guardIds for all actions based on the most recent guardId found that doesn't equal the current guardId being processed. var currGuardId = string.Empty; foreach (var act in AllActions) if (!act.MissingGuardId && act.GuardId != currGuardId) currGuardId = act.GuardId; else act.GuardId = currGuardId; //Group our sorted and processed list by GuardId var grouped = AllActions.GroupBy(x => x.GuardId); //Initialize and fill our list of GuardRecords GuardRecords = new List<GuardRecord>(); foreach (var group in grouped) { var newRecord = new GuardRecord(group.Key); foreach (var value in group) newRecord.AddAction(value); newRecord.ProcessStats(); GuardRecords.Add(newRecord); } return GuardRecords; } } }
37.608247
162
0.561129
[ "MIT" ]
Oninaig/Oninaig.Advent2018
Day4_ReposeRecord/GuardRecordProcessor.cs
3,650
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 disable using System; using System.Threading; using System.Windows; using System.Windows.Threading; using EnvDTE; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Threading; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.InProcess { /// <summary> /// Base class for all components that run inside of the Visual Studio process. /// <list type="bullet"> /// <item>Every in-proc component should provide a public, static, parameterless "Create" method. /// This will be called to construct the component in the VS process.</item> /// <item>Public methods on in-proc components should be instance methods to ensure that they are /// marshalled properly and execute in the VS process. Static methods will execute in the process /// in which they are called.</item> /// </list> /// </summary> internal abstract class InProcComponent : MarshalByRefObject { private static JoinableTaskFactory _joinableTaskFactory; protected InProcComponent() { } private static Dispatcher CurrentApplicationDispatcher => Application.Current.Dispatcher; protected static JoinableTaskFactory JoinableTaskFactory { get { if (_joinableTaskFactory is null) { Interlocked.CompareExchange(ref _joinableTaskFactory, ThreadHelper.JoinableTaskFactory.WithPriority(CurrentApplicationDispatcher, DispatcherPriority.Background), null); } return _joinableTaskFactory; } } protected static void InvokeOnUIThread(Action<CancellationToken> action) { using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout); var operation = JoinableTaskFactory.RunAsync(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); action(cancellationTokenSource.Token); }); operation.Task.Wait(cancellationTokenSource.Token); } protected static T InvokeOnUIThread<T>(Func<CancellationToken, T> action) { using var cancellationTokenSource = new CancellationTokenSource(Helper.HangMitigatingTimeout); var operation = JoinableTaskFactory.RunAsync(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationTokenSource.Token); return action(cancellationTokenSource.Token); }); operation.Task.Wait(cancellationTokenSource.Token); return operation.Task.Result; } protected static TInterface GetGlobalService<TService, TInterface>() where TService : class where TInterface : class => InvokeOnUIThread(cancellationToken => (TInterface)ServiceProvider.GlobalProvider.GetService(typeof(TService))); protected static TService GetComponentModelService<TService>() where TService : class => InvokeOnUIThread(cancellationToken => GetComponentModel().GetService<TService>()); protected static DTE GetDTE() => GetGlobalService<SDTE, DTE>(); protected static IComponentModel GetComponentModel() => GetGlobalService<SComponentModel, IComponentModel>(); protected static bool IsCommandAvailable(string commandName) => GetDTE().Commands.Item(commandName).IsAvailable; protected static void ExecuteCommand(string commandName, string args = "") { var task = Task.Run(() => GetDTE().ExecuteCommand(commandName, args)); task.Wait(Helper.HangMitigatingTimeout); } /// <summary> /// Waiting for the application to 'idle' means that it is done pumping messages (including WM_PAINT). /// </summary> protected static void WaitForApplicationIdle(TimeSpan timeout) #pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs => CurrentApplicationDispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle).Wait(timeout); #pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs protected static void WaitForSystemIdle() #pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs => CurrentApplicationDispatcher.Invoke(() => { }, DispatcherPriority.SystemIdle); #pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs // Ensure InProcComponents live forever public override object InitializeLifetimeService() => null; } }
41.825
188
0.688982
[ "MIT" ]
Acidburn0zzz/roslyn
src/VisualStudio/IntegrationTest/TestUtilities/InProcess/InProcComponent.cs
5,021
C#
using CERental.Core.Contract.Repository; using CERental.Core.Domain; namespace CERental.Data.Repositories { public class RentalRepository : Repository<Rental>, IRentalRepository { } }
19.8
73
0.762626
[ "MIT" ]
RassK/CERental
CERental.Data/Repositories/RentalRepository.cs
200
C#
namespace JSM.Swashbuckle.AspNetCore.Swagger.Settings { /// <summary> /// Providing the properties Redoc Options of Internal Doc and External Doc in AppSettings /// </summary> public class RedocOptionsSettings { /// <summary> /// Property SpecUrl of Redoc Options /// </summary> public string SpecUrl { get; set; } /// <summary> /// Property RoutePrefix of Redoc Options /// </summary> public string RoutePrefix { get; set; } /// <summary> /// Property DocumentTitle of Redoc Options /// </summary> public string DocumentTitle { get; set; } } }
30.272727
94
0.587087
[ "MIT" ]
juntossomosmais/JSM.Swashbuckle.AspNetCore
src/JSM.Swashbuckle.AspNetCore.Swagger/Settings/RedocOptionsSettings.cs
668
C#
namespace UblTr.Common { [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.8.3928.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] [System.Xml.Serialization.XmlRootAttribute("CompanyLegalForm", Namespace = "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", IsNullable = false)] public partial class CompanyLegalFormType : TextType1 { } }
52.416667
171
0.772655
[ "MIT" ]
canyener/Ubl-Tr
Ubl-Tr/Common/CommonBasicComponents/CompanyLegalFormType.cs
629
C#
using HtmlAgilityPack; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Windows.Forms; using static onlineplayer.Utils; using static onlineplayer.Json; using System.Xml; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace onlineplayer { public partial class Form1 : Form { List<Item> itemsList = new List<Item>(); List<Track> queueTracks = new List<Track>(); List<Models.JSON.JsonSearch.Result> searchResults = new List<Models.JSON.JsonSearch.Result>(); int offset = 0; bool streamMode = false; HttpTools httpTools = new HttpTools(); Core.IAudioPlayer player; public Form1(List<string> tags, List<Track> restoreQueue, Core.IAudioPlayer plr) { InitializeComponent(); player = plr; //player.Init(); switch (Core.Config.viewType) { case "Tile": listAlbums.Columns.Clear(); listAlbums.Columns.AddRange(new ColumnHeader[] { new ColumnHeader(), new ColumnHeader(), new ColumnHeader() }); listAlbums.TileSize = new Size(256, Core.Config.viewSize); break; case "Large Images": if (listAlbums.LargeImageList != null) { listAlbums.LargeImageList.ImageSize = new Size(Core.Config.viewSize, Core.Config.viewSize); } listAlbums.View = View.LargeIcon; break; case "Details": listAlbums.Columns.Clear(); listAlbums.Columns.AddRange(new ColumnHeader[] { new ColumnHeader(), new ColumnHeader()}); listAlbums.Columns[0].Text = "Album name"; listAlbums.Columns[1].Text = "Artist"; listAlbums.View = View.Details; break; default: listAlbums.Columns.Clear(); listAlbums.Columns.AddRange(new ColumnHeader[] { new ColumnHeader(), new ColumnHeader(), new ColumnHeader() }); listAlbums.TileSize = new Size(256, Core.Config.viewSize); break; } queueList.Columns.AddRange(new ColumnHeader[] { new ColumnHeader(), new ColumnHeader(), new ColumnHeader() }); queueList.TileSize = new Size(256, 64); Directory.CreateDirectory("artwork_cache"); toolStream.Enabled = false; listAlbums.MouseUp += (s, args) => { if (args.Button == MouseButtons.Right) { contextMenuStrip1.Show(Cursor.Position); } }; queueList.MouseUp += (s, args) => { if (args.Button == MouseButtons.Right) { contextMenuStrip2.Show(Cursor.Position); } }; comboFormat.SelectedIndex = 0; toolSearch.Enabled = false; // adding tags listTags.Items.AddRange(tags.ToArray()); // adding queue tracks foreach (Track trk in restoreQueue) { if (trk != null) { ListViewItem lst = new ListViewItem(new string[] { trk.Title, trk.Album.Artist, trk.Album.Title }); queueList.Items.Add(lst); queueTracks.Add(trk); } } if (restoreQueue.Count > 1) { UpdateQueueImages(); } labelStatus.Text = "Done!"; } private void toolStripButton1_Click(object sender, EventArgs e) { itemsList.Clear(); listAlbums.Items.Clear(); listAlbums.LargeImageList.Images.Clear(); listAlbums.LargeImageList = null; toolRefresh.Enabled = false; listTags.Enabled = true; } private void listBox1_Click(object sender, EventArgs e) { textTags.Text += listTags.SelectedItem + " "; } private void AlbumList(object sender, EventArgs e) { PlayFormList(); } private void timer1_Tick(object sender, EventArgs e) { try { trackSeek.Enabled = true; toolPlay.Enabled = true; toolNext.Enabled = true; toolPrev.Enabled = true; openTrackPage.Enabled = true; trackSeek.Value = (int)player.GetCurrentTimeTotalSeconds(); TimeSpan time = TimeSpan.FromSeconds(player.GetCurrentTimeTotalSeconds()); label3.Text = time.ToString(@"hh\:mm\:ss"); label5.Text = player.GetPlaybackState(); } catch (NullReferenceException) { trackSeek.Enabled = false; label3.Text = "00:00:00"; label5.Text = "Stopped"; } if (Math.Abs(player.GetTotalTimeSeconds() - player.GetCurrentTimeTotalSeconds()) < 0.1 && queueTracks.Count > 1) { PlayNext(); } if (queueTracks.Count <= 0) { toolNext.Enabled = false; toolPrev.Enabled = false; } } private void toolStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void trackBar2_Scroll(object sender, EventArgs e) { label4.Text = "Volume: " + trackVolume.Value + "%"; try { player.SetVolume(trackVolume.Value / 100f); } catch (Exception) { } } private void playToolStripMenuItem_Click(object sender, EventArgs e) { PlayFormList(); } private void openInBrowserToolStripMenuItem_Click(object sender, EventArgs e) { try { Item selectedAlbum = itemsList.Find(item => item.artist.Equals(listAlbums.FocusedItem.SubItems[1].Text) && item.title.Equals(listAlbums.FocusedItem.SubItems[0].Text)); System.Diagnostics.Process.Start(selectedAlbum.tralbum_url); } catch (NullReferenceException) { MessageBox.Show("Cannot open in browser!", "Opening failed...", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void toolStripButton5_Click(object sender, EventArgs e) { } private void listView1_SelectedIndexChanged(object sender, EventArgs e) { } private async void addAlbumTracksInQueueifAvailbleToolStripMenuItem_Click(object sender, EventArgs e) { Item selectedAlbum = itemsList.Find(item => item.artist.Equals(listAlbums.FocusedItem.SubItems[1].Text) && item.title.Equals(listAlbums.FocusedItem.SubItems[0].Text)); AddToQueueList(selectedAlbum.tralbum_url, selectedAlbum.band_url); UpdateQueueImages(); } private void queueList_DoubleClick(object sender, EventArgs e) { offset = queueList.FocusedItem.Index; PlayOffset(); labelStatus.Text = "Done!"; } private void toolStripButton4_Click(object sender, EventArgs e) { PlayNext(); } private void toolStripButton2_Click(object sender, EventArgs e) { PlayPrev(); } private void toolStripButton3_Click(object sender, EventArgs e) { player.PlayPause(); } private void removeFromQueueToolStripMenuItem_Click(object sender, EventArgs e) { try { queueList.Items.Remove(queueList.FocusedItem); queueTracks.RemoveAt(queueList.FocusedItem.Index); queueList.LargeImageList.Images.RemoveAt(queueList.FocusedItem.Index); } catch (NullReferenceException) { labelStatus.Text = "All items has been removed!"; } } private void pictureBox1_Click(object sender, EventArgs e) { try { Form artForm = new ViewArtwork(queueTracks[offset].Album.ArtworkId); artForm.Show(); } catch (Exception) { Form artForm = new ViewArtwork(itemsList[listAlbums.FocusedItem.Index].art_id.ToString()); artForm.Show(); } } private void trackBar1_Scroll(object sender, EventArgs e) { try { player.SetPos((int)trackSeek.Value); } catch (NullReferenceException) { trackSeek.Value = 0; labelStatus.Text = "Cannot seek: Audio file not loaded!"; } } private async void toolStripButton5_Click_1(object sender, EventArgs e) { if (!streamMode) { toolStream.Enabled = false; streamMode = true; bool firstSong = false; CleanUp(); toolStream.Text = "Stop stream mode"; labelStatus.Text = "Loading tracks metadata..."; List<string> blocked = viewBlocked(); foreach (Item item in itemsList) { if (!streamMode) { break; } String response = await httpTools.MakeRequestAsync(item.tralbum_url); Album album = httpTools.GetAlbum(response); if (!blocked.Contains(album.Artist)) { foreach (Track trk in album.Tracks) { if (!streamMode) { break; } ListViewItem lst = new ListViewItem(new string[] { trk.Title, trk.Album.Artist, trk.Album.Title }); queueList.Items.Add(lst); queueTracks.Add(trk); } if (queueList.Items.Count > 0 && !firstSong) { firstSong = true; PlayOffset(); toolStream.Enabled = true; } } } labelStatus.Text = "Done!"; } else { streamMode = false; CleanUp(); timer1.Stop(); player.Close(); toolStream.Text = "Play as stream mode"; } } private void toolStripButton6_Click(object sender, EventArgs e) { Form settings = new FormSettings(); settings.Show(); } private void toolStripButton7_Click(object sender, EventArgs e) { BlockArtist(); } private void blockSelectedArtiststreamingModeToolStripMenuItem_Click(object sender, EventArgs e) { BlockArtist(); } private void toolStripButton9_Click(object sender, EventArgs e) { var res = MessageBox.Show("Clear queue items completely?", "Queue manager", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (res == DialogResult.Yes) { queueTracks.Clear(); queueList.LargeImageList.Images.Clear(); queueList.Clear(); } } private void toolStripTextBox1_TextChanged(object sender, EventArgs e) { listAlbums.Items.Clear(); foreach (var alb in itemsList) { if (alb.title.ToLower().Contains(toolSearch.Text.ToLower()) || alb.artist.ToLower().Contains(toolSearch.Text.ToLower())) { ListViewItem lst = new ListViewItem(new string[] { alb.title, alb.artist }); listAlbums.Items.Add(lst); } } if (toolSearch.Text.Length == 0) { listAlbums.Items.Clear(); foreach (var item in itemsList) { // title, artist, mp3_url, url, artworkid ListViewItem lst = new ListViewItem(new string[] { item.title, item.artist }); listAlbums.Items.Add(lst); } int count = 0; labelStatus.Text = "Loading ablum images..."; foreach (ListViewItem listItem in listAlbums.Items) { listItem.ImageIndex = count++; } labelStatus.Text = "Done..."; } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { File.Delete("queueList.xml"); if (getSettingsAttrBool("settings.xml", "saveQueue") && !streamMode && queueTracks.Count > 0) { Playlist.SavePlaylist("queueList.xml", queueTracks); } try { player.Close(); } catch (NullReferenceException) { } File.Delete("tempfile.wav"); } private void toolSavePlaylist_Click(object sender, EventArgs e) { if (queueTracks.Count > 0) { saveFileDialog1.Filter = "BandcampOnlinePlayer Playlists (*.bpl)|*.bpl"; saveFileDialog1.FilterIndex = 2; saveFileDialog1.RestoreDirectory = true; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { Playlist.SavePlaylist(saveFileDialog1.FileName, queueTracks); MessageBox.Show("Playlist saved!", "Saved!"); } } } private async void openPlaylist_Click(object sender, EventArgs e) { openFileDialog1.Filter = "BandcampOnlinePlayer Playlists (*.bpl)|*.bpl"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { //Get the path of specified file string filePath = openFileDialog1.FileName; XmlDocument doc = new XmlDocument(); doc.Load(filePath); XmlElement xRoot = doc.DocumentElement; XmlNode attr; labelStatus.Text = "Restoring play queue..."; List<Models.QueueRestoreData> resetoreData = new List<Models.QueueRestoreData>(); foreach (XmlNode xnode in xRoot) { if (xnode.Attributes.Count > 0) { Models.QueueRestoreData restoreTrack = new Models.QueueRestoreData(); attr = xnode.Attributes.GetNamedItem("artistUrl"); if (attr != null) { restoreTrack.ArtistUrl = attr.Value; } attr = xnode.Attributes.GetNamedItem("trackUrl"); if (attr != null) { restoreTrack.TrackUrl = attr.Value; } resetoreData.Add(restoreTrack); } } foreach (Models.QueueRestoreData restore in resetoreData) { string responseAlbum = await httpTools.MakeRequestAsync(restore.ArtistUrl + restore.TrackUrl); Album album = httpTools.GetAlbum(responseAlbum); foreach (Track trk in album.Tracks) { trk.ArtistUrl = restore.ArtistUrl; queueTracks.Add(trk); ListViewItem lst = new ListViewItem(new string[] { trk.Title, trk.Album.Artist, trk.Album.Title }); queueList.Items.Add(lst); labelStatus.Text = "Restoring play queue: " + trk.Album.Artist + " - " + trk.Title + " ..."; } } } labelStatus.Text = "Done..."; } private async void textBox1_TextChanged(object sender, EventArgs e) { listGlobalSearch.Items.Clear(); searchResults.Clear(); string response = await httpTools.MakeRequestAsync("https://bandcamp.com/api/fuzzysearch/1/autocomplete?q=" + textBox1.Text); if (textBox1.Text.Length > 0) { try { Models.JSON.JsonSearch.RootObject items = JsonConvert.DeserializeObject<Models.JSON.JsonSearch.RootObject>(response); foreach (Models.JSON.JsonSearch.Result searchItem in items.auto.results) { ListViewItem lst; switch (searchItem.type) { case "a": lst = new ListViewItem(new string[] { searchItem.name, searchItem.band_name, "Album" }); break; case "f": lst = new ListViewItem(new string[] { searchItem.name, searchItem.band_name, "Fan" }); break; case "b": lst = new ListViewItem(new string[] { searchItem.name, searchItem.band_name, "Artist/Band" }); break; case "t": lst = new ListViewItem(new string[] { searchItem.name, searchItem.band_name, "Track" }); break; default: lst = new ListViewItem(new string[] { searchItem.name, searchItem.band_name, "Unknown: " + searchItem.type }); break; } listGlobalSearch.Items.Add(lst); searchResults.Add(searchItem); } } catch (Exception) { } } } private async void listGlobalSearch_DoubleClick(object sender, EventArgs e) { if (listGlobalSearch.FocusedItem.SubItems[2].Text == "Album" || listGlobalSearch.FocusedItem.SubItems[2].Text == "Track") { labelStatus.Text = "Loading album/track metadata: " + searchResults[listGlobalSearch.FocusedItem.Index].url; String response = await httpTools.MakeRequestAsync(searchResults[listGlobalSearch.FocusedItem.Index].url); Album album = httpTools.GetAlbum(response); foreach (Track trk in album.Tracks) { ListViewItem lst = new ListViewItem(new string[] { trk.Title, trk.Album.Artist, trk.Album.Title }); queueList.Items.Add(lst); trk.ArtistUrl = "https://" + searchResults[listGlobalSearch.FocusedItem.Index].url.Split('/')[2]; queueTracks.Add(trk); } UpdateQueueImages(); tabControl1.SelectedIndex = 1; } else { DialogResult res = MessageBox.Show("Open webpage page in external browser?", searchResults[listGlobalSearch.FocusedItem.Index].url, MessageBoxButtons.YesNo, MessageBoxIcon.Warning); if (res == DialogResult.Yes) { System.Diagnostics.Process.Start(searchResults[listGlobalSearch.FocusedItem.Index].url); } } } private void playToolStripMenuItem1_Click(object sender, EventArgs e) { PlayOffset(); } private void button1_Click(object sender, EventArgs e) { tabControl1.SelectedIndex = 1; UpdateAlbums(); buttonLoad.Enabled = false; } private void textTags_TextChanged(object sender, EventArgs e) { buttonLoad.Enabled = textTags.Text.Length > 0; buttonFullLoad.Enabled = textTags.Text.Length > 0; } private void openAlbumWebpageInBrowserToolStripMenuItem_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start(queueTracks[queueList.FocusedItem.Index].ArtistUrl + queueTracks[queueList.FocusedItem.Index].Url); } private void tileToolStripMenuItem_Click(object sender, EventArgs e) { listAlbums.View = View.Tile; listAlbums.Columns.Clear(); listAlbums.Columns.AddRange(new ColumnHeader[] { new ColumnHeader(), new ColumnHeader(), new ColumnHeader() }); listAlbums.TileSize = new Size(256, Core.Config.viewSize); } private void largeImagesToolStripMenuItem_Click(object sender, EventArgs e) { listAlbums.View = View.LargeIcon; } private void detailsToolStripMenuItem_Click(object sender, EventArgs e) { listAlbums.Columns.Clear(); listAlbums.Columns.AddRange(new ColumnHeader[] { new ColumnHeader(), new ColumnHeader(), new ColumnHeader() }); listAlbums.Columns[0].Text = "Album name"; listAlbums.Columns[1].Text = "Artist"; listAlbums.View = View.Details; } private void ascendToolStripMenuItem_Click(object sender, EventArgs e) { listAlbums.Sorting = SortOrder.Ascending; } private void descendToolStripMenuItem_Click(object sender, EventArgs e) { listAlbums.Sorting = SortOrder.Descending; } private void openTrackPage_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start(queueTracks[offset].ArtistUrl + queueTracks[offset].Url); } private async void buttonFullLoad_Click(object sender, EventArgs e) { await Task.Run(() => { string[] files = Directory.GetFiles(@"artwork_cache\", "*.json"); foreach (string file in files) { File.Delete(file); } }); tabControl1.SelectedIndex = 1; UpdateAlbums(); buttonLoad.Enabled = false; buttonFullLoad.Enabled = false; } private void addClipboard_Click(object sender, EventArgs e) { if (Clipboard.GetText().Contains("https://bandcamp.com") && Clipboard.GetText().Contains("/track") || Clipboard.GetText().Contains("/album")) { AddToQueueList(Clipboard.GetText(), "https://" + Clipboard.GetText().Split('/')[2]); UpdateQueueImages(); } else { MessageBox.Show("Clipboard contains invalid data: " + Clipboard.GetText(), "Opening failed...", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
36.953052
197
0.516368
[ "MIT" ]
LaineZ/BandcampOnlinePlayer
onlineplayer/Form1.cs
23,615
C#
using System.Text; using System.Collections.Generic; using System.IO; using UnityEngine; using System.Linq; namespace Parabox.STL { /** * Describes the file format of an STL file. */ public enum FileType { Ascii, Binary }; /** * Export STL files from Unity mesh assets. */ public static class pb_Stl { /** * Write a mesh file to STL. */ public static bool WriteFile(string path, Mesh mesh, FileType type = FileType.Ascii, bool convertToRightHandedCoordinates = true) { return WriteFile(path, new Mesh[] { mesh }, type, convertToRightHandedCoordinates); } /** * Write a collection of mesh assets to an STL file. * No transformations are performed on meshes in this method. * Eg, if you want to export a set of a meshes in a transform * hierarchy the meshes should be transformed prior to this call. * * string path - Where to write the file. * IList<Mesh> meshes - The mesh assets to write. * FileType type - How to format the file (in ASCII or binary). */ public static bool WriteFile(string path, IList<Mesh> meshes, FileType type = FileType.Ascii, bool convertToRightHandedCoordinates = true) { try { switch(type) { case FileType.Binary: { // http://paulbourke.net/dataformats/stl/ // http://www.fabbers.com/tech/STL_Format using (BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create), new ASCIIEncoding())) { // 80 byte header writer.Write(new byte[80]); uint totalTriangleCount = (uint) (meshes.Sum(x => x.triangles.Length) / 3); // unsigned long facet count (4 bytes) writer.Write( totalTriangleCount ); foreach(Mesh mesh in meshes) { Vector3[] v = convertToRightHandedCoordinates ? Left2Right(mesh.vertices) : mesh.vertices; Vector3[] n = convertToRightHandedCoordinates ? Left2Right(mesh.normals) : mesh.normals; int[] t = mesh.triangles; int triangleCount = t.Length; if(convertToRightHandedCoordinates) System.Array.Reverse(t); for(int i = 0; i < triangleCount; i += 3) { int a = t[i], b = t[i+1], c = t[i+2]; Vector3 avg = AvgNrm(n[a], n[b], n[c]); writer.Write(avg.x); writer.Write(avg.y); writer.Write(avg.z); writer.Write(v[a].x); writer.Write(v[a].y); writer.Write(v[a].z); writer.Write(v[b].x); writer.Write(v[b].y); writer.Write(v[b].z); writer.Write(v[c].x); writer.Write(v[c].y); writer.Write(v[c].z); // specification says attribute byte count should be set to 0. writer.Write( (ushort)0 ); } } } } break; default: string model = WriteString(meshes); File.WriteAllText(path, model); break; } } catch(System.Exception e) { UnityEngine.Debug.LogError(e.ToString()); return false; } return true; } /** * Write a Unity mesh to an ASCII STL string. */ public static string WriteString(Mesh mesh, bool convertToRightHandedCoordinates = true) { return WriteString(new Mesh[] { mesh }, convertToRightHandedCoordinates); } /** * Write a set of meshes to an ASCII string in STL format. */ public static string WriteString(IList<Mesh> meshes, bool convertToRightHandedCoordinates = true) { StringBuilder sb = new StringBuilder(); string name = meshes.Count == 1 ? meshes[0].name : "Composite Mesh"; sb.AppendLine(string.Format("solid {0}", name)); foreach(Mesh mesh in meshes) { Vector3[] v = convertToRightHandedCoordinates ? Left2Right(mesh.vertices) : mesh.vertices; Vector3[] n = convertToRightHandedCoordinates ? Left2Right(mesh.normals) : mesh.normals; int[] t = mesh.triangles; if(convertToRightHandedCoordinates) System.Array.Reverse(t); int triLen = t.Length; for(int i = 0; i < triLen; i+=3) { int a = t[i]; int b = t[i+1]; int c = t[i+2]; Vector3 nrm = AvgNrm(n[a], n[b], n[c]); sb.AppendLine(string.Format("facet normal {0} {1} {2}", nrm.x, nrm.y, nrm.z)); sb.AppendLine("outer loop"); sb.AppendLine(string.Format("\tvertex {0} {1} {2}", v[a].x, v[a].y, v[a].z)); sb.AppendLine(string.Format("\tvertex {0} {1} {2}", v[b].x, v[b].y, v[b].z)); sb.AppendLine(string.Format("\tvertex {0} {1} {2}", v[c].x, v[c].y, v[c].z)); sb.AppendLine("endloop"); sb.AppendLine("endfacet"); } } sb.AppendLine(string.Format("endsolid {0}", name)); return sb.ToString(); } private static Vector3[] Left2Right(Vector3[] v) { Vector3[] r = new Vector3[v.Length]; for (int i = 0; i < v.Length; i++) r[i] = new Vector3(v[i].z, -v[i].x, v[i].y); return r; } /** * Average of 3 vectors. */ private static Vector3 AvgNrm(Vector3 a, Vector3 b, Vector3 c) { return new Vector3( (a.x + b.x + c.x) / 3f, (a.y + b.y + c.y) / 3f, (a.z + b.z + c.z) / 3f ); } } }
26.623037
140
0.60236
[ "MIT" ]
Excludos/pb_Stl
Assets/pb_Stl/pb_Stl.cs
5,085
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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GreetingsWindowsService")] [assembly: AssemblyTrademark("")] // 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("1fce5320-e949-41a4-a3b9-a8369f2b4ac2")]
41.65
84
0.785114
[ "MIT" ]
uQr/Paramore.Brighter
Examples/GreetingsWindowsService/Properties/AssemblyInfo.cs
835
C#
 using System; using System.Configuration; namespace SoftvConfiguration { public class TrabajoElement : ConfigurationElement { /// <summary> /// Gets assembly name for Trabajo class /// </summary> [ConfigurationProperty("Assembly")] public String Assembly { get { string assembly = (string)base["Assembly"]; assembly = String.IsNullOrEmpty(assembly) ? SoftvSettings.Settings.Assembly : (string)base["Assembly"]; return assembly; } } /// <summary> /// Gets class name for Trabajo ///</summary> [ConfigurationProperty("DataClassTrabajo", DefaultValue = "Softv.DAO.TrabajoData")] public String DataClass { get { return (string)base["DataClassTrabajo"]; } } /// <summary> /// Gets connection string for database Trabajo access ///</summary> [ConfigurationProperty("ConnectionString")] public String ConnectionString { get { string connectionString = (string)base["ConnectionString"]; connectionString = String.IsNullOrEmpty(connectionString) ? SoftvSettings.Settings.ConnectionString : (string)base["ConnectionString"]; return connectionString; } } } }
28.92
151
0.555325
[ "Apache-2.0" ]
nubiancc/CallCenter
Encuestas/Softv/Softv.Configuration/TrabajoElement.cs
1,448
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 appmesh-2019-01-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.AppMesh.Model { /// <summary> /// The specified resource doesn't exist. Check your request syntax and try again. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class NotFoundException : AmazonAppMeshException { /// <summary> /// Constructs a new NotFoundException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public NotFoundException(string message) : base(message) {} /// <summary> /// Construct instance of NotFoundException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public NotFoundException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of NotFoundException /// </summary> /// <param name="innerException"></param> public NotFoundException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of NotFoundException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public NotFoundException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of NotFoundException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public NotFoundException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the NotFoundException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected NotFoundException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); } #endif } }
46.459677
178
0.675056
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/AppMesh/Generated/Model/NotFoundException.cs
5,761
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("JN Soundboard")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("JN Soundboard")] [assembly: AssemblyCopyright("Copyright © Jitnaught 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("791ce5fc-fb35-4471-a28e-b5a5e99e9355")] // 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.1.1.0")] [assembly: AssemblyFileVersion("1.1.1.0")]
38.054054
84
0.745739
[ "MIT" ]
Indiana8000/JNSoundboard
Properties/AssemblyInfo.cs
1,411
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace PsychesBound { public interface IDamageSender : ITileObject { int GetAttack(DamageType type); } }
15.571429
48
0.701835
[ "MIT" ]
AirMaster453/Turn-Based_RPG-Unity
Turn_Based_RPG/Assets/Scripts/Interfaces/IDamageSender.cs
218
C#
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace SupportTickets.React { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
39.194595
199
0.609213
[ "Apache-2.0" ]
AKrasheninnikov/PnP
Samples/SharePoint.React.SupportTicket/deploy/SupportTickets.React/SharePointContext.cs
36,255
C#
using System; using CloudsdaleLib.Models; using Cloudsdale_Metro.Controllers; using WinRTXamlToolkit.AwaitableUI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236 namespace Cloudsdale_Metro.Views.Controls { public sealed partial class UserList { private readonly CloudController _controller; public UserList(CloudController controller) { InitializeComponent(); _controller = controller; InitializeFlyout(); } private async void UserList_OnLoaded(object sender, RoutedEventArgs e) { await this.WaitForNonZeroSizeAsync(); DataContext = _controller; } private void UserClicked(object sender, ItemClickEventArgs e) { new UserPanel((User)e.ClickedItem).FlyOut(); } public override string Header { get { return "Users"; } } public override Uri Image { get { return _controller.Cloud.Avatar.Preview; } } } }
29.810811
96
0.659112
[ "MIT" ]
cloudsdaleapp/cloudsdale-metro
Cloudsdale-Metro/Views/Controls/Flyout Panels/UserList.xaml.cs
1,105
C#
namespace Ruyi.SDK.Online { /// <summary> /// A k-factor used when calculating ELO ratings using Fide. /// </summary> public class FideKFactor : KFactor { /// <summary> /// Default construction. /// </summary> public FideKFactor() { } /// <summary> /// Returns the k-factor for the specified rating. /// </summary> /// <param name="rating">The rating to get the k-factor for.</param> /// <returns>15 if the rating is less than 2400, otherwise 10.</returns> public override double GetValueForRating(double rating) { if (rating < 2400) { return 15; } return 10; } /// <summary> /// Provisional k-factor for people who have played less than 30 games. /// </summary> public class Provisional : FideKFactor { /// <summary> /// Default construction. /// </summary> public Provisional() { } /// <summary> /// Returns the provisional k-factor of 25. /// </summary> /// <param name="rating">The rating to get the k-factor for.</param> /// <returns>25</returns> public override double GetValueForRating(double rating) { return 25; } } } }
27.148148
80
0.482265
[ "MIT" ]
c04x/sdk
RuyiSDK/RuyiNet/Skill/Elo/FideKFactor.cs
1,468
C#
using CharacterGen.CharacterClasses; using CharacterGen.Domain.Tables; using NUnit.Framework; using System.Linq; namespace CharacterGen.Tests.Integration.Tables.Magics.Spells.Known.Druids { [TestFixture] public class Level11DruidKnownSpellsTests : AdjustmentsTests { protected override string tableName { get { return string.Format(TableNameConstants.Formattable.Adjustments.LevelXCLASSKnownSpells, 11, CharacterClassConstants.Druid); } } [Test] public override void CollectionNames() { var names = Enumerable.Range(0, 7).Select(i => i.ToString()); AssertCollectionNames(names); } [TestCase(0, 6)] [TestCase(1, 5)] [TestCase(2, 4)] [TestCase(3, 4)] [TestCase(4, 3)] [TestCase(5, 2)] [TestCase(6, 1)] public void Adjustment(int spellLevel, int quantity) { base.Adjustment(spellLevel.ToString(), quantity); } } }
27.051282
139
0.598104
[ "MIT" ]
DnDGen/CharacterGen
CharacterGen.Tests.Integration.Tables/Magics/Spells/Known/Druids/Level11DruidKnownSpellsTests.cs
1,057
C#
using System; namespace OpenCvSharp { // ReSharper disable once InconsistentNaming /// <summary> /// Abstract base class for shape distance algorithms. /// </summary> public abstract class ShapeDistanceExtractor : Algorithm { /// <summary> /// Compute the shape distance between two shapes defined by its contours. /// </summary> /// <param name="contour1">Contour defining first shape.</param> /// <param name="contour2">Contour defining second shape.</param> /// <returns></returns> public virtual float ComputeDistance(InputArray contour1, InputArray contour2) { if (ptr == IntPtr.Zero) throw new ObjectDisposedException(GetType().Name); if (contour1 == null) throw new ArgumentNullException(nameof(contour1)); if (contour2 == null) throw new ArgumentNullException(nameof(contour2)); contour1.ThrowIfDisposed(); contour2.ThrowIfDisposed(); float ret = NativeMethods.shape_ShapeDistanceExtractor_computeDistance( ptr, contour1.CvPtr, contour2.CvPtr); GC.KeepAlive(contour1); GC.KeepAlive(contour2); return ret; } } }
33.25641
86
0.605243
[ "BSD-3-Clause" ]
CollegiumXR/OpenCvSharp-Xamarin.Droid
src/OpenCvSharp/Modules/shape/ShapeDistanceExtractor.cs
1,299
C#
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Threading; using MindTouch.Tasking; namespace MindTouch.Threading { /// <summary> /// RendezVousEvent is a lightweight synchronization primitive. It used to align exactly one signal source to a signal receiver (i.e. a rendez-vous). /// The order in which the signal is set and waited on are not important. The RendezVousEvent will remember that it was signaled and immediately /// trigger the receiver. <br/> /// The receiver must be a continuation. The RendezVousEvent does not allow for blocking wait. /// </summary> public sealed class RendezVousEvent { // NOTE (steveb): 'RendezVousEvent' is as a tuple-space implementation; it is succesful only when // both Signal() and Wait() have been invoked once and exactly once; the invocation order is irrelevant. //--- Constants --- private readonly static object TOKEN = new object(); private readonly static object USED = new object(); //--- Class Fields --- // TODO (steveb): there is a race condition where pending events get added, but not removed; the reason is that we don't have a hint that the event // was already removed and hence should not be added; note that since '_pendingCounter' uses atomic operation, it is not affected. /// <summary> /// Capture the state of the task (set to <see langword="False"/> by default.) /// </summary> public static bool CaptureTaskState = false; /// <summary> /// Dictionary of pending events. /// </summary> public static readonly Dictionary<object, KeyValuePair<TaskEnv, System.Diagnostics.StackTrace>> Pending = new Dictionary<object, KeyValuePair<TaskEnv, System.Diagnostics.StackTrace>>(); private static log4net.ILog _log = MindTouch.LogUtils.CreateLog(); private static int _pendingCounter = 0; //--- Class Properties --- /// <summary> /// Returns the number of pending RendezVousEvent instances. A pending RendezVousEvent instance has a continuation, but has not been signaled yet. /// </summary> public static int PendingCounter { get { return _pendingCounter; } } //--- Fields --- private object _placeholder; private IDispatchQueue _dispatchQueue; private System.Diagnostics.StackTrace _stacktrace = DebugUtil.GetStackTrace(); private bool _captured; //--- Properties --- /// <summary> /// Returns true if the RendezVousEvent instance has been signaled and the receiver continuation has been triggered. /// </summary> public bool HasCompleted { get { return ReferenceEquals(_placeholder, USED); } } //--- Methods --- /// <summary> /// Ensure the receiver continuation is executed on the current thread. /// </summary> /// <exception cref="InvalidOperationException">The RendezVousEvent is already pinned to an IDispatchQueue.</exception> [Obsolete("PinToThread is obsolete. Use the continuation to dispatch to the desired thread.")] public void PinToThread() { // TODO 2.0 (steveb): remove implementation PinTo(SynchronizationContext.Current); } /// <summary> /// Ensure the receiver continuation is executed on the given synchronization context. /// </summary> /// <param name="context">Synchronization context for the receiver continuation.</param> /// <exception cref="InvalidOperationException">The RendezVousEvent is already pinned to an IDispatchQueue.</exception> [Obsolete("PinTo is obsolete. Use the continuation to dispatch to the desired thread.")] public void PinTo(SynchronizationContext context) { // TODO 2.0 (steveb): remove implementation PinTo(new SynchronizationDispatchQueue(context)); } /// <summary> /// Ensure the receiver continuation is executed on the given IDispatchQueue. /// </summary> /// <param name="dispatchQueue">IDispatchQueue for the receiver continuation.</param> /// <exception cref="InvalidOperationException">The RendezVousEvent is already pinned to an IDispatchQueue.</exception> [Obsolete("PinTo is obsolete. Use the continuation to dispatch to the desired thread.")] public void PinTo(IDispatchQueue dispatchQueue) { // TODO 2.0 (steveb): remove implementation if(_dispatchQueue != null) { throw new InvalidOperationException("RendezVousEvent is already pinned to an IDispatchQueue"); } _dispatchQueue = dispatchQueue; } /// <summary> /// Signal the RendezVousEvent. If a receiver continuation is present, trigger it. /// Otherwise, store the signal until a continuation is registered. /// </summary> /// <exception cref="InvalidOperationException">The RendezVousEvent instance has already been signaled.</exception> public void Signal() { if(HasCompleted) { throw new InvalidOperationException("event has already been used"); } object value = Interlocked.Exchange(ref _placeholder, TOKEN); if(value != null) { if(!(value is Action)) { throw new InvalidOperationException("event has already been signaled"); } Action handler = (Action)value; Interlocked.Decrement(ref _pendingCounter); if(_captured) { lock(Pending) { Pending.Remove(this); } } _placeholder = USED; if(_dispatchQueue != null) { _dispatchQueue.QueueWorkItem(handler); } else { try { handler(); } catch(Exception e) { // log exception, but ignore it; outer task is immune to it _log.WarnExceptionMethodCall(e, "Signal: unhandled exception in continuation"); } } } } /// <summary> /// Register the receiver continuation to activate when the RendezVousEvent instance is signaled. /// </summary> /// <param name="handler">Receiver continuation to invoke when RendezVousEvent instance is signaled.</param> /// <exception cref="InvalidOperationException">The RendezVousEvent instance has already a continuation.</exception> public void Wait(Action handler) { if(handler == null) { throw new ArgumentNullException("handler"); } if(HasCompleted) { throw new InvalidOperationException("event has already been used"); } object token = Interlocked.Exchange(ref _placeholder, handler); if(token != null) { if(!ReferenceEquals(token, TOKEN)) { throw new InvalidOperationException("event has already a continuation"); } _placeholder = USED; if(_dispatchQueue != null) { _dispatchQueue.QueueWorkItem(handler); } else { try { handler(); } catch(Exception e) { // log exception, but ignore it; outer task is immune to it _log.WarnExceptionMethodCall(e, "Wait: unhandled exception in continuation"); } } } else { Interlocked.Increment(ref _pendingCounter); if(CaptureTaskState) { lock(Pending) { if(!HasCompleted) { Pending.Add(this, new KeyValuePair<TaskEnv, System.Diagnostics.StackTrace>(TaskEnv.CurrentOrNull, DebugUtil.GetStackTrace())); _captured = true; } } } } } /// <summary> /// Reset RendezVousEvent instance to its initial state without a signal and a continuation. /// </summary> public void Abandon() { object value = Interlocked.Exchange(ref _placeholder, null); if(ReferenceEquals(value, USED)) { // rendez-vous already happened; nothing to do } else if(ReferenceEquals(value, TOKEN)) { // only signal was set; nothing to do } else if(!ReferenceEquals(value, null)) { // decrease counter and remove stack trace if one exists Interlocked.Decrement(ref _pendingCounter); if(_captured) { lock(Pending) { Pending.Remove(this); } } } } /// <summary> /// Atomically check if RendezVousEvent is already signaled. If so, return true and mark the RendezVousEvent instance as having /// completed its synchronization operation. Otherwise, register the receiver continuation to activate when the RendezVousEvent /// instance is signaled. /// </summary> /// <param name="handler">Receiver continuation to invoke when RendezVousEvent instance is signaled.</param> /// <returns>Returns true if RendezVousEvent instance is already signaled.</returns> public bool IsReadyOrWait(Action handler) { if(handler == null) { throw new ArgumentNullException("handler"); } if(HasCompleted) { throw new InvalidOperationException("event has already been used"); } object token = Interlocked.Exchange(ref _placeholder, handler); if(token != null) { if(!ReferenceEquals(token, TOKEN)) { throw new InvalidOperationException("event has already a continuation"); } _placeholder = USED; return true; } else { Interlocked.Increment(ref _pendingCounter); if(CaptureTaskState) { lock(Pending) { if(!HasCompleted) { Pending.Add(this, new KeyValuePair<TaskEnv, System.Diagnostics.StackTrace>(TaskEnv.CurrentOrNull, DebugUtil.GetStackTrace())); _captured = true; } } } } return false; } } }
45.609195
194
0.578965
[ "Apache-2.0" ]
nataren/DReAM
src/mindtouch.dream/Threading/RendezVousEvent.cs
11,904
C#