content stringlengths 23 1.05M |
|---|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OCM.API.Common.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
namespace OCM.Import.Providers
{
public class ImportProvider_PS : BaseImportProvider, IImportProvider
{
public ImportProvider_PS()
{
ProviderName = "PlugShare";
OutputNamePrefix = "PlugShare_";
IsAutoRefreshed = false;
IsProductionReady = false;
UseCustomReader = true;
SourceEncoding = Encoding.GetEncoding("UTF-8");
MergeDuplicatePOIEquipment = false;
IncludeInvalidPOIs = true;
AllowDuplicatePOIWithDifferentOperator = true;
DataProviderID = 27; //PlugShare
}
/// <summary>
/// http://stackoverflow.com/questions/9026508/incremental-json-parsing-in-c-sharp
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="readerStream"></param>
/// <returns></returns>
public static IEnumerable<T> DeserializeSequenceFromJson<T>(TextReader readerStream)
{
using (var reader = new JsonTextReader(readerStream))
{
var serializer = new JsonSerializer();
if (!reader.Read() || reader.TokenType != JsonToken.StartArray)
throw new Exception("Expected start of array in the deserialized json string");
while (reader.Read())
{
if (reader.TokenType == JsonToken.EndArray) break;
var item = serializer.Deserialize<T>(reader);
yield return item;
}
}
}
public List<API.Common.Model.ChargePoint> Process(CoreReferenceData coreRefData)
{
//TODO: operator not well matched, usage type not known, multiple connectors at same site not imported due to duplicate POI. Requires merge process.
List<ChargePoint> outputList = new List<ChargePoint>();
var submissionStatus = coreRefData.SubmissionStatusTypes.First(s => s.ID == 100);//imported and published
var operationalStatus = coreRefData.StatusTypes.First(os => os.ID == 50);
var unknownStatus = coreRefData.StatusTypes.First(os => os.ID == 0);
var usageTypePublic = coreRefData.UsageTypes.First(u => u.ID == 1);
var usageTypePrivate = coreRefData.UsageTypes.First(u => u.ID == 2);
var usageTypePrivateForStaffAndVisitors = coreRefData.UsageTypes.First(u => u.ID == 6); //staff and visitors
var operatorUnknown = coreRefData.Operators.First(opUnknown => opUnknown.ID == 1);
int itemCount = 0;
var distinctCountries = new List<string>();
var textReader = System.IO.File.OpenText(InputPath);
foreach (var item in DeserializeSequenceFromJson<JObject>(textReader))
{
ChargePoint cp = new ChargePoint();
cp.DataProvider = new DataProvider() { ID = this.DataProviderID };
cp.DataProvidersReference = item["id"].ToString();
cp.DateLastStatusUpdate = DateTime.UtcNow;
cp.AddressInfo = new AddressInfo();
cp.AddressInfo.Title = item["address"].ToString();
cp.OperatorsReference = item["name"].ToString();
cp.AddressInfo.AddressLine1 = item["address"].ToString().Trim();
//cp.AddressInfo.Town = item["city"].ToString().Trim();
//cp.AddressInfo.StateOrProvince = item["StateOrProvince"].ToString().Trim();
//cp.AddressInfo.Postcode = item["postalcode"].ToString().Trim();
cp.AddressInfo.Latitude = double.Parse(item["latitude"].ToString());
cp.AddressInfo.Longitude = double.Parse(item["longitude"].ToString());
// var countryCode = item["locale"].ToString().ToLower();
//if (!distinctCountries.Exists(c => c == countryCode)) distinctCountries.Add(countryCode);
//fix incorrect country codes
//cp.AddressInfo.Country = coreRefData.Countries.FirstOrDefault(c => c.ISOCode.ToLower() == countryCode);
if (!String.IsNullOrEmpty(item["url"].ToString())) cp.AddressInfo.RelatedURL = item["url"].ToString();
//if (!String.IsNullOrEmpty(item["email"].ToString())) cp.AddressInfo.ContactEmail = item["email"].ToString();
//if (!String.IsNullOrEmpty(item["phone"].ToString())) cp.AddressInfo.ContactTelephone1 = item["phone"].ToString();
/*var price = item["price"].ToString();
var pricemethod = item["pricemethod"].ToString();
cp.UsageCost = (!String.IsNullOrEmpty(price) ? price + " " : "") + pricemethod;
//set network operators
//cp.OperatorInfo = new OperatorInfo { ID = 89 };
//TODO: Operator, usage,price, power, connector type
var owner = item["owner"].ToString().ToLower();
var operatoInfo = coreRefData.Operators.FirstOrDefault(op => op.Title.ToLower().Contains(owner));
if (operatoInfo == null)
{
Log("Unknown operator: " + owner);
}
else
{
cp.OperatorID = operatoInfo.ID;
}
bool isPublic = bool.Parse(item["IsPublic"].ToString());
if (isPublic)
{
cp.UsageType = usageTypePublic;
}
else
{
cp.UsageType = usageTypePrivate;
}
*/
//cp.NumberOfPoints = int.Parse(item["nroutlets"].ToString());
cp.StatusType = operationalStatus;
//populate connectioninfo from Ports
/*var connectorType = item["connectortype"].ToString();
var chargetype = item["chargetype"].ToString();
var power = item["power"].ToString();
ConnectionInfo cinfo = new ConnectionInfo();
try
{
if (!String.IsNullOrEmpty(power))
{
cinfo.PowerKW = double.Parse(power.Replace("kW", ""));
}
}
catch (System.FormatException) { }
if (connectorType.ToLower().Contains("j1772"))
{
cinfo.ConnectionTypeID = (int)StandardConnectionTypes.J1772;
cinfo.LevelID = 2;
}
else if (connectorType.ToLower().Contains("mennekes"))
{
cinfo.ConnectionTypeID = (int)StandardConnectionTypes.MennekesType2;
cinfo.LevelID = 2;
}
else if (connectorType.ToLower().Contains("chademo"))
{
cinfo.ConnectionTypeID = (int)StandardConnectionTypes.CHAdeMO;
cinfo.LevelID = 3;
}
else if (connectorType.ToLower().Contains("schuko"))
{
cinfo.ConnectionTypeID = (int)StandardConnectionTypes.Schuko;
cinfo.LevelID = 2;
}
else
{
Log("Unknown connectorType:" + connectorType);
}
if (cinfo.PowerKW >= 50)
{
cinfo.LevelID = 3;
}
if (!String.IsNullOrEmpty(chargetype))
{
if (chargetype.StartsWith("DC")) cinfo.CurrentTypeID = (int)StandardCurrentTypes.DC;
if (chargetype.StartsWith("AC simpel")) cinfo.CurrentTypeID = (int)StandardCurrentTypes.SinglePhaseAC;
//TODO: 3 phase?
}
// System.Diagnostics.Debug.WriteLine("Unknown chargetype:" + chargetype+ " "+power);
if (cp.Connections == null)
{
cp.Connections = new List<ConnectionInfo>();
if (!IsConnectionInfoBlank(cinfo))
{
cp.Connections.Add(cinfo);
}
}
* */
if (cp.DataQualityLevel == null) cp.DataQualityLevel = 3;
cp.SubmissionStatus = submissionStatus;
var poiType = item["icon_type"].ToString();
if (poiType != "H")
{
outputList.Add(cp);
}
itemCount++;
}
/*private var distinctCountries = new List<string>();
foreach (private var item in dataList)
{
private string temp = "";
foreach (private var countryCode in distinctCountries)
{
temp += ", " + countryCode;
}
Log("Countries in import:" + temp);
* */
return outputList.Take(1000).ToList();
}
}
} |
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using ModelBazy;
using UI;
using WypozyczalniaElektronarzedzi;
namespace WypozyczalniaElektronarzedzi
{
/// <summary>
/// Logika interakcji dla klasy DodawaniePracownika.xaml
/// </summary>
public partial class DodawaniePracownika : UserControl
{
public DodawaniePracownika()
{
InitializeComponent();
PunktyObslugiService pkt = new PunktyObslugiService();
PunktObslugi.ItemsSource = pkt.PunktyObslugi;
PunktObslugi.DisplayMemberPath = "Miasto";
}
private void CreatePracownikBtn_Click(object sender, RoutedEventArgs e)
{
Pracownicy pracownik = new Pracownicy
{
Imie = ImieTextBox.Text,
Nazwisko = NazwiskoTextBox.Text,
PESEL = PESELTextBox.Text,
Haslo = HasloTextBox.Text,
IDPunktuObslugi = (PunktObslugi.SelectedItem as PunktyObslugi).IDPunktuObslugi,
DataZatrudnienia = DateTime.Now
};
using (var prac = new PracownicyService())
{
prac.AddEntity(pracownik);
}
MainWindow.AppWindow.WyswietlaniePracownikowUC.UpdateUI();
ImieTextBox.Text = String.Empty;
NazwiskoTextBox.Text = String.Empty;
PESELTextBox.Text = String.Empty;
HasloTextBox.Text = String.Empty;
}
}
} |
//
// Please make sure to read and understand README.md and LICENSE.txt.
//
// This file was prepared in the research project COCOP (Coordinating
// Optimisation of Complex Industrial Processes).
// https://cocop-spire.eu/
//
// Author: Petri Kannisto, Tampere University, Finland
// File created: 3/2019
// Last modified: 2/2020
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Cocop.MessageSerialiser.Meas;
using XsdNs = Cocop.MessageSerialiser.Meas.XsdGen;
namespace TaskRequestTest
{
[TestClass]
public class TestGetStatus
{
[TestMethod]
public void TaskGetStatusReq_Read()
{
string filepath = TestCommon.TestHelper.TestFileFolder + @"\TaskGetStatusRequest.xml";
var testObject = new TaskRequest(ReadFile(filepath));
Assert.AreEqual("mytask", testObject.TaskId);
Assert.AreEqual(TaskOperationType.GetStatus, testObject.Operation);
}
[TestMethod]
public void TaskGetStatusReq_Create()
{
var testObject = TaskRequest.CreateGetStatusRequest(taskId: "sometask");
var xmlBytes = testObject.ToXmlBytes();
// Validating
Validate(xmlBytes);
var testObjectIn = new TaskRequest(xmlBytes);
// Use separate function to make sure the correct object is asserted
TaskGetStatusReq_Create_Assert(testObjectIn);
}
private void TaskGetStatusReq_Create_Assert(TaskRequest testObjectIn)
{
Assert.AreEqual("sometask", testObjectIn.TaskId);
Assert.AreEqual(TaskOperationType.GetStatus, testObjectIn.Operation);
}
[TestMethod]
public void TaskGetStatusReq_Create_Params()
{
// Parameters are not allowed for a cancel request
var testObject = TaskRequest.CreateGetStatusRequest("sometask");
testObject.Parameters = new Item_DataRecord
{
{ "MyParam", new Item_Count(3) }
};
try
{
testObject.ToXmlBytes();
Assert.Fail("Expected exception");
}
catch (ArgumentException e)
{
Assert.IsTrue(e.Message.StartsWith("Parameters are not supported in get task status request"));
}
}
private byte[] ReadFile(string filepath)
{
return System.IO.File.ReadAllBytes(filepath);
}
private void Validate(byte[] xmlBytes)
{
// Validating the document
var validator = new TestCommon.Validator(TestCommon.Validator.SchemaType.Sps_GmlSwe);
using (var xmlStream = new System.IO.MemoryStream(xmlBytes))
{
validator.Validate(xmlStream, typeof(XsdNs.GetStatusType));
}
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using Azure.Core;
namespace Azure.Storage.Blobs.Models
{
/// <summary>
/// Optional parameters for downloading a range of a blob.
/// </summary>
public class BlobDownloadOptions
{
/// <summary>
/// If provided, only download the bytes of the blob in the specified
/// range. If not provided, download the entire blob.
/// </summary>
public HttpRange Range { get; set; }
/// <summary>
/// Optional <see cref="BlobRequestConditions"/> to add conditions on
/// downloading this blob.
/// </summary>
public BlobRequestConditions Conditions { get; set; }
/// <summary>
/// Optional <see cref="IProgress{Long}"/> to provide
/// progress updates about data transfers.
/// </summary>
public IProgress<long> ProgressHandler { get; set; }
/// <summary>
/// Optional transactional hashing options.
/// Range must be provided explicitly stating a range withing Azure
/// Storage size limits for requesting a transactional hash. See the
/// <a href="https://docs.microsoft.com/en-us/rest/api/storageservices/get-blob">
/// REST documentation</a> for range limitation details.
/// </summary>
public DownloadTransactionalHashingOptions TransactionalHashingOptions { get; set; }
/// <summary>
/// Default constructor.
/// </summary>
public BlobDownloadOptions()
{
}
/// <summary>
/// Deep copy constructor.
/// </summary>
/// <param name="deepCopySource"></param>
private BlobDownloadOptions(BlobDownloadOptions deepCopySource)
{
Argument.AssertNotNull(deepCopySource, nameof(deepCopySource));
Range = new HttpRange(offset: deepCopySource.Range.Offset, length: deepCopySource.Range.Length);
Conditions = BlobRequestConditions.CloneOrDefault(deepCopySource.Conditions);
ProgressHandler = deepCopySource.ProgressHandler;
// can't access an internal deep copy in Storage.Common
TransactionalHashingOptions = deepCopySource.TransactionalHashingOptions == default
? default
: new DownloadTransactionalHashingOptions()
{
Algorithm = deepCopySource.TransactionalHashingOptions.Algorithm,
Validate = deepCopySource.TransactionalHashingOptions.Validate
};
}
/// <summary>
/// Creates a deep copy of the given instance, if any.
/// </summary>
/// <param name="deepCopySource">Instance to deep copy.</param>
/// <returns>The deep copy, or null.</returns>
internal static BlobDownloadOptions CloneOrDefault(BlobDownloadOptions deepCopySource)
{
if (deepCopySource == default)
{
return default;
}
return new BlobDownloadOptions(deepCopySource);
}
}
}
|
namespace Gang.State.Commands
{
public interface IGangCommand
{
object Data { get; }
GangAudit Audit { get; }
}
} |
using System;
using System.Collections.Generic;
namespace Observer
{
internal class CentralBank : IObservable
{
private readonly List<IObserver> _observers;
private ExchangeRates _rates;
public CentralBank()
{
_observers = new List<IObserver>();
_rates = new ExchangeRates
{
UsdRub = 60,
EurRub = 70,
GbpRub = 100
};
}
public void RegisterObserver(IObserver observer)
{
if (!_observers.Contains(observer))
_observers.Add(observer);
}
public void RemoveObserver(IObserver observer)
{
if (_observers.Contains(observer))
_observers.Remove(observer);
}
public void Notify()
{
foreach (var observer in _observers)
{
observer.Update(_rates);
}
}
public void ChangeRates()
{
var rnd = new Random().NextDouble();
Console.WriteLine($"rnd: {rnd}");
var rndCoefficient = rnd + 1;
_rates.UsdRub *= rndCoefficient;
_rates.EurRub *= rndCoefficient;
_rates.GbpRub *= rndCoefficient;
Notify();
}
}
} |
namespace SampleApp.DatabaseObjects.Oracle
{
public class CustomerCountryByID_SP : OracleDatabaseObject
{
public override string ExecuteSqlCreateString(string defaultSchema)
{
return
$"CREATE OR REPLACE PROCEDURE {defaultSchema}.GETCOUNTRYBYCUSTOMERID(\n" +
$"\tCUSTOMERID IN VARCHAR2,\n" +
$"\tCOUNTRY OUT VARCHAR2)\n " +
$"AS\n" +
$"BEGIN\n" +
$"\tSELECT {defaultSchema}.\"Customers\".\"Country\"\n" +
$"\tINTO COUNTRY\n" +
$"\tFROM {defaultSchema}.\"Customers\"\n" +
$"\tWHERE {defaultSchema}.\"Customers\".\"CustomerID\" = CUSTOMERID;\n" +
$"END;\n";
}
public override string ExecuteSqlDropString(string defaultSchema)
{
return
$"DROP PROCEDURE {defaultSchema}.GETCOUNTRYBYCUSTOMERID;";
}
}
}
|
// 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.
namespace Owin.Scim.Patching.Operations
{
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public class OperationBase
{
[JsonProperty("path")]
public string Path { get; set; }
[JsonProperty("op", ItemConverterType = typeof(StringEnumConverter))]
public OperationType OperationType { get; set; }
public OperationBase()
{
}
public OperationBase(OperationType operationType, string path)
{
if (path == null)
{
throw new ArgumentNullException("path");
}
this.OperationType = operationType;
this.Path = path;
}
}
} |
using System;
using System.Reflection;
using GHIElectronics.TinyCLR.Devices.SecureStorage;
namespace Bytewizer.Playground
{
public class SettingsProvider
{
private static bool _initialized;
private static readonly object _lock = new object();
public static SecureStorageController Controller { get; private set; }
public static FlashObject Flash { get; private set; }
public static void Initialize()
{
if (_initialized)
return;
Controller = new SecureStorageController(SecureStorage.Configuration);
Flash = ReadFlash();
_initialized = true;
}
public static bool IsErased()
{
var isBlank = true;
for (uint block = 0; block < Controller.TotalSize / Controller.BlockSize; block++)
{
if (!Controller.IsBlank(block)) isBlank = false;
}
return isBlank;
}
public static void Write(FlashObject settings)
{
if (_initialized == false)
{
Initialize();
}
lock (_lock)
{
var buffer = new byte[1 * 1024];
byte[] flashBuffer = Reflection.Serialize(settings, typeof(FlashObject));
Array.Copy(BitConverter.GetBytes(flashBuffer.Length), buffer, 4);
Array.Copy(flashBuffer, 0, buffer, 4, flashBuffer.Length);
if (IsErased() == false)
{
Controller.Erase();
}
var dataBlock = new byte[Controller.BlockSize];
for (uint block = 0; block < buffer.Length / Controller.BlockSize; block++)
{
Array.Copy(buffer, (int)(block * Controller.BlockSize), dataBlock, 0, (int)(Controller.BlockSize));
Controller.Write(block, dataBlock);
}
}
}
private static FlashObject ReadFlash()
{
lock (_lock)
{
if (IsErased() == false)
{
var buffer = new byte[1 * 1024];
var dataBlock = new byte[Controller.BlockSize];
for (uint block = 0; block < buffer.Length / Controller.BlockSize; block++)
{
Controller.Read(block, dataBlock);
Array.Copy(dataBlock, 0, buffer, (int)(block * Controller.BlockSize), dataBlock.Length);
}
var length = BitConverter.ToInt16(buffer, 0);
byte[] flashBuffer = new byte[length];
Array.Copy(buffer, 4, flashBuffer, 0, length);
return (FlashObject)Reflection.Deserialize(flashBuffer, typeof(FlashObject));
}
else
{
Write(new FlashObject());
return ReadFlash();
}
}
}
}
} |
using System;
namespace Account.Service.Domain.Entities
{
public class Account
{
/// <summary>
/// Gets or sets the account id
/// </summary>
public int AccountId { get; set; }
/// <summary>
/// Gets or sets the user
/// </summary>
public virtual User User { get; set; }
/// <summary>
/// Gets or sets the account type
/// </summary>
public string AccountType { get; set; }
/// <summary>
/// Gets or sets the created by.
/// </summary>
/// <value>
/// The created by.
/// </value>
public string CreatedBy { get; set; }
/// <summary>
/// Gets or sets the created date.
/// </summary>
/// <value>
/// The created date.
/// </value>
public DateTime CreatedDate { get; set; }
/// <summary>
/// Gets or sets the updated by.
/// </summary>
/// <value>
/// The updated by.
/// </value>
public string UpdatedBy { get; set; }
/// <summary>
/// Gets or sets the updated date.
/// </summary>
/// <value>
/// The updated date.
/// </value>
public DateTime UpdatedDate { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this instance is active.
/// </summary>
/// <value>
/// <c>true</c> if this instance is active; otherwise, <c>false</c>.
/// </value>
public bool IsActive { get; set; }
}
}
|
using Circle.Game.Beatmaps;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osuTK;
namespace Circle.Game.Screens.Select.Carousel
{
public class PanelContent : Container
{
public PanelContent(BeatmapInfo info)
{
RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
new FillFlowContainer
{
RelativeSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Padding = new MarginPadding { Horizontal = 20, Vertical = 10 },
Spacing = new Vector2(5),
Children = new Drawable[]
{
new SpriteText
{
Text = info.Beatmap.Settings.Song,
Font = FontUsage.Default.With("OpenSans-Bold", size: 30)
},
new SpriteText
{
Text = info.Beatmap.Settings.Author,
Font = FontUsage.Default.With(size: 24)
}
}
}
};
}
}
}
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace GitDependencies
{
public class WorkingFile
{
[XmlAttribute]
public string Name;
[XmlAttribute]
public string Hash;
[XmlAttribute]
public string ExpectedHash;
[XmlAttribute]
public long Timestamp;
}
public class WorkingManifest
{
[XmlArrayItem("File")]
public List<WorkingFile> Files = new List<WorkingFile>();
}
}
|
using NUnit.Framework;
using Sanatana.Notifications.DAL.Entities;
using Sanatana.Notifications.DAL.EntityFrameworkCore;
using Sanatana.Notifications.DAL.EntityFrameworkCore.Context;
using Sanatana.Notifications.DAL.EntityFrameworkCoreSpecs.TestTools.Interfaces;
using SpecsFor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using SpecsFor.StructureMap;
using Sanatana.Notifications.DAL.EntityFrameworkCore.Queries;
namespace Sanatana.Notifications.DAL.EntityFrameworkCoreSpecs.Queries
{
public class SqlSubscriberScheduleSettingsQueriesSpecs
{
[TestFixture]
public class when_schedule_settings_rewriting_sets_using_ef
: SpecsFor<SqlSubscriberScheduleSettingsQueries>, INeedDbContext
{
private List<SubscriberScheduleSettings<long>> _insertedData;
private long _subscriberId;
public SenderDbContext DbContext { get; set; }
protected override void When()
{
_subscriberId = 11;
_insertedData = new List<SubscriberScheduleSettings<long>>
{
new SubscriberScheduleSettings<long>
{
Order = 1,
PeriodBegin = TimeSpan.FromHours(1),
PeriodEnd = TimeSpan.FromHours(2),
Set = 1,
SubscriberId = _subscriberId
},
new SubscriberScheduleSettings<long>
{
Order = 2,
PeriodBegin = TimeSpan.FromHours(13),
PeriodEnd = TimeSpan.FromHours(14),
Set = 1,
SubscriberId = _subscriberId
}
};
SUT.RewriteSets(_subscriberId, _insertedData).Wait();
}
[Test]
public void then_schedule_settings_rewriten_sets_are_found_using_ef()
{
List<SubscriberScheduleSettingsLong> actual = DbContext.SubscriberScheduleSettings
.Where(x => x.SubscriberId == _subscriberId)
.OrderBy(x => x.Set)
.ThenBy(x => x.Order)
.ToList();
actual.Should().NotBeEmpty();
actual.Count.Should().Be(_insertedData.Count);
for (int i = 0; i < _insertedData.Count; i++)
{
SubscriberScheduleSettingsLong actualItem = actual[i];
SubscriberScheduleSettings<long> expectedItem = _insertedData[i];
actualItem.Order.Should().Be(expectedItem.Order);
actualItem.PeriodBegin.Should().Be(expectedItem.PeriodBegin);
actualItem.PeriodEnd.Should().Be(expectedItem.PeriodEnd);
actualItem.Set.Should().Be(expectedItem.Set);
}
}
}
}
}
|
namespace FluentLinqToSql.Tests {
using System.Linq;
using System.Xml.Linq;
using Mappings;
using NUnit.Framework;
[TestFixture]
public class BelongsToTester {
private BelongsToMapping<Order, Customer> mapping;
[SetUp]
public void Setup() {
mapping = new BelongsToMapping<Order, Customer>(typeof(Order).GetProperty("Customer"));
}
[Test]
public void Should_automatically_set_IsForeignKey() {
MappingXml.ShouldHaveAttribute("IsForeignKey", "true");
}
protected XElement MappingXml {
get { return mapping.CastTo<IPropertyMapping>().ToXml().Single(); }
}
}
} |
using System;
using System.Windows;
namespace ArtZilla.Wpf {
public interface IFormStorage {
Boolean Save(Window window);
Boolean Restore(Window window);
}
} |
using System;
using System.Collections.Generic;
using System.IO;
namespace _200oker
{
public class FlatFileProvider
{
public List<UrlToCheck> GetChecks(string filename)
{
var checks = new List<UrlToCheck>();
if (!File.Exists(filename))
throw new ArgumentException(String.Format("Input file {0} not found", filename));
using (var fr = File.OpenRead(filename))
using (var sr = new StreamReader(fr))
{
while (!sr.EndOfStream)
{
var line = sr.ReadLine();
// ignore empty and comment lines
if (!String.IsNullOrWhiteSpace(line) &&
!line.StartsWith("#"))
{
var check = ParseCheckLine(line);
if (check != null)
checks.Add(check);
}
}
}
return checks;
}
private UrlToCheck ParseCheckLine(string line)
{
var lineParts = line.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
var url = lineParts[0].Trim();
string childSelector = null;
if (lineParts.Length > 1)
childSelector = lineParts[1].Trim();
return new UrlToCheck()
{
Url = url,
ChildSelector = childSelector,
};
}
}
} |
using pjsip4net.Core.Data;
using pjsip4net.Core.Interfaces;
using pjsip4net.IM;
namespace pjsip4net.Interfaces
{
public interface IBuddy : IInitializable
{
int Id { get; }
string Uri { get; set; }
bool Subscribe { get; set; }
string Contact { get; }
BuddyStatus Status { get; }
string StatusText { get; }
bool MonitoringPresence { get; }
BuddyActivity Activity { get; }
string ActivityNote { get; }
void UpdatePresenceState();
void Unregister();
}
} |
using System.Reflection;
using Newtonsoft.Json;
namespace LiveObjects.ModelDescription
{
public class PropertyDescriptor
{
[JsonIgnore]
public PropertyInfo PropertyInfo { get; set; }
public string Name => PropertyInfo.Name;
public string CsTypeName => PropertyInfo.PropertyType.ToString();
}
} |
public class ProfiBrainSettings
{
public int codeLength = 4;
public int numberOfColors = 4;
public bool emptyInputs = false;
public bool onlyUsedColors = false;
public bool orderedEval = false;
}
|
using UnityEngine;
using System.Collections;
namespace BlGame.Resource
{
//这是场景的环境光和雾效等设定
public class EnviromentSetting : MonoBehaviour
{
public bool isFogOn;
public Color fogColor;
public FogMode fogMode;
public float fogDensity;
public float linearFogStart;
public float linearFogEnd;
public Color ambientLight;
public Material skyboxMaterial;
public float haloStrength;
public float flareStrength;
public float flareFadeSpeed;
public Texture haloTexture;
public Texture spotCookie;
public void setValueByRenderSetting()
{
isFogOn = RenderSettings.fog;
fogColor = RenderSettings.fogColor;
fogMode = RenderSettings.fogMode;
fogDensity = RenderSettings.fogDensity;
linearFogStart = RenderSettings.fogStartDistance;
linearFogEnd = RenderSettings.fogEndDistance;
ambientLight = RenderSettings.ambientLight;
skyboxMaterial = RenderSettings.skybox;
haloStrength = RenderSettings.haloStrength;
flareStrength = RenderSettings.flareStrength;
flareFadeSpeed = RenderSettings.flareFadeSpeed;
}
// Use this for initialization
void Start()
{
RenderSettings.fog = isFogOn;
RenderSettings.fogColor = fogColor;
RenderSettings.fogMode = fogMode;
RenderSettings.fogDensity = fogDensity;
RenderSettings.fogStartDistance = linearFogStart;
RenderSettings.fogEndDistance = linearFogEnd;
RenderSettings.ambientLight = ambientLight;
RenderSettings.skybox = skyboxMaterial;
RenderSettings.haloStrength = haloStrength;
RenderSettings.flareStrength = flareStrength;
RenderSettings.flareFadeSpeed = flareFadeSpeed;
//RenderSettings.
}
// Update is called once per frame
void Update()
{
}
}
}
|
using NQuery.Syntax;
namespace NQuery.Authoring.Selection.Providers
{
internal sealed class ArgumentListSelectionSpanProvider : SeparatedSyntaxListSelectionSpanProvider<ArgumentListSyntax, ExpressionSyntax>
{
protected override SeparatedSyntaxList<ExpressionSyntax> GetList(ArgumentListSyntax node)
{
return node.Arguments;
}
}
} |
using System.Threading.Tasks;
namespace PurviewAutomation.Clients;
internal interface ILineageOnboardingClient
{
internal Task AddLineageManagedPrivateEndpointsAsync();
internal Task OnboardLineageAsync(string principalId);
}
|
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using System;
namespace Raytracer
{
static class Surfaces
{
// Only works with X-Z plane.
public static readonly Surface CheckerBoard =
new Surface(
(Vector pos) => ((Math.Floor(pos.Z) + Math.Floor(pos.X)) % 2 != 0)
? new Color(1, 1, 1)
: new Color(0.02, 0.0, 0.14),
(Vector pos) => new Color(1, 1, 1),
(Vector pos) => ((Math.Floor(pos.Z) + Math.Floor(pos.X)) % 2 != 0) ? .1 : .5,
150);
public static readonly Surface Shiny =
new Surface(
(Vector pos) => new Color(1, 1, 1),
(Vector pos) => new Color(.5, .5, .5),
(Vector pos) => .7,
250);
public static readonly Surface MatteShiny =
new Surface(
(Vector pos) => new Color(1, 1, 1),
(Vector pos) => new Color(.25, .25, .25),
(Vector pos) => .7,
250);
}
}
|
// ======================================
// Copyright © 2019 Vadim Prokopchuk. All rights reserved.
// Contacts: mailvadimprokopchuk@gmail.com
// License: http://opensource.org/licenses/MIT
// ======================================
using System;
using System.Collections.Generic;
using System.Windows.Media;
using PRM.Models;
namespace PRM.Utils
{
public static class DrawUtils
{
public static void DrawClass(this DrawingGroup drawingGroup, int colorNumber, AreaPoints areaPoints)
{
var ellipses = new GeometryGroup();
foreach (var point in areaPoints.GetPoints())
{
var pointSize = areaPoints.CompareCore(point) ? 4 : 1;
ellipses.Children.Add(new EllipseGeometry(point, pointSize, pointSize));
}
var classColor = colorNumber.GetColor();
var brush = new SolidColorBrush(classColor);
var geometryDrawing = new GeometryDrawing(brush, new Pen(brush, 1), ellipses)
{
Geometry = ellipses
};
drawingGroup.Children.Add(geometryDrawing);
}
public static DrawingImage GetDrawingImage(this List<AreaPoints> areaPointsList)
{
var drawingGroup = new DrawingGroup();
var colorStep = (int)Math.Pow(2, 24) / areaPointsList.Count;
for (var i = 0; i < areaPointsList.Count; i++)
{
drawingGroup.DrawClass(colorStep * i, areaPointsList[i]);
}
return new DrawingImage(drawingGroup);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace SocialApis.Mastodon
{
[DataContract]
public class Attachment
{
[DataMember(Name = "id")]
[Utf8Json.JsonFormatter(typeof(Formatters.StringLongFormatter))]
public long Id { get; private set; }
/// <summary>
/// SocialApis.Mastodon.AttachmentTypes.*
/// </summary>
[DataMember(Name = "type")]
public string Type { get; private set; }
[DataMember(Name = "url")]
public string Url { get; private set; }
[DataMember(Name = "remote_url")]
public string RemoteUrl { get; private set; }
[DataMember(Name = "preview_url")]
public string PreviewUrl { get; private set; }
[DataMember(Name = "text_uri")]
public string TextUri { get; private set; }
[DataMember(Name = "meta")]
public AttachmentMeta Meta { get; private set; }
[DataMember(Name = "description")]
public string Description { get; private set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
string[] line = Console.ReadLine().Split();
int n = int.Parse(line[0]);
int s = int.Parse(line[1]);
int x = int.Parse(line[2]);
Stack<int> num = new Stack<int>(Console.ReadLine().Split().Select(int.Parse));
for (int i = 0; i < s; i++)
{
num.Pop();
}
bool isContainX = num.Contains(x);
if (isContainX)
{
Console.WriteLine(isContainX.ToString().ToLower());
}
else
{
if (!num.Any())
{
Console.WriteLine(0);
}
else
{
Console.WriteLine(num.ToList().Min());
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class OgreMeleeState : IOgreState
{
private Ogre enemy;
private float attackTimer;
private float attackCoolDown = 1.5f;
private bool canExit = true;
bool preattack = false;
float timer;
float delay = 0.1f;
public void Enter(Ogre enemy)
{
this.enemy = enemy;
enemy.armature.animation.timeScale = 1.6f;
}
public void Execute()
{
Attack();
if (enemy.Target == null && canExit)
{
enemy.ChangeState(new OgrePatrolState());
}
if (enemy.Target != null && !enemy.canAttack && canExit)
{
enemy.ChangeState(new OgreIdleState());
}
}
public void Exit()
{
enemy.walk = false;
enemy.isAttacking = false;
enemy.AttackCollider.enabled = false;
enemy.armature.animation.timeScale = 1f;
}
public void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.CompareTag("Edge"))
{
enemy.ChangeDirection();
}
}
private void Attack()
{
if (enemy.canAttack)
{
if (!preattack)
{
enemy.armature.animation.timeScale = 1.8f;
canExit = false;
enemy.isAttacking = true;
enemy.armature.animation.FadeIn("pre_atk", -1, 1);
preattack = true;
}
if (enemy.armature.animation.lastAnimationName == "pre_atk" && enemy.armature.animation.isCompleted)
{
enemy.armature.animation.FadeIn("atk", -1, 1);
SoundManager.PlaySound("ogre_hit_sound");
enemy.AttackCollider.enabled = true;
}
if (enemy.armature.animation.lastAnimationName == "atk" && enemy.armature.animation.isCompleted)
{
enemy.AttackCollider.enabled = false;
enemy.isAttacking = false;
enemy.canAttack = false;
enemy.isTimerTick = true;
preattack = false;
canExit = true;
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace PeefyLeetCode.GenerateParenthesis
{
public class Solution {
public IList<string> GenerateParenthesis(int n) {
List<string> res = new List<string>();
recursive(n, 0, 0, res, "");
return res;
}
void recursive(int n, int count1, int count2, List<string> res, string ans){
if (count1 > n || count2 > n)
return;
if (count1 == n && count2 == n)
res.Add(ans);
if (count1 >= count2){
string ans1 = ans;
recursive(n, count1+1, count2, res, ans+"(");
recursive(n, count1, count2+1, res, ans1+")");
}
}
}
} |
using UnityEngine;
using System.Collections.Generic;
public class CityGenerator : MonoBehaviour
{
// Use this for initialization
void Start()
{
//Random.InitState(123);
float[,] heightmap = new float[1024, 1024];
for (int x=0; x<1024; x++)
{
for (int y=0; y<1024; y++)
{
heightmap[x, y] = getHeight(x, y);
}
}
RoadNetworkGenerator rng = GetComponent<RoadNetworkGenerator>();
Graph<Vector2, Segment> roadGraph = rng.generateNetwork(heightmap);
roadGraph.addNode(new Vector2(511, 511));
Dictionary<Vector2, Vector3> pos = new Dictionary<Vector2, Vector3>();
foreach (Vector2 v in roadGraph.edges.Keys)
{
pos.Add(v, new Vector3(v.x, heightmap[(int)v.x+512,(int)v.y + 512], v.y));
}
transform.GetChild(0).GetComponent<RoadPGraph>().heightmap = heightmap;
transform.GetChild(0).GetComponent<RoadPGraph>().drawGraph(roadGraph, pos);
TestRenderer renderer = new TestRenderer(heightmap, 1024, 1024);
transform.GetChild(1).GetComponent<PhysicalMap>().init(1024, 1024);
transform.GetChild(1).GetComponent<PhysicalMap>().draw(renderer);
}
public float getHeight(int x, int y)
{
float scale = 0.002f;
float n = 0;
n += Mathf.PerlinNoise(x * scale, y * scale) * 4f;
n += Mathf.PerlinNoise(x * scale * 2, y * scale * 2)*2;
n += Mathf.PerlinNoise(x * scale * 4, y * scale * 4);
n /= 7f;
n = Mathf.Min(1, n);
n = Mathf.Max(0, n);
return n*100;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Mercury.Clients.Mvc.Views.Forms {
public class FormRenderEngine {
#region Private Properties
#endregion
#region Public Properties
#endregion
#region Constructors
#endregion
#region Support Methods
#endregion
#region Render - Basic HTML Elements
#endregion
#region Render - Form Controls
#endregion
}
public enum RenderEngineMode { Designer, Editor, Viewer }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace zertoBulkCreate.Models
{
public class ZvmConnection
{
public static string zvm;
public static string zvm_username;
public static string zvm_password;
}
}
|
/*
* Database message model.
*
* @author Michel Megens
* @email michel@michelmegens.net
*/
using System;
using System.ComponentModel.DataAnnotations;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver.GeoJsonObjectModel;
using Newtonsoft.Json;
using SensateIoT.Platform.Network.Data.Abstract;
using SensateIoT.Platform.Network.Data.Converters;
namespace SensateIoT.Platform.Network.Data.Models
{
public class Message
{
[BsonId, BsonRequired, JsonConverter(typeof(ObjectIdJsonConverter))]
public ObjectId InternalId { get; set; }
[BsonRequired]
public DateTime Timestamp { get; set; }
[BsonRequired]
public DateTime PlatformTimestamp { get; set; }
[BsonRequired, JsonConverter(typeof(ObjectIdJsonConverter))]
public ObjectId SensorId { get; set; }
[JsonConverter(typeof(GeoJsonPointJsonConverter))]
public GeoJsonPoint<GeoJson2DGeographicCoordinates> Location { get; set; }
[BsonRequired, StringLength(8192, MinimumLength = 1)]
public string Data { get; set; }
public MessageEncoding Encoding { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace JieDDDFramework.Core.EntitySpecifications
{
public interface ICreatedTimeState
{
DateTime CreatedTime { get; }
}
}
|
using System;
namespace funkyBot.Objects
{
[Serializable]
public class LuisResult
{
public string query { get; set; }
public Topscoringintent topScoringIntent { get; set; }
public Intent[] intents { get; set; }
public Entity[] entities { get; set; }
}
[Serializable]
public class Topscoringintent
{
public string intent { get; set; }
public float score { get; set; }
}
[Serializable]
public class Intent
{
public string intent { get; set; }
public float score { get; set; }
}
[Serializable]
public class Entity
{
public string entity { get; set; }
public string type { get; set; }
public int startIndex { get; set; }
public int endIndex { get; set; }
public float score { get; set; }
}
} |
namespace MovieLibrary.Models
{
/// <summary>
/// oqiasjf;ojas;odfh
/// </summary>
/// <remarks></remarks>
/// <example></example>
public class Director : IDirector
{
public string Name { get; set; }
public override string ToString()
{
return "<< " + Name + " >>";
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FireBreath : FireZone {
/// <summary>
/// Initial radius the breath will have
/// </summary>
public float initialRadius;
/// <summary>
/// Final radius the breath will have
/// </summary>
public float finalRadius;
/// <summary>
/// How far the breath reaches
/// </summary>
public float reach;
private void OnTriggerEnter2D(Collider2D other) {
Affectable a = other.GetComponent<Affectable>();
if (a) {
burningEffect.Apply(a);
}
}
public IEnumerator ExpandBreath() {
yield break;
}
}
|
//
// Gendarme.Rules.Design.UseFlagsAttributeRule
//
// Authors:
// Jesse Jones <jesjones@mindspring.com>
//
// Copyright (C) 2009 Jesse Jones
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Mono.Cecil;
using Gendarme.Framework;
using Gendarme.Framework.Helpers;
using Gendarme.Framework.Rocks;
namespace Gendarme.Rules.Design {
/// <summary>
/// This rule will fire if an enum's values look like they are intended to
/// be composed together with the bitwise OR operator and the enum is not
/// decorated with <c>System.FlagsAttribute</c>. Using <c>FlagsAttribute</c> will
/// allow <c>System.Enum.ToString()</c> to return a better string when
/// values are ORed together and helps indicate to readers of the code
/// the intended usage of the enum.
/// </summary>
/// <example>
/// Bad example:
/// <code>
/// [Serializable]
/// enum Options {
/// First = 1,
/// Second = 2,
/// Third = 4,
/// All = First | Second | Third,
/// }
/// </code>
/// </example>
/// <example>
/// Good example:
/// <code>
/// [Flags]
/// [Serializable]
/// enum Options {
/// First = 1,
/// Second = 2,
/// Third = 4,
/// All = First | Second | Third,
/// }
/// </code>
/// </example>
/// <remarks>This rule is available since Gendarme 2.6</remarks>
[Problem ("The enum seems to be composed of flag values, but is not decorated with [Flags].")]
[Solution ("Add [Flags] to the enum, change the values so that they are not powers of two, or ignore the defect.")]
[FxCopCompatibility ("Microsoft.Design", "CA1027:MarkEnumsWithFlags")]
public sealed class UseFlagsAttributeRule : Rule, ITypeRule {
private List<ulong> values = new List<ulong> ();
private void GetValues (TypeDefinition type)
{
values.Clear ();
foreach (FieldDefinition field in type.Fields) {
if (field.IsStatic) {
object o = field.Constant;
ulong value;
if (o is ulong) {
value = (ulong) o;
if (value != 0 && !values.Contains (value))
values.Add (value);
} else {
long v = Convert.ToInt64 (o, CultureInfo.InvariantCulture);
if (v > 0) {
value = (ulong) v;
if (!values.Contains (value))
values.Add (value);
} else if (v < 0) {
values.Clear ();
break;
}
}
}
}
}
static bool IsPowerOfTwo (ulong x)
{
Debug.Assert (x > 0, "x is not positive");
return (x & (x - 1)) == 0;
}
private bool IsBitmask (ulong x)
{
for (int i = 0; i < values.Count && x != 0; ++i) {
ulong bit = values [i];
if (IsPowerOfTwo (bit))
x &= ~bit;
}
return x == 0;
}
private int CountSequential ()
{
int count = 0;
int currentCount = 1;
for (int i = 1; i < values.Count; ++i) {
if (values [i] == values [i - 1] + 1) {
++currentCount;
} else {
count = Math.Max (currentCount, count);
currentCount = 0;
}
}
return Math.Max (currentCount, count);
}
public RuleResult CheckType (TypeDefinition type)
{
if (!type.IsEnum)
return RuleResult.DoesNotApply;
if (type.IsFlags ())
return RuleResult.DoesNotApply;
GetValues (type);
if (values.Count < 3)
return RuleResult.Success;
#if DEBUG
Log.WriteLine (this);
Log.WriteLine (this, "------------------------------------");
Log.WriteLine (this, type);
Log.WriteLine (this, "values: {0}", string.Join (" ", (from x in values select x.ToString ("X4")).ToArray ()));
#endif
int numFlags = 0;
int numMasks = 0;
foreach (ulong value in values) {
if (IsPowerOfTwo (value))
++numFlags;
else if (IsBitmask (value))
++numMasks;
}
Log.WriteLine (this, "numFlags: {0}", numFlags);
Log.WriteLine (this, "numMasks: {0}", numMasks);
// The enum is bad if all of the values are powers of two or composed
// of defined powers of two,
if (numFlags + numMasks == values.Count) {
values.Sort (); // sometimes enums are all sequential but not in order
int numSequential = CountSequential ();
Log.WriteLine (this, "numSequential: {0}", numSequential);
// and there are not too many sequential values (so we don't
// complain about stuff like 1, 2, 3, 4, 5, 6).
if (numSequential < 3) {
Confidence confidence = values.Count >= 4 && numMasks == 0 ? Confidence.High : Confidence.Normal;
Runner.Report (type, Severity.Medium, confidence);
}
}
return Runner.CurrentRuleResult;
}
}
}
|
using PulsarPluginLoader.Chat.Commands.CommandRouter;
namespace PulsarPluginLoader.Chat.Commands
{
class ClearCommand : ChatCommand
{
public override string[] CommandAliases()
{
return new string[] { "clear" };
}
public override string Description()
{
return "Clears the chat window.";
}
public override void Execute(string arguments)
{
PLNetworkManager.Instance.ConsoleText.Clear();
}
}
}
|
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Eciton
{
/// <summary>登録された処理を複文のスタイルで順に実行し、最後に実行した値を返却する関数を表します。</summary>
[DataContract]
public class EcitonSequence : EcitonObject
{
//TODO: ほんとはList相当な処理が欲しい?
[DataMember]
private readonly List<EcitonObject> _process = new List<EcitonObject>();
[IgnoreDataMember]
public int SequenceLength => _process.Count;
public void Add(EcitonObject statement) => _process.Add(statement);
public void Insert(int position, EcitonObject statement)
{
if (position >= SequenceLength)
{
Add(statement);
}
else
{
_process.Insert(position, statement);
}
}
//TODO: 途中でのreturnとかがうまく捌けてない点に留意せよ。
public override object Eval()
{
object result = EcitonEmpty.Empty;
foreach (var elem in _process)
{
result = elem.Eval();
}
return result;
}
}
}
|
using GoogleApi.Attributes;
using GoogleApi.Places.Search.Types;
using GoogleApi.Places.Types;
using GoogleApi.QueryBuilder;
namespace GoogleApi.Places.Search.ParameterBuilder.QueryBuilder
{
internal class SearchQueryBuilderBase : QueryBuilderBase
{
public SearchQueryBuilderBase(string baseUrl, string apiKey) :
base(baseUrl, apiKey)
{
}
public void SetQuery(string query)
{
AddParameter(ApiParameters.Query, query);
}
public void SetRadius(int radius)
{
AddParameter(ApiParameters.Radius, radius.ToString());
}
public void SetLocation(double latitude, double longitude)
{
AddParameter(ApiParameters.Location, $"{latitude},{longitude}");
}
public void SetRankingBy(RankBy rankBy)
{
AddParameter(ApiParameters.RankBy, rankBy.ToString().ToLowerInvariant());
}
public void SetKeyword(string keyword)
{
AddParameter(ApiParameters.Keyword, keyword);
}
public void SetLanguage(Languages language)
{
CodeAttribute codeAttribute = ArrtibutesHelper.GetEnumCodeAttribute(language);
AddParameter(ApiParameters.Language, codeAttribute?.Code);
}
public void SetPrice(int? minprice, int? maxprice)
{
if (minprice.HasValue)
AddParameter(ApiParameters.MinPrice, minprice.Value.ToString());
if (maxprice.HasValue)
AddParameter(ApiParameters.MaxnPrice, maxprice.Value.ToString());
}
public void SetNames(params string[] names)
{
AddParameter(ApiParameters.Name, string.Join("|", names));
}
public void SetPageToken(string pageToken)
{
AddParameter(ApiParameters.PageToken, pageToken);
}
public void SetType(SearchTypes type)
{
AddParameter(ApiParameters.Type, type.ToString().ToLowerInvariant());
}
}
} |
using EnvDTE;
namespace EnvDTE80
{
public delegate void _dispCodeModelEvents_ElementDeletedEventHandler(
object Parent,
CodeElement Element);
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace ADTeam5.Models
{
public partial class Department
{
public Department()
{
DisbursementList = new HashSet<DisbursementList>();
EmployeeRequestRecord = new HashSet<EmployeeRequestRecord>();
User = new HashSet<User>();
}
[StringLength(5)]
public string DepartmentCode { get; set; }
[StringLength(50)]
[Display(Name="Department Name")]
public string DepartmentName { get; set; }
public int CollectionPointId { get; set; }
[RegularExpression(@"^[0-9]*$", ErrorMessage = "Numbers only")]
public int HeadId { get; set; }
[RegularExpression(@"^[0-9]*$", ErrorMessage = "Numbers only")]
public int RepId { get; set; }
[RegularExpression(@"^[0-9]*$", ErrorMessage = "Numbers only")]
public int? CoveringHeadId { get; set; }
[StringLength(50)]
public string CollectionPassword { get; set; }
public virtual CollectionPoint CollectionPoint { get; set; }
public virtual User CoveringHead { get; set; }
public virtual User Head { get; set; }
public virtual User Rep { get; set; }
public virtual ICollection<DisbursementList> DisbursementList { get; set; }
public virtual ICollection<EmployeeRequestRecord> EmployeeRequestRecord { get; set; }
public virtual ICollection<User> User { get; set; }
}
}
|
@using ApiaryDiary.Controllers.Models.QueenBees
@model AddQueenBeePostModel
<div class="container-fluid">
<form asp-action="Create" method="post" class="form">
<div class="form-group">
<label asp-for="QueenType"></label>
<select asp-for="QueenType" class="form-control col-md-4"
asp-items="@Html.GetEnumSelectList<QueenBeeType>()"></select>
<span asp-validation-for="QueenType" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="MarkingColour"></label>
<input asp-for="MarkingColour" class="form-control col-md-4" />
<span asp-validation-for="MarkingColour" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Origin"></label>
<input asp-for="Origin" class="form-control col-md-4" />
<span asp-validation-for="Origin" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Temper"></label>
<input asp-for="Temper" class="form-control col-md-4" />
<span asp-validation-for="Temper" class="text-danger"></span>
</div>
<div class="form-group invisible">
<label asp-for="BeehiveId"></label>
<input asp-for="BeehiveId" value="@Model.BeehiveId" class="form-control col-md-4" />
<span asp-validation-for="BeehiveId" class="text-danger"></span>
</div>
<br />
<input asp-route-id="@Model.Id" type="submit" value="Create" class="btn btn-primary" />
</form>
</div>
|
using System;
using Xunit;
namespace AzureDevOps.WikiPDFExport.Test
{
public class PDFTests
{
[Fact]
public void FlatFileTest()
{
}
}
}
|
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Xunit;
using FluentAssertions;
namespace Microsoft.DotNet.Interactive.SqlServer.Tests
{
public class MsSqlServiceClientTests
{
[Theory]
[InlineData("\r\n")]
[InlineData("\n")]
public void Should_parse_doc_change_correctly_with_different_line_endings(string lineEnding)
{
string oldText = string.Join(lineEnding, "abc", "def", "", "abc", "abcdef");
int oldTextLineCount = 5;
int oldTextLastCharacterNum = 6;
string newText = string.Join(lineEnding, "abc", "def");
var testUri = new Uri("untitled://test");
var docChange = ToolsServiceClient.GetDocumentChangeForText(testUri, newText, oldText);
docChange.ContentChanges.Length
.Should()
.Be(1);
docChange.ContentChanges[0].Range.End.Line
.Should()
.Be(oldTextLineCount - 1);
docChange.ContentChanges[0].Range.End.Character
.Should()
.Be(oldTextLastCharacterNum);
docChange.ContentChanges[0].Range.Start.Line
.Should()
.Be(0);
docChange.ContentChanges[0].Range.Start.Character
.Should()
.Be(0);
docChange.ContentChanges[0].Text
.Should()
.Be(newText);
docChange.TextDocument.Uri
.Should()
.Be(testUri.AbsolutePath);
docChange.TextDocument.Version
.Should()
.Be(1);
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Cimbalino.Toolkit.Extensions;
using KursyWalut.Cache;
using KursyWalut.Extensions;
using KursyWalut.Model;
using KursyWalut.Progress;
using KursyWalut.Provider;
namespace KursyWalut.ProviderImpl
{
public class StandardErService : IErService, ICacheable
{
private readonly IErProvider _exchangeRatesProvider;
public StandardErService(IErProvider exchangeRatesProvider)
{
_exchangeRatesProvider = exchangeRatesProvider;
}
public async Task InitCache(IPProgress p)
{
var initCache = (_exchangeRatesProvider as ICacheable)?.InitCache(p);
if (initCache != null)
await initCache;
p.ReportProgress(1.00);
}
public async Task FlushCache(IPProgress p)
{
var flushCache = (_exchangeRatesProvider as ICacheable)?.FlushCache(p);
if (flushCache != null)
await flushCache;
p.ReportProgress(1.00);
}
public async Task<IList<int>> GetAvailableYears(IPProgress p)
{
return await _exchangeRatesProvider.GetAvailableYears(p);
}
public async Task<IList<DateTimeOffset>> GetAvailableDays(int year, IPProgress p)
{
return await _exchangeRatesProvider.GetAvailableDays(year, p);
}
public async Task<IList<ExchangeRate>> GetExchangeRates(DateTimeOffset day, IPProgress p)
{
return await _exchangeRatesProvider.GetExchangeRates(day, p);
}
public async Task<ExchangeRate> GetExchangeRate(Currency currency, DateTimeOffset day, IPProgress p)
{
var exchangeRates = await GetExchangeRates(day, p);
return exchangeRates.FirstOrDefault(e => e.Currency.Equals(currency));
}
public async Task<DateTimeOffset> GetFirstAvailableDay(IPProgress p)
{
var firstYear = (await GetAvailableYears(p.SubPercent(0.00, 0.40))).First();
var firstDate = (await GetAvailableDays(firstYear, p.SubPercent(0.40, 1.00))).First();
p.ReportProgress(1.00);
return firstDate;
}
public async Task<DateTimeOffset> GetLastAvailableDay(IPProgress p)
{
var lastYear = (await GetAvailableYears(p.SubPercent(0.00, 0.40))).Last();
var lastDate = (await GetAvailableDays(lastYear, p.SubPercent(0.40, 1.00))).Last();
p.ReportProgress(1.00);
return lastDate;
}
public async Task<IList<DateTimeOffset>> GetAllAvailablesDay(IPProgress p)
{
var firstYear = (await GetAvailableYears(p.SubPercent(0.00, 0.05))).First();
var lastYear = (await GetAvailableYears(p.SubPercent(0.05, 0.10))).Last();
var availableDays = await GetDaysBetweenYears(firstYear, lastYear, p.SubPercent(0.10, 1.00));
p.ReportProgress(1.00);
return availableDays;
}
public async Task GetExchangeRateAveragedHistory(
Currency currency, DateTimeOffset startDay, DateTimeOffset endDay,
ICollection<ExchangeRate> outErs, int expectedSize, IPProgress p)
{
if (startDay > endDay)
throw new ArgumentException("start.day > stop.day");
if (startDay < await GetFirstAvailableDay(p.SubPercent(0.00, 0.05)))
throw new ArgumentException("start.day < GetFirstAvailableDay()");
if (endDay > await GetLastAvailableDay(p.SubPercent(0.05, 0.10)))
throw new ArgumentException("end.day > GetLastvailableDay()");
var availableDays = await GetDaysBetweenYears(startDay.Year, endDay.Year, p.SubPercent(0.10, 0.20));
var properDays = availableDays
.Where(day => (day >= startDay) && (day <= endDay))
.Averaged(expectedSize)
.ToImmutableList();
await GetExchangeRatesInDays(properDays, currency, outErs, p.SubPercent(0.20, 1.00));
p.ReportProgress(1.00);
}
private async Task<IList<DateTimeOffset>> GetDaysBetweenYears(int startYear, int endYear, IPProgress p)
{
var years = Enumerable.Range(startYear, endYear - startYear + 1).ToImmutableList();
var work = new Task<IList<DateTimeOffset>>[years.Count];
for (var i = 0; i < years.Count; i++)
{
var t = years[i];
var progress = p.SubPart(i, years.Count);
work[i] = GetAvailableDays(t, progress);
}
var workDone = await Task.WhenAll(work);
p.ReportProgress(1.00);
return workDone.SelectMany(x => x).ToImmutableList();
}
private async Task GetExchangeRatesInDays(
IList<DateTimeOffset> days, Currency currency,
ICollection<ExchangeRate> ourErs, IPProgress p)
{
var work = new List<Task<ExchangeRate>>();
var waitFor = Environment.ProcessorCount*10;
for (var i = 0; i < days.Count; i++)
{
var day = days[i];
var progress = p.SubPart(i, days.Count);
var isCheckpoint = (i%waitFor == 0) || (i == days.Count - 1);
work.Add(GetExchangeRate(currency, day, progress));
if (isCheckpoint)
{
await AwaitDoneAndFill(work, ourErs);
work.Clear();
p.ReportProgress((i + 1.0)/days.Count);
}
if ((days.Count > 10) && (i%(days.Count/10) == 0))
Debug.WriteLine("DL-{0}-{1}", days.Count, i);
}
}
private static async Task AwaitDoneAndFill<T>(
IEnumerable<Task<T>> work,
ICollection<T> @out)
{
var workT = await Task.WhenAll(work);
var nonNullT = workT.Where(c => !ReferenceEquals(c, null));
@out.AddRange(nonNullT);
}
}
} |
using System.Reflection;
namespace CouchPotato.Odm {
/// <summary>
/// Contain information for loading related entities using view(s).
/// </summary>
internal class LoadRelatedWithViewInfo {
private readonly PropertyInfo propInfo;
private readonly string viewName;
public LoadRelatedWithViewInfo(PropertyInfo propInfo, string viewName) {
this.propInfo = propInfo;
this.viewName = viewName;
}
public PropertyInfo PropertyInfo {
get { return propInfo; }
}
public string ViewName {
get { return viewName; }
}
}
}
|
using PS.Patterns.Aware;
namespace PS.WPF.Controls.BusyContainer
{
public class BusyState : BaseNotifyPropertyChanged,
IMutableTitleAware,
IMutableDescriptionAware
{
private string _description;
private string _title;
#region Constructors
public BusyState()
{
}
public BusyState(string title, string description = null)
{
Title = title;
Description = description;
}
#endregion
#region IMutableDescriptionAware Members
public string Description
{
get { return _description; }
set { SetField(ref _description, value); }
}
#endregion
#region IMutableTitleAware Members
public string Title
{
get { return _title; }
set { SetField(ref _title, value); }
}
#endregion
#region Members
public void Dispose()
{
}
#endregion
}
} |
namespace SmartConnect.Web.ViewModels.Deals
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Common;
using Data.Models;
using Infrastructure.Mappings;
public class DealViewModel : BaseViewModel<Deal, int>, IMapFrom<Deal>
{
[Required]
[MaxLength(100)]
public string Name { get; set; }
[Required]
[Range(0.0, double.MaxValue)]
public decimal Value { get; set; }
public string ClientId { get; set; }
public IEnumerable<RequirementViewModel> Requirements { get; set; }
}
}
|
using BookFast.SeedWork;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Text;
using System.Threading.Tasks;
namespace BookFast.Api.Formatters
{
internal class BusinessExceptionOutputFormatter : TextOutputFormatter
{
public BusinessExceptionOutputFormatter()
{
SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
SupportedMediaTypes.Add("application/json");
}
protected override bool CanWriteType(Type type)
{
return typeof(BusinessException).IsAssignableFrom(type);
}
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
var options = context.HttpContext.RequestServices.GetService(typeof(IOptions<MvcJsonOptions>)) as IOptions<MvcJsonOptions>;
var exception = (BusinessException)context.Object;
var payload = JsonConvert.SerializeObject(new { error = exception.ErrorCode, error_description = exception.ErrorDescription }, options.Value.SerializerSettings);
return context.HttpContext.Response.WriteAsync(payload);
}
}
}
|
using System;
namespace StackCalculatorProgram
{
public class StackArray<T> : IStack<T>
{
private T[] arr;
private int size = 0;
private int capacity = 100;
public StackArray()
{
arr = new T[capacity];
}
private void SizeUp()
{
T[] newArr = new T[capacity * 2];
for (int i = 0; i < capacity; i++)
{
newArr[i] = arr[i];
}
capacity *= 2;
arr = newArr;
}
public void Push(T element)
{
if (size == capacity)
{
SizeUp();
}
arr[size] = element;
size++;
}
public T Pop()
{
if (IsEmpty())
{
throw new Exception("Error.Stack is empty!");
}
else
{
size--;
return arr[size];
}
}
public bool IsEmpty() => size == 0;
public int GetSize() => size;
}
}
|
using System.Drawing;
using System.Runtime.Versioning;
using System.Windows.Forms;
namespace MagicalNuts.UI.Base
{
/// <summary>
/// Controlの拡張を表します。
/// </summary>
[SupportedOSPlatform("windows")]
public static class ControlExtensions
{
/// <summary>
/// Controlを左寄せします。
/// </summary>
/// <param name="me">自Control</param>
/// <param name="baseCtrl">基準Control</param>
public static void AlignLeft(this Control me, Control baseCtrl)
{
me.Left = baseCtrl.Left + baseCtrl.Width + baseCtrl.Margin.Right + me.Margin.Left;
}
/// <summary>
/// Controlを上寄せします。
/// </summary>
/// <param name="me">自Control</param>
/// <param name="baseCtrl">基準Control</param>
public static void AlignTop(this Control me, Control baseCtrl)
{
me.Top = baseCtrl.Top + baseCtrl.Height + baseCtrl.Margin.Bottom + me.Margin.Top;
}
/// <summary>
/// クリップボードにキャプチャ画像をコピーします。
/// </summary>
/// <param name="me">自Control</param>
/// <param name="zoom">倍率</param>
public static void CopyToClipboard(this Control me, double zoom)
{
// キャプチャ
Bitmap bmp = new Bitmap(me.Width, me.Height);
me.DrawToBitmap(bmp, new Rectangle(0, 0, me.Width, me.Height));
// 拡縮
Bitmap canvas = new Bitmap((int)(me.Width * zoom), (int)(me.Height * zoom));
Graphics g = Graphics.FromImage(canvas);
g.DrawImage(bmp, 0, 0, (int)(bmp.Width * zoom), (int)(bmp.Height * zoom));
// クリップボードにコピー
Clipboard.SetImage(canvas);
// 終了
g.Dispose();
canvas.Dispose();
bmp.Dispose();
}
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Car.BLL.Services.Interfaces;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using File = Google.Apis.Drive.v3.Data.File;
namespace Car.BLL.Services.Implementation
{
public class GoogleDriveService : IDriveService<File>
{
private readonly ICompressor compressor;
private readonly IWebHostEnvironment webHostEnvironment;
private readonly IConfiguration configuration;
private DriveService service;
public GoogleDriveService(
IConfiguration configuration,
IWebHostEnvironment webHostEnvironment,
ICompressor compressor)
{
this.configuration = configuration;
this.webHostEnvironment = webHostEnvironment;
this.compressor = compressor;
}
/// <summary>
/// Deletes the file.
/// </summary>
/// <param name="fileId">The file identifier.</param>
/// <returns>Empty string if successful</returns>
public Task<string> DeleteFile(string fileId)
{
return service.Files.Delete(fileId).ExecuteAsync();
}
/// <summary>
/// Gets all files.
/// </summary>
/// <returns>All files</returns>
public async Task<IEnumerable<File>> GetAllFiles()
{
return (await service.Files.List().ExecuteAsync()).Files;
}
/// <summary>
/// Gets the file by identifier.
/// </summary>
/// <param name="fileId">The file identifier.</param>
/// <returns>The file instance</returns>
public Task<File> GetFileById(string fileId)
{
return service.Files.Get(fileId).ExecuteAsync();
}
/// <summary>
/// Gets the file bytes by identifier.
/// </summary>
/// <param name="fileId">The file identifier.</param>
/// <returns>base64 array of file</returns>
public async Task<byte[]> GetFileBytesById(string fileId)
{
using var stream = new MemoryStream();
await service.Files.Get(fileId).DownloadAsync(stream);
return stream.GetBuffer();
}
/// <summary>
/// Sets the credentials.
/// </summary>
/// <param name="credentialFilePath">The credential file path.</param>
public void SetCredentials(string credentialFilePath)
{
var keyFilePath = Path.Combine(
webHostEnvironment.WebRootPath,
"Credentials",
credentialFilePath);
var stream = new FileStream(keyFilePath, FileMode.Open, FileAccess.Read);
var credential = GoogleCredential.FromStream(stream);
credential = credential.CreateScoped(new string[] { DriveService.Scope.Drive });
service = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = configuration["GoogleApplicationName"],
});
}
/// <summary>
/// Uploads the file.
/// </summary>
/// <param name="fileStream">The file stream.</param>
/// <param name="folderId">The folder identifier.</param>
/// <param name="fileName">Name of the file.</param>
/// <param name="contentType">Type of the content.</param>
/// <returns>Uploaded file</returns>
public async Task<File> UploadFile(Stream fileStream, string folderId, string fileName, string contentType)
{
const int quality = 40;
var fileMetadata = new File();
fileMetadata.Name = fileName;
fileMetadata.Parents = new List<string> { folderId };
FilesResource.CreateMediaUpload request;
using (fileStream)
{
using var compresedFile = compressor.CompressFile(fileStream, quality);
request = service.Files.Create(fileMetadata, compresedFile, contentType);
request.Fields = "id, name, webViewLink, size";
await request.UploadAsync();
}
return request.ResponseBody;
}
}
}
|
using DesignPattern.Observer.Subject;
namespace DesignPattern.Observer.Observer
{
/// <summary>
/// 抽象观察类 - IObserver接口
/// </summary>
public interface IObserver
{
string Name { get; set; }
void Help(); // 声明支援盟友的方法
void BeAttacked(AllyControlCenter acc); // 声明遭受攻击的方法
}
}
|
namespace gs.FillTypes
{
public class BridgeFillType : BaseFillType
{
private readonly double bridgeSpeed;
public BridgeFillType(double volumeScale = 1, double speed = 1) : base(volumeScale)
{
bridgeSpeed = speed;
}
public static string Label => "bridge";
public override string GetLabel()
{
return Label;
}
public override double ModifySpeed(double speed, SpeedHint speedHint)
{
return bridgeSpeed;
}
}
} |
using HarmonyLib;
using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using Verse;
using static HarmonyLib.AccessTools;
namespace RimThreaded
{
class WorkGiver_DoBill_Transpile
{
internal static void RunNonDestructivePatches()
{
Type original = typeof(WorkGiver_DoBill);
Type patched = typeof(WorkGiver_DoBill_Transpile);
RimThreadedHarmony.Transpile(original, patched, "TryFindBestBillIngredients");
RimThreadedHarmony.Transpile(original, patched, "AddEveryMedicineToRelevantThings");
}
public static IEnumerable<CodeInstruction> TryFindBestBillIngredients(IEnumerable<CodeInstruction> instructions, ILGenerator iLGenerator)
{
int[] matchesFound = new int[8]; //EDIT
List<CodeInstruction> instructionsList = instructions.ToList();
LocalBuilder workGiver_DoBill_RegionProcessor = iLGenerator.DeclareLocal(typeof(WorkGiver_DoBill_RegionProcessor));
yield return new CodeInstruction(OpCodes.Newobj, typeof(WorkGiver_DoBill_RegionProcessor).GetConstructor(Type.EmptyTypes));
yield return new CodeInstruction(OpCodes.Stloc, workGiver_DoBill_RegionProcessor.LocalIndex);
int i = 0;
while (i < instructionsList.Count)
{
int matchIndex = 0;
if (
instructionsList[i].opcode == OpCodes.Ldsfld && //EDIT
(FieldInfo)instructionsList[i].operand == Field(typeof(WorkGiver_DoBill), "newRelevantThings") //EDIT
)
{
matchesFound[matchIndex]++;
instructionsList[i].opcode = OpCodes.Ldloc;
instructionsList[i].operand = workGiver_DoBill_RegionProcessor.LocalIndex;
yield return instructionsList[i++];
yield return new CodeInstruction(OpCodes.Ldfld, Field(typeof(WorkGiver_DoBill_RegionProcessor), "newRelevantThings"));
continue;
}
matchIndex++;
if (
instructionsList[i].opcode == OpCodes.Ldsfld && //EDIT
(FieldInfo)instructionsList[i].operand == Field(typeof(WorkGiver_DoBill), "relevantThings") //EDIT
)
{
matchesFound[matchIndex]++;
instructionsList[i].opcode = OpCodes.Ldloc;
instructionsList[i].operand = workGiver_DoBill_RegionProcessor.LocalIndex;
yield return instructionsList[i++];
yield return new CodeInstruction(OpCodes.Ldfld, Field(typeof(WorkGiver_DoBill_RegionProcessor), "relevantThings"));
continue;
}
matchIndex++;
if (
instructionsList[i].opcode == OpCodes.Ldsfld && //EDIT
(FieldInfo)instructionsList[i].operand == Field(typeof(WorkGiver_DoBill), "processedThings") //EDIT
)
{
matchesFound[matchIndex]++;
instructionsList[i].opcode = OpCodes.Ldloc;
instructionsList[i].operand = workGiver_DoBill_RegionProcessor.LocalIndex;
yield return instructionsList[i++];
yield return new CodeInstruction(OpCodes.Ldfld, Field(typeof(WorkGiver_DoBill_RegionProcessor), "processedThings"));
continue;
}
matchIndex++;
if (
instructionsList[i].opcode == OpCodes.Ldsfld && //EDIT
(FieldInfo)instructionsList[i].operand == Field(typeof(WorkGiver_DoBill), "ingredientsOrdered") //EDIT
)
{
matchesFound[matchIndex]++;
instructionsList[i].opcode = OpCodes.Ldloc;
instructionsList[i].operand = workGiver_DoBill_RegionProcessor.LocalIndex;
yield return instructionsList[i++];
yield return new CodeInstruction(OpCodes.Ldfld, Field(typeof(WorkGiver_DoBill_RegionProcessor), "ingredientsOrdered"));
continue;
}
matchIndex++;
if (
instructionsList[i].opcode == OpCodes.Call && //EDIT
(MethodInfo)instructionsList[i].operand == Method(typeof(WorkGiver_DoBill), "AddEveryMedicineToRelevantThings") //EDIT
)
{
matchesFound[matchIndex]++;
instructionsList[i].operand = Method(typeof(WorkGiver_DoBill_Patch), "AddEveryMedicineToRelevantThings2");
yield return instructionsList[i++];
continue;
}
matchIndex++;
if (
instructionsList[i].opcode == OpCodes.Call && //EDIT
(MethodInfo)instructionsList[i].operand == Method(typeof(WorkGiver_DoBill), "TryFindBestBillIngredientsInSet") //EDIT
)
{
matchesFound[matchIndex]++;
yield return new CodeInstruction(OpCodes.Ldloc, workGiver_DoBill_RegionProcessor.LocalIndex);
yield return new CodeInstruction(OpCodes.Ldfld, Field(typeof(WorkGiver_DoBill_RegionProcessor), "ingredientsOrdered"));
instructionsList[i].operand = Method(typeof(WorkGiver_DoBill_Patch), "TryFindBestBillIngredientsInSet2");
yield return instructionsList[i++];
continue;
}
matchIndex++;
if (
i + 1 < instructionsList.Count &&
instructionsList[i+1].opcode == OpCodes.Ldftn && //EDIT
(MethodInfo)instructionsList[i+1].operand == Method(TypeByName("RimWorld.WorkGiver_DoBill+<>c__DisplayClass20_0"), "<TryFindBestBillIngredients>b__3") //EDIT
)
{
matchesFound[matchIndex]++;
instructionsList[i].opcode = OpCodes.Ldloc;
instructionsList[i].operand = workGiver_DoBill_RegionProcessor.LocalIndex;
yield return instructionsList[i++];
yield return new CodeInstruction(OpCodes.Ldarg_0);
yield return new CodeInstruction(OpCodes.Stfld, Field(typeof(WorkGiver_DoBill_RegionProcessor), "bill"));
yield return new CodeInstruction(OpCodes.Ldloc, workGiver_DoBill_RegionProcessor.LocalIndex);
yield return new CodeInstruction(OpCodes.Ldarg_1);
yield return new CodeInstruction(OpCodes.Stfld, Field(typeof(WorkGiver_DoBill_RegionProcessor), "pawn"));
yield return new CodeInstruction(OpCodes.Ldloc, workGiver_DoBill_RegionProcessor.LocalIndex);
yield return new CodeInstruction(OpCodes.Ldloc_0);
yield return new CodeInstruction(OpCodes.Ldfld, Field(TypeByName("RimWorld.WorkGiver_DoBill+<>c__DisplayClass20_0"), "baseValidator"));
yield return new CodeInstruction(OpCodes.Stfld, Field(typeof(WorkGiver_DoBill_RegionProcessor), "baseValidator"));
yield return new CodeInstruction(OpCodes.Ldloc, workGiver_DoBill_RegionProcessor.LocalIndex);
yield return new CodeInstruction(OpCodes.Ldloc_0);
yield return new CodeInstruction(OpCodes.Ldfld, Field(TypeByName("RimWorld.WorkGiver_DoBill+<>c__DisplayClass20_0"), "billGiverIsPawn"));
yield return new CodeInstruction(OpCodes.Stfld, Field(typeof(WorkGiver_DoBill_RegionProcessor), "billGiverIsPawn"));
yield return new CodeInstruction(OpCodes.Ldloc, workGiver_DoBill_RegionProcessor.LocalIndex);
yield return new CodeInstruction(OpCodes.Ldloc_0);
yield return new CodeInstruction(OpCodes.Ldfld, Field(TypeByName("RimWorld.WorkGiver_DoBill+<>c__DisplayClass20_0"), "adjacentRegionsAvailable"));
yield return new CodeInstruction(OpCodes.Stfld, Field(typeof(WorkGiver_DoBill_RegionProcessor), "adjacentRegionsAvailable"));
yield return new CodeInstruction(OpCodes.Ldloc, workGiver_DoBill_RegionProcessor.LocalIndex);
yield return new CodeInstruction(OpCodes.Ldloc_0);
yield return new CodeInstruction(OpCodes.Ldfld, Field(TypeByName("RimWorld.WorkGiver_DoBill+<>c__DisplayClass20_0"), "rootCell"));
yield return new CodeInstruction(OpCodes.Stfld, Field(typeof(WorkGiver_DoBill_RegionProcessor), "rootCell"));
yield return new CodeInstruction(OpCodes.Ldloc, workGiver_DoBill_RegionProcessor.LocalIndex);
yield return new CodeInstruction(OpCodes.Ldloc_0);
yield return new CodeInstruction(OpCodes.Ldfld, Field(TypeByName("RimWorld.WorkGiver_DoBill+<>c__DisplayClass20_0"), "chosen"));
yield return new CodeInstruction(OpCodes.Stfld, Field(typeof(WorkGiver_DoBill_RegionProcessor), "chosen"));
yield return new CodeInstruction(OpCodes.Ldloc, workGiver_DoBill_RegionProcessor.LocalIndex);
instructionsList[i].operand = Method(typeof(WorkGiver_DoBill_RegionProcessor), "Get_RegionProcessor");
yield return instructionsList[i++];
yield return instructionsList[i++];
yield return instructionsList[i++];
continue;
}
matchIndex++;
if (i + 1 < instructionsList.Count &&
instructionsList[i+1].opcode == OpCodes.Ldfld && //EDIT
(FieldInfo)instructionsList[i+1].operand == Field(TypeByName("RimWorld.WorkGiver_DoBill+<>c__DisplayClass20_0"), "foundAll") //EDIT
)
{
matchesFound[matchIndex]++;
instructionsList[i].opcode = OpCodes.Ldloc;
instructionsList[i].operand = workGiver_DoBill_RegionProcessor.LocalIndex;
yield return instructionsList[i++];
instructionsList[i].operand = Field(typeof(WorkGiver_DoBill_RegionProcessor), "foundAll");
yield return instructionsList[i++];
continue;
}
yield return instructionsList[i++];
}
for (int mIndex = 0; mIndex < matchesFound.Length; mIndex++)
{
if (matchesFound[mIndex] < 1)
Log.Error("IL code instruction set " + mIndex + " not found");
}
}
public static IEnumerable<CodeInstruction> AddEveryMedicineToRelevantThings(IEnumerable<CodeInstruction> instructions, ILGenerator iLGenerator)
{
int[] matchesFound = new int[1]; //EDIT
List<CodeInstruction> instructionsList = instructions.ToList();
LocalBuilder tmpMedicine = iLGenerator.DeclareLocal(typeof(List<Thing>));
yield return new CodeInstruction(OpCodes.Newobj, typeof(List<Thing>).GetConstructor(Type.EmptyTypes));
yield return new CodeInstruction(OpCodes.Stloc, tmpMedicine.LocalIndex);
int i = 0;
while (i < instructionsList.Count)
{
int matchIndex = 0;
if (
instructionsList[i].opcode == OpCodes.Ldsfld && //EDIT
(FieldInfo)instructionsList[i].operand == Field(typeof(WorkGiver_DoBill), "tmpMedicine") //EDIT
)
{
matchesFound[matchIndex]++;
instructionsList[i].opcode = OpCodes.Ldloc;
instructionsList[i].operand = tmpMedicine.LocalIndex;
yield return instructionsList[i++];
continue;
}
yield return instructionsList[i++];
}
for (int mIndex = 0; mIndex < matchesFound.Length; mIndex++)
{
if (matchesFound[mIndex] < 1)
Log.Error("IL code instruction set " + mIndex + " not found");
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class MainCol : MonoBehaviour {
GameObject Player1Obj;
GameObject Player2Obj;
GameObject CameraObj;
GameObject FadeObj;
GameObject BgmObj;
GameObject WinObj;
GameObject StageObj;
[SerializeField]
private Text _textCountdown;
public int Stock_Player1; //プレーヤ1のストック
public int Stock_Player2; //プレーヤ2のストック
public bool GameEndFlag; //ゲームが終了したかどうか
public bool mainCame_Flag;
public bool P1Came_Flag;
public bool P2Came_Flag;
public bool GameStartFlag;
public bool BGMFlag;
public bool WinFlag;
public AudioClip CountSound;//カウントダウン音
public AudioClip GameStartSound;//ゲーム開始音
BGMScript BgmScript;
BGMScript WinBGMScript;
AudioSource audioSource;
bool CountStartFlag;
// Use this for initialization
void Start () {
Player1Obj = GameObject.Find("Player1");
Player2Obj = GameObject.Find("Player2");
CameraObj = GameObject.Find("camera");
FadeObj = GameObject.Find("fadePanel");
BgmObj = GameObject.Find("BGM");
StageObj = GameObject.Find("StageControl");
WinObj = GameObject.Find("WinBGM");
BgmScript = BgmObj.GetComponent<BGMScript>();
WinBGMScript = WinObj.GetComponent<BGMScript>();
Stock_Player1 = Player1Obj.GetComponent<PrefabGeneration>().Stock;
Stock_Player2 = Player2Obj.GetComponent<PrefabGeneration>().Stock;
audioSource = GetComponent<AudioSource>();
mainCame_Flag = true;
P1Came_Flag = false;
P2Came_Flag = false;
GameEndFlag = false;
_textCountdown.text = "";
CountStartFlag = false;
GameStartFlag = false;
BGMFlag = false;
WinFlag = false;
}
// Update is called once per frame
void Update () {
Stock_Player1 = Player1Obj.GetComponent<PrefabGeneration>().Stock;
Stock_Player2 = Player2Obj.GetComponent<PrefabGeneration>().Stock;
if (!CountStartFlag)
{
CountStartFlag = true;
StartCoroutine(CountdownCoroutine());
}
GameStart();
}
void GameStart()
{
if (!BGMFlag)
{
BGMFlag = true;
BgmScript.BGM_ON_Stage(StageObj.GetComponent<Prefab_Stage>().StageID);
}
//どちらかのストックが0になったら終了
if (Stock_Player1 <= 0 || Stock_Player2 <= 0)
{
BgmScript.BGM_Stop();
if (FadeObj.GetComponent<FadeScript>().CameraChange == false)
{
FadeObj.GetComponent<FadeScript>().FadeFlag = true;
}
else
{
if (Stock_Player1 <= 0)
{
mainCame_Flag = false;
P2Came_Flag = true;
GameEndFlag = true;
if (!WinFlag)
{
WinFlag = true;
WinBGMScript.BGM_ON_Chara(Player2Obj.GetComponent<PrefabGeneration>().CharaID);
}
}
if (Stock_Player2 <= 0)
{
mainCame_Flag = false;
P1Came_Flag = true;
GameEndFlag = true;
if (!WinFlag)
{
WinFlag = true;
WinBGMScript.BGM_ON_Chara(Player1Obj.GetComponent<PrefabGeneration>().CharaID);
}
}
}
}
}
IEnumerator CountdownCoroutine()
{
_textCountdown.gameObject.SetActive(true);
yield return new WaitForSeconds(2.0f);
_textCountdown.text = "3";
audioSource.PlayOneShot(CountSound);
yield return new WaitForSeconds(1.0f);
_textCountdown.text = "2";
audioSource.PlayOneShot(CountSound);
yield return new WaitForSeconds(1.0f);
_textCountdown.text = "1";
audioSource.PlayOneShot(CountSound);
yield return new WaitForSeconds(1.0f);
_textCountdown.text = "GO!";
audioSource.PlayOneShot(GameStartSound);
GameStartFlag = true;
yield return new WaitForSeconds(1.0f);
_textCountdown.text = "";
_textCountdown.gameObject.SetActive(false);
}
}
|
@{
ViewData["Title"] = "Configuration Data refreshed from Config Server";
}
<h2>Configuration refresh complete!</h2>
|
//=============================================================================
// System : ASP.NET Web Control Library
// File : NumericTextBox.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : Fri 02/20/04
// Note : Copyright 2002-2004, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a derived CompareTextBox class that can automatically
// generate a range validator for itself that checks to see if the data
// entered is a numeric value (currency, integer, or double) and, optionally,
// if it is above, below, or between minimum and maximum values. A regular
// expression validator can also be emitted to limit the number of decimal
// places in double and decimal type numbers.
//
// Version Date Who Comments
// ============================================================================
// 1.0.0 09/04/2002 EFW Created the code
//=============================================================================
using System;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace EWSoftware.Web.Controls
{
/// <summary>
/// This enumerated type is a subset of
/// <see cref="System.Web.UI.WebControls.ValidationDataType"/>
/// (numeric only) and is used by the <see cref="NumericTextBox"/> control.
/// </summary>
[Serializable]
public enum NumericType
{
/// <summary>A 32-bit signed integer value</summary>
Integer = ValidationDataType.Integer,
/// <summary>A double precision floating point value</summary>
Double = ValidationDataType.Double,
/// <summary>A monetary data type treated like a <b>System.Decimal</b>
/// value</summary>
Currency = ValidationDataType.Currency
}
/// <summary>
/// This derived CompareTextBox class can generate a RangeValidator
/// for itself to insure a date value is entered and is optionally
/// within a specified range. It also has special formatting abilities
/// when rendered in Internet Explorer.
/// </summary>
/// <include file='Doc/Controls.xml'
/// path='Controls/NumericTextBox/Member[@name="Class"]/*' />
[DefaultProperty("NumberErrorMessage"),
ToolboxData("<{0}:NumericTextBox runat=\"server\" " +
"Type=\"Integer\" MinimumValue=\"0\" MaximumValue=\"999\" " +
"NumberErrorMessage=\"Not a valid numeric value\" />"),
AspNetHostingPermission(SecurityAction.LinkDemand,
Level=AspNetHostingPermissionLevel.Minimal),
AspNetHostingPermission(SecurityAction.InheritanceDemand,
Level=AspNetHostingPermissionLevel.Minimal)]
public class NumericTextBox : EWSoftware.Web.Controls.CompareTextBox
{
//=====================================================================
// Private class members
private RangeValidator rvRange; // The validators
private RegularExpressionValidator reDecimals;
//=====================================================================
// Properties
/// <summary>
/// This is the error message to display if the number is not valid or
/// it is not in the expected range. The string can contain the place
/// holders {MinVal} and {MaxVal} so that the current minimum and
/// maximum values are displayed.
/// </summary>
[Category("Appearance"), Bindable(true),
DefaultValue("Not a valid numeric value"),
Description("The error message to display for invalid numbers")]
public string NumberErrorMessage
{
get
{
Object oMsg = ViewState["NumErrMsg"];
return (oMsg == null) ? "Not a valid numeric value" :
(string)oMsg;
}
set
{
EnsureChildControls();
ViewState["NumErrMsg"] = value;
// Clear the message in the validator. It'll get formatted
// when rendering the control.
rvRange.ErrorMessage = String.Empty;
}
}
/// <summary>
/// The numeric type. Note that use of any of the Min/Max
/// properties will automatically set the appropriate data type.
/// </summary>
[Category("Behavior"), DefaultValue(NumericType.Integer), Bindable(true),
Description("The numeric type")]
public NumericType Type
{
get
{
EnsureChildControls();
return (NumericType)rvRange.Type;
}
set
{
EnsureChildControls();
rvRange.Type = (ValidationDataType)value;
// Set the data type on the base class's compare
// validator too.
CompareType = (ValidationDataType)value;
}
}
/// <summary>
/// This allows the specification of a minimum value. The Type
/// property must be set accordingly or the range validator type
/// will default to integer.
/// </summary>
[Category("Behavior"), DefaultValue("-2147483648"), Bindable(true),
Description("The minimum value")]
public string MinimumValue
{
get { return rvRange.MinimumValue; }
set
{
EnsureChildControls();
// Parse it as a decimal to ensure that it is at least
// a number. It'll throw an exception if it isn't.
decimal dTemp = Decimal.Parse(value);
rvRange.MinimumValue = value;
// The error message is cleared to force reformatting when
// rendered.
rvRange.ErrorMessage = String.Empty;
}
}
/// <summary>
/// This allows the specification of a maximum value. The Type
/// property must be set accordingly or the range validator type
/// will default to integer.
/// </summary>
[Category("Behavior"), DefaultValue("2147483647"), Bindable(true),
Description("The maximum value")]
public string MaximumValue
{
get { return rvRange.MaximumValue; }
set
{
EnsureChildControls();
// Parse it as a decimal to ensure that it is at least
// a number. It'll throw an exception if it isn't.
decimal dTemp = Decimal.Parse(value);
rvRange.MaximumValue = value;
// The error message is cleared to force reformatting when
// rendered.
rvRange.ErrorMessage = String.Empty;
}
}
/// <summary>
/// This sets the maximum number of decimal places allowed on the
/// number. Set it to -1 to allow any number of decimal places.
/// </summary>
[Category("Behavior"), DefaultValue(-1), Bindable(true),
Description("The number of decimal places")]
public int DecimalPlaces
{
get
{
Object oNumDecs = ViewState["DecimalPlaces"];
return (oNumDecs == null) ? -1 : (int)oNumDecs;
}
set
{
EnsureChildControls();
ViewState["DecimalPlaces"] = value;
if(value > -1)
{
// Set the validation expression with the right number of
// decimal places. There can be a leading + or -.
reDecimals.ValidationExpression = String.Format(
@"^\s*([\+-])?(\d+)?(\.(\d{{0,{0}}}))?\s*$", value);
// The error message is cleared to force reformatting when
// rendered.
reDecimals.ErrorMessage = String.Empty;
}
}
}
/// <summary>
/// This is the error message to display if the number of decimal
/// places is not valid. The message can contain the place holder
/// {Decimals} to display the current maximum decimal places value.
/// </summary>
[Category("Appearance"), Bindable(true),
DefaultValue("There can be a maximum of {Decimals} decimal place(s)"),
Description("The error to display if an invalid number of decimal places is entered")]
public string DecimalErrorMessage
{
get
{
Object oMsg = ViewState["DecErrMsg"];
return (oMsg == null) ?
"There can be a maximum of {Decimals} decimal place(s)" :
(string)oMsg;
}
set
{
EnsureChildControls();
ViewState["DecErrMsg"] = value;
// Clear the message in the validator. It'll get formatted
// when rendering the control.
reDecimals.ErrorMessage = String.Empty;
}
}
/// <summary>
/// This sets the client-side formatting behaviour for numbers with
/// decimal places. If set to true, the decimal point is inserted
/// into the number. If false, decimal places are appended to the
/// number.
/// </summary>
[Category("Behavior"), DefaultValue(false), Bindable(true),
Description("Insert or append decimal point for client-side formatting")]
public bool InsertDecimal
{
get
{
Object oInsDec = ViewState["InsertDecimal"];
return (oInsDec == null) ? false : (bool)oInsDec;
}
set { ViewState["InsertDecimal"] = value; }
}
//=====================================================================
// Methods, etc
/// <summary>
/// Constructor. Default state: Any number of decimals allowed and,
/// unless overridden, the field will be right-aligned.
/// </summary>
public NumericTextBox()
{
this.Style["text-align"] = "right";
}
/// <summary>
/// CreateChildControls() is overridden to create the validator
/// </summary>
protected override void CreateChildControls()
{
base.CreateChildControls();
rvRange = new RangeValidator();
reDecimals = new RegularExpressionValidator();
// Assume an integer type by default
MinimumValue = Int32.MinValue.ToString();
MaximumValue = Int32.MaxValue.ToString();
rvRange.Type = CompareType = ValidationDataType.Integer;
rvRange.Enabled = reDecimals.Enabled = this.Enabled;
// Use validation summary by default
rvRange.Display = reDecimals.Display = ValidatorDisplay.None;
this.Controls.Add(rvRange);
this.Controls.Add(reDecimals);
}
/// <summary>
/// OnPreRender is overridden to set the control to validate and the
/// validation control IDs. These can't be set earlier as we can't
/// guarantee the order in which the properties are set. The names of
/// the validator controls are based on the control to validate.
/// It also sets the decimal places validator to invisible if it isn't
/// being used.
/// </summary>
/// <param name="e">The event arguments</param>
protected override void OnPreRender(System.EventArgs e)
{
if(Visible)
{
if(DecimalPlaces > -1 && Type != NumericType.Integer)
{
reDecimals.Visible = true;
reDecimals.ControlToValidate = this.ID;
reDecimals.ID = this.ID + "_NMREV";
reDecimals.Attributes["insdec"] = InsertDecimal.ToString();
reDecimals.Attributes["decplaces"] = DecimalPlaces.ToString();
// Format the error message if necessary
if(reDecimals.ErrorMessage.Length == 0)
reDecimals.ErrorMessage = CtrlUtils.ReplaceParameters(
DecimalErrorMessage, "{Decimals}",
DecimalPlaces.ToString());
}
else
reDecimals.Visible = false;
// Register formatting script if needed
if(!this.AutoPostBack && this.EnableClientScript &&
this.CanRenderUpLevel)
{
this.Attributes["onblur"] = "javascript:NTB_FormatNumeric(this);";
if(!Page.ClientScript.IsClientScriptBlockRegistered("EWS_NTBFormat"))
this.Page.ClientScript.RegisterClientScriptInclude(
typeof(NumericTextBox), "EWS_NTBFormat",
this.Page.ClientScript.GetWebResourceUrl(
typeof(NumericTextBox),
CtrlUtils.ScriptsPath + "NumericTextBox.js"));
}
}
base.OnPreRender(e);
rvRange.ControlToValidate = this.ID;
rvRange.ID = this.ID + "_NMRV";
// Format the error message if necessary
if(rvRange.ErrorMessage.Length == 0)
rvRange.ErrorMessage = CtrlUtils.ReplaceParameters(
NumberErrorMessage, "{MinVal}", rvRange.MinimumValue,
"{MaxVal}", rvRange.MaximumValue, "{Decimals}",
DecimalPlaces.ToString());
}
/// <summary>
/// Render this control to the output parameter specified.
/// </summary>
/// <param name="writer">The HTML writer to which the output is written</param>
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
if(rvRange != null)
{
rvRange.RenderControl(writer);
if(reDecimals.Visible == true)
reDecimals.RenderControl(writer);
}
}
/// <summary>
/// This returns the current value of the textbox as an integer.
/// </summary>
/// <returns>If empty, it returns 0.</returns>
public int ToInteger()
{
if(this.Text.Length == 0)
return 0;
return Int32.Parse(this.Text);
}
/// <summary>
/// This returns the current value of the textbox as a double.
/// </summary>
/// <returns>If empty, it returns 0.0.</returns>
public double ToDouble()
{
if(this.Text.Length == 0)
return 0.0;
return Double.Parse(this.Text);
}
/// <summary>
/// This returns the current value of the textbox as a
/// <see cref="System.Decimal"/>.
/// </summary>
/// <returns>If empty, it returns 0.0.</returns>
public Decimal ToDecimal()
{
if(this.Text.Length == 0)
return 0.0M;
return Decimal.Parse(this.Text);
}
}
}
|
// 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.Windows;
using System.Windows.Markup;
using System.Windows.Media;
namespace ModernWpf.Toolkit.UI.Extensions
{
/// <summary>
/// An abstract <see cref="MarkupExtension"/> which to produce text-based icons.
/// </summary>
public abstract class TextIconExtension : MarkupExtension
{
/// <summary>
/// Gets or sets the size of the icon to display.
/// </summary>
public double FontSize { get; set; }
[ThreadStatic]
private static FontFamily segoeMDL2AssetsFontFamily;
/// <summary>
/// Gets the reusable "Segoe MDL2 Assets" <see cref="FontFamily"/> instance.
/// </summary>
protected static FontFamily SegoeMDL2AssetsFontFamily
{
get => segoeMDL2AssetsFontFamily ??= new FontFamily("Segoe MDL2 Assets");
}
/// <summary>
/// Gets or sets the thickness of the icon glyph.
/// </summary>
public FontWeight FontWeight { get; set; } = FontWeights.Normal;
/// <summary>
/// Gets or sets the font style for the icon glyph.
/// </summary>
public FontStyle FontStyle { get; set; } = FontStyles.Normal;
/// <summary>
/// Gets or sets the foreground <see cref="Brush"/> for the icon.
/// </summary>
public Brush Foreground { get; set; }
}
}
|
using UnityEngine;
public abstract class EnemyBase : MonoBehaviour, IShootable {
public enum EnemyTypes
{
Undefined, Ground, Air
}
public EnemyTypes Type;
public event System.Action<EnemyBase> OnDeath = delegate { };
/// <summary>
/// Animations and additional effects to go here
/// </summary>
protected abstract void OnHit(Bullet bullet);
protected abstract void OnSpawn();
protected Animator anim;
protected Rigidbody2D body;
public void Spawn(Vector2 location)
{
OnSpawn();
transform.position = location;
}
// For IShootable
public void HandleShot(Bullet bullet)
{
OnHit(bullet);
}
protected void DeathAnimationComplete()
{
OnDeath?.Invoke(this);
}
private void Awake()
{
anim = GetComponent<Animator>();
body = GetComponent<Rigidbody2D>();
Spawn(transform.position);
}
}
|
namespace WinTerMul
{
internal interface ITerminalFactory
{
ITerminal CreateTerminal();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#pragma warning disable 1591
namespace CoreAngular.Model
{
public class ProductViewModel
{
public long ProductId { get; set; }
public string Name { get; set; }
public string ProductNumber { get; set; }
public string StandardCost { get; set; }
public string ListPrice { get; set; }
public string SubCategoryName { get; set; }
public string ThumbnailPhotoFileName { get; set; }
public string LargePhotoFileName { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GuruDataModel;
using GuruBO;
namespace Admin.Areas.Administrador.Controllers
{
public class CategoriaController : Controller
{
CategoriaBO bo = new CategoriaBO();
//
// GET: /Administrador/Categoria/
public ActionResult Index()
{
return View();
}
}
}
|
namespace fmdev.ArgsParser
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class CommandArgAttribute : Attribute
{
public CommandArgAttribute()
{
IsRequired = false;
}
public string HelpText { get; set; }
public bool IsRequired { get; set; }
}
} |
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public class DatabaseModel: Observable
{
public SqlConnection ModelConnection { get; }
public SqlDataAdapter ModelDataAdaptor { get; }
public DataSet ModelDataSet { get; }
public BindingSource ModelBindingSource { get; }
private static readonly string ServerName =
ConfigurationManager.ConnectionStrings["serverName"].ConnectionString;
private static readonly string DatabaseName =
ConfigurationManager.ConnectionStrings["databaseName"].ConnectionString;
public DatabaseModel() : this(ServerName, DatabaseName) { }
public DatabaseModel(string dataSource, string databaseName)
{
ModelConnection = new SqlConnection(
"Data Source =" + dataSource + "; " +
"Initial Catalog =" + databaseName + "; " +
"Integrated Security = True"
);
ModelDataAdaptor = new SqlDataAdapter();
ModelDataSet = new DataSet();
ModelBindingSource = new BindingSource();
}
public DataTable GetTable(DatabaseTable table)
{
ModelDataAdaptor.SelectCommand = new SqlCommand(ConfigurationManager
.AppSettings["SelectQuery"] + table.Name, ModelConnection);
ModelDataSet.Clear();
ModelDataAdaptor.Fill(ModelDataSet);
ModelBindingSource.DataSource = ModelDataSet.Tables[0];
return ModelDataSet.Tables[0];
}
public DataTable GetTableFromForeignKey(DatabaseTable table, int foreignKey)
{
ModelDataAdaptor.SelectCommand = new SqlCommand(ConfigurationManager
.AppSettings["SelectQuery"] + table.Name + " where "
+ table.ForeignKey + " = " + foreignKey, ModelConnection);
ModelDataSet.Clear();
ModelDataAdaptor.Fill(ModelDataSet);
ModelBindingSource.DataSource = ModelDataSet.Tables[0];
return ModelDataSet.Tables[0];
}
private bool IsNumber(string data)
{
return new Regex(@"^\d$").IsMatch(data);
}
private string GetValue(string data)
{
return IsNumber(data) ? data : "'" + data + "'";
; }
public void InsertTable(DatabaseTable table, List<string> values)
{
ModelDataAdaptor.InsertCommand = new SqlCommand(ConfigurationManager
.AppSettings["InsertQuery"], ModelConnection);
var added = table.Parameters.Aggregate(" (", (accumulator, element) =>
accumulator + GetValue(values[table.Parameters.IndexOf(element)]) + ",");
added = added.Remove(added.Length - 1) + ")";
ModelDataAdaptor.InsertCommand = new SqlCommand(ConfigurationManager
.AppSettings["InsertQuery"].Replace("@TableName", table.Name) + added, ModelConnection);
ModelConnection.Open();
ModelDataAdaptor.InsertCommand.ExecuteNonQuery();
ModelDataSet.Clear();
ModelDataAdaptor.Fill(ModelDataSet, table.Name);
ModelConnection.Close();
NotifyObservers(NotificationType.NotificationAdd);
}
public void UpdateTable(DatabaseTable table, List<string> values, int primaryKey)
{
var rest = table.Columns.Aggregate(" ", (accumulator, element) =>
accumulator + (element + " = " + GetValue(values[table.Columns.IndexOf(element)]) + ","));
rest = rest.Remove(rest.Length - 1) + " where " + table.PrimaryKey + " = " + primaryKey;
ModelDataAdaptor.UpdateCommand =
new SqlCommand(ConfigurationManager
.AppSettings["UpdateQuery"].Replace("@TableName", table.Name) + rest, ModelConnection);
ModelConnection.Open();
ModelDataAdaptor.UpdateCommand.ExecuteNonQuery();
ModelDataSet.Clear();
ModelDataAdaptor.Fill(ModelDataSet, table.Name);
ModelConnection.Close();
NotifyObservers(NotificationType.NotificationUpdate);
}
public void DeleteTable(DatabaseTable table, int primaryKey)
{
ModelDataAdaptor.DeleteCommand = new SqlCommand(ConfigurationManager
.AppSettings["DeleteQuery"]
.Replace("@TableName", table.Name)
.Replace("@PK", table.PrimaryKey)
.Replace("@Value", primaryKey.ToString()), ModelConnection);
ModelConnection.Open();
ModelDataAdaptor.DeleteCommand.ExecuteNonQuery();
ModelDataSet.Clear();
ModelDataAdaptor.Fill(ModelDataSet, table.Name);
ModelConnection.Close();
NotifyObservers(NotificationType.NotificationDelete);
}
}
} |
using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinSync.Controls
{
public class AnimatedProgressBar : ProgressBar
{
const int frameRate = 200; //in frames per second
const float animationStep = 1; //in percent
float _value = 0;
float _displayValue = 0;
int _lastProgressBarPaintWidth = 0;
bool _animationRunning;
public AnimatedProgressBar()
{
Margin = new Padding(5, 5, 5, 5);
BackColor = Color.White;
ForeColor = Color.FromArgb(0,100,100);
SetStyle(ControlStyles.UserPaint, true);
}
protected override void OnPaint(PaintEventArgs e)
{
int height = e.ClipRectangle.Height;
int width = (int)(e.ClipRectangle.Width * DisplayValue / 100);
if(_lastProgressBarPaintWidth < width)
e.Graphics.FillRectangle(new SolidBrush(ForeColor), _lastProgressBarPaintWidth, 0, width, height);
else if (_lastProgressBarPaintWidth > width)
e.Graphics.FillRectangle(new SolidBrush(BackColor), width, 0, _lastProgressBarPaintWidth, height);
_lastProgressBarPaintWidth = width;
}
/// <summary>
/// paint background only on initialisation
/// </summary>
/// <param name="pevent"></param>
protected override void OnPaintBackground(PaintEventArgs pevent)
{
if(Value == 0 && !_animationRunning)
base.OnPaintBackground(pevent);
}
/// <summary>
/// progress value in percent
/// </summary>
public new float Value
{
get { return _value; }
set
{
_value = value;
Animate();
}
}
/// <summary>
/// displayed progress value in percent
/// </summary>
public float DisplayValue
{
get { return _displayValue; }
protected set { _displayValue = value; }
}
/// <summary>
/// start animation
/// </summary>
protected async void Animate()
{
if (_animationRunning) return;
_animationRunning = true;
await Task.Run(new Action(() =>
{
while (DisplayValue != Value)
{
if (Math.Abs(DisplayValue - Value) < animationStep)
DisplayValue = Value;
else
DisplayValue += DisplayValue < Value ? animationStep : -animationStep;
Invalidate();
System.Threading.Thread.Sleep((int)(1000f / frameRate));
}
}));
_animationRunning = false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace WikiLibs.Models
{
public abstract class PatchModel<Model, DataModel>
where Model : PatchModel<Model, DataModel>, new()
where DataModel : new()
{
public abstract DataModel CreatePatch(in DataModel current);
public ICollection<DataModel> PatchCollection(in ICollection<DataModel> currents)
{
var mdls = new HashSet<DataModel>();
foreach (var mdl in currents)
mdls.Add(CreatePatch(mdl));
return (mdls);
}
}
}
|
using io.rong.models.response;
using io.rong.methods.chatroom;
using io.rong.methods.chatroom.demotion;
using io.rong.models.chatroom;
using io.rong.util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Newtonsoft.Json;
using io.rong.models.conversation;
namespace io.rong.example.chatroom
{
public class DemotionExample
{
/**
* 此处替换成您的appKey
* */
private static readonly String appKey = "kj7swf8okyqt2";
/**
* 此处替换成您的appSecret
* */
private static readonly String appSecret = "mFe3U1UClx4gx";
/**
* 自定义api地址
* */
//private static readonly String api = "http://api.cn.ronghub.com";
static void Main(String[] args)
{
RongCloud rongCloud = RongCloud.GetInstance(appKey, appSecret);
//自定义 api地址方式
//RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret,api);
Demotion demotion = rongCloud.Chatroom.demotion;
/**
*
* API 文档: http://www.rongcloud.cn/docs/server_sdk_api/chatroom/demotion.html#add
* 添加应用内聊天室降级消息
*
* */
String[] messageType = { "RC:VcMsg", "RC:ImgTextMsg", "RC:ImgMsg" };
ResponseResult addResult = demotion.Add(messageType);
Console.WriteLine("add demotion: " + addResult.ToString());
/**
*
*API 文档: http://www.rongcloud.cn/docs/server_sdk_api/chatroom/demotion.html#remove
* 移除应用内聊天室降级消息
*
* */
ResponseResult removeResult = demotion.Remove(messageType);
Console.WriteLine("remove demotion: " + removeResult.ToString());
/**
*
* API 文档: http://www.rongcloud.cn/docs/server_sdk_api/chatroom/demotion.html#getList
* 添加聊天室消息优先级demo
*
* */
ChatroomDemotionMsgResult demotionMsgResult = demotion.GetList();
Console.WriteLine("get demotion: " + demotionMsgResult.ToString());
Console.ReadLine();
}
}
}
|
using UnityEngine;
using System.Collections;
public class TumbleweedMotion : MonoBehaviour {
float wind = 7;
// Use this for initialization
void Start () {
rigidbody.velocity = new Vector3(0,Random.value * 2,0);
}
void Update () {
rigidbody.AddForceAtPosition(new Vector3(wind, 2, 0), transform.position);
if (transform.position.x > 30) Destroy (gameObject);
}
}
|
@{
Layout = null;
}
Origin: cydia.kemmis.info
Label: cydia.kemmis.info
Suite: stable
Version: 1.3
Codename: ios
Architectures: iphoneos-arm
Components: main
Description: cydia.kemmis.info
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace Draco.Api.Proxies
{
/// <summary>
/// Shared configuration object needed to create internal API proxies.
/// </summary>
public class ProxyConfiguration
{
public ProxyConfiguration() { }
public ProxyConfiguration(string baseUrl)
{
BaseUrl = baseUrl;
}
/// <summary>
/// Base URL of internal API endpoint. Trailing URL slash optional.
/// </summary>
/// <value></value>
public string BaseUrl { get; set; }
}
}
|
using Serilog.Configuration;
namespace Serilog.Sinks.Prometheus
{
public static class LoggerSincConfigurationExtensions
{
public static LoggerConfiguration Prometheus(this LoggerSinkConfiguration sinkConfiguration)
{
return sinkConfiguration.Sink(new PrometheusLogLevelEventSink());
}
}
} |
using System;
namespace HttpService.Interface
{
public interface IHttpServer
{
Uri Uri { get; }
void Close();
void Start();
}
} |
//
// Copyright (c) 2003-2006 Jaroslaw Kowalski <jaak@jkowalski.net>
// Copyright (c) 2006-2014 Piotr Fusik <piotr@fusik.info>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using Sooda.Schema;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
namespace Sooda.CodeGen
{
public enum PrimitiveRepresentation
{
Boxed,
SqlType,
Raw,
Nullable,
RawWithIsNull
}
public class ExternalProjectInfo
{
public ExternalProjectInfo()
{
}
public ExternalProjectInfo(string projectType)
{
this.ProjectType = projectType;
}
public ExternalProjectInfo(string projectType, string projectFile)
{
this.ProjectType = projectType;
this.ProjectFile = projectFile;
}
[XmlIgnore]
public IProjectFile ProjectProvider;
[XmlIgnore]
public string ActualProjectFile;
[XmlAttribute("type")]
public string ProjectType;
[XmlAttribute("file")]
public string ProjectFile;
}
[XmlRoot("sooda-project", Namespace = "http://www.sooda.org/schemas/SoodaProject.xsd")]
public class SoodaProject
{
public static string NamespaceURI = "http://www.sooda.org/schemas/SoodaProject.xsd";
public static Stream GetSoodaProjectXsdStream()
{
Assembly ass = typeof(SoodaProject).Assembly;
foreach (string name in ass.GetManifestResourceNames())
{
if (name.EndsWith(".SoodaProject.xsd"))
{
return ass.GetManifestResourceStream(name);
};
}
throw new SoodaSchemaException("SoodaProject.xsd not embedded in Sooda.CodeGen assembly");
}
public static XmlReader GetSoodaProjectXsdStreamXmlReader()
{
return new XmlTextReader(GetSoodaProjectXsdStream());
}
[XmlElement("schema-file")]
public string SchemaFile;
[XmlElement("language")]
public string Language = "c#";
[XmlElement("output-assembly")]
public string AssemblyName;
[XmlElement("output-namespace")]
public string OutputNamespace;
[XmlElement("output-path")]
public string OutputPath;
[XmlElement("output-partial-path")]
public string OutputPartialPath;
[XmlElement("nullable-representation")]
public PrimitiveRepresentation NullableRepresentation = PrimitiveRepresentation.SqlType;
[XmlElement("not-null-representation")]
public PrimitiveRepresentation NotNullRepresentation = PrimitiveRepresentation.Raw;
[XmlElement("null-propagation")]
[System.ComponentModel.DefaultValue(false)]
public bool NullPropagation = false;
[XmlElement("base-class-name")]
public string BaseClassName = null;
[XmlElement("with-typed-queries")]
[System.ComponentModel.DefaultValue(true)]
public bool WithTypedQueryWrappers = true;
[XmlElement("with-soql")]
[System.ComponentModel.DefaultValue(true)]
public bool WithSoql = true;
[XmlElement("file-per-namespace")]
[System.ComponentModel.DefaultValue(false)]
public bool FilePerNamespace = false;
[XmlElement("loader-class")]
[System.ComponentModel.DefaultValue(false)]
public bool LoaderClass = false;
[XmlElement("stubs-compiled-separately")]
[System.ComponentModel.DefaultValue(false)]
public bool SeparateStubs = false;
[XmlElement("embedded-schema-type")]
public EmbedSchema EmbedSchema = EmbedSchema.Binary;
[XmlArray("external-projects")]
[XmlArrayItem("project")]
public List<ExternalProjectInfo> ExternalProjects = new List<ExternalProjectInfo>();
[XmlElement("use-partial")]
[System.ComponentModel.DefaultValue(false)]
public bool UsePartial = false;
[XmlElement("partial-suffix")]
public string PartialSuffix = "";
public void WriteTo(string fileName)
{
using (FileStream fs = File.Create(fileName))
{
WriteTo(fs);
}
}
public void WriteTo(Stream stream)
{
using (StreamWriter sw = new StreamWriter(stream))
{
WriteTo(sw);
}
}
public void WriteTo(TextWriter tw)
{
XmlTextWriter xtw = new XmlTextWriter(tw);
xtw.Indentation = 4;
xtw.Formatting = Formatting.Indented;
WriteTo(xtw);
}
public void WriteTo(XmlTextWriter xtw)
{
XmlSerializer ser = new XmlSerializer(typeof(SoodaProject));
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(String.Empty, "http://www.sooda.org/schemas/SoodaProject.xsd");
ser.Serialize(xtw, this, ns);
xtw.Flush();
}
public static SoodaProject LoadFrom(string fileName)
{
using (FileStream fs = File.OpenRead(fileName))
{
return LoadFrom(fs);
}
}
public static SoodaProject LoadFrom(Stream stream)
{
using (StreamReader sr = new StreamReader(stream))
{
return LoadFrom(sr);
}
}
public static SoodaProject LoadFrom(TextReader reader)
{
XmlTextReader xmlreader = new XmlTextReader(reader);
return LoadFrom(xmlreader);
}
public static SoodaProject LoadFrom(XmlTextReader reader)
{
#if SOODA_NO_VALIDATING_READER
XmlSerializer ser = new XmlSerializer(typeof(SoodaProject));
SoodaProject project = (SoodaProject)ser.Deserialize(reader);
#else
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas.Add(NamespaceURI, GetSoodaProjectXsdStreamXmlReader());
XmlReader validatingReader = XmlReader.Create(reader, readerSettings);
XmlSerializer ser = new XmlSerializer(typeof(SoodaProject));
SoodaProject project = (SoodaProject)ser.Deserialize(validatingReader);
#endif
return project;
}
}
}
|
namespace ScriptableObjects.ScriptableArchitecture.Framework.Utility
{
public class GenericValueWrapper < T >
{
public T Value { get; set; }
#region Public
public GenericValueWrapper( T value )
{
Value = value;
}
public override string ToString()
{
return $"{nameof( Value )}: {Value}";
}
#endregion
}
}
|
@model COMCMS.Core.Member
@{
ViewBag.title = "查看/编辑用户详情";
}
<div class="wrapper wrapper-content">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>@ViewBag.title</h5>
<div class="ibox-tools">
</div>
</div>
<div class="ibox-content">
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "editMemberForm", @class = "form-horizontal m-t" }))
{
<div class="tabs-container">
<ul class="nav nav-tabs">
<li class="active">
<a data-toggle="tab" href="#tab-1" aria-expanded="true"> 用户基本设置</a>
</li>
<li class="">
<a data-toggle="tab" href="#tab-2" aria-expanded="false"> 详细信息</a>
</li>
<li class="">
<a data-toggle="tab" href="#tab-3" aria-expanded="false"> 余额变化记录</a>
</li>
<li class="hide">
<a data-toggle="tab" href="#tab-5" aria-expanded="false"> 赠送余额变化记录</a>
</li>
<li class="hide">
<a data-toggle="tab" href="#tab-6" aria-expanded="false"> 销售返现变化记录</a>
</li>
<li class="hide">
<a data-toggle="tab" href="#tab-4" aria-expanded="false"> 手动充值</a>
</li>
<li class="hide">
<a data-toggle="tab" href="#tab-7" aria-expanded="false"> 手动清除返现</a>
</li>
</ul>
<div class="tab-content">
<div id="tab-1" class="tab-pane active">
<div class="panel-body">
<div class="form-group">
<label class="col-sm-3 control-label">所属用户组:</label>
<div class="col-sm-8">
<select class="form-control m-b" asp-for="RoleId">
@foreach (var m in ViewBag.RoleList)
{
<option value="@m.Id">@m.RoleName</option>
}
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">昵称:</label>
<div class="col-sm-8">
<input id="Nickname" name="Nickname" maxlength="200" type="text" class="form-control" value="@Model.Nickname" aria-required="true" placeholder="昵称" readonly>
</div>
</div>
<div class="form-group hidden">
<label class="col-sm-3 control-label">用户名:</label>
<div class="col-sm-8">
<input id="UserName" name="UserName" maxlength="20" type="text" class="form-control" value="@Model.UserName" required aria-required="true" placeholder="登录用户名">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">手机号码:</label>
<div class="col-sm-8">
<input id="Tel" name="Tel" maxlength="20" type="text" class="form-control" value="@Model.Tel" aria-required="true" placeholder="用户手机号码">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">修改密码:</label>
<div class="col-sm-8">
<input id="PassWord" name="PassWord" maxlength="20" type="password" class="form-control" value="" aria-required="true" placeholder="如果修改密码,请填写,不修改,留空">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">重复密码:</label>
<div class="col-sm-8">
<input id="PassWord2" name="PassWord2" maxlength="20" type="password" class="form-control" value="" aria-required="true" placeholder="请再次填写用户密码">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">真实姓名:</label>
<div class="col-sm-8">
<input id="Realname" name="Realname" maxlength="20" type="text" class="form-control" value="@Model.RealName" aria-required="true" placeholder="真实姓名">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">电子邮件:</label>
<div class="col-sm-8">
<input id="Email" name="Email" maxlength="100" type="text" class="form-control" value="@Model.Email" aria-required="true" placeholder="电子邮件">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">父级用户:</label>
<div class="col-sm-8">
<select class="form-control m-b" asp-for="Parent">
<option value="0">顶层用户,无父级用户</option>
@foreach (COMCMS.Core.Member m in ViewBag.allmember)
{
<option value="@m.Id">@System.Web.HttpUtility.UrlDecode(m.RealName)</option>
}
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">爷级用户:</label>
<div class="col-sm-8">
<select class="form-control m-b" name="Grandfather" id="Grandfather" asp-for="Grandfather">
<option value="0">顶层用户,无爷级用户</option>
@foreach (COMCMS.Core.Member m in ViewBag.allmember)
{
<option value="@m.Id">@System.Web.HttpUtility.UrlDecode(m.RealName)</option>
}
</select>
</div>
</div>
<div style="display:none">
<div class="form-group">
<label class="col-sm-3 control-label">QQ:</label>
<div class="col-sm-8">
<input id="QQ" name="QQ" maxlength="20" type="text" class="form-control" value="@Model.QQ
" required aria-required="true" placeholder="QQ">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">微信:</label>
<div class="col-sm-8">
<input id="Weixin" name="Weixin" maxlength="20" type="text" class="form-control" value="@Model.Weixin
" required aria-required="true" placeholder="微信" readonly>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">省份:</label>
<div class="col-sm-8">
<input id="Province" name="Province" maxlength="20" type="text" class="form-control" value="@Model.Province
" required aria-required="true" placeholder="省份">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">城市:</label>
<div class="col-sm-8">
<input id="City" name="City" maxlength="20" type="text" class="form-control" value="@Model.City
" required aria-required="true" placeholder="城市">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">区域:</label>
<div class="col-sm-8">
<input id="District" name="District" maxlength="20" type="text" class="form-control" value="@Model.District
" required aria-required="true" placeholder="区域">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">详细地址:</label>
<div class="col-sm-8">
<input id="Address" name="Address" maxlength="20" type="text" class="form-control" value="@Model.Address
" required aria-required="true" placeholder="详细地址">
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">可用余额:</label>
<div class="col-sm-8">
<label class="control-label">@Model.Balance.ToString("N2")</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">赠送余额:</label>
<div class="col-sm-8">
<label class="control-label">@Model.GiftBalance.ToString("N2")</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">分销返现余额:</label>
<div class="col-sm-8">
<label class="control-label">@Model.ExtCredits1.ToString("N2")</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">联系电话:</label>
<div class="col-sm-8">
<input id="Phone" name="Phone" type="text" maxlength="20" class="form-control" placeholder="可以设置一个其他的联系电话" value="@Model.Phone">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">支付宝账号:</label>
<div class="col-sm-8">
<input id="Alipay" name="Alipay" type="text" maxlength="50" class="form-control" placeholder="请填写您的支付宝账号" value="@Model.Alipay">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">PayPal账号:</label>
<div class="col-sm-8">
<input id="Skype" name="Skype" type="text" maxlength="100" class="form-control" placeholder="请填写您的PayPal账号" value="@Model.Skype">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">银行卡号码:</label>
<div class="col-sm-8">
<input id="BankCardNO" name="BankCardNO" maxlength="20" type="text" class="form-control" value="@Model.BankCardNO" aria-required="true" placeholder="银行卡号码" readonly>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">开户行:</label>
<div class="col-sm-8">
<input id="Bank" name="Bank" maxlength="20" type="text" class="form-control" value="@Model.Bank" aria-required="true" placeholder="开户银行" readonly>
</div>
</div>
<div class="form-group hidden">
<label class="col-sm-3 control-label">已缴费代理商:</label>
<div class="col-sm-8">
<label class="checkbox-inline i-checks">
<input type="checkbox" value="1" name="IsVerifySellers" id="IsVerifySellers" @(Model.IsVerifySellers == 1 ? "checked" : "")> 已经缴费(注意,如果手动勾选,该用户会变成已经缴费的代理商,请慎重使用本功能)
</label>
</div>
</div>
<div class="row white-bg">
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-3">
<input type="hidden" name="Id" value="@Model.Id" id="Id" />
<button class="btn btn-primary" type="submit"><i class="fa fa-save"></i> 提交 </button>
<button class="btn btn-default" type="button" onclick="closethisdialog();"><i class="fa fa-close"></i> 取消 </button>
</div>
</div>
</div>
</div>
</div>
<div id="tab-2" class="tab-pane">
<div class="panel-body">
<div class="alert alert-info">
温馨提示:此部分信息只读。
</div>
<div class="form-group">
<label class="col-sm-3 control-label">注册时间:</label>
<div class="col-sm-8">
<label class="control-label">@Model.RegTime.ToString("yyyy-MM-dd HH:mm")</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">注册IP:</label>
<div class="col-sm-8">
<label class="control-label">@Model.RegIP</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">最后登录时间:</label>
<div class="col-sm-8">
<label class="control-label">@Model.LastLoginTime.ToString("yyyy-MM-dd HH:mm")</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">最后登录IP:</label>
<div class="col-sm-8">
<label class="control-label">@Model.LastLoginIP</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">登录次数:</label>
<div class="col-sm-8">
<label class="control-label">@Model.LoginCount</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">用户推广二维码:<br />仅限有生成过</label>
<div class="col-sm-8">
<label class="control-label"><img src="/userfiles/qrcode/invite/@(Model.Id).png" /></label>
</div>
</div>
</div>
</div>
<div id="tab-3" class="tab-pane">
<table class="table table-bordered" style="margin-top:15px">
<thead>
<tr>
<th>类型</th>
<th>变化值</th>
<th>变化前</th>
<th>变化后</th>
<th>时间</th>
<th>理由</th>
</tr>
</thead>
@foreach (COMCMS.Core.BalanceChangeLog b in ViewBag.listbalancelogs)
{
<tr>
<td>@COMCMS.Core.Member.GetBalanceTypeName(b.TypeId)</td>
<td>@b.Reward.ToString("N2")</td>
<td>@b.BeforChange.ToString("N2")</td>
<td>@b.AfterChange.ToString("N2")</td>
<td>@b.AddTime.ToString("yyyy-MM-dd HH:mm")</td>
<td>@b.Actions</td>
</tr>
}
</table>
</div>
<div id="tab-5" class="tab-pane">
</div>
<div id="tab-6" class="tab-pane">
<table class="table table-bordered" style="margin-top:15px">
<thead>
<tr>
<th>类型</th>
<th>变化值</th>
<th>变化前</th>
<th>变化后</th>
<th>时间</th>
<th>理由</th>
</tr>
</thead>
@foreach (COMCMS.Core.RebateChangeLog b in ViewBag.listrechargebalancelogs)
{
<tr>
<td>@COMCMS.Core.Member.GetBalanceTypeName(b.TypeId)</td>
<td>@b.Reward.ToString("N2")</td>
<td>@b.BeforChange.ToString("N2")</td>
<td>@b.AfterChange.ToString("N2")</td>
<td>@b.AddTime.ToString("yyyy-MM-dd HH:mm")</td>
<td>@b.Actions</td>
</tr>
}
</table>
</div>
<div id="tab-4" class="tab-pane">
<div style="height:20px"></div>
<div class="form-group">
<div class="form-group">
<label class="col-sm-3 control-label">充值金额:</label>
<div class="col-sm-8">
<input id="price" name="price" maxlength="20" type="text" class="form-control" value="" aria-required="true" placeholder="请输入充值金额,大于0为充值,小于0为扣款">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">理由:</label>
<div class="col-sm-8">
<input id="reason" name="reason" maxlength="30" type="text" class="form-control" value="" aria-required="true" placeholder="记录充值或者扣款原因,30个字符以内">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">充值金额:</label>
<div class="col-sm-8">
<button class="btn btn-warning" type="button" onclick="doRecharge(@Model.Id)"><i class="fa fa-save"></i> 确认充值 </button> 说明:充值后,无法撤回,请确认金额
</div>
</div>
</div>
</div>
<div id="tab-7" class="tab-pane">
<div style="height:20px"></div>
<div class="form-group">
<div class="form-group">
<label class="col-sm-3 control-label">用户返现余额:</label>
<div class="col-sm-8">
<label class="control-label">@Model.ExtCredits1.ToString("N2")</label>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">清除返现金额:</label>
<div class="col-sm-8">
<input id="pricex" name="pricex" maxlength="20" type="text" class="form-control" value="" aria-required="true" placeholder="请输入扣除返现金额,小于0为扣款,必须小于0">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">理由:</label>
<div class="col-sm-8">
<input id="reasonx" name="reasonx" maxlength="30" type="text" class="form-control" value="" aria-required="true" placeholder="记录充值或者扣款原因,30个字符以内">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">确认扣款:</label>
<div class="col-sm-8">
<button class="btn btn-warning" type="button" onclick="doDeduction(@Model.Id)"><i class="fa fa-save"></i> 确认扣除 </button> 说明:扣除后,无法撤销
</div>
</div>
</div>
</div>
</div>
</div>
}
</div>
</div>
</div>
<script>
$(function () {
DoPost("editMemberForm");
})
</script> |
using iHRS.Domain.Common;
namespace iHRS.Domain.Models
{
public class CommunicationMethod : Enumeration
{
public static readonly CommunicationMethod Email = new CommunicationMethod(1, "Email");
public static readonly CommunicationMethod Sms = new CommunicationMethod(2, "Sms");
public CommunicationMethod(int id, string name) : base(id, name)
{
}
}
}
|
@using MichaelBrandonMorris.Extensions.Web.HtmlHelper.Bootstrap.Display.Horizontal
@model MichaelBrandonMorris.KingsportMillSafetyTraining.Models.CompanyViewModel
@{
Layout = null;
}
@Html.BootstrapHorizontalDefinitionListFor(model => model.Name)
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Integration.Heartbeats {
public class Vibrate {
public const string Type = "vibrate";
public uint Index;
public double? Speed;
public double[]? Speeds;
public Dictionary<uint, double>? SpeedsByFeature;
}
}
|
using System;
using Delta.CapiNet.Logging;
namespace Delta.SmartCard.Logging
{
internal interface ILogService : CapiNetLogger.ILogService { }
}
|
using Umbraco.Cms.Core.Persistence.Repositories;
using Umbraco.Extensions;
namespace Umbraco.Cms.Infrastructure.Persistence.Repositories.Implement
{
internal static class LanguageRepositoryExtensions
{
public static bool IsDefault(this ILanguageRepository repo, string culture)
{
if (culture == null || culture == "*") return false;
return repo.GetDefaultIsoCode().InvariantEquals(culture);
}
}
}
|
using System;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using BusinessForms;
using Microsoft.AspNetCore.Mvc;
namespace PalvelutoriModel.PassthroughControllers
{
public class ChangePasswordController : PassthroughBaseController
{
public ChangePasswordController(BFContext context) : base("users/x/change_password", context)
{
}
[HttpGet]
public Task<JObject> Create(string contextId = null)
{
return Task.FromResult(Serialize(new ChangePasswordMessage
{
OldPassword = "",
NewPassword = "",
NewPassword2 = "",
UserId = ""
}));
}
[HttpPost]
public virtual async Task<IActionResult> Post([FromBody] ChangePasswordMessage body)
{
if (body == null)
{
throw new ArgumentException("Invalid body");
}
if (string.IsNullOrEmpty(body.OldPassword))
{
ModelState.AddModelError("old_password", "Tieto on pakollinen.");
}
if (string.IsNullOrEmpty(body.NewPassword))
{
ModelState.AddModelError("new_password", "Tieto on pakollinen.");
}
if (string.IsNullOrEmpty(body.NewPassword2))
{
ModelState.AddModelError("new_password2", "Tieto on pakollinen.");
}
else
{
if (body.NewPassword != body.NewPassword2)
{
ModelState.AddModelError("new_password", "Tarkista salasana.");
}
}
if (!ModelState.IsValid)
{
return new BadRequestObjectResult(ModelState);
}
var succeed = true;
var api = "users/" + body.UserId + "/change_password/";
JObject result;
JObject obj = Serialize(body);
try
{
result = await PutJson(api, obj);
}
catch (DjangoFailedException)
{
succeed = false;
}
ChangePasswordReply r = new ChangePasswordReply { Succeed = succeed };
return Json(r);
}
public class ChangePasswordReply
{
[JsonProperty("succeed")]
public bool Succeed { get; set; }
}
public class ChangePasswordMessage
{
[JsonProperty("old_password")]
public string OldPassword { get; set; }
[JsonProperty("new_password")]
public string NewPassword { get; set; }
[JsonProperty("new_password2")]
public string NewPassword2 { get; set; }
[JsonProperty("userId")]
public string UserId { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Charlotte.Flowertact.Tools;
using Charlotte.Satellite.Tools;
namespace Charlotte.Flowertact
{
public class Fortewave : IDisposable
{
private object SYNCROOT = new object();
private PostOfficeBox _rPob; // closed 確認用
private PostOfficeBox _wPob;
public Fortewave(string ident)
: this(ident, ident)
{ }
public Fortewave(string rIdent, string wIdent)
{
if (rIdent == null)
throw new ArgumentNullException("rIdent");
if (wIdent == null)
throw new ArgumentNullException("wIdent");
_rPob = new PostOfficeBox(rIdent);
_wPob = new PostOfficeBox(wIdent);
}
public void Clear()
{
lock (SYNCROOT)
{
if (_rPob == null)
throw new Exception("already closed");
_rPob.Clear();
_wPob.Clear();
}
}
public void Send(object sendObj)
{
if (sendObj == null)
throw new ArgumentNullException("sendObj");
lock (SYNCROOT)
{
if (_rPob == null)
throw new Exception("already closed");
QueueData<SubBlock> sendData = new Serializer(sendObj).GetBuff();
_wPob.Send(sendData);
}
}
public object Recv(int millis)
{
if (millis < Timeout.Infinite)
throw new ArgumentException("millis lt min");
lock (SYNCROOT)
{
if (_rPob == null)
throw new Exception("already closed");
byte[] recvData = _rPob.Recv(millis);
if (recvData == null)
return null;
object recvObj = new Deserializer(recvData).Next();
return recvObj;
}
}
public void Pulse()
{
lock (SYNCROOT)
{
if (_rPob == null)
throw new Exception("already closed");
_rPob.Pulse();
_wPob.Pulse();
}
}
public void Close()
{
lock (SYNCROOT)
{
if (_rPob != null) // ? not closed
{
_rPob.Close();
_wPob.Close();
_rPob = null;
_wPob = null;
}
}
}
public void Dispose()
{
this.Close();
}
}
}
|
//*********************************************************************
//xCAD
//Copyright(C) 2021 Xarial Pty Limited
//Product URL: https://www.xcad.net
//License: https://xcad.xarial.com/license/
//*********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xarial.XCad.Geometry;
using Xarial.XCad.Geometry.Structures;
using Xarial.XCad.Geometry.Wires;
using Xarial.XCad.SolidWorks.Geometry.Curves;
namespace Xarial.XCad.SolidWorks.Geometry
{
public interface ISwRegion : IXRegion
{
new ISwCurve[] Boundary { get; }
}
internal class SwRegion : ISwRegion
{
public IXSegment[] Boundary { get; }
public Plane Plane
{
get
{
Plane plane = null;
var firstCurve = Boundary.FirstOrDefault() as SwCurve;
if (firstCurve?.TryGetPlane(out plane) == true)
{
return plane;
}
else
{
//TODO: check if not colinear
//TODO: check if all on the same plane
//TODO: fix if a single curve
var refVec1 = Boundary[0].EndPoint.Coordinate - Boundary[0].StartPoint.Coordinate;
var refVec2 = Boundary[1].EndPoint.Coordinate - Boundary[1].StartPoint.Coordinate;
var normVec = refVec1.Cross(refVec2);
return new Plane(Boundary.First().StartPoint.Coordinate, normVec, refVec1);
}
}
}
ISwCurve[] ISwRegion.Boundary => m_LazyBoundary.Value;
private readonly Lazy<ISwCurve[]> m_LazyBoundary;
internal SwRegion(IXSegment[] boundary)
{
Boundary = boundary;
//TODO: check if segment is not curve - then create curve (e.g. from the edge)
m_LazyBoundary = new Lazy<ISwCurve[]>(() => boundary.Cast<ISwCurve>().ToArray());
}
}
}
|
using dnsl48.SGF.Attributes;
namespace dnsl48.SGF.Model.Property
{
/// <summary>
/// A property containing a move (position on the board) and a colour.
/// The colour should be assigned by the class attributes <see cref="ColourAttribute" />
/// </summary>
public class ColouredMove<T>: APositionValue<T>, IColour
where T: ColouredMove<T>
{
/// <summary>
/// Initialize with the values
/// </summary>
/// <param name="x">X axis of the position</param>
/// <param name="y">Y axis of the position</param>
public ColouredMove(byte x, byte y) : base(x, y) {}
/// <summary>
/// Returns the colour
/// <seealso cref="ColourAttribute" />
/// </summary>
/// <returns>The colour</returns>
public Colour GetColour()
{
var attr = (ColourAttribute) System.Attribute.GetCustomAttribute(typeof(T), typeof(ColourAttribute));
return attr.GetValue();
}
}
}
|
namespace System.Web.ModelBinding {
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
public class CollectionModelBinder<TElement> : IModelBinder {
// Used when the ValueProvider contains the collection to be bound as multiple elements, e.g. foo[0], foo[1].
private static List<TElement> BindComplexCollection(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) {
string indexPropertyName = ModelBinderUtil.CreatePropertyModelName(bindingContext.ModelName, "index");
ValueProviderResult vpResultIndex = bindingContext.UnvalidatedValueProvider.GetValue(indexPropertyName);
IEnumerable<string> indexNames = CollectionModelBinderUtil.GetIndexNamesFromValueProviderResult(vpResultIndex);
return BindComplexCollectionFromIndexes(modelBindingExecutionContext, bindingContext, indexNames);
}
internal static List<TElement> BindComplexCollectionFromIndexes(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext, IEnumerable<string> indexNames) {
bool indexNamesIsFinite;
if (indexNames != null) {
indexNamesIsFinite = true;
}
else {
indexNamesIsFinite = false;
indexNames = CollectionModelBinderUtil.GetZeroBasedIndexes();
}
List<TElement> boundCollection = new List<TElement>();
foreach (string indexName in indexNames) {
string fullChildName = ModelBinderUtil.CreateIndexModelName(bindingContext.ModelName, indexName);
ModelBindingContext childBindingContext = new ModelBindingContext(bindingContext) {
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TElement)),
ModelName = fullChildName
};
object boundValue = null;
IModelBinder childBinder = bindingContext.ModelBinderProviders.GetBinder(modelBindingExecutionContext, childBindingContext);
if (childBinder != null) {
if (childBinder.BindModel(modelBindingExecutionContext, childBindingContext)) {
boundValue = childBindingContext.Model;
// merge validation up
bindingContext.ValidationNode.ChildNodes.Add(childBindingContext.ValidationNode);
}
}
else {
// should we even bother continuing?
if (!indexNamesIsFinite) {
break;
}
}
boundCollection.Add(ModelBinderUtil.CastOrDefault<TElement>(boundValue));
}
return boundCollection;
}
public virtual bool BindModel(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext) {
ModelBinderUtil.ValidateBindingContext(bindingContext);
ValueProviderResult vpResult = bindingContext.UnvalidatedValueProvider.GetValue(bindingContext.ModelName, skipValidation: !bindingContext.ValidateRequest);
List<TElement> boundCollection = (vpResult != null)
? BindSimpleCollection(modelBindingExecutionContext, bindingContext, vpResult.RawValue, vpResult.Culture)
: BindComplexCollection(modelBindingExecutionContext, bindingContext);
bool retVal = CreateOrReplaceCollection(modelBindingExecutionContext, bindingContext, boundCollection);
return retVal;
}
// Used when the ValueProvider contains the collection to be bound as a single element, e.g. the raw value
// is [ "1", "2" ] and needs to be converted to an int[].
internal static List<TElement> BindSimpleCollection(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext, object rawValue, CultureInfo culture) {
if (rawValue == null) {
return null; // nothing to do
}
List<TElement> boundCollection = new List<TElement>();
object[] rawValueArray = ModelBinderUtil.RawValueToObjectArray(rawValue);
foreach (object rawValueElement in rawValueArray) {
ModelBindingContext innerBindingContext = new ModelBindingContext(bindingContext) {
ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TElement)),
ModelName = bindingContext.ModelName,
ValueProvider = new ValueProviderCollection() { // aggregate value provider
new ElementalValueProvider(bindingContext.ModelName, rawValueElement, culture), // our temporary provider goes at the front of the list
bindingContext.ValueProvider
}
};
object boundValue = null;
IModelBinder childBinder = bindingContext.ModelBinderProviders.GetBinder(modelBindingExecutionContext, innerBindingContext);
if (childBinder != null) {
if (childBinder.BindModel(modelBindingExecutionContext, innerBindingContext)) {
boundValue = innerBindingContext.Model;
bindingContext.ValidationNode.ChildNodes.Add(innerBindingContext.ValidationNode);
}
}
boundCollection.Add(ModelBinderUtil.CastOrDefault<TElement>(boundValue));
}
return boundCollection;
}
// Extensibility point that allows the bound collection to be manipulated or transformed before
// being returned from the binder.
protected virtual bool CreateOrReplaceCollection(ModelBindingExecutionContext modelBindingExecutionContext, ModelBindingContext bindingContext, IList<TElement> newCollection) {
CollectionModelBinderUtil.CreateOrReplaceCollection(bindingContext, newCollection, () => new List<TElement>());
return true;
}
}
}
|
namespace Inshapardaz.Domain.Models
{
public static class MimeTypes
{
public const string Json = "application/json";
public const string Markdown = "text/markdown";
public const string Pdf = "application/pdf";
public const string Jpg = "image/jpeg";
public const string Text = "text/plain";
public const string Html = "text/html";
public const string MsWord = "application/msword";
public const string Epub = "application/epub+zip";
public const string Zip = "application/zip";
public const string CompressedFile = "application/x-zip-compressed";
}
}
|
using System.Collections;
using System.Collections.Generic;
using System;
using ilPSP;
using BoSSS.Platform;
namespace BoSSS.Foundation.Grid.Voronoi.Meshing.Cutter
{
class Divider<T>
{
Mesh<T> mesh;
InsideCellEnumerator<T> insideCells;
public Divider(Mesh<T> mesh, Boundary<T> boundary)
{
insideCells = new InsideCellEnumerator<T>(mesh, boundary);
this.mesh = mesh;
}
public Divider(Domain<T> mesh)
{
insideCells = new InsideCellEnumerator<T>(mesh);
this.mesh = mesh.Mesh;
}
public MeshCell<T> GetFirst(BoundaryLine boundaryLine)
{
insideCells.SetFirstCell((Vector)boundaryLine.Start);
return insideCells.GetFirstCell();
}
public void RemoveOutsideCells()
{
IdentifyInsideCells();
List<MeshCell<T>> insideCells = CollectInsideCells();
mesh.Cells = insideCells;
List<T> nodes = CollectNodes(insideCells);
mesh.Nodes = nodes;
}
List<MeshCell<T>> CollectInsideCells()
{
List<MeshCell<T>> cells = new List<MeshCell<T>>(mesh.Cells.Count);
foreach(MeshCell<T> cell in mesh.Cells)
{
if(cell.Type == MeshCellType.Inside)
{
cell.ID = cells.Count;
cells.Add(cell);
}
}
return cells;
}
static List<T> CollectNodes(List<MeshCell<T>> cells)
{
List<T> nodes = new List<T>(cells.Count);
foreach(MeshCell<T> cell in cells)
{
nodes.Add(cell.Node);
}
return nodes;
}
void IdentifyInsideCells()
{
foreach (MeshCell<T> cell in insideCells.EnumerateCellsInConcentricCircles())
{
cell.Type = MeshCellType.Inside;
}
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Forum.Core;
using Forum.Transfer.Post.Command;
using Forum.Transfer.Post.Query;
using Forum.Transfer.Shared;
using Forum.Web.Infrastructure;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
namespace Forum.Web.Controllers
{
[ApiController]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public class PostController : ControllerBase
{
private readonly IMediator _mediator;
public PostController(IMediator mediator)
{
_mediator = mediator;
}
[AllowAnonymous]
[HttpGet(ApiRoutes.Post.GetList)]
public async Task<IActionResult> List()
{
if (!ModelState.IsValid)
return BadRequest();
var result = await _mediator.Send(new GetAllPostsQuery());
return Ok(result.ToResponseDto());
}
[AllowAnonymous]
[HttpGet(ApiRoutes.Post.Get)]
public async Task<IActionResult> Get(int postId)
{
if (!ModelState.IsValid)
return BadRequest();
var result = await _mediator.Send(new GetPostQuery(postId));
return Ok(result.ToResponseDto());
}
[HttpPost(ApiRoutes.Post.Create)]
public async Task<IActionResult> Create([FromBody] CreatePostCommand command)
{
if (!ModelState.IsValid)
return BadRequest();
var result = await _mediator.Send(command);
return Ok(result.ToResponseDto());
}
[HttpPut(ApiRoutes.Post.Update)]
public async Task<IActionResult> Update([FromBody] UpdatePostCommand command)
{
if (!ModelState.IsValid)
return BadRequest();
var result = await _mediator.Send(command);
return Ok(result.ToResponseDto());
}
[HttpDelete(ApiRoutes.Post.Delete)]
public async Task<IActionResult> Delete([FromBody] DeletePostCommand command)
{
if (!ModelState.IsValid)
return BadRequest();
var result = await _mediator.Send(command);
return Ok(result.ToResponseDto());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace ABBConfigMaker
{
class MainChecker
{
private bool hasError;
private List<Delegate> checkers;
public List<ErrorDataModel> errors;
public MainChecker()
{
checkers = new List<Delegate>();
errors = new List<ErrorDataModel>();
}
public void addChecker(Func<ErrorDataModel> checkMethod)
{
checkers.Add(checkMethod);
}
public bool checkAll()
{
foreach(Func<ErrorDataModel> checkMethod in checkers)
{
errors.Add(checkMethod());
}
string errMsg = string.Empty;
foreach(ErrorDataModel error in errors)
{
if (error.isError)
{
hasError = true;
errMsg += error.errorMessage + '\n';
}
}
if (hasError)
{
MessageBox.Show(errMsg);
}
return hasError;
}
}
}
|
// Licensed to Finnovation Labs Limited under one or more agreements.
// Finnovation Labs Limited licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using AutoMapper;
namespace FinnovationLabs.OpenBanking.Library.Connector.Converters
{
public class IdentityValueConverter<TValue> : IValueConverter<TValue, TValue>
{
public TValue Convert(TValue sourceMember, ResolutionContext context)
{
return sourceMember;
}
}
}
|
using System;
using System.IO;
namespace RECOM_Toolkit
{
internal static class Extension
{
public static string extractName(this byte[] data)
{
string text = string.Empty;
for (int i = 0; i < data.Length; i++)
{
byte b = data[i];
if (b == 0)
{
break;
}
text += Convert.ToChar(b);
}
return text;
}
public static int extractInt32(this byte[] bytes, int index = 0)
{
return (int)bytes[index + 3] << 24 | (int)bytes[index + 2] << 16 | (int)bytes[index + 1] << 8 | (int)bytes[index];
}
public static byte[] extractPiece(this MemoryStream ms, int offset, int length, long changeOffset = -1L)
{
if (changeOffset > -1L)
{
ms.Position = changeOffset;
}
byte[] array = new byte[length];
ms.Read(array, 0, length);
return array;
}
public static byte[] int32ToByteArray(this int value)
{
byte[] array = new byte[4];
for (int i = 0; i < 4; i++)
{
array[i] = (byte)(value >> i * 8 & 255);
}
return array;
}
}
}
|
public class RoundInfoArgs
{
public int MonsterIndex;
public int RoundIndex;
}
|
namespace SharemundoBulgaria.Areas.Administration.Services.RemovePart
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using CloudinaryDotNet;
using Microsoft.EntityFrameworkCore;
using SharemundoBulgaria.Data;
using SharemundoBulgaria.Services.Cloud;
public class RemovePartService : IRemovePartService
{
private readonly ApplicationDbContext db;
private readonly Cloudinary cloudinary;
public RemovePartService(ApplicationDbContext db, Cloudinary cloudinary)
{
this.db = db;
this.cloudinary = cloudinary;
}
public Dictionary<string, string> GetAllParts()
{
var allParts = this.db.SectionParts.ToList();
var result = new Dictionary<string, string>();
foreach (var part in allParts)
{
result.Add(part.Id, part.Name);
}
return result;
}
public async Task<string> RemovePart(string id)
{
var targetPart = await this.db.SectionParts.FirstOrDefaultAsync(x => x.Id == id);
var removedSectionName = targetPart.Name;
var targetTexts = this.db.PartTexts.Where(x => x.SectionPartId == id).ToList();
var targetImages = this.db.PartImages.Where(x => x.SectionPartId == id);
foreach (var targetImage in targetImages)
{
ApplicationCloudinary.DeleteImage(this.cloudinary, targetImage.Name);
this.db.PartImages.Remove(targetImage);
}
this.db.PartTexts.RemoveRange(targetTexts);
this.db.SectionParts.Remove(targetPart);
await this.db.SaveChangesAsync();
return removedSectionName;
}
}
} |
using Castle.DynamicProxy;
namespace MikyM.Autofac.Extensions;
/// <summary>
/// Interceptor adapter that allows registering asynchronous interceptors
/// </summary>
public sealed class AsyncInterceptorAdapter<TAsyncInterceptor> : AsyncDeterminationInterceptor
where TAsyncInterceptor : IAsyncInterceptor
{
public AsyncInterceptorAdapter(TAsyncInterceptor asyncInterceptor)
: base(asyncInterceptor)
{ }
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FPS.ViewModels.Timekeeping
{
public class TimeAttendance
{
public int EmployeeId { get; set; }
public string EmployeeTitle { get; set; }
public string EmployeeName { get; set; }
public DateTime Date { get; set; }
public DateTime? TimeIn { get; set; }
public DateTime? TimeOut { get; set; }
public TimeSpan Worktime { get; set; }
public TimeSpan Late { get; set; }
public TimeSpan Overtime { get; set; }
public TimeSpan Undertime { get; set; }
public string Remarks { get; set; }
public TimeAttendance ComputeOT()
{
if (TimeIn != null && TimeOut != null)
{
// compute worktime
Worktime = (TimeSpan)(TimeOut - TimeIn);
Overtime = Worktime;
// deduct 5 minutes from overtime
if (Overtime >= new TimeSpan(0, 5, 0))
Overtime = Overtime.Add(new TimeSpan(0, -5, 0));
Remarks = "OVERTIME";
}
return this;
}
private static bool IsWeekDay(DateTime date)
{
return date.DayOfWeek >= DayOfWeek.Monday && date.DayOfWeek <= DayOfWeek.Friday;
}
public TimeAttendance Compute()
{
var date = Date;
var timein = string.IsNullOrEmpty(EmployeeTitle) && IsWeekDay(date)
? new DateTime(date.Year, date.Month, date.Day, 8, 30, 0)
: new DateTime(date.Year, date.Month, date.Day, 9, 00, 0);
var timeout = date.DayOfWeek == DayOfWeek.Saturday
? new DateTime(date.Year, date.Month, date.Day, 12, 00, 0)
: new DateTime(date.Year, date.Month, date.Day, 17, 30, 0);
// update to grace period re: updated company policy
// starting march 15, 2016
var gracePeriod = string.IsNullOrEmpty(EmployeeTitle) && IsWeekDay(date)
? (date < new DateTime(2016, 3, 15) ? new TimeSpan(0, 10, 0) : new TimeSpan(0, 20, 0))
: new TimeSpan();
var overtime = IsWeekDay(date)
? new DateTime(date.Year, date.Month, date.Day, 19, 00, 0)
: new DateTime(date.Year, date.Month, date.Day, 14, 00, 0);
var lunch = new DateTime(date.Year, date.Month, date.Day, 12, 00, 0);
var afterLunch = new DateTime(date.Year, date.Month, date.Day, 13, 00, 0);
var remarks = new List<string>();
// 1 hour late if no timein
if (TimeIn == null)
{
TimeIn = timein.AddMinutes(60);
remarks.Add("NO TIMEIN");
}
// late if beyond grace period
if (TimeIn > timein.Add(gracePeriod))
{
Late = (TimeSpan)(TimeIn - timein);
remarks.Add("LATE");
}
// 1 hour undertime if no timeout
if (TimeOut == null && Date != DateTime.Today)
{
TimeOut = timeout.AddMinutes(-60);
remarks.Add("NO TIMEOUT");
}
if (TimeIn != null && TimeOut != null)
{
// ignore undertime for employees with the
// following title
var ignoreTitles = new[]
{
"Admin",
"Customs Rep",
"Driver"
};
// undertime
if (TimeOut < timeout)
{
if (ignoreTitles.Contains(EmployeeTitle))
{
Undertime = new TimeSpan(0, 0, 0);
remarks.Add("EARLY OUT");
}
else
{
Undertime = (TimeSpan)(timeout - TimeOut);
remarks.Add("UNDERTIME");
}
}
// compute worktime
Worktime = (TimeSpan)(TimeOut - TimeIn);
// if weekdays then deduct one hour from worktime as lunch break
if (IsWeekDay(date))
{
if (TimeOut > lunch && TimeOut < afterLunch)
{
Worktime = Worktime.Add((TimeSpan)(TimeOut - lunch));
}
if (TimeOut >= afterLunch && Worktime >= new TimeSpan(1, 0, 0))
{
Worktime -= new TimeSpan(1, 0, 0);
}
}
// overtime
if (TimeOut > overtime)
{
Overtime = (TimeSpan)(TimeOut - overtime);
// deduct 5 minutes from overtime
if (Overtime >= new TimeSpan(0, 5, 0))
Overtime = Overtime.Add(new TimeSpan(0, -5, 0));
remarks.Add("OVERTIME");
}
}
if (remarks.Any())
Remarks = string.Join(" | ", remarks);
return this;
}
}
}
|
using CommandDotNet;
using CommandDotNet.Rendering;
using System;
using System.ComponentModel.DataAnnotations;
using System.Threading;
namespace aggregator.cli.Commands.Mapping
{
[Command(Description = "Manages Aggregator Mapping in Azure DevOps.")]
public class Local
{
[Command(Description = "Lists mappings from existing Azure DevOps Projects to Aggregator Rules.")]
public void List(IConsole console, CancellationToken cancellationToken,
CommonOptions commonOpts, [Required] Credentials cred,
[Required] InstanceIdOptions instanceOpts,
[EnvVar("AGGREGATOR_PROJECT")]
[Option('p', Description = "Azure DevOps project name."), Required]
string project
)
{
Console.WriteLine($"list mappings");
}
[Command(Description = "Maps an Aggregator Rule to existing Azure DevOps Server Projects.")]
public void Add(IConsole console, CancellationToken cancellationToken,
CommonOptions commonOpts, [Required] Credentials cred,
[Required] AddMappingOptions mappingOpts,
[Option('t', Description = "Aggregator instance URL."), Required] string targetUrl)
{
Console.WriteLine($"rule added");
}
[Command(Description = "Removes a rule mapping.")]
public void Remove(IConsole console, CancellationToken cancellationToken,
CommonOptions commonOpts, [Required] Credentials cred,
[Required] AddMappingOptions mappingOpts)
{
Console.WriteLine($"rule removed");
}
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace Lauo {
static class XMLExtensions {
public static bool ReadBoolean(this XElement element, string key, bool @default = false) {
var child = element.Element(key);
return (child != null ? Boolean.Parse(child.Value) : @default);
}
public static void WriteBoolean(this XElement element, string key, bool value) {
element.SetElementValue(key, value.ToString(CultureInfo.InvariantCulture));
}
public static List<string> ReadStringList(this XElement element, string key) {
var child = element.Element(key);
List<string> results = new List<string>();
if(child != null) foreach(var el in child.Elements("s")) {
results.Add(el.Value);
}
return results;
}
public static void WriteStringList(this XElement element, string key, IEnumerable<string> values) {
var root = new XElement(key);
foreach (var el in values.Select(s => new XElement("s", s))) root.Add(el);
element.Add(root);
}
public static string ReadString(this XElement element, string key, string @default = "") {
var child = element.Element(key);
return (child != null ? child.Value : @default);
}
public static void WriteString(this XElement element, string key, string value) {
element.SetElementValue(key, value);
}
}
}
|
using System.Linq;
using BethanysPieShop.API.Models;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace BethanysPieShop.API.Controllers
{
[Route("api/[controller]")]
public class OrderController : Controller
{
private readonly AppDbContext _appDbContext;
public OrderController(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
[HttpPost]
// GET: /<controller>/
public IActionResult Add([FromBody]Order order)
{
//handling of order not fully implemented in this demo
var shoppingCart = _appDbContext.ShoppingCarts.FirstOrDefault(s => s.UserId == order.UserId);
var shoppingCartItemsToRemove =
_appDbContext.ShoppingCartItems.Where(s => s.ShoppingCartId == shoppingCart.ShoppingCartId);
_appDbContext.ShoppingCartItems.RemoveRange(shoppingCartItemsToRemove);
_appDbContext.SaveChanges();
return Ok(order);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.