text stringlengths 13 6.01M |
|---|
using UnityEditor;
using UnityEngine;
namespace Binocle
{
[InitializeOnLoad]
public class VersionControlAutomation
{
static VersionControlAutomation()
{
//If you want the scene to be fully loaded before your startup operation,
// for example to be able to use Object.FindObjectsOfType, you can defer your
// logic until the first editor update, like this:
EditorApplication.update += RunOnce;
}
static void RunOnce()
{
EditorApplication.update -= RunOnce;
ReadVersionAndIncrement();
}
static void ReadVersionAndIncrement()
{
//the file name and path. No path is the base of the Unity project directory (same level as Assets folder)
string versionTextFileNameAndPath = "version.txt";
string versionText = Utils.ReadTextFile(versionTextFileNameAndPath);
if (versionText != null)
{
versionText = versionText.Trim(); //clean up whitespace if necessary
string[] lines = versionText.Split('.');
int MajorVersion = int.Parse(lines[0]);
int MinorVersion = int.Parse(lines[1]);
int SubMinorVersion = int.Parse(lines[2]) + 1; //increment here
string SubVersionText = lines[3].Trim();
Debug.Log("Major, Minor, SubMinor, SubVerLetter: " + MajorVersion + " " + MinorVersion + " " + SubMinorVersion + " " + SubVersionText);
versionText = MajorVersion.ToString("0") + "." +
MinorVersion.ToString("0") + "." +
SubMinorVersion.ToString("000") + "." +
SubVersionText;
Debug.Log("Version Incremented " + versionText);
//save the file (overwrite the original) with the new version number
Utils.WriteTextFile(versionTextFileNameAndPath, versionText);
//save the file to the Resources directory so it can be used by Game code
Utils.WriteTextFile("Assets/Resources/version.txt", versionText);
//tell unity the file changed (important if the versionTextFileNameAndPath is in the Assets folder)
AssetDatabase.Refresh();
}
else
{
Debug.Log("Creating new default version file");
//no file at that path, make it
Utils.WriteTextFile(versionTextFileNameAndPath, "0.0.0.dev");
}
}
}
} |
using System;
using Yasl;
using UnityEngine;
using Yasl.Internal;
namespace Yasl
{
public class Texture2DSerializer : Serializer<Texture2D>
{
public Texture2DSerializer()
{
}
public override void SerializeConstructor(Texture2D value, ISerializationWriter writer)
{
writer.Write<int>("Width", value.width);
writer.Write<int>("Height", value.height);
writer.Write<TextureFormat>("Format", value.format);
}
public override void SerializeContents(Texture2D value, ISerializationWriter writer)
{
writer.Write<byte[]>("PngData", value.EncodeToPNG());
}
public override Texture2D DeserializeConstructor(int version, ISerializationReader reader)
{
var width = reader.Read<int>("Width");
var height = reader.Read<int>("Height");
var format = reader.Read<TextureFormat>("Format");
return new Texture2D(width, height, format, false);
}
public override void DeserializeContents(Texture2D value, int version, ISerializationReader reader)
{
var data = reader.Read<byte[]>("PngData");
var success = value.LoadImage(data);
Assert.That(success);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Xml;
using Framework.Db;
using Framework.Utils;
namespace Framework.Metadata
{
public class CxWinSectionsCustomizer : CxCustomizerBase
{
//-------------------------------------------------------------------------
private CxWinSectionsMetadata m_Metadata;
private IList<CxWinSectionCustomizer> m_SectionCustomizersList;
private IDictionary<string, CxWinSectionCustomizer> m_SectionCustomizers;
private CxWinSectionsCustomizerData m_CurrentData;
private CxWinSectionsCustomizerData m_InitialData;
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
/// <summary>
/// The unique identifier.
/// </summary>
public override string Id
{
get { return Metadata != null ? Metadata.ToString(): string.Empty; }
}
//-------------------------------------------------------------------------
/// <summary>
/// Current data snapshot, non-saved data.
/// </summary>
public CxWinSectionsCustomizerData CurrentData
{
get { return m_CurrentData; }
set { m_CurrentData = value; }
}
//-------------------------------------------------------------------------
/// <summary>
/// Initial data snapshot, the data which is actually applied to the application.
/// </summary>
public CxWinSectionsCustomizerData InitialData
{
get { return m_InitialData; }
set { m_InitialData = value; }
}
//-------------------------------------------------------------------------
/// <summary>
/// The metadata object the customizer belongs to.
/// </summary>
public CxWinSectionsMetadata Metadata
{
get { return m_Metadata; }
set { m_Metadata = value; }
}
//-------------------------------------------------------------------------
public IList<CxWinSectionCustomizer> SectionCustomizersList
{
get { return m_SectionCustomizersList; }
set { m_SectionCustomizersList = value; }
}
//-------------------------------------------------------------------------
public IDictionary<string, CxWinSectionCustomizer> SectionCustomizers
{
get { return m_SectionCustomizers; }
set { m_SectionCustomizers = value; }
}
//-------------------------------------------------------------------------
#region Ctors
//-------------------------------------------------------------------------
/// <summary>
/// Constructor.
/// </summary>
public CxWinSectionsCustomizer(CxCustomizationManager manager, CxWinSectionsMetadata metadata, IxCustomizationContext context)
: base(manager)
{
Metadata = metadata;
Context = context;
SectionCustomizersList = new List<CxWinSectionCustomizer>();
SectionCustomizers = new Dictionary<string, CxWinSectionCustomizer>();
Initialize();
}
//-------------------------------------------------------------------------
#endregion
//-------------------------------------------------------------------------
/// <summary>
/// Initialize sections customizer.
/// </summary>
private void Initialize()
{
InitializeSectionCustomizers();
// Initializing the Current Data
CurrentData = new CxWinSectionsCustomizerData(this);
CurrentData.InitializeFromMetadata();
// Setting the current data as the initial one.
InitialData = CurrentData.Clone();
}
//-------------------------------------------------------------------------
/// <summary>
/// Initialize list of section customizer.
/// </summary>
private void InitializeSectionCustomizers()
{
SectionCustomizers.Clear();
foreach (CxWinSectionMetadata section in Metadata.AllItemsList)
{
CxWinSectionCustomizer sectionCustomizer =
new CxWinSectionCustomizer(this, section);
SectionCustomizersList.Add(sectionCustomizer);
SectionCustomizers.Add(section.Id, sectionCustomizer);
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Resets customizer data to defaults.
/// </summary>
public override void ResetToDefault()
{
base.ResetToDefault();
CxWinSectionOrder order = Metadata.WinSectionOrder;
order.ResetToDefault();
CurrentData.VisibleOrder.Clear();
foreach (string id in order.OrderIds)
{
CurrentData.VisibleOrder.Add(SectionCustomizers[id]);
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Applies latest version of the customization to the current metadata.
/// </summary>
public override bool ApplyToMetadata()
{
base.ApplyToMetadata();
CxWinSectionOrder orderSection = Metadata.WinSectionOrder;
if (!CxList.CompareOrdered(
CurrentData.VisibleOrder.ToStringList(),
orderSection.XmlOrderIds))
{
orderSection.SetCustomOrder(
CxText.ComposeCommaSeparatedString(CurrentData.VisibleOrder.ToStringList()));
}
else
{
orderSection.SetCustomOrder(null);
}
foreach (CxWinSectionCustomizer sectionCustomizer in SectionCustomizersList)
{
sectionCustomizer.ApplyToMetadata();
}
return true;
}
//-------------------------------------------------------------------------
/// <summary>
/// Saves customization data to the database.
/// </summary>
/// <param name="connection">database connection</param>
public void Save(CxDbConnection connection)
{
SaveData(connection);
SaveLocalization(connection);
}
//-------------------------------------------------------------------------
private void SaveData(CxDbConnection connection)
{
if (GetIsModifiedData())
{
DbInsertOrUpdate(connection);
foreach (CxWinSectionCustomizer sectionCustomizer in SectionCustomizersList)
{
sectionCustomizer.SaveData(connection);
}
InitialData = CurrentData.Clone();
}
}
//-------------------------------------------------------------------------
private void SaveLocalization(CxDbConnection connection)
{
foreach (CxWinSectionCustomizer sectionCustomizer in SectionCustomizersList)
{
sectionCustomizer.SaveLocalization(connection);
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Indicates whether the customizer has been modified somehow.
/// </summary>
/// <returns>true if modified, otherwise false</returns>
public bool GetIsModifiedData()
{
bool isModified = !CurrentData.Compare(InitialData);
if (!isModified)
{
foreach (CxWinSectionCustomizer sectionCustomizer in SectionCustomizersList)
{
if (sectionCustomizer.GetIsModifiedData())
{
isModified = true;
break;
}
}
}
return isModified;
}
//-------------------------------------------------------------------------
public void InitializeForLanguage(string languageCd)
{
foreach (CxWinSectionCustomizer sectionCustomizer in SectionCustomizersList)
{
sectionCustomizer.CurrentLocalization.InitializeForLanguage(languageCd);
sectionCustomizer.InitialLocalization.InitializeForLanguage(languageCd);
}
}
//-------------------------------------------------------------------------
#region Database related
//-------------------------------------------------------------------------
/// <summary>
/// Returns value provider for a data operation.
/// </summary>
/// <returns></returns>
protected override IxValueProvider GetValueProvider()
{
CxHashtable provider = new CxHashtable();
provider["ApplicationCd"] = Metadata.Holder.ApplicationCode;
provider["MetadataObjectId"] = "singleton";
provider["MetadataObjectTypeCd"] = "win_sections";
CxXmlRenderedObject renderedObject = Metadata.RenderToXml(new XmlDocument(), true, null);
provider["MetadataContent"] = renderedObject.ToString();
return provider;
}
//-------------------------------------------------------------------------
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace Zealous.Models
{
public class AspNetUsers
{
public string Id { get; set; }
public string Email { get; set; }
public byte Status { get; set; }
[NotMapped]
public string StatusName { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.cs;
namespace Simple_VM {
public class Program {
static void Main(string[] args) {
Dictionary<string, IInstruction> instructionTypes = new Dictionary<string, IInstruction>();
/*/ for every iinstruction instance in file
instructiontypes.add(x.operator, x);
end
/*/
// the main Script
string assembly = @"
SET x, 1000
GET x
ADD x, 5
SUB x, 3
MUL x, 1
DIV x, 8
PRINT x
";
// lets get rid of those disgusting commas.
assembly = assembly.Replace(",", "");
List<string> bytecode = new List<string>();
char[] newLine = Environment.NewLine.ToCharArray();
foreach (string line in assembly.Split(newLine)) {
// we want to know whats inbetween the spaces so we can parse to byte code :)
string[] instruction = line.Split(' ');
// Operator
IInstruction i = instructionTypes[instruction[0]];
bytecode.Add(Convert.ToString(i.bytecode,2));
for (int j = 0; j < i.paramCount; j++) {
//byte[] l = Encoding.ASCII.GetBytes()
//bytecode.Add(binary);
}
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Enumerables
{
class Aula : IEnumerable<Alumno>
{
private List<Alumno> lista = new List<Alumno>();
private string _Nombre;
public string Nombre
{
get { return _Nombre; }
set { _Nombre = value; }
}
private int _Capacidad;
public int Capacidad
{
get { return _Capacidad; }
set { _Capacidad = value; }
}
public void Matricular(Alumno chicoIa)
{
if(lista.Count + 1 <= this.Capacidad)
{
lista.Add(chicoIa);
}
else
{
throw new Exception("Has superado la capacidad.");
}
}
public void Expulsar(Alumno chicoIa)
{
lista.Remove(chicoIa);
}
public IEnumerator<Alumno> GetEnumerator()
{
return ((IEnumerable<Alumno>)lista).GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<Alumno>)lista).GetEnumerator();
}
public Alumno this[int index]
{
get { return lista[index]; }
set { /*lista.Insert(index, value);*/ lista[index] = value; }
}
public static Aula operator +(Aula Aula1, Alumno alumno)
{
Aula1.Matricular(alumno);
return Aula1;
}
public static Aula operator +(Aula Aula1, Aula Aula2)
{
if (Aula2.lista.Count + Aula1.lista.Count < Aula1.Capacidad)
{
foreach (Alumno alumno in Aula2)
{
Aula1.Matricular(alumno);
}
}
return Aula1;
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace OpcClient
{
using System.IO;
using System.Linq;
using System.Threading;
using static OpcApplicationConfiguration;
using static Program;
/// <summary>
/// Class for the applications internal OPC relevant configuration.
/// </summary>
public static class OpcConfiguration
{
/// <summary>
/// list of all OPC sessions to manage
/// </summary>
public static List<OpcSession> OpcSessions { get; set; }
/// <summary>
/// Semaphore to protect access to the OPC sessions list.
/// </summary>
public static SemaphoreSlim OpcSessionsListSemaphore { get; set; }
/// <summary>
/// Semaphore to protect the access to the action list.
/// </summary>
public static SemaphoreSlim OpcActionListSemaphore { get; set; }
/// <summary>
/// Filename of the configuration file.
/// </summary>
public static string OpcActionConfigurationFilename { get; set; } = $"{System.IO.Directory.GetCurrentDirectory()}{Path.DirectorySeparatorChar}actionconfig.json";
/// <summary>
/// Reports number of OPC sessions.
/// </summary>
public static int NumberOfOpcSessions
{
get
{
int result = 0;
try
{
OpcSessionsListSemaphore.Wait();
result = OpcSessions.Count();
}
finally
{
OpcSessionsListSemaphore.Release();
}
return result;
}
}
/// <summary>
/// Reports number of connected OPC sessions.
/// </summary>
public static int NumberOfConnectedOpcSessions
{
get
{
int result = 0;
try
{
OpcSessionsListSemaphore.Wait();
result = OpcSessions.Count(s => s.State == OpcSession.SessionState.Connected);
}
finally
{
OpcSessionsListSemaphore.Release();
}
return result;
}
}
/// <summary>
/// Reports number of configured recurring actions.
/// </summary>
public static int NumberOfRecurringActions
{
get
{
int result = 0;
try
{
OpcSessionsListSemaphore.Wait();
result = OpcSessions.Where(s => s.OpcActions.Count > 0).Select(s => s.OpcActions).Sum(a => a.Count(i => i.Interval > 0));
}
finally
{
OpcSessionsListSemaphore.Release();
}
return result;
}
}
/// <summary>
/// Reports number of all actions.
/// </summary>
public static int NumberOfActions
{
get
{
int result = 0;
try
{
OpcSessionsListSemaphore.Wait();
result = OpcSessions.Select(s => s.OpcActions).Sum(a => a.Count());
}
finally
{
OpcSessionsListSemaphore.Release();
}
return result;
}
}
/// <summary>
/// Initialize resources for the configuration management.
/// </summary>
public static void Init()
{
OpcSessionsListSemaphore = new SemaphoreSlim(1);
OpcSessions = new List<OpcSession>();
OpcActionListSemaphore = new SemaphoreSlim(1);
OpcSessions = new List<OpcSession>();
_actionConfiguration = new List<OpcActionConfigurationModel>();
}
/// <summary>
/// Frees resources for configuration management.
/// </summary>
public static void Deinit()
{
OpcSessions = null;
OpcSessionsListSemaphore.Dispose();
OpcSessionsListSemaphore = null;
OpcActionListSemaphore.Dispose();
OpcActionListSemaphore = null;
}
/// <summary>
/// Read and parse the startup configuration file.
/// </summary>
public static async Task<bool> ReadOpcConfigurationAsync()
{
try
{
await OpcActionListSemaphore.WaitAsync();
// if the file exists, read it, if not just continue
if (File.Exists(OpcActionConfigurationFilename))
{
Logger.Information($"Attemtping to load action configuration from: {OpcActionConfigurationFilename}");
_actionConfiguration = JsonConvert.DeserializeObject<List<OpcActionConfigurationModel>>(File.ReadAllText(OpcActionConfigurationFilename));
}
else
{
Logger.Information($"The action configuration file '{OpcActionConfigurationFilename}' does not exist. Continue...");
}
// add connectivity test action if requested
if (TestConnectivity)
{
Logger.Information($"Creating test action to test connectivity");
_actionConfiguration.Add(new OpcActionConfigurationModel(new TestActionModel()));
}
// add unsecure connectivity test action if requested
if (TestUnsecureConnectivity)
{
Logger.Information($"Creating test action to test unsecured connectivity");
_actionConfiguration.Add(new OpcActionConfigurationModel(new TestActionModel(), DefaultEndpointUrl, false));
}
}
catch (Exception e)
{
Logger.Fatal(e, "Loading of the action configuration file failed. Does the file exist and has correct syntax? Exiting...");
return false;
}
finally
{
OpcActionListSemaphore.Release();
}
Logger.Information($"There is(are) {_actionConfiguration.Sum(c => c.Read.Count + c.Test.Count)} action(s) configured.");
return true;
}
/// <summary>
/// Create the data structures to manage actions.
/// </summary>
public static async Task<bool> CreateOpcActionDataAsync()
{
try
{
await OpcActionListSemaphore.WaitAsync();
await OpcSessionsListSemaphore.WaitAsync();
// create actions out of the configuration
var uniqueSessionInfo = _actionConfiguration.Select(n => new Tuple<Uri, bool>(n.EndpointUrl, n.UseSecurity)).Distinct();
foreach (var sessionInfo in uniqueSessionInfo)
{
// create new session info.
OpcSession opcSession = new OpcSession(sessionInfo.Item1, sessionInfo.Item2, OpcSessionCreationTimeout);
// add all actions to the session
List<OpcAction> actionsOnEndpoint = new List<OpcAction>();
var endpointConfigs = _actionConfiguration.Where(c => c.EndpointUrl == sessionInfo.Item1 && c.UseSecurity == sessionInfo.Item2);
foreach (var config in endpointConfigs)
{
config?.Read.ForEach(a => opcSession.OpcActions.Add(new OpcReadAction(config.EndpointUrl, a)));
config?.Test.ForEach(a => opcSession.OpcActions.Add(new OpcTestAction(config.EndpointUrl, a)));
}
// report actions
Logger.Information($"Actions on '{opcSession.EndpointUrl.AbsoluteUri}' {(opcSession.UseSecurity ? "with" : "without")} security.");
foreach (var action in opcSession.OpcActions)
{
Logger.Information($"{action.Description}, recurring each: {action.Interval} sec");
}
// add session
OpcSessions.Add(opcSession);
}
}
catch (Exception e)
{
Logger.Fatal(e, "Creation of the internal OPC management structures failed. Exiting...");
return false;
}
finally
{
OpcSessionsListSemaphore.Release();
OpcActionListSemaphore.Release();
}
return true;
}
/// <summary>
/// Create an OPC session management data structures.
/// </summary>
private static void CreateOpcSession(Uri endpointUrl, bool useSecurity)
{
try
{
// create new session info
OpcSession opcSession = new OpcSession(endpointUrl, useSecurity, OpcSessionCreationTimeout);
// add all actions to the session
List<OpcAction> actionsOnEndpoint = new List<OpcAction>();
var endpointConfigs = _actionConfiguration.Where(c => c.EndpointUrl == endpointUrl);
foreach (var config in endpointConfigs)
{
config?.Read.ForEach(a => opcSession.OpcActions.Add(new OpcReadAction(config.EndpointUrl, a)));
config?.Test.ForEach(a => opcSession.OpcActions.Add(new OpcTestAction(config.EndpointUrl, a)));
}
}
catch (Exception e)
{
Logger.Fatal(e, "Creation of the OPC session failed.");
throw e;
}
}
private static List<OpcActionConfigurationModel> _actionConfiguration;
}
}
|
using System;
using Gtk;
using ResxEditor.Core.Interfaces;
using ResxEditor.Core.Models;
using ResxEditor.Core.Views;
using System.ComponentModel.Design;
namespace ResxEditor.Core.Controllers
{
public class ResourceController : IResourceController
{
public event EventHandler<bool> OnDirtyChanged;
public event EventHandler RemoveFailed;
ResourceHandler m_resxHandler;
public ResourceController ()
{
ResourceEditorView = new ResourceEditorView ();
StoreController = new ResourceStoreController(() => ResourceEditorView.ResourceControlBar.FilterEntry.Text);
ResourceEditorView.ResourceControlBar.FilterEntry.Changed += (_, e) => StoreController.Refilter ();
ResourceEditorView.ResourceList.OnResourceAdded += (_, e) => {
ResourceEditorView.ResourceControlBar.FilterEntry.Text = "";
StoreController.Refilter();
};
ResourceEditorView.ResourceList.RightClicked += (sender, e) => {
var selectedRows = ResourceEditorView.ResourceList.GetSelectedResource().GetSelectedRows();
if (selectedRows.Length > 0) {
var contextMenu = new CellContextMenu (this, StoreController, selectedRows);
contextMenu.Popup ();
} else {
var contextMenu = new NoCellContextMenu(this);
contextMenu.Popup ();
}
};
ResourceEditorView.ResourceList.Model = StoreController.Model;
AttachListeners ();
}
void AttachListeners () {
ResourceEditorView.OnAddResource += (_, __) => AddNewResource ();
ResourceEditorView.OnRemoveResource += (_, __) => RemoveCurrentResource ();
ResourceEditorView.ResourceList.OnNameEdited += (_, e) => {
TreeIter iter;
StoreController.GetIter(out iter, new TreePath(e.Path));
string oldName = StoreController.GetName(new TreePath(e.Path));
m_resxHandler.RemoveResource(oldName);
m_resxHandler.AddResource(e.NextText, string.Empty);
StoreController.SetName (e.Path, e.NextText);
OnDirtyChanged(this, true);
};
ResourceEditorView.ResourceList.OnValueEdited += (_, e) => {
string name = StoreController.GetName(new TreePath(e.Path));
m_resxHandler.RemoveResource(name);
m_resxHandler.AddResource(name, e.NextText);
StoreController.SetValue (e.Path, e.NextText);
OnDirtyChanged (this, true);
};
ResourceEditorView.ResourceList.OnCommentEdited += (_, e) => {
TreePath path = new TreePath(e.Path);
string name = StoreController.GetName(path);
string value = StoreController.GetValue(path);
m_resxHandler.RemoveResource(name);
m_resxHandler.AddResource(name, value, e.NextText);
StoreController.SetComment (e.Path, e.NextText);
OnDirtyChanged (this, true);
};
}
public void AddNewResource() {
TreeIter iter = StoreController.Prepend();
TreePath path = StoreController.GetPath(iter);
ResourceEditorView.ResourceList.SetCursor(path, ResourceEditorView.ResourceList.NameColumn, true);
OnDirtyChanged(this, true);
}
public void RemoveCurrentResource() {
TreePath[] selectedPaths = ResourceEditorView.ResourceList.GetSelectedResource ().GetSelectedRows ();
foreach (var selectedPath in selectedPaths) {
string name = StoreController.GetName (selectedPath);
StoreController.Remove (selectedPath);
if (m_resxHandler.RemoveResource (name) > 0) {
OnDirtyChanged (this, true);
}
}
}
public string Filename {
get;
set;
}
public IResourceListStore StoreController {
get;
set;
}
public ResourceEditorView ResourceEditorView {
get;
set;
}
public void Load (string fileName)
{
Filename = fileName;
m_resxHandler = new ResourceHandler (fileName);
m_resxHandler.Resources.ForEach ((resource) => {
if (resource.FileRef == null) {
object value = resource.GetValue((ITypeResolutionService) null);
var str = value as string;
StoreController.AppendValues (new ResourceModel (resource.Name, str, resource.Comment));
} else {
throw new NotImplementedException();
}
});
}
public void Save(string fileName) {
m_resxHandler.WriteToFile (fileName);
OnDirtyChanged(this, false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using DataAccessLayer.basis;
using Model.DataEntity;
using Model.Helper;
using Model.InvoiceManagement;
using Model.Locale;
using Model.Models.ViewModel;
using Model.Security;
using Model.Security.MembershipManagement;
using ModelExtension.Service;
using Utility;
namespace eIVOGo.Helper
{
public static class InvoiceBusinessExtensionMethods
{
public static void MarkPrintedLog<TEntity>(this GenericManager<EIVOEntityDataContext,TEntity> models,InvoiceItem item,UserProfileMember profile)
where TEntity : class, new()
{
models.MarkPrintedLog(item, profile.UID);
}
public static void MarkPrintedLog<TEntity>(this GenericManager<EIVOEntityDataContext, TEntity> models, InvoiceAllowance item, UserProfileMember profile)
where TEntity : class, new()
{
models.MarkPrintedLog(item, profile.UID);
}
public static IQueryable<InvoiceItem> FilterInvoiceByRole(this GenericManager<EIVOEntityDataContext> models, UserProfileMember profile, IQueryable<InvoiceItem> items)
{
return models.DataContext.FilterInvoiceByRole(profile, items);
}
public static IQueryable<InvoiceItem> FilterInvoiceByRole(this EIVOEntityDataContext models, UserProfileMember profile, IQueryable<InvoiceItem> items)
{
switch ((Naming.CategoryID)profile.CurrentUserRole.OrganizationCategory.CategoryID)
{
case Naming.CategoryID.COMP_SYS:
case Naming.CategoryID.COMP_WELFARE:
return items;
case Naming.CategoryID.COMP_INVOICE_AGENT:
return models.GetInvoiceByAgent(items, profile.CurrentUserRole.OrganizationCategory.CompanyID);
case Naming.CategoryID.COMP_E_INVOICE_GOOGLE_TW:
case Naming.CategoryID.COMP_E_INVOICE_B2C_SELLER:
return items.Where(i => i.SellerID == profile.CurrentUserRole.OrganizationCategory.CompanyID);
case Naming.CategoryID.COMP_E_INVOICE_B2C_BUYER:
return items.Where(i => i.InvoiceBuyer.BuyerID == profile.CurrentUserRole.OrganizationCategory.CompanyID);
default:
return items.Where(i => i.SellerID == profile.CurrentUserRole.OrganizationCategory.CompanyID
|| i.InvoiceBuyer.BuyerID == profile.CurrentUserRole.OrganizationCategory.CompanyID);
}
}
public static IQueryable<Organization> FilterOrganizationByRole(this EIVOEntityDataContext models, UserProfileMember profile, IQueryable<Organization> items = null)
{
if(items == null)
{
items = models.GetTable<Organization>();
}
switch ((Naming.CategoryID)profile.CurrentUserRole.OrganizationCategory.CategoryID)
{
case Naming.CategoryID.COMP_SYS:
return items;
case Naming.CategoryID.COMP_INVOICE_AGENT:
var issuers = models.GetTable<InvoiceIssuerAgent>().Where(a => a.AgentID == profile.CurrentUserRole.OrganizationCategory.CompanyID);
return items.Where(i => i.CompanyID == profile.CurrentUserRole.OrganizationCategory.CompanyID
|| issuers.Any(a => a.IssuerID == i.CompanyID));
case Naming.CategoryID.COMP_E_INVOICE_GOOGLE_TW:
case Naming.CategoryID.COMP_E_INVOICE_B2C_BUYER:
case Naming.CategoryID.COMP_WELFARE:
default:
return items.Where(i => i.CompanyID == profile.CurrentUserRole.OrganizationCategory.CompanyID);
}
}
public static IQueryable<InvoiceAllowance> FilterAllowanceByRole(this GenericManager<EIVOEntityDataContext> models, UserProfileMember profile, IQueryable<InvoiceAllowance> items)
{
return models.DataContext.FilterAllowanceByRole(profile, items);
}
public static IQueryable<InvoiceAllowance> FilterAllowanceByRole(this EIVOEntityDataContext models, UserProfileMember profile, IQueryable<InvoiceAllowance> items)
{
switch ((Naming.CategoryID)profile.CurrentUserRole.OrganizationCategory.CategoryID)
{
case Naming.CategoryID.COMP_SYS:
case Naming.CategoryID.COMP_WELFARE:
return items;
case Naming.CategoryID.COMP_INVOICE_AGENT:
case Naming.CategoryID.COMP_E_INVOICE_GOOGLE_TW:
return models.GetAllowanceByAgent(items, profile.CurrentUserRole.OrganizationCategory.CompanyID);
case Naming.CategoryID.COMP_E_INVOICE_B2C_BUYER:
return items.Where(i => i.InvoiceAllowanceBuyer.BuyerID == profile.CurrentUserRole.OrganizationCategory.CompanyID);
default:
return items.Where(i => i.InvoiceAllowanceSeller.SellerID == profile.CurrentUserRole.OrganizationCategory.CompanyID
|| i.InvoiceAllowanceBuyer.BuyerID == profile.CurrentUserRole.OrganizationCategory.CompanyID);
}
}
public static IQueryable<ProcessRequest> FilterProcessRequestByRole(this EIVOEntityDataContext models, UserProfileMember profile, IQueryable<ProcessRequest> items)
{
switch ((Naming.CategoryID)profile.CurrentUserRole.OrganizationCategory.CategoryID)
{
case Naming.CategoryID.COMP_SYS:
return items;
default:
var agentID = profile.CurrentUserRole.OrganizationCategory.CompanyID;
var issuers = models.GetTable<InvoiceIssuerAgent>().Where(a => a.AgentID == agentID)
.Select(a => a.IssuerID);
return items.Where(i => i.AgentID == agentID
|| issuers.Any(a => i.AgentID == a));
}
}
public static IQueryable<ProductCatalog> FilterProductCatalogByRole(this EIVOEntityDataContext models, UserProfileMember profile, IQueryable<ProductCatalog> items)
{
switch ((Naming.CategoryID)profile.CurrentUserRole.OrganizationCategory.CategoryID)
{
case Naming.CategoryID.COMP_SYS:
return items;
default:
var agentID = profile.CurrentUserRole.OrganizationCategory.CompanyID;
return items.Where(i => i.ProductSupplier.Any(s => s.SupplierID == agentID));
}
}
public static List<InvoiceNoAllocation> AllocateInvoiceNo(this GenericManager<EIVOEntityDataContext> models, POSDeviceViewModel viewModel)
{
List<InvoiceNoAllocation> items = new List<InvoiceNoAllocation>();
//receiptNo = receiptNo.GetEfficientString();
var seller = models.GetTable<Organization>().Where(c => c.ReceiptNo == viewModel.company_id).FirstOrDefault();
bool auth = true;
if (seller != null)
{
if (viewModel.Seed != null && viewModel.Authorization != null)
{
auth = models.CheckAuthToken(seller, viewModel) != null;
}
if (auth)
{
try
{
using (TrackNoManager mgr = new TrackNoManager(models, seller.CompanyID))
{
for (int i = 0; i < viewModel.quantity; i++)
{
var item = mgr.AllocateInvoiceNo();
if (item == null)
break;
item.RandomNo = String.Format("{0:0000}", (DateTime.Now.Ticks % 10000));
item.EncryptedContent = String.Concat(item.InvoiceNoInterval.InvoiceTrackCodeAssignment.InvoiceTrackCode.TrackCode,
String.Format("{0:00000000}", item.InvoiceNo),
item.RandomNo).EncryptContent();
models.SubmitChanges();
items.Add(item);
}
mgr.Close();
}
}
catch(Exception ex)
{
Logger.Error(ex);
}
}
}
return items;
}
public static bool CheckAvailableInterval(this GenericManager<EIVOEntityDataContext> models, POSDeviceViewModel viewModel,out String reason)
{
reason = null;
var seller = models.GetTable<Organization>().Where(c => c.ReceiptNo == viewModel.company_id).FirstOrDefault();
bool auth = true;
if (seller != null)
{
if (viewModel.Seed != null && viewModel.Authorization != null)
{
auth = models.CheckAuthToken(seller, viewModel) != null;
}
if (auth)
{
try
{
using (TrackNoManager mgr = new TrackNoManager(models, seller.CompanyID))
{
if(!mgr.PeekInvoiceNo().HasValue)
{
auth = false;
reason = "inovice no not available!";
}
}
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
else
{
reason = "auth failed!";
}
}
return auth;
}
}
} |
//
// - PropertyTreeSource{T}.cs -
//
// Copyright 2012 Carbonfrost Systems, Inc. (http://carbonfrost.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.IO;
namespace Carbonfrost.Commons.PropertyTrees {
public class PropertyTreeSource<T> : PropertyTreeSource {
public override object Load(TextReader reader, Type instanceType) {
if (instanceType == null) {
instanceType = typeof(T);
}
return base.Load(reader, instanceType);
}
public override void Save(System.IO.TextWriter writer, object value) {
if (value is T)
base.Save(writer, value);
else
throw new NotImplementedException();
}
}
}
|
using KPI.Model.DAO;
using KPI.Model.EF;
using KPI.Model.ViewModel;
using MvcBreadCrumbs;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace KPI.Web.Controllers
{
[BreadCrumb(Clear = true)]
public class AdminLevelController : BaseController
{
[BreadCrumb(Clear = true)]
public ActionResult Index()
{
BreadCrumb.Add(Url.Action("Index", "Home"), "Home");
BreadCrumb.SetLabel("OC");
var user = (UserProfileVM)Session["UserProfile"];
if (user.User.Permission == 1)
{
return View();
}
else
{
return Redirect("~/Error/NotFound");
}
}
public async Task<JsonResult> GetListTree()
{
return Json(await new LevelDAO().GetListTree(), JsonRequestBehavior.AllowGet);
}
public async Task<JsonResult> AddOrUpdate(Level entity)
{
return Json(await new LevelDAO().AddOrUpdate(entity), JsonRequestBehavior.AllowGet);
}
public async Task<JsonResult> GetByID(int id)
{
//string Code = JsonConvert.SerializeObject(code);
return Json(await new LevelDAO().GetByID(id), JsonRequestBehavior.AllowGet);
}
public async Task<JsonResult> Rename(LevelActionVM level)
{
//string Code = JsonConvert.SerializeObject(code);
return Json(await new LevelDAO().Rename(level), JsonRequestBehavior.AllowGet);
}
public async Task<JsonResult> Remove(int id)
{
//string Code = JsonConvert.SerializeObject(code);
return Json(await new LevelDAO().Remove(id), JsonRequestBehavior.AllowGet);
}
public async Task<JsonResult> Add(Level level)
{
return Json(await new LevelDAO().Add(level), JsonRequestBehavior.AllowGet);
}
}
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Schema;
using MyCouch;//https://github.com/danielwertheim/mycouch
using performanceTest.Models;
namespace couchDBCsharp
{
class Program
{
static void Main(string[] args) {
var sw = Stopwatch.StartNew();
Task.Run(async () => {
var client = new MyCouchClient("http://localhost:5984/", "test");
var json = JsonConvert.SerializeObject(new Person());
await client.Documents.PostAsync(json);//newtonsoft.json
}).Wait();
sw.Stop();
Console.WriteLine($"elapsed time {sw.Elapsed}");
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Web.Identity;
namespace Web.Models
{
public class ScoRecord
{
public int Id { get; set; }
[MaxLength(50)]
public string Title { get; set; }
public int EnrollmentId { get; set; }
//[Required]
public virtual Enrollment Enrollment { get; set; }
[MaxLength(10)]
public string CatalogueNumber { get; set; }
public bool IsEnabled { get; set; }
public bool IsCompleted { get; set; }
public string ActorId { get; set; }
public ApplicationUser Actor { get; set; }
[Column(TypeName = "DateTime2")]
public DateTime TimeStamp { get; set; }
[Column(TypeName = "DateTime2")]
public DateTime Stored { get; set; }
//public int CourseScoId { get; set; }
//public CourseSco CourseSco { get; set; }
public int ScoId { get; set; }
public Sco Sco { get; set; }
public int CourseId { get; set; }
public Course Course { get; set; }
public int CourseTemplateId { get; set; }
[MaxLength(50)]
public string ScormName { get; set; }
public string ScormValue { get; set; }
[MaxLength(25)]
public string LessonStatus { get; set; }
[Column(TypeName = "DateTime2")]
public DateTime LastClosed { get; set; }
public int RequiredScoId { get; set; }
public decimal Score { get; set; }
public bool IsFinalExam { get; set; }
public string CurrentScoValue { get; set; }
//For EF...
public ScoRecord()
{
}
public ScoRecord(ApplicationUser actor, Sco sco, Course course, string scormName, string scormValue, string catalogueNumber)
{
Actor = actor;
Sco = sco;
//Course = course;
ScormName = scormName;
ScormValue = scormValue;
CatalogueNumber = catalogueNumber;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ECommerceApp.Core.Interfaces;
namespace ECommerceApp.Core.Models
{
public class Category : IEntity
{
public Guid Id { get; set; }
[Required]
[MaxLength(100)]
public string CategoryName { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[ForeignKey("Catalog")]
public Guid CatalogId { get; set; }
public virtual Catalog Catalog { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
}
|
using Logging.Core.DataAccess;
using Logging.DataAccess.Abstract;
using Logging.DataAccess.Concrete.Context;
using Logging.Entities;
using Logging.Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Text;
namespace Logging.DataAccess.Concrete
{
public class InstructorDal : EntityRepositoryBase<Instructor, OnlineExaminationSystemContext>, IInstructorDal
{
}
}
|
using LuigiApp.Client.ViewModels;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace LuigiApp.Client.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ClientsPage : ContentPage
{
ClientsViewModel viewModel;
public ClientsPage()
{
InitializeComponent();
BindingContext = viewModel = new ClientsViewModel();
}
protected override void OnAppearing()
{
viewModel.OnAppearing();
base.OnAppearing();
}
}
} |
using Contoso.Spa.Flow.Requests;
using System;
namespace Contoso.Spa.Flow.Dialogs
{
public class DetailDialogHandler : BaseDialogHandler
{
public override void Complete(IFlowManager flowManager, RequestBase request)
{
if (request.CommandButtonRequest == null)
throw new ArgumentException($"{nameof(request.CommandButtonRequest)}: {{59B88099-D16F-4C53-8E2D-0E352E40D210}}");
if (request is not DetailRequest detailRequest)
throw new ArgumentException($"{nameof(request)}: {{F63094B0-F9C6-4AA1-B896-002B372E5690}}");
if (!request.CommandButtonRequest.Cancel
&& detailRequest.Entity != null)
{
flowManager.FlowDataCache.Items[detailRequest.Entity.GetType().FullName ?? throw new ArgumentException($"{nameof(request)}: {{07006628-25D9-46D2-8A6D-91BD3BD276E7}}")] = detailRequest.Entity;
}
base.Complete(flowManager, request);
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
using Newtonsoft.Json;
namespace Dnn.PersonaBar.SiteSettings.Services.Dto
{
[JsonObject]
public class LocalizationEntry
{
public string Name { get; set; }
public string DefaultValue { get; set; }
public string NewValue { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace PhonemesAndStuff
{
public class PhoneInWordSupporter
{
public int PhonePosition { get; set; }
public int WordID { get; set; }
public PhoneInWordSupporter()
{
}
}
}
|
using CVBuilder.Core.Models;
using FluentValidation;
namespace CVBuilder.Core.Validators
{
/// <summary>
/// Address Validator implemented with Fluent validation
/// This is a example of how we can do, the example is not complete.
/// </summary>
public class AddressValidator : AbstractValidator<Address>
{
public AddressValidator()
{
RuleFor(x => x.Country).Must(BeAValidPostcode).WithMessage("Please specify a Country");
RuleFor(x => x.County).NotEmpty().WithMessage("Please specify a County");
RuleFor(x => x.City).NotEqual(string.Empty).When(x => x.Street == null);
RuleFor(x => x.Street).Length(20, 250);
RuleFor(x => x.StreetNumber).Length(20, 250).WithMessage("Please specify a valid streetNumber");
RuleFor(x => x.PostalCode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
}
private bool BeAValidPostcode(string postcode)
{
// custom postcode validating logic goes here
return !string.IsNullOrEmpty(postcode);
}
private bool BeAValidCountry(string country)
{
// custom country validating logic goes here
// all countries are available throw an api, we can check if the name is into the list.
return !string.IsNullOrEmpty(country);
}
}
}
|
using UnityEngine;
using System.Collections;
public class Walk : AbstractBehavior {
public float speed = 50f;
public float runMultiplier = 2f;
public bool running;
//public PlayerAttack attacking;
//public bool isAttacking;
//public GameObject Player;
//protected override void Awake() {
// Player = GameObject.FindGameObjectWithTag("Player");
//attacking = Player.GetComponent<PlayerAttack>();
//}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
running = false;
var right = inputState.GetButtonValue(inputButtons[0]);
var left = inputState.GetButtonValue(inputButtons[1]);
//isAttacking = PlayerAttack.attacking;
if (right || left) {
var velX = speed * (float)inputState.direction;
body2d.velocity = new Vector2(velX, body2d.velocity.y);
}
else if (collisionState.standing){
body2d.velocity = new Vector2(0, body2d.velocity.y);
}
}
}
|
using System;
using System.Collections.Generic;
namespace SheMediaConverterClean.Infra.Data.Models
{
public partial class DynBelegProperties
{
public int BelegId { get; set; }
public int BenutzerId { get; set; }
public string AblagePfad { get; set; }
public string PropertyKey { get; set; }
public string PropertyValue { get; set; }
}
}
|
using Microsoft.WindowsAzure.Storage.Blob;
namespace Microsoft.DataStudio.Services.Data.Models.Solutions
{
internal class NativeSolution : Solution
{
public CloudBlobContainer Container { get; set; }
public string BlobName { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraController : MonoBehaviour
{
//camera look at variables
public Transform target;
public Vector3 offset;
public bool useOffsetValues;
//camera rotation variables
public float rotateSpeed;
public Transform pivot;
void Start ()
{
if (!useOffsetValues)
{
//camera position offset
offset = target.position - transform.position;
}
pivot.transform.position = target.transform.position;
pivot.transform.parent = target.transform;
Cursor.lockState = CursorLockMode.Locked;
}
void LateUpdate ()
{
//Get the X position of the mouse & rotate target
float horizontal = Input.GetAxis ("Mouse X") * rotateSpeed;
target.Rotate (0, horizontal, 0);
//get the Y position of Mouse & rotate the pivot
float vertical = Input.GetAxis("Mouse Y") * rotateSpeed;
pivot.Rotate (-vertical, 0, 0);
//limit up & down camera rotation
if (pivot.rotation.eulerAngles.x > 80f && pivot.rotation.eulerAngles.x < 180)
{
pivot.rotation = Quaternion.Euler (80f, 0, 0);
}
if (pivot.rotation.eulerAngles.x > 180 && pivot.rotation.eulerAngles.x < 315)
{
pivot.rotation = Quaternion.Euler (315f, 0, 0);
}
//move the camera based on current target rotation & offset
float desiredYAngle = target.eulerAngles.y;
float desiredXAngle = pivot.eulerAngles.x;
Quaternion rotation = Quaternion.Euler (desiredXAngle, desiredYAngle, 0);
transform.position = target.position - (rotation * offset);
if (transform.position.y < target.position.y)
{
transform.position = new Vector3 (transform.position.x, target.position.y, transform.position.z);
}
//camera position from player, look at the player
transform.LookAt (target);
}
}
|
namespace TreeStore.Model
{
public enum FacetPropertyTypeValues
{
String = 0,
Long = 1,
Double = 2,
Decimal = 3,
DateTime = 4,
Guid = 5,
Bool = 6
}
} |
namespace Athena.Data.SpreadsheetData {
public class SpreadsheetCategoryData {
public string Colour { get; set; }
public string Name { get; set; }
}
} |
using LuaInterface;
using RO;
using SLua;
using System;
public class Lua_RO_DateTimeHelper : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int IsCurTimeInRegion_s(IntPtr l)
{
int result;
try
{
string startStrTime;
LuaObject.checkType(l, 1, out startStrTime);
string endStrTime;
LuaObject.checkType(l, 2, out endStrTime);
bool b = DateTimeHelper.IsCurTimeInRegion(startStrTime, endStrTime);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, b);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetTimeProgressInDay_s(IntPtr l)
{
int result;
try
{
int num = LuaDLL.lua_gettop(l);
if (num == 0)
{
float timeProgressInDay = DateTimeHelper.GetTimeProgressInDay();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, timeProgressInDay);
result = 2;
}
else if (num == 1)
{
float secondsInDay;
LuaObject.checkType(l, 1, out secondsInDay);
float timeProgressInDay2 = DateTimeHelper.GetTimeProgressInDay(secondsInDay);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, timeProgressInDay2);
result = 2;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int DateTimeToTimeStamp_s(IntPtr l)
{
int result;
try
{
DateTime dateTime;
LuaObject.checkValueType<DateTime>(l, 1, out dateTime);
long i = DateTimeHelper.DateTimeToTimeStamp(dateTime);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, i);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int FormatTimeTick_s(IntPtr l)
{
int result;
try
{
long secendStamp;
LuaObject.checkType(l, 1, out secendStamp);
string format;
LuaObject.checkType(l, 2, out format);
string s = DateTimeHelper.FormatTimeTick(secendStamp, format);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, s);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int IsTimeInRegionByDeltaDay_s(IntPtr l)
{
int result;
try
{
string startStrTime;
LuaObject.checkType(l, 1, out startStrTime);
long secendStamp;
LuaObject.checkType(l, 2, out secendStamp);
int deltaDay;
LuaObject.checkType(l, 3, out deltaDay);
bool b = DateTimeHelper.IsTimeInRegionByDeltaDay(startStrTime, secendStamp, deltaDay);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, b);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SysNow_s(IntPtr l)
{
int result;
try
{
DateTime dateTime = DateTimeHelper.SysNow();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, dateTime);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_MINUTES_AN_HOUR(IntPtr l)
{
int result;
try
{
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, 60f);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_SECONDS_A_MINUTE(IntPtr l)
{
int result;
try
{
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, 60f);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_HOURS_A_DAY(IntPtr l)
{
int result;
try
{
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, 24f);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_SECONDS_AN_HOUR(IntPtr l)
{
int result;
try
{
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, 3600f);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_MINUTES_A_DAY(IntPtr l)
{
int result;
try
{
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, 1440f);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_SECONDS_A_DAY(IntPtr l)
{
int result;
try
{
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, 86400f);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "RO.DateTimeHelper");
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_DateTimeHelper.IsCurTimeInRegion_s));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_DateTimeHelper.GetTimeProgressInDay_s));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_DateTimeHelper.DateTimeToTimeStamp_s));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_DateTimeHelper.FormatTimeTick_s));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_DateTimeHelper.IsTimeInRegionByDeltaDay_s));
LuaObject.addMember(l, new LuaCSFunction(Lua_RO_DateTimeHelper.SysNow_s));
LuaObject.addMember(l, "MINUTES_AN_HOUR", new LuaCSFunction(Lua_RO_DateTimeHelper.get_MINUTES_AN_HOUR), null, false);
LuaObject.addMember(l, "SECONDS_A_MINUTE", new LuaCSFunction(Lua_RO_DateTimeHelper.get_SECONDS_A_MINUTE), null, false);
LuaObject.addMember(l, "HOURS_A_DAY", new LuaCSFunction(Lua_RO_DateTimeHelper.get_HOURS_A_DAY), null, false);
LuaObject.addMember(l, "SECONDS_AN_HOUR", new LuaCSFunction(Lua_RO_DateTimeHelper.get_SECONDS_AN_HOUR), null, false);
LuaObject.addMember(l, "MINUTES_A_DAY", new LuaCSFunction(Lua_RO_DateTimeHelper.get_MINUTES_A_DAY), null, false);
LuaObject.addMember(l, "SECONDS_A_DAY", new LuaCSFunction(Lua_RO_DateTimeHelper.get_SECONDS_A_DAY), null, false);
LuaObject.createTypeMetatable(l, null, typeof(DateTimeHelper));
}
}
|
using FluentValidation;
namespace DDDSouthWest.Domain.Features.Account.Speaker.ManageTalks.AddNewTalk
{
public class AddNewTalkValidator : AbstractValidator<AddNewTalk.Command>
{
public AddNewTalkValidator()
{
RuleFor(x => x.TalkTitle).NotEmpty();
RuleFor(x => x.TalkSummary).NotEmpty().WithMessage("'Short Abstract' must not be empty");
RuleFor(x => x.TalkBodyMarkdown).NotEmpty().WithMessage("'Long' Abstract' must not be empty");
}
}
} |
/********************************************************************
* FulcrumWeb RAD Framework - Fulcrum of your business *
* Copyright (c) 2002-2010 FulcrumWeb, ALL RIGHTS RESERVED *
* *
* THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED *
* FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE *
* COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE *
* AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT *
* AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE *
* AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. *
********************************************************************/
using System;
using System.Collections.Generic;
using System.Xml;
using Framework.Utils;
namespace Framework.Metadata
{
public class CxSlTreeItemMetadata: CxMetadataObject
{
//-------------------------------------------------------------------------
protected CxSlSectionMetadata m_Section = null;
protected CxSlTreeItemsMetadata m_Items = null;
protected CxSlTreeItemMetadata m_ProviderItem = null;
protected object m_Tag = null;
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
/// <summary>
/// Constructor
/// </summary>
/// <param name="holder">parent metadata holder object</param>
/// <param name="section">parent section</param>
/// <param name="id">tree item id</param>
public CxSlTreeItemMetadata(
CxMetadataHolder holder,
CxSlSectionMetadata section,
string id)
: base(holder)
{
Id = id;
m_Section = section;
m_Section.RegisterTreeItem(this);
m_Items = new CxSlTreeItemsMetadata(Holder, Section);
}
//-------------------------------------------------------------------------
/// <summary>
/// Constructor
/// </summary>
/// <param name="holder">parent metadata holder object</param>
/// <param name="section">parent section</param>
/// <param name="element">XML element to load data from</param>
public CxSlTreeItemMetadata(
CxMetadataHolder holder,
CxSlSectionMetadata section,
XmlElement element)
: base(holder, element)
{
m_Section = section;
m_Section.RegisterTreeItem(this);
m_Items = new CxSlTreeItemsMetadata(Holder, Section, element);
}
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
/// <summary>
/// Returns ID of the entity usage linked to the tree node.
/// </summary>
public string EntityUsageId
{
get
{
return this["entity_usage_id"];
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Corresponding entity usage metadata object.
/// </summary>
public CxEntityUsageMetadata EntityUsage
{
get
{
return CxUtils.NotEmpty(EntityUsageId) ? Holder.EntityUsages[EntityUsageId] : null;
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns ID of the frame class to display for the content pane.
/// </summary>
public string FrameClassId
{
get
{
return this["frame_class_id"];
}
}
/// <summary>
/// Returns true if the Tree Item is selected by default.
/// </summary>
public bool DefaultSelected
{
get
{
bool defSelected;
if (bool.TryParse(this["default_selected"], out defSelected))
return defSelected;
return false;
}
}
/// <summary>
/// Returns true if the Tree Item will show in dashboard.
/// </summary>
public bool DashboardItem
{
get
{
bool dashboardItem;
if (bool.TryParse(this["dashboard_item"], out dashboardItem))
return dashboardItem;
return false;
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns metadata of the frame class to display for the content pane.
/// </summary>
public CxClassMetadata FrameClass
{
get
{
if (CxUtils.NotEmpty(FrameClassId))
{
return Holder.Classes[FrameClassId];
}
else if (EntityUsage != null)
{
return EntityUsage.FrameClass;
}
return null;
}
}
//----------------------------------------------------------------------------
/// <summary>
/// The value of the display order for the section.
/// The less the value the earlier it will be placed in the list.
/// </summary>
public int DisplayOrder
{ get { return CxInt.Parse(this["display_order"], int.MaxValue); } }
//-------------------------------------------------------------------------
/// <summary>
/// Returns ID of the image to display for the tree item.
/// </summary>
public string ImageId
{
get
{
return this["image_id"];
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns metadata of the the image to display for the tree item.
/// </summary>
public CxImageMetadata Image
{
get
{
if (CxUtils.NotEmpty(ImageId))
{
return Holder.Images[ImageId];
}
else if (EntityUsage != null)
{
return EntityUsage.Image;
}
return null;
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns ID of the tree item provider class to get child or neighbour items.
/// </summary>
public string ItemProviderClassId
{
get
{
return this["item_provider_class_id"];
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns tree item provider class to get child or neighbour items.
/// </summary>
public CxClassMetadata ItemProviderClass
{
get
{
return CxUtils.NotEmpty(ItemProviderClassId) ? Holder.Classes[ItemProviderClassId] : null;
}
}
//-------------------------------------------------------------------------
/// <summary>
/// Item provider constant parameters.
/// </summary>
public string ItemProviderParameters
{
get
{
return this["item_provider_parameters"];
}
}
//-------------------------------------------------------------------------
/// <summary>
/// If true, items returned by the item provider should replace this item.
/// Otherwise, items returned by item provider are added as child items.
/// </summary>
public bool ItemProviderReplacement
{
get
{
return this["item_provider_replacement"].ToLower() == "true";
}
}
//-------------------------------------------------------------------------
/// <summary>
/// True to make item initially expanded.
/// </summary>
public bool Expanded
{
get
{
return this["expanded"].ToLower() == "true";
}
}
//-------------------------------------------------------------------------
/// <summary>
/// True to draw item with italic font.
/// </summary>
public bool Italic
{
get
{
return this["italic"].ToLower() == "true";
}
}
//-------------------------------------------------------------------------
/// <summary>
/// For dynamic tree items created by item provider indicates that
/// these dynamic items should be refreshed when some listed entity
/// usage is changed. List is comma-separated.
/// </summary>
public string DependsOnEntityUsageIds
{
get { return this["depends_on_entity_usage_ids"]; }
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns list of items provided by the item provider class.
/// </summary>
public IList<CxSlTreeItemMetadata> GetItemProviderItems()
{
if (ItemProviderClass != null)
{
Type providerType = ItemProviderClass.Class;
IxSlTreeItemsProvider provider = (IxSlTreeItemsProvider) CxType.CreateInstance(providerType);
IList<CxSlTreeItemMetadata> items = provider.GetItems(this);
if (items != null)
{
foreach (CxSlTreeItemMetadata item in items)
{
item.m_ProviderItem = this;
}
}
return items;
}
return null;
}
//-------------------------------------------------------------------------
/// <summary>
/// Child tree items.
/// </summary>
public CxSlTreeItemsMetadata Items
{ get { return m_Items; } }
//-------------------------------------------------------------------------
/// <summary>
/// Returns parent portal.
/// </summary>
public CxSlSectionMetadata Section
{ get { return m_Section; } }
//-------------------------------------------------------------------------
/// <summary>
/// Returns item that is an item provider for this item.
/// </summary>
public CxSlTreeItemMetadata ProviderItem
{ get { return m_ProviderItem; } }
//-------------------------------------------------------------------------
/// <summary>
/// Gets or sets custom tag of the tree item metadata.
/// </summary>
public object Tag
{
get { return m_Tag; }
set { m_Tag = value; }
}
//-------------------------------------------------------------------------
/// <summary>
/// Checks tree item access permission depending on security settings.
/// </summary>
public bool GetIsAllowed()
{
if (Holder != null && Holder.Security != null)
{
return Holder.Security.GetRight(this, EntityUsage);
}
return true;
}
//-------------------------------------------------------------------------
/// <summary>
/// True if metadata object is visible
/// </summary>
protected override bool GetIsVisible()
{
bool isVisible = true;
if (EntityUsage != null)
isVisible = EntityUsage.Visible && EntityUsage.GetIsAccessGranted();
// Just hide the item if it has some child items but no one of them is visible.
if (isVisible && Items != null && Items.Items != null && Items.Items.Count > 0)
{
bool subItemsVisible = false;
foreach (CxSlTreeItemMetadata item in Items.Items)
{
if (item.Visible)
{
subItemsVisible = true;
break;
}
}
isVisible = subItemsVisible;
}
return isVisible && base.GetIsVisible();
}
//-------------------------------------------------------------------------
/// <summary>
/// Returns object type code for localization.
/// </summary>
override public string LocalizationObjectTypeCode
{
get
{
return "Metadata.SlTreeItem";
}
}
//----------------------------------------------------------------------------
/// <summary>
/// Returns unique object name for localization.
/// </summary>
override public string LocalizationObjectName
{
get
{
return Section != null ? Section.LocalizationObjectName + "." + Id : base.LocalizationObjectName;
}
}
//----------------------------------------------------------------------------
}
}
|
using System;
using System.Runtime.InteropServices;
using FluentAssertions;
using OmniSharp.Extensions.LanguageServer.Protocol;
using Xunit;
namespace Lsp.Tests
{
public class VsCodeDocumentUriTests
{
[Fact(DisplayName = "file#toString")]
public void FileToString()
{
}
[Fact(DisplayName = "file#toString")]
public void file_toString()
{
DocumentUri.File("c:/win/path").ToString().Should().Be("file:///c:/win/path");
DocumentUri.File("C:/win/path").ToString().Should().Be("file:///c:/win/path");
DocumentUri.File("c:/win/path/").ToString().Should().Be("file:///c:/win/path/");
DocumentUri.File("/c:/win/path").ToString().Should().Be("file:///c:/win/path");
}
[Fact(DisplayName = "DocumentUri.File (win-special)")]
public void URI_file__win_special_()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
DocumentUri.File("c:\\win\\path").ToString().Should().Be("file:///c:/win/path");
DocumentUri.File("c:\\win/path").ToString().Should().Be("file:///c:/win/path");
}
else
{
DocumentUri.File("/usr/win\\path").ToString().Should().Be("file:///usr/win%5Cpath");
DocumentUri.File("/usr/win/path").ToString().Should().Be("file:///usr/win/path");
}
}
[Fact(DisplayName = "file#fsPath (win-special)")]
public void file_fsPath__win_special_()
{
DocumentUri.File("c:\\win\\path").GetFileSystemPath().Should().Be("c:\\win\\path");
DocumentUri.File("c:\\win/path").GetFileSystemPath().Should().Be("c:\\win\\path");
DocumentUri.File("c:/win/path").GetFileSystemPath().Should().Be("c:\\win\\path");
DocumentUri.File("c:/win/path/").GetFileSystemPath().Should().Be("c:\\win\\path\\");
DocumentUri.File("C:/win/path").GetFileSystemPath().Should().Be("c:\\win\\path");
DocumentUri.File("/c:/win/path").GetFileSystemPath().Should().Be("c:\\win\\path");
DocumentUri.File("./c/win/path").GetFileSystemPath().Should().Be("/./c/win/path");
}
[Fact(DisplayName = "URI#fsPath - no `fsPath` when no `path`")]
public void URI_fsPath___no_fsPath_when_no_path()
{
var value = DocumentUri.Parse("file://%2Fhome%2Fticino%2Fdesktop%2Fcpluscplus%2Ftest.cpp");
value.Authority.Should().Be("/home/ticino/desktop/cpluscplus/test.cpp");
value.Path.Should().Be("/");
value.GetFileSystemPath().Should().Be("/");
}
[Fact(DisplayName = "http#toString")]
public void http_toString()
{
DocumentUri.From(
new DocumentUriComponents
{ Scheme = "http", Authority = "www.msft.com", Path = "/my/path" }
).ToString().Should().Be(
"http://www.msft.com/my/path"
);
DocumentUri.From(
new DocumentUriComponents
{ Scheme = "http", Authority = "www.msft.com", Path = "/my/path" }
).ToString().Should().Be(
"http://www.msft.com/my/path"
);
DocumentUri.From(
new DocumentUriComponents
{ Scheme = "http", Authority = "www.MSFT.com", Path = "/my/path" }
).ToString().Should().Be(
"http://www.msft.com/my/path"
);
DocumentUri.From(new DocumentUriComponents { Scheme = "http", Authority = "", Path = "my/path" })
.ToString().Should().Be("http:/my/path");
DocumentUri.From(new DocumentUriComponents { Scheme = "http", Authority = "", Path = "/my/path" })
.ToString().Should().Be("http:/my/path");
//http://a-test-site.com/#test=true
DocumentUri.From(
new DocumentUriComponents
{ Scheme = "http", Authority = "a-test-site.com", Path = "/", Query = "test=true" }
).ToString()
.Should()
.Be(
"http://a-test-site.com/?test%3Dtrue"
);
DocumentUri.From(
new DocumentUriComponents {
Scheme = "http", Authority = "a-test-site.com", Path = "/", Query = "", Fragment = "test=true"
}
)
.ToString().Should().Be("http://a-test-site.com/#test%3Dtrue");
}
[Fact(DisplayName = "http#toString, encode=FALSE")]
public void http_toString__encode_FALSE()
{
DocumentUri.From(
new DocumentUriComponents
{ Scheme = "http", Authority = "a-test-site.com", Path = "/", Query = "test=true" }
)
.ToUnencodedString().Should().Be("http://a-test-site.com/?test=true");
DocumentUri.From(
new DocumentUriComponents {
Scheme = "http", Authority = "a-test-site.com", Path = "/", Query = "", Fragment = "test=true"
}
)
.ToUnencodedString().Should().Be("http://a-test-site.com/#test=true");
DocumentUri.From(
new DocumentUriComponents
{ Scheme = "http", Path = "/api/files/test.me", Query = "t=1234" }
).ToUnencodedString().Should().Be(
"http:/api/files/test.me?t=1234"
);
var value = DocumentUri.Parse("file://shares/pröjects/c%23/#l12");
value.Authority.Should().Be("shares");
value.Path.Should().Be("/pröjects/c#/");
value.Fragment.Should().Be("l12");
value.ToString().Should().Be("file://shares/pr%C3%B6jects/c%23/#l12");
value.ToUnencodedString().Should().Be("file://shares/pröjects/c%23/#l12");
var uri2 = DocumentUri.Parse(value.ToUnencodedString());
var uri3 = DocumentUri.Parse(value.ToString());
uri2.Authority.Should().Be(uri3.Authority);
uri2.Path.Should().Be(uri3.Path);
uri2.Query.Should().Be(uri3.Query);
uri2.Fragment.Should().Be(uri3.Fragment);
}
[Fact(DisplayName = "with, identity")]
public void with__identity()
{
var uri = DocumentUri.Parse("foo:bar/path");
var uri2 = uri.With(new DocumentUriComponents());
Assert.True(uri == uri2);
uri2 = uri.With(new DocumentUriComponents { Scheme = "foo", Path = "bar/path" });
Assert.True(uri == uri2);
}
[Fact(DisplayName = "with, changes")]
public void with__changes()
{
DocumentUri.Parse("before:some/file/path").With(new DocumentUriComponents { Scheme = "after" })
.ToString().Should().Be("after:some/file/path");
DocumentUri.From(new DocumentUriComponents { Scheme = "s" }).With(
new DocumentUriComponents
{ Scheme = "http", Path = "/api/files/test.me", Query = "t=1234" }
).ToString().Should().Be(
"http:/api/files/test.me?t%3D1234"
);
DocumentUri.From(new DocumentUriComponents { Scheme = "s" }).With(
new DocumentUriComponents
{ Scheme = "http", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = "" }
)
.ToString().Should().Be("http:/api/files/test.me?t%3D1234");
DocumentUri.From(new DocumentUriComponents { Scheme = "s" }).With(
new DocumentUriComponents {
Scheme = "https", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = ""
}
)
.ToString().Should().Be("https:/api/files/test.me?t%3D1234");
DocumentUri.From(new DocumentUriComponents { Scheme = "s" }).With(
new DocumentUriComponents
{ Scheme = "HTTP", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = "" }
)
.ToString().Should().Be("HTTP:/api/files/test.me?t%3D1234");
DocumentUri.From(new DocumentUriComponents { Scheme = "s" }).With(
new DocumentUriComponents {
Scheme = "HTTPS", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = ""
}
)
.ToString().Should().Be("HTTPS:/api/files/test.me?t%3D1234");
DocumentUri.From(new DocumentUriComponents { Scheme = "s" }).With(
new DocumentUriComponents
{ Scheme = "boo", Authority = "", Path = "/api/files/test.me", Query = "t=1234", Fragment = "" }
)
.ToString().Should().Be("boo:/api/files/test.me?t%3D1234");
}
[Fact(DisplayName = "with, remove components #8465")]
public void with__remove_components__8465()
{
DocumentUri.Parse("scheme://authority/path").With(new DocumentUriComponents { Authority = "" })
.ToString().Should().Be("scheme:/path");
DocumentUri.Parse("scheme:/path").With(new DocumentUriComponents { Authority = "authority" })
.With(new DocumentUriComponents { Authority = "" }).ToString().Should().Be("scheme:/path");
DocumentUri.Parse("scheme:/path").With(new DocumentUriComponents { Authority = "authority" })
.With(new DocumentUriComponents { Path = "" }).ToString().Should().Be("scheme://authority");
DocumentUri.Parse("scheme:/path").With(new DocumentUriComponents { Authority = "" }).ToString().Should()
.Be("scheme:/path");
}
[Fact(DisplayName = "with, validation")]
public void with_validation()
{
var uri = DocumentUri.Parse("foo:bar/path");
Assert.Throws<UriFormatException>(() => uri.With(new DocumentUriComponents { Scheme = "fai:l" }));
Assert.Throws<UriFormatException>(() => uri.With(new DocumentUriComponents { Scheme = "fäil" }));
Assert.Throws<UriFormatException>(() => uri.With(new DocumentUriComponents { Authority = "fail" }));
Assert.Throws<UriFormatException>(() => uri.With(new DocumentUriComponents { Path = "//fail" }));
}
[Fact(DisplayName = "parse")]
public void Parse()
{
var value = DocumentUri.Parse("http:/api/files/test.me?t=1234");
value.Scheme.Should().Be("http");
value.Authority.Should().Be("");
value.Path.Should().Be("/api/files/test.me");
value.Query.Should().Be("t=1234");
value.Fragment.Should().Be("");
value = DocumentUri.Parse("http://api/files/test.me?t=1234");
value.Scheme.Should().Be("http");
value.Authority.Should().Be("api");
value.Path.Should().Be("/files/test.me");
value.Query.Should().Be("t=1234");
value.Fragment.Should().Be("");
value = DocumentUri.Parse("file:///c:/test/me");
value.Scheme.Should().Be("file");
value.Authority.Should().Be("");
value.Path.Should().Be("/c:/test/me");
value.Fragment.Should().Be("");
value.Query.Should().Be("");
value.GetFileSystemPath().Should().Be("c:\\test\\me");
value = DocumentUri.Parse("file://shares/files/c%23/p.cs");
value.Scheme.Should().Be("file");
value.Authority.Should().Be("shares");
value.Path.Should().Be("/files/c#/p.cs");
value.Fragment.Should().Be("");
value.Query.Should().Be("");
value.GetFileSystemPath().Should().Be("\\\\shares\\files\\c#\\p.cs");
value = DocumentUri.Parse(
"file:///c:/Source/Z%C3%BCrich%20or%20Zurich%20(%CB%88zj%CA%8A%C9%99r%C9%AAk,/Code/resources/app/plugins/c%23/plugin.json"
);
value.Scheme.Should().Be("file");
value.Authority.Should().Be("");
value.Path.Should().Be(
"/c:/Source/Zürich or Zurich (ˈzjʊərɪk,/Code/resources/app/plugins/c#/plugin.json"
);
value.Fragment.Should().Be("");
value.Query.Should().Be("");
value = DocumentUri.Parse("file:///c:/test %25/path");
value.Scheme.Should().Be("file");
value.Authority.Should().Be("");
value.Path.Should().Be("/c:/test %/path");
value.Fragment.Should().Be("");
value.Query.Should().Be("");
value = DocumentUri.Parse("inmemory:");
value.Scheme.Should().Be("inmemory");
value.Authority.Should().Be("");
value.Path.Should().Be("");
value.Query.Should().Be("");
value.Fragment.Should().Be("");
value = DocumentUri.Parse("foo:api/files/test");
value.Scheme.Should().Be("foo");
value.Authority.Should().Be("");
value.Path.Should().Be("api/files/test");
value.Query.Should().Be("");
value.Fragment.Should().Be("");
value = DocumentUri.Parse("file:?q");
value.Scheme.Should().Be("file");
value.Authority.Should().Be("");
value.Path.Should().Be("/");
value.Query.Should().Be("q");
value.Fragment.Should().Be("");
value = DocumentUri.Parse("file:#d");
value.Scheme.Should().Be("file");
value.Authority.Should().Be("");
value.Path.Should().Be("/");
value.Query.Should().Be("");
value.Fragment.Should().Be("d");
value = DocumentUri.Parse("f3ile:#d");
value.Scheme.Should().Be("f3ile");
value.Authority.Should().Be("");
value.Path.Should().Be("");
value.Query.Should().Be("");
value.Fragment.Should().Be("d");
value = DocumentUri.Parse("foo+bar:path");
value.Scheme.Should().Be("foo+bar");
value.Authority.Should().Be("");
value.Path.Should().Be("path");
value.Query.Should().Be("");
value.Fragment.Should().Be("");
value = DocumentUri.Parse("foo-bar:path");
value.Scheme.Should().Be("foo-bar");
value.Authority.Should().Be("");
value.Path.Should().Be("path");
value.Query.Should().Be("");
value.Fragment.Should().Be("");
value = DocumentUri.Parse("foo.bar:path");
value.Scheme.Should().Be("foo.bar");
value.Authority.Should().Be("");
value.Path.Should().Be("path");
value.Query.Should().Be("");
value.Fragment.Should().Be("");
}
[Fact(DisplayName = "parse, disallow")]
public void parse_disallow() => Assert.Throws<UriFormatException>(() => DocumentUri.Parse("file:////shares/files/p.cs"));
[Fact(DisplayName = "URI#file, win-speciale")]
public void URI_file__win_speciale()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var value = DocumentUri.File("c:\\test\\drive");
value.Path.Should().Be("/c:/test/drive");
value.ToString().Should().Be("file:///c:/test/drive");
value = DocumentUri.File("\\\\shäres\\path\\c#\\plugin.json");
value.Scheme.Should().Be("file");
value.Authority.Should().Be("shäres");
value.Path.Should().Be("/path/c#/plugin.json");
value.Fragment.Should().Be("");
value.Query.Should().Be("");
value.ToString().Should().Be("file://sh%C3%A4res/path/c%23/plugin.json");
value = DocumentUri.File("\\\\localhost\\c$\\GitDevelopment\\express");
value.Scheme.Should().Be("file");
value.Path.Should().Be("/c$/GitDevelopment/express");
value.GetFileSystemPath().Should().Be("\\\\localhost\\c$\\GitDevelopment\\express");
value.Query.Should().Be("");
value.Fragment.Should().Be("");
value.ToString().Should().Be("file://localhost/c%24/GitDevelopment/express");
value = DocumentUri.File("c:\\test with %\\path");
value.Path.Should().Be("/c:/test with %/path");
value.ToString().Should().Be("file:///c:/test%20with%20%25/path");
value = DocumentUri.File("c:\\test with %25\\path");
value.Path.Should().Be("/c:/test with %25/path");
value.ToString().Should().Be("file:///c:/test%20with%20%2525/path");
value = DocumentUri.File("c:\\test with %25\\c#code");
value.Path.Should().Be("/c:/test with %25/c#code");
value.ToString().Should().Be("file:///c:/test%20with%20%2525/c%23code");
value = DocumentUri.File("\\\\shares");
value.Scheme.Should().Be("file");
value.Authority.Should().Be("shares");
value.Path.Should().Be("/"); // slash is always there
value = DocumentUri.File("\\\\shares\\");
value.Scheme.Should().Be("file");
value.Authority.Should().Be("shares");
value.Path.Should().Be("/");
}
}
[Fact(DisplayName = "VSCode URI module\"s driveLetterPath regex is incorrect, #32961")]
public void VSCode_URI_module_s_driveLetterPath_regex_is_incorrect__32961()
{
var uri = DocumentUri.Parse("file:///_:/path");
uri.GetFileSystemPath().Should().Be("/_:/path");
}
[Fact(DisplayName = "URI#file, no path-is-uri check")]
public void URI_file__no_path_is_uri_check()
{
// we don"t complain here
var value = DocumentUri.File("file://path/to/file");
value.Scheme.Should().Be("file");
value.Authority.Should().Be("");
value.Path.Should().Be("/file://path/to/file");
}
[Fact(DisplayName = "URI#file, always slash")]
public void URI_file__always_slash()
{
var value = DocumentUri.File("a.file");
value.Scheme.Should().Be("file");
value.Authority.Should().Be("");
value.Path.Should().Be("/a.file");
value.ToString().Should().Be("file:///a.file");
value = DocumentUri.Parse(value.ToString());
value.Scheme.Should().Be("file");
value.Authority.Should().Be("");
value.Path.Should().Be("/a.file");
value.ToString().Should().Be("file:///a.file");
}
[Fact(DisplayName = "URI.toString, only scheme and query")]
public void URI_toString_only_scheme_and_query()
{
var value = DocumentUri.Parse("stuff:?qüery");
value.ToString().Should().Be("stuff:?q%C3%BCery");
}
[Fact(DisplayName = "URI#toString, upper-case percent espaces")]
public void URI_toString_upper_case_percent_espaces()
{
var value = DocumentUri.Parse("file://sh%c3%a4res/path");
value.ToString().Should().Be("file://sh%C3%A4res/path");
}
[Fact(DisplayName = "URI#toString, lower-case windows drive letter")]
public void URI_toString_lower_case_windows_drive_letter()
{
DocumentUri.Parse("untitled:c:/Users/jrieken/Code/abc.txt").ToString().Should().Be(
"untitled:c:/Users/jrieken/Code/abc.txt"
);
DocumentUri.Parse("untitled:C:/Users/jrieken/Code/abc.txt").ToString().Should().Be(
"untitled:c:/Users/jrieken/Code/abc.txt"
);
}
[Fact(DisplayName = "URI#toString, escape all the bits")]
public void URI_toString__escape_all_the_bits()
{
var value = DocumentUri.File("/Users/jrieken/Code/_samples/18500/Mödel + Other Thîngß/model.js");
value.ToString().Should().Be(
"file:///Users/jrieken/Code/_samples/18500/M%C3%B6del%20%2B%20Other%20Th%C3%AEng%C3%9F/model.js"
);
}
[Fact(DisplayName = "URI#toString, don\"t encode port")]
public void URI_toString_don_t_encode_port()
{
var value = DocumentUri.Parse("http://localhost:8080/far");
value.ToString().Should().Be("http://localhost:8080/far");
value = DocumentUri.From(
new DocumentUriComponents
{ Scheme = "http", Authority = "löcalhost:8080", Path = "/far", Query = null, Fragment = null }
);
value.ToString().Should().Be("http://l%C3%B6calhost:8080/far");
}
[Fact(DisplayName = "URI#toString, user information in authority")]
public void URI_toString_user_information_in_authority()
{
var value = DocumentUri.Parse("http://foo:bar@localhost/far");
value.ToString().Should().Be("http://foo:bar@localhost/far");
value = DocumentUri.Parse("http://foo@localhost/far");
value.ToString().Should().Be("http://foo@localhost/far");
value = DocumentUri.Parse("http://foo:bAr@localhost:8080/far");
value.ToString().Should().Be("http://foo:bAr@localhost:8080/far");
value = DocumentUri.Parse("http://foo@localhost:8080/far");
value.ToString().Should().Be("http://foo@localhost:8080/far");
value = DocumentUri.From(
new DocumentUriComponents
{ Scheme = "http", Authority = "föö:bör@löcalhost:8080", Path = "/far", Query = null, Fragment = null }
);
value.ToString().Should().Be("http://f%C3%B6%C3%B6:b%C3%B6r@l%C3%B6calhost:8080/far");
}
[Fact(DisplayName = "correctFileUriToFilePath2")]
public void CorrectFileUriToFilePath2()
{
Action<string, string> test = (input, expected) => {
var value = DocumentUri.Parse(input);
value.GetFileSystemPath().Should().Be(expected);
var value2 = DocumentUri.File(value.GetFileSystemPath());
value2.GetFileSystemPath().Should().Be(expected);
value.ToString().Should().Be(value2.ToString());
};
test("file:///c:/alex.txt", "c:\\alex.txt");
test(
"file:///c:/Source/Z%C3%BCrich%20or%20Zurich%20(%CB%88zj%CA%8A%C9%99r%C9%AAk,/Code/resources/app/plugins",
"c:\\Source\\Zürich or Zurich (ˈzjʊərɪk,\\Code\\resources\\app\\plugins"
);
test(
"file://monacotools/folder/isi.txt",
"\\\\monacotools\\folder\\isi.txt"
);
test(
"file://monacotools1/certificates/SSL/",
"\\\\monacotools1\\certificates\\SSL\\"
);
}
[Fact(DisplayName = "URI - http, query & toString")]
public void URI___http__query___toString()
{
var uri = DocumentUri.Parse("https://go.microsoft.com/fwlink/?LinkId=518008");
uri.Query.Should().Be("LinkId=518008");
uri.ToUnencodedString().Should().Be("https://go.microsoft.com/fwlink/?LinkId=518008");
uri.ToString().Should().Be("https://go.microsoft.com/fwlink/?LinkId%3D518008");
var uri2 = DocumentUri.Parse(uri.ToString());
uri2.Query.Should().Be("LinkId=518008");
uri2.Query.Should().Be(uri.Query);
uri = DocumentUri.Parse("https://go.microsoft.com/fwlink/?LinkId=518008&foö&ké¥=üü");
uri.Query.Should().Be("LinkId=518008&foö&ké¥=üü");
uri.ToUnencodedString().Should().Be("https://go.microsoft.com/fwlink/?LinkId=518008&foö&ké¥=üü");
uri.ToString().Should().Be(
"https://go.microsoft.com/fwlink/?LinkId%3D518008%26fo%C3%B6%26k%C3%A9%C2%A5%3D%C3%BC%C3%BC"
);
uri2 = DocumentUri.Parse(uri.ToString());
uri2.Query.Should().Be("LinkId=518008&foö&ké¥=üü");
uri2.Query.Should().Be(uri.Query);
// #24849
uri = DocumentUri.Parse("https://twitter.com/search?src=typd&q=%23tag");
uri.ToUnencodedString().Should().Be("https://twitter.com/search?src=typd&q=%23tag");
}
[Fact(DisplayName = "class URI cannot represent relative file paths #34449")]
public void class_URI_cannot_represent_relative_file_paths__34449()
{
var path = "/foo/bar";
DocumentUri.File(path).Path.Should().Be(path);
path = "foo/bar";
DocumentUri.File(path).Path.Should().Be("/foo/bar");
path = "./foo/bar";
DocumentUri.File(path).Path.Should().Be("/./foo/bar"); // missing normalization
var fileUri1 = DocumentUri.Parse("file:foo/bar");
fileUri1.Path.Should().Be("/foo/bar");
fileUri1.Authority.Should().Be("");
var uri = fileUri1.ToString();
uri.Should().Be("file:///foo/bar");
var fileUri2 = DocumentUri.Parse(uri);
fileUri2.Path.Should().Be("/foo/bar");
fileUri2.Authority.Should().Be("");
}
[Fact(DisplayName = "Ctrl click to follow hash query param url gets urlencoded #49628")]
public void Ctrl_click_to_follow_hash_query_param_url_gets_urlencoded_49628()
{
var input = "http://localhost:3000/#/foo?bar=baz";
var uri = DocumentUri.Parse(input);
uri.ToUnencodedString().Should().Be(input);
input = "http://localhost:3000/foo?bar=baz";
uri = DocumentUri.Parse(input);
uri.ToUnencodedString().Should().Be(input);
}
[Fact(DisplayName = "Unable to open \"%A0.txt\": URI malformed #76506")]
public void Unable_to_open_URI_malformed_76506()
{
var uri = DocumentUri.File("/foo/%A0.txt");
var uri2 = DocumentUri.Parse(uri.ToString());
uri.Scheme.Should().Be(uri2.Scheme);
uri.Path.Should().Be(uri2.Path);
uri = DocumentUri.File("/foo/%2e.txt");
uri2 = DocumentUri.Parse(uri.ToString());
uri.Scheme.Should().Be(uri2.Scheme);
uri.Path.Should().Be(uri2.Path);
}
[Fact(DisplayName = "Unable to open \"%A0.txt\": URI malformed #76506")]
public void Unable_to_open_URI_malformed_76506_2()
{
DocumentUri.Parse("file://some/%.txt").ToString().Should().Be("file://some/%25.txt");
DocumentUri.Parse("file://some/%A0.txt").ToString().Should().Be("file://some/%25A0.txt");
}
}
}
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using smoothie_shack.Models;
using smoothie_shack.Repositories;
namespace smoothie_shack.Controllers
{
[Route("[controller]")]
public class AccountController : Controller
{
private readonly UserRepository _repo;
public AccountController(UserRepository repo)
{
_repo = repo;
}
[HttpGet("login")]
public IActionResult Login()
{
return View();
}
[HttpPost("login")]
public async Task<User> Login([FromBody]UserLogin creds)
{
if (ModelState.IsValid)
{
var user = _repo.Login(creds);
if (user == null) {return null;}
user.SetClaims();
await HttpContext.SignInAsync(user.GetPrincipal());
return user;
}
return null;
}
[HttpPost("register")]
public async Task<User> Register([FromBody]UserRegistration creds)
{
if (ModelState.IsValid)
{
var user = _repo.Register(creds);
if (user == null) //User already exists most likely
{
return null;
}
user.SetClaims();
await HttpContext.SignInAsync(user.GetPrincipal());
return user;
}
return null;
}
[Authorize]
[HttpGet("Authenticate")]
public User Authenticate()
{
var user = HttpContext.User;
var id = User.Identity.Name;
return _repo.GetUserById(id);
}
}
} |
//Extra references added which are commenly used for interacting with CE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xrm.Tooling.Connector;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Configuration;
namespace ConsoletoConnecttoDynamics365CRMv9.x
{
class Program
{
private static CrmServiceClient _crmServiceClient;
static void Main(string[] args)
{
//Change the connection string name in next line to use Office365/ClientSecret connection string as per your requirement
using (_crmServiceClient = new CrmServiceClient(ConfigurationManager.ConnectionStrings["D365ConnectionStringClientSecret"].ConnectionString))
{
if (_crmServiceClient.IsReady)
{
Console.WriteLine("Authenticated To D365.");
//Write your code here
}
else
{
Console.WriteLine("Authentication Failed.");
throw _crmServiceClient.LastCrmException;
}
}
}
}
}
|
using bot_backEnd.Models.DbModels;
using bot_backEnd.Models.ViewModels.Statistic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace bot_backEnd.BL.Interfaces
{
public interface IPostTypeBL
{
List<PostType> GetAllPostTypes();
List<TypeStats> GetPostTypeStats();
}
}
|
namespace Rak.Mini.Cqrs.Abstractions.Responses
{
public enum ResponseMessageType
{
SystemError,
Information,
ValidationError,
Warning
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameOverScreen : MonoBehaviour
{
[SerializeField] Text gameOverMessage;
[SerializeField] Image background;
[SerializeField] GameObject buttons;
public void MethodStart()
{
StartCoroutine(AdjustBlackScreen());
}
IEnumerator ProgressUI()
{
StartCoroutine(TypingEffect(gameOverMessage, "Game Over", 0.32f));
WaitForSeconds waitDelay00 = new WaitForSeconds("Game Over".Length * 0.32f + 1f);
yield return waitDelay00;
buttons.SetActive(true);
}
WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame();
IEnumerator AdjustBlackScreen()
{
float timeCounter = 0f;
background.gameObject.SetActive(true);
while (true)
{
float deltaTime = Time.deltaTime;
timeCounter += deltaTime;
background.color = new Color(background.color.r, background.color.g, background.color.b, background.color.a + (deltaTime * 0.4f));
if (timeCounter >= 4f)
{
break;
}
yield return waitForEndOfFrame;
}
StartCoroutine(ProgressUI());
}
IEnumerator TypingEffect(Text _text, string _message, float _speed)
{
WaitForSeconds ddd = new WaitForSeconds(_speed);
for (int i = 0; i < _message.Length; i++)
{
_text.text = _message.Substring(0, i + 1);
yield return ddd;
}
}
}
|
using Microsoft.EntityFrameworkCore;
using PDB.Models;
namespace PDB.Services
{
public class MapPointService : IMapPointService
{
private readonly ApplicationContext _context;
//Those are constant for that map that will be variable at some point.
private const int XMinimumValue = 0;
private const int YMinimumValue = 0;
private const int XMaximumValue = 24;
private const int YMaximumValue = 24;
private const int GridRange = 5;
public MapPointService(ApplicationContext context)
{
_context = context;
}
public async Task<MapPoint?> GetMapPoint(long id)
{
MapPoint? mapPoint = await _context.FindAsync<MapPoint>(id);
return mapPoint;
}
public async Task<IEnumerable<IEnumerable<MapPoint>>> LoadGrid(MapPoint center)
{
(int x1, int x2) = calculateMinMax(GridRange, XMinimumValue, XMaximumValue, center.X);
(int y1, int y2) = calculateMinMax(GridRange, YMinimumValue, YMaximumValue, center.Y);
var grid = await _context.MapPoints.Where(x => x.X >= x1 && x.X <= x2 && x.Y >= y1 && x.Y <= y2).OrderBy(x => x.X).ThenBy(x => x.Y).ToListAsync();
return grid.GroupBy(x => x.X);
}
private (int, int) calculateMinMax(int radius, int minMap, int maxMap, int center)
{
var overflow = 0;
var underflow = 0;
var borderLeft = center - radius;
var borderRight = center + radius;
if (borderLeft < minMap)
{
overflow = Math.Abs(borderLeft); //This works only because the min is 0, otherwise I would have to calculate it
}
if (borderRight > maxMap)
{
underflow = borderRight - maxMap;
}
var absMin = Math.Max(borderLeft, minMap);
absMin -= underflow;
var absMax = Math.Min(borderRight, maxMap);
absMax += overflow;
return (absMin, absMax);
}
public async Task<IDictionary<Direction, MapPoint>> Neighbors(MapPoint center)
{
var neighbors = new Dictionary<Direction, MapPoint>();
foreach(var direction in Direction.AllDirections)
{
var mapPoint = await _context.MapPoints.Where(point => point.X == center.X + direction.DeltaX && point.Y == center.Y + direction.DeltaY).SingleOrDefaultAsync();
if(mapPoint != null)
{
neighbors.Add(direction, mapPoint);
}
}
return neighbors;
}
}
}
|
using DuaControl.Web.Data.Entities;
using DuaControl.Web.Data.Helpers;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace DuaControl.Web.Data
{
public class SeedDb
{
private readonly DataContext _dataContext;
private readonly IRoleHelper _roleHelper;
public SeedDb(
DataContext context,
IRoleHelper roleHelper)
{
_dataContext = context;
_roleHelper = roleHelper;
}
public async Task SeedAsync()
{
await _dataContext.Database.EnsureCreatedAsync();
await CheckPortsAsync();
await CheckRolesAsync();
await CheckUserAsync();
//await CheckAgendasAsync();
}
private async Task CheckPortsAsync()
{
if (!_dataContext.Puertos.Any())
{
_dataContext.Puertos.Add(new Puerto { Name = "Default" });
_dataContext.Puertos.Add(new Puerto { Name = "Elias Piña" });
_dataContext.Puertos.Add(new Puerto { Name = "Dajabón" });
_dataContext.Puertos.Add(new Puerto { Name = "Venezuela" });
_dataContext.Puertos.Add(new Puerto { Name = "Puerto Rico" });
await _dataContext.SaveChangesAsync();
}
}
private async Task CheckRolesAsync()
{
if (!_dataContext.Roles.Any())
{
_dataContext.Roles.Add(new Role { Name = "Admin" });
_dataContext.Roles.Add(new Role { Name = "SuperUser" });
_dataContext.Roles.Add(new Role { Name = "User" });
await _dataContext.SaveChangesAsync();
}
//await _roleHelper.CheckRoleAsync("Admin");
//await _roleHelper.CheckRoleAsync("SuperUser");
//await _roleHelper.CheckRoleAsync("User");
}
private async Task CheckUserAsync()
{
if (!_dataContext.Users.Any())
{
_dataContext.Users.Add(new User { UserName = "soportet", FirstName = "Soporte", LastName = "Técnico", IsActive = true, LastLoginDate = DateTime.Now, CreatedOn = DateTime.Now, CreatedBy = "soportet", ModifiedOn = DateTime.Now, ModifiedBy = "soportet" });
await _dataContext.SaveChangesAsync();
var user = _dataContext.Users.FirstOrDefault();
var role = _dataContext.Roles.FirstOrDefault(r => r.Name == "Admin");
_dataContext.UserRoles.Add(new UserRole { Role = role, User = user });
await _dataContext.SaveChangesAsync();
}
//await _roleHelper.CheckRoleAsync("Admin");
//await _roleHelper.CheckRoleAsync("SuperUser");
//await _roleHelper.CheckRoleAsync("User");
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.WindowsAPICodePack.Dialogs;
namespace GITRepoManager
{
public partial class AddRepoFRM : Form
{
private string StorePath { get; set; }
private string RepoName { get; set; }
public bool Repo_Added { get; set; }
public AddRepoFRM(string path)
{
StorePath = path;
InitializeComponent();
}
#region BrowseRepoSourceBT
private void BrowseRepoSourceBT_Click(object sender, EventArgs e)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog
{
InitialDirectory = @"C:\",
IsFolderPicker = true
};
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
NewRepoNameTB.Text = dialog.FileName;
}
}
#endregion
#region AddRepoFRM
private void AddRepoFRM_Load(object sender, EventArgs e)
{
Repo_Added = false;
StorePathTB.Text = StorePath;
NewRepoNameTB.Focus();
NewRepoNameTB.Select();
}
#endregion
#region AddRepoBT
private void AddRepoBT_Click(object sender, EventArgs e)
{
this.Cursor = Cursors.WaitCursor;
AddingPB.MarqueeAnimationSpeed = 10;
AddingPB.Style = ProgressBarStyle.Marquee;
AddingPB.Visible = true;
if (!string.IsNullOrEmpty(NewRepoNameTB.Text) && !string.IsNullOrWhiteSpace(NewRepoNameTB.Text))
{
RepoName = NewRepoNameTB.Text;
Repo_Added = RepoHelpers.Create_Blank_Repository(StorePathTB.Text, RepoName);
DirectoryInfo storeInfo = new DirectoryInfo(StorePath);
if (Repo_Added)
{
AutoClosingMessageBox.Show(RepoName + " added to " + storeInfo.Name, "Repo Added Successfully", 1500);
Close();
}
else
{
MessageBox.Show("Unable to add repo.\nMay be issue with permissions on directory where GIT is located or on the destination directory.", "Unable To Add Repo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Please provide a repository name to continue", "Blank Repository Name", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
AddingPB.Visible = false;
AddingPB.Style = ProgressBarStyle.Blocks;
this.Cursor = Cursors.Default;
}
#endregion
#region AddRepoBT
private void AddRepoBT_MouseEnter(object sender, EventArgs e)
{
AddRepoBT.BackgroundImage = Properties.Resources.NewIcon_Hover;
}
#endregion
#region AddRepoBT
private void AddRepoBT_MouseLeave(object sender, EventArgs e)
{
AddRepoBT.BackgroundImage = Properties.Resources.NewIcon;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace WeaponGame
{
public class MeleeWeapons : Weapons
{
public int Poke(int baseDamage)
{
return 1;
}
public MeleeWeapons(string weaponName, int baseDamage, int baseRange, int critiChance, int critiDamage, int actionPoint)
: base(weaponName, baseDamage, critiChance, critiDamage, actionPoint, baseRange)
{
actionPoint = 1;
Random random = new Random();
int randomNumber = random.Next(1, 101);
if (baseRange < 1)
{
baseDamage = 0;
}
if (randomNumber <= critiChance)
{
Player.strength -= actionPoint;
int Damage = baseDamage * critiDamage;
}
else
{
Player.strength -= actionPoint;
int Damage = baseDamage;
}
}
}
}
|
/*
FileName: ZByteGenie.cs
Version: 0.1
Namespace: Omi24.Cryptography
Description: Byte related functions.
Web: http://www.omi24.com
History:
0.10: 20180523, 馮瑞祥 - Zak Fong
*/
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Omi24
{
/// <summary>
/// Byte related functions.
/// </summary>
public class ZByteGenie
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Task 23, 24
namespace GenericsExercise
{
class Program
{
static void Main(string[] args)
{
//run GenericListTest class
GenericListTest.TestGenericList();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using API_FlashSales.Objetos;
using System.Data;
namespace API_FlashSales
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
public class Service1 : API_Services
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
public List<TipoProducto> Tipos()
{
try
{
List<TipoProducto> Lista = new List<TipoProducto>();
DataTable Tipos = new DataTable();
Tipos = DB_Connection.ExecuteSP("obtenerTipos");
foreach (DataRow row in Tipos.Rows)
{
Lista.Add(
new TipoProducto
{
ID = (int)row["ID"],
Nombre = row["Nombre"].ToString()
}
);
}
return Lista;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
|
using LibreriaPersonas;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Windows1
{
public partial class Form1 : Form
{
BindingList<Person> binding;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
IPersonService service = new PersonService();
binding = new BindingList<Person>(service.FindAll());
dataGridView1.DataSource = binding;
}
private void Button1_Click(object sender, EventArgs e)
{
IPersonService servicio = new PersonService();
servicio.InsertPerson(new Person(textBox1.Text, textBox2.Text, Int32.Parse(textBox3.Text)));
binding = new BindingList<Person>(servicio.FindAll());
dataGridView1.DataSource = binding;
}
}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Logging.Business.Abstract;
using Logging.Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Logging.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private IUserService _userService;
public UsersController(IUserService userService)
{
_userService = userService;
}
[HttpGet("getlist")]
public IActionResult GetList()
{
_userService.GetList();
return StatusCode(200);
}
[HttpGet("getbyid")]
public IActionResult GetById(int userId)
{
_userService.GetById(userId);
return StatusCode(200);
}
[HttpPost("update")]
public IActionResult Update(User user)
{
_userService.Update(user);
return StatusCode(201);
}
[HttpPost("delete")]
public IActionResult Delete(User user)
{
_userService.Delete(user);
return StatusCode(201);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace taszimozgas_c
{
class DB
{
public static bool Belepve = false;
public static string LogName = "";
public static Boolean AdminUser = false;
public static int userid = -1;
public static string ipk;
public static NpgsqlConnection connection;
static NpgsqlDataAdapter adapter;
public static NpgsqlDataAdapter iranyadapter;
public static NpgsqlCommandBuilder iranycb;
public static DataTable tbllogin;
public static DataTable tblEszkoz;
public static DataTable tblFelelos;
public static DataTable tblForras;
public static DataTable tblIrany;
public static DataTable tblIskola;
public static DataTable tblMegnevezes;
public static DataTable tblMozgas;
public static DataTable tblNaplo;
public static DataTable tblOprendszer;
public static DataTable tblTarhely;
public static DataTable tblTechnologia;
public static DataTable tblMozgatas;
static NpgsqlCommand command;
static string connectionString = ConfigurationManager.ConnectionStrings["taszimozgasCS"].ConnectionString;
static string connectionString2 = ConfigurationManager.ConnectionStrings["taszimozgasCSt"].ConnectionString;
//Helyi ip cím lekérése
public static void GetLocalIPAddress()
{
ipk = "";
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
ipk += ip.ToString() + "---";
}
}
}
public static bool Login(String str_login, String str_password)
{
connection = new NpgsqlConnection(connectionString);
try
{
connection.Open();
}
catch (System.TimeoutException)
{
//MessageBox.Show("A szerver nem elérhető");
connection.Close();
connection = null;
connection = new NpgsqlConnection(connectionString2);
try
{
connection.Open();
}
catch (System.TimeoutException)
{
MessageBox.Show("Nincsenek szerverek.\nKilépés","Végzetes hiba");
Environment.Exit(1);
}
catch
{
MessageBox.Show("Minden szerver leállt. \nKilépés.", "Végzetes hiba");
Environment.Exit(1);
}
}
NpgsqlParameter login = new NpgsqlParameter("LOGIN",DbType.String);
NpgsqlParameter password = new NpgsqlParameter("PASSWORD", DbType.String);
login.Value = str_login;
password.Value = str_password;
command = new NpgsqlCommand("Select * From public.user where login = @LOGIN and password = md5(@PASSWORD)", connection);
command.Parameters.Add(login);
command.Parameters.Add(password);
tbllogin = new DataTable();
adapter = new NpgsqlDataAdapter(command);
adapter.Fill(tbllogin);
if (tbllogin.Rows.Count==1)
{
DataRow dr = tbllogin.Rows[0];
if (Convert.ToBoolean(dr["engedve"]))
{
AdminUser = Convert.ToBoolean(dr["admin"]);
Belepve = true;
LogName = login.Value.ToString();
userid = Convert.ToInt32(dr["id"]);
logol();
return true;
}
else
{
MessageBox.Show("Zárolt felhasználó, nem léphet be.","Engedély megtagadva.", MessageBoxButtons.OK);
return false;
}
}
else
{
Belepve = false;
return false;
}
}
//Naplózás
public static void logol()
{
command = new NpgsqlCommand("insert into public.naplo (juser) values (@LOGNAME)", connection);
NpgsqlParameter logname = new NpgsqlParameter("LOGNAME", DbType.Int32);
//NpgsqlParameter ip = new NpgsqlParameter("IP", DbType.String);
//NpgsqlParameter idopont = new NpgsqlParameter("IDOPONT", DbType.Date);
logname.Value = Convert.ToInt32(userid);
//ip.Value = ipk;
//DateTime most = DateTime.Now;
//idopont.Value = most;
command.Parameters.Add(logname);
//command.Parameters.Add(ip);
//command.Parameters.Add(idopont);
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
command.ExecuteNonQuery();
}
public static void Kapcs_Eszkoz()
{
if (connection.State == ConnectionState.Closed)
{
try
{
connection.Open();
}
catch (Exception)
{
MessageBox.Show("Sikertelen kapcsolódás.");
throw;
}
}
string sql = "Select * from eszkoz";
command = new NpgsqlCommand(sql, connection);
adapter = new NpgsqlDataAdapter(command);
tblEszkoz = new DataTable();
adapter.Fill(tblEszkoz);
}
public static void Kapcs_Felelos()
{
string sql = "Select * from felelos";
command = new NpgsqlCommand(sql, connection);
adapter = new NpgsqlDataAdapter(command);
tblFelelos = new DataTable();
adapter.Fill(tblFelelos);
}
public static void Kapcs_Irany()
{
string sql = "Select * from irany";
command = new NpgsqlCommand(sql, connection);
iranyadapter = new NpgsqlDataAdapter(command);
tblIrany = new DataTable();
iranyadapter.Fill(tblIrany);
}
public static void Kapcs_Forras()
{
string sql = "Select * from forras";
command = new NpgsqlCommand(sql, connection);
adapter = new NpgsqlDataAdapter(command);
tblForras = new DataTable();
adapter.Fill(tblForras);
}
public static void Kapcs_Iskola()
{
string sql = "Select * from iskola";
command = new NpgsqlCommand(sql, connection);
adapter = new NpgsqlDataAdapter(command);
tblIskola = new DataTable();
adapter.Fill(tblIskola);
}
public static void Kapcs_Megnevezes()
{
string sql = "Select * from megnevezes";
command = new NpgsqlCommand(sql, connection);
adapter = new NpgsqlDataAdapter(command);
tblMegnevezes = new DataTable();
adapter.Fill(tblMegnevezes);
}
public static void Kapcs_Mozgas()
{
string sql = "Select * from mozgas";
command = new NpgsqlCommand(sql, connection);
adapter = new NpgsqlDataAdapter(command);
tblMozgas = new DataTable();
adapter.Fill(tblMozgas);
}
public static void Kapcs_Mozgatas()
{
string sql = "Select * from mozgatas";
command = new NpgsqlCommand(sql, connection);
adapter = new NpgsqlDataAdapter(command);
tblMozgas = new DataTable();
adapter.Fill(tblMozgatas);
}
public static void Kapcs_Naplo()
{
string sql = "Select * from naplo";
command = new NpgsqlCommand(sql, connection);
adapter = new NpgsqlDataAdapter(command);
tblNaplo = new DataTable();
adapter.Fill(tblNaplo);
}
public static void Kapcs_Oprendszer()
{
string sql = "Select * from oprendszer";
command = new NpgsqlCommand(sql, connection);
adapter = new NpgsqlDataAdapter(command);
tblOprendszer = new DataTable();
adapter.Fill(tblOprendszer);
}
public static void Kapcs_Tarhely()
{
string sql = "Select * from tarhely";
command = new NpgsqlCommand(sql, connection);
adapter = new NpgsqlDataAdapter(command);
tblTarhely = new DataTable();
adapter.Fill(tblTarhely);
}
public static void Kapcs_Technologia()
{
string sql = "Select * from technologia";
command = new NpgsqlCommand(sql, connection);
adapter = new NpgsqlDataAdapter(command);
tblTechnologia = new DataTable();
adapter.Fill(tblTechnologia);
}
public static void Insert_Irany(string irany)
{
string sql = "Insert into irany (nev) values ('" + irany + "')";
command = new NpgsqlCommand(sql, connection);
try
{
command.ExecuteNonQuery();
tblIrany.Clear();
iranyadapter.Fill(tblIrany);
}
catch (Exception e)
{
MessageBox.Show("Valami hiba történt" + e.Message);
}
}
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Xunit;
namespace Microsoft.EntityFrameworkCore
{
public class CustomConvertersSqliteTest : CustomConvertersTestBase<CustomConvertersSqliteTest.CustomConvertersSqliteFixture>
{
public CustomConvertersSqliteTest(CustomConvertersSqliteFixture fixture)
: base(fixture)
{
Fixture.TestSqlLoggerFactory.Clear();
}
// Disabled: SQLite database is case-sensitive
public override void Can_insert_and_read_back_with_case_insensitive_string_key()
{
}
[ConditionalFact]
public override void Value_conversion_is_appropriately_used_for_join_condition()
{
base.Value_conversion_is_appropriately_used_for_join_condition();
AssertSql(
@"@__blogId_0='1' (DbType = String)
SELECT ""b"".""Url""
FROM ""Blog"" AS ""b""
INNER JOIN ""Post"" AS ""p"" ON ((""b"".""BlogId"" = ""p"".""BlogId"") AND (""b"".""IsVisible"" = 'Y')) AND (""b"".""BlogId"" = @__blogId_0)
WHERE ""b"".""IsVisible"" = 'Y'");
}
[ConditionalFact]
public override void Value_conversion_is_appropriately_used_for_left_join_condition()
{
base.Value_conversion_is_appropriately_used_for_left_join_condition();
AssertSql(
@"@__blogId_0='1' (DbType = String)
SELECT ""b"".""Url""
FROM ""Blog"" AS ""b""
LEFT JOIN ""Post"" AS ""p"" ON ((""b"".""BlogId"" = ""p"".""BlogId"") AND (""b"".""IsVisible"" = 'Y')) AND (""b"".""BlogId"" = @__blogId_0)
WHERE ""b"".""IsVisible"" = 'Y'");
}
[ConditionalFact]
public override void Where_bool_gets_converted_to_equality_when_value_conversion_is_used()
{
base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used();
AssertSql(
@"SELECT ""b"".""BlogId"", ""b"".""Discriminator"", ""b"".""IndexerVisible"", ""b"".""IsVisible"", ""b"".""Url"", ""b"".""RssUrl""
FROM ""Blog"" AS ""b""
WHERE ""b"".""IsVisible"" = 'Y'");
}
[ConditionalFact]
public override void Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used()
{
base.Where_negated_bool_gets_converted_to_equality_when_value_conversion_is_used();
AssertSql(
@"SELECT ""b"".""BlogId"", ""b"".""Discriminator"", ""b"".""IndexerVisible"", ""b"".""IsVisible"", ""b"".""Url"", ""b"".""RssUrl""
FROM ""Blog"" AS ""b""
WHERE ""b"".""IsVisible"" = 'N'");
}
public override void Where_bool_with_value_conversion_inside_comparison_doesnt_get_converted_twice()
{
base.Where_bool_with_value_conversion_inside_comparison_doesnt_get_converted_twice();
AssertSql(
@"SELECT ""b"".""BlogId"", ""b"".""Discriminator"", ""b"".""IndexerVisible"", ""b"".""IsVisible"", ""b"".""Url"", ""b"".""RssUrl""
FROM ""Blog"" AS ""b""
WHERE ""b"".""IsVisible"" = 'Y'",
//
@"SELECT ""b"".""BlogId"", ""b"".""Discriminator"", ""b"".""IndexerVisible"", ""b"".""IsVisible"", ""b"".""Url"", ""b"".""RssUrl""
FROM ""Blog"" AS ""b""
WHERE ""b"".""IsVisible"" <> 'Y'");
}
public override void Select_bool_with_value_conversion_is_used()
{
base.Select_bool_with_value_conversion_is_used();
AssertSql(
@"SELECT ""b"".""IsVisible""
FROM ""Blog"" AS ""b""");
}
[ConditionalFact]
public override void Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty()
{
base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_EFProperty();
AssertSql(
@"SELECT ""b"".""BlogId"", ""b"".""Discriminator"", ""b"".""IndexerVisible"", ""b"".""IsVisible"", ""b"".""Url"", ""b"".""RssUrl""
FROM ""Blog"" AS ""b""
WHERE ""b"".""IsVisible"" = 'Y'");
}
[ConditionalFact]
public override void Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer()
{
base.Where_bool_gets_converted_to_equality_when_value_conversion_is_used_using_indexer();
AssertSql(
@"SELECT ""b"".""BlogId"", ""b"".""Discriminator"", ""b"".""IndexerVisible"", ""b"".""IsVisible"", ""b"".""Url"", ""b"".""RssUrl""
FROM ""Blog"" AS ""b""
WHERE ""b"".""IndexerVisible"" = 'Nay'");
}
private void AssertSql(params string[] expected)
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);
public class CustomConvertersSqliteFixture : CustomConvertersFixtureBase
{
public override bool StrictEquality
=> false;
public override bool SupportsAnsi
=> false;
public override bool SupportsUnicodeToAnsiConversion
=> true;
public override bool SupportsLargeStringComparisons
=> true;
public override bool SupportsDecimalComparisons
=> false;
protected override ITestStoreFactory TestStoreFactory
=> SqliteTestStoreFactory.Instance;
public TestSqlLoggerFactory TestSqlLoggerFactory
=> (TestSqlLoggerFactory)ListLoggerFactory;
public override bool SupportsBinaryKeys
=> true;
public override DateTime DefaultDateTime
=> new();
}
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Lib.Net.Http.WebPush;
namespace Services.Abstractions
{
public interface IPushSubscriptionStore
{
Task StoreSubscriptionAsync(PushSubscription subscription, int teamId);
Task<PushSubscription> GetSubscriptionAsync(string endpoint, int teamId);
Task DiscardSubscriptionAsync(string endpoint, int teamId);
Task ForEachSubscriptionAsync(int? teamId, Action<PushSubscription> action);
Task ForEachSubscriptionAsync(int? teamId, Action<PushSubscription> action, CancellationToken cancellationToken);
}
}
|
/* 03. Cats are Animals. */
namespace AnimalClasses
{
public class Cat : Animal, ISound
{
public Cat(string catName, int catAge, Gender catSex)
: base(catName, catAge, catSex)
{
}
public override void MakeSound()
{
System.Console.WriteLine("Meow :)");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArteVida.Dominio.Entidades
{
public class Socio : Pessoa
{
public DateTime? DataAdesao { get; set; }
public decimal Mensalidade { get; set; }
}
}
|
using System;
using DataAccess.POCO;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace DataAccess.Interfaces
{
public interface ICustomersContext : IDisposable
{
DbSet<Addresses> Addresses { get; set; }
DbSet<Customers> Customers { get; set; }
int SaveChanges();
//DbContext methods
EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
EntityEntry Entry(object entity);
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class constraintInventory : MonoBehaviour {
GameObject inventoryPanel;
GameObject slotPanel;
GameObject slotPanel2;
// GameObject
GridLayoutGroup gridLayoutGroup;
GridLayoutGroup gridLayoutGroup2;
RectTransform rect;
public float height;
public List<Item> slots1Items = new List<Item> ();
public List<GameObject> slots = new List<GameObject> ();
RectTransform itemsRect;
// Use this for initialization
void Start () {
inventoryPanel = GameObject.Find ("inventory Panel");
slotPanel = inventoryPanel.transform.FindChild ("slot Panel").gameObject;
slotPanel2 = inventoryPanel.transform.FindChild ("slot In Game Panel").gameObject;
gridLayoutGroup = slotPanel.GetComponent<GridLayoutGroup> ();
gridLayoutGroup2 = slotPanel2.GetComponent<GridLayoutGroup> ();
rect = gridLayoutGroup2.GetComponent<RectTransform> ();
gridLayoutGroup2.cellSize = new Vector2 ((float)(rect.rect.width * 0.3), (float)(rect.rect.width * 0.3));
// gridLayoutGroup2.padding = new RectOffset((int)(rect.rect.width * 0.10),0,(int)(rect.rect.height * 0.1),0);
float spacing2 = (slotPanel2.GetComponent<RectTransform> ().rect.width - (3 * gridLayoutGroup2.cellSize.x)) / 2;
gridLayoutGroup2.spacing = new Vector2 (spacing2, 0);
int cellCont = 10;
gridLayoutGroup.cellSize = new Vector2 ((float)(rect.rect.width * 0.3), (float)(rect.rect.width * 0.3));
float spacing = (slotPanel.GetComponent<RectTransform> ().rect.width - ((cellCont/2) * gridLayoutGroup.cellSize.x)) / ((cellCont/2) - 1);
gridLayoutGroup.spacing = new Vector2 (spacing, (float)(rect.rect.height * 0.30));
// gridLayoutGroup.padding = new RectOffset((int)(rect.rect.width * 0.10),0,(int)(rect.rect.height * 0.1),0);
print (slotPanel2.GetComponent<RectTransform> ().rect.width);
}
void OnRectTransformDimensionsChange ()
{
Debug.Log("RectTransformDimensionsChange firing on " + this.name + " finee.");
if (gridLayoutGroup != null && rect != null) {
rect = gridLayoutGroup2.GetComponent<RectTransform> ();
gridLayoutGroup2.cellSize = new Vector2 ((float)(rect.rect.width * 0.3), (float)(rect.rect.width * 0.3));
// gridLayoutGroup2.padding = new RectOffset((int)(rect.rect.width * 0.10),0,(int)(rect.rect.height * 0.1),0);
float spacing2 = (slotPanel2.GetComponent<RectTransform> ().rect.width - (3 * gridLayoutGroup2.cellSize.x)) / 2;
gridLayoutGroup2.spacing = new Vector2 (spacing2, 0);
int cellCont = 10;
gridLayoutGroup.cellSize = new Vector2 ((float)(rect.rect.width * 0.3), (float)(rect.rect.width * 0.3));
float spacing = (slotPanel.GetComponent<RectTransform> ().rect.width - ((cellCont/2) * gridLayoutGroup.cellSize.x)) / ((cellCont/2) - 1);
gridLayoutGroup.spacing = new Vector2 (spacing, (float)(rect.rect.height * 0.30));
}
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
[Attribute38("ChatLogMessageFrame")]
public class ChatLogMessageFrame : MonoBehaviour
{
public ChatLogMessageFrame(IntPtr address) : this(address, "ChatLogMessageFrame")
{
}
public ChatLogMessageFrame(IntPtr address, string className) : base(address, className)
{
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public Color GetColor()
{
return base.method_11<Color>("GetColor", Array.Empty<object>());
}
public string GetMessage()
{
return base.method_13("GetMessage", Array.Empty<object>());
}
public void SetColor(Color color)
{
object[] objArray1 = new object[] { color };
base.method_8("SetColor", objArray1);
}
public void SetMessage(string message)
{
object[] objArray1 = new object[] { message };
base.method_8("SetMessage", objArray1);
}
public void UpdateBackground()
{
base.method_8("UpdateBackground", Array.Empty<object>());
}
public void UpdateText()
{
base.method_8("UpdateText", Array.Empty<object>());
}
public GameObject m_Background
{
get
{
return base.method_3<GameObject>("m_Background");
}
}
public float m_initialBackgroundHeight
{
get
{
return base.method_2<float>("m_initialBackgroundHeight");
}
}
public float m_initialBackgroundLocalScaleY
{
get
{
return base.method_2<float>("m_initialBackgroundLocalScaleY");
}
}
public float m_initialPadding
{
get
{
return base.method_2<float>("m_initialPadding");
}
}
public UberText m_Text
{
get
{
return base.method_3<UberText>("m_Text");
}
}
}
}
|
using System;
using System.Windows.Forms;
using System.Threading;
using irc_client.forms;
using irc_client.services;
using irc_client.connection;
using irc_client.connection.requests;
using irc_client.session;
namespace irc_client {
public partial class Registration : Form {
public Registration() {
InitializeComponent();
}
private void tableLayoutPanel2_Paint(object sender, PaintEventArgs e) {
}
private void button2_Click(object sender, EventArgs e) {
this.Hide();
FormManager.Instance.GetForm(FormType.Auth).Show();
}
protected override void OnFormClosing(FormClosingEventArgs e) {
if (e.CloseReason == CloseReason.UserClosing) {
e.Cancel = true;
FormManager.Instance.GetForm(FormType.Auth).Show();
this.Visible = false;
}
base.OnFormClosing(e);
}
private void button1_Click(object sender, EventArgs e) {
// reading the textboxs with a registration data.
string login = loginBox.Text;
string password = passwordBox.Text;
string confirmPassword = confirmPasswordBox.Text;
string nickname = nicknameBox.Text;
string addressString = addressBox.Text;
OperationStatus.Instance.RegistrationFeedback = false;
// if password aren't equials then return from the method and writes the message.
if (!password.Equals(confirmPassword)) {
MessageBox.Show("Passwords are not equials!");
return;
}
// Повтор кода. надо бы пофиксить
ServerConnection connection = new ServerConnection();
if (!connection.Open(ServerConnection.STANDART_ADDRESS, ServerConnection.STANDART_PORT)) {
MessageBox.Show("Connection failed. Host " + ServerConnection.STANDART_ADDRESS + ":" + ServerConnection.STANDART_PORT.ToString() + " not found.");
return;
}
connection.StartListen();
ConnectionService.Instance.StartHandling(connection);
IRequest request = new RegisterRequest(login, password, nickname);
RequestRepository.Instance.OutputRequests.Enqueue(request);
Console.WriteLine(!OperationStatus.Instance.RegistrationFeedback);
while (!OperationStatus.Instance.RegistrationFeedback) {
// waiting for the message from the server
Thread.Sleep(100);
}
ConnectionService.Instance.Close(connection);
}
private void Registration_Load(object sender, EventArgs e) {
addressBox.Text = ServerConnection.STANDART_ADDRESS + ":" + ServerConnection.STANDART_PORT;
}
}
}
|
//
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
namespace Dnn.PersonaBar.Themes.Components
{
public class Constants
{
public const string MenuName = "Dnn.Themes";
public const string Edit = "EDIT";
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Fall : MonoBehaviour {
public Transform spawnPoint;
public PlayerController hearth;
void Start(){
hearth = FindObjectOfType<PlayerController> ();
}
void OnCollisionEnter2D(Collision2D col){
if (col.transform.CompareTag ("Player"))
hearth.curHealth -= 2;
col.transform.position = spawnPoint.position;
}
}
|
using BookMyMovie.Data.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace BookMyMovie.Service
{
public interface IMovieService
{
IEnumerable<Movie> GetAll();
Movie GetById(int id);
}
}
|
// Accord Machine Learning Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
//
// This code has been based on the LIBLINEAR project;s implementation for the
// L2-regularized L2-loss support vector classification (dual) machines. The
// original LIBLINEAR license is given below:
//
//
// Copyright (c) 2007-2011 The LIBLINEAR Project.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither name of copyright holders nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
//
// THIS SOFTWARE IS PROVIDED BY THE 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 REGENTS 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.
//
namespace Accord.MachineLearning.VectorMachines.Learning
{
using System;
using System.Diagnostics;
using System.Threading;
/// <summary>
/// Coordinate descent algorithm for the L1 or L2-loss linear Support
/// Vector Regression (epsilon-SVR) learning problem in the dual form
/// (-s 12 and -s 13).
/// </summary>
///
/// <remarks>
/// <para>
/// This class implements a <see cref="SupportVectorMachine"/> learning algorithm
/// specifically crafted for linear machines only. It provides a L2-regularized, L1
/// or L2-loss coordinate descent learning algorithm for optimizing the dual form of
/// learning. The code has been based on liblinear's method <c>solve_l2r_l1l2_svc</c>
/// method, whose original description is provided below.
/// </para>
///
/// <para>
/// Liblinear's solver <c>-s 12</c>: <c>L2R_L2LOSS_SVR_DUAL</c> and <c>-s 13</c>:
/// <c>L2R_L1LOSS_SVR_DUAL</c>. A coordinate descent algorithm for L1-loss and
/// L2-loss linear epsilon-vector regression (epsilon-SVR).
/// </para>
///
/// <code>
/// min_\beta 0.5\beta^T (Q + diag(lambda)) \beta - p \sum_{i=1}^l|\beta_i| + \sum_{i=1}^l yi\beta_i,
/// s.t. -upper_bound_i <= \beta_i <= upper_bound_i,
/// </code>
///
/// <para>
/// where Qij = yi yj xi^T xj and
/// D is a diagonal matrix </para>
///
/// <para>
/// In L1-SVM case:</para>
/// <code>
/// upper_bound_i = C
/// lambda_i = 0
/// </code>
/// <para>
/// In L2-SVM case:</para>
/// <code>
/// upper_bound_i = INF
/// lambda_i = 1/(2*C)
/// </code>
///
/// <para>
/// Given: x, y, p, C and eps as the stopping tolerance</para>
///
/// <para>
/// See Algorithm 4 of Ho and Lin, 2012.</para>
/// </remarks>
///
/// <see cref="SequentialMinimalOptimization"/>
/// <see cref="LinearNewtonMethod"/>
///
public class LinearRegressionCoordinateDescent : BaseSupportVectorRegression,
ISupportVectorMachineLearning, ISupportCancellation
{
int max_iter = 1000;
private double eps = 0.1;
private double[] alpha;
private double[] beta;
private double[] weights;
private double bias;
private Loss loss = Loss.L2;
/// <summary>
/// Constructs a new coordinate descent algorithm for L1-loss and L2-loss SVM dual problems.
/// </summary>
///
/// <param name="machine">A support vector machine.</param>
/// <param name="inputs">The input data points as row vectors.</param>
/// <param name="outputs">The output label for each input point. Values must be either -1 or +1.</param>
///
public LinearRegressionCoordinateDescent(SupportVectorMachine machine, double[][] inputs, double[] outputs)
: base(machine, inputs, outputs)
{
int samples = inputs.Length;
int dimension = inputs[0].Length;
if (!IsLinear)
throw new ArgumentException("Only linear machines are supported.", "machine");
// Lagrange multipliers
this.alpha = new double[samples];
this.beta = new double[samples];
this.weights = new double[dimension];
}
/// <summary>
/// Gets or sets the <see cref="Loss"/> cost function that
/// should be optimized. Default is
/// <see cref="Accord.MachineLearning.VectorMachines.Learning.Loss.L2"/>.
/// </summary>
///
public Loss Loss
{
get { return loss; }
set { loss = value; }
}
/// <summary>
/// Gets the value for the Lagrange multipliers
/// (alpha) for every observation vector.
/// </summary>
///
public double[] Lagrange { get { return alpha; } }
/// <summary>
/// Convergence tolerance. Default value is 0.1.
/// </summary>
///
/// <remarks>
/// The criterion for completing the model training process. The default is 0.1.
/// </remarks>
///
public double Tolerance
{
get { return this.eps; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
this.eps = value;
}
}
/// <summary>
/// Runs the learning algorithm.
/// </summary>
///
/// <param name="token">A token to stop processing when requested.</param>
/// <param name="c">The complexity for each sample.</param>
///
protected override void Run(CancellationToken token, double[] c)
{
double[] w = weights;
double[][] x = Inputs;
double[] y = Outputs;
var random = Accord.Math.Random.Generator.Random;
// Lagrange multipliers
Array.Clear(alpha, 0, alpha.Length);
Array.Clear(beta, 0, beta.Length);
Array.Clear(w, 0, w.Length);
bias = 0;
double C = Complexity;
double p = Epsilon;
double eps = Tolerance;
int iter = 0;
int active_size = x.Length;
int[] index = new int[x.Length];
double d, G, H;
double Gmax_old = Double.PositiveInfinity;
double Gmax_new, Gnorm1_new;
double Gnorm1_init = -1.0; // Gnorm1_init is initialized at the first iteration
double[] QD = new double[x.Length];
// L2R_L2LOSS_SVR_DUAL
double lambda = 0.5 / C;
double upper_bound = Double.PositiveInfinity;
if (loss == Loss.L1)
{
lambda = 0;
upper_bound = C;
}
for (int i = 0; i < x.Length; i++)
{
QD[i] = 0;
double[] xi = x[i];
for (int j = 0; j < xi.Length; j++)
{
double val = xi[j];
QD[i] += val * val;
w[j] += beta[i] * val;
}
index[i] = i;
}
while (iter < max_iter)
{
if (token.IsCancellationRequested)
break;
int i;
Gmax_new = 0;
Gnorm1_new = 0;
for (i = 0; i < active_size; i++)
{
int j = i + random.Next() % (active_size - i);
var old = index[i];
index[i] = index[j];
index[j] = old;
}
for (int s = 0; s < active_size; s++)
{
i = index[s];
G = -y[i] + lambda * beta[i];
H = QD[i] + lambda;
double[] xi = x[i];
for (int j = 0; j < xi.Length; j++)
G += xi[j] * w[j];
double Gp = G + p;
double Gn = G - p;
double violation = 0;
if (beta[i] == 0)
{
if (Gp < 0)
{
violation = -Gp;
}
else if (Gn > 0)
{
violation = Gn;
}
else if (Gp > Gmax_old && Gn < -Gmax_old)
{
active_size--;
var old = index[s];
index[s] = index[active_size];
index[active_size] = old;
s--;
continue;
}
}
else if (beta[i] >= upper_bound)
{
if (Gp > 0)
{
violation = Gp;
}
else if (Gp < -Gmax_old)
{
active_size--;
var old = index[s];
index[s] = index[active_size];
index[active_size] = old;
s--;
continue;
}
}
else if (beta[i] <= -upper_bound)
{
if (Gn < 0)
{
violation = -Gn;
}
else if (Gn > Gmax_old)
{
active_size--;
var old = index[s];
index[s] = index[active_size];
index[active_size] = old;
s--;
continue;
}
}
else if (beta[i] > 0)
{
violation = Math.Abs(Gp);
}
else
{
violation = Math.Abs(Gn);
}
Gmax_new = Math.Max(Gmax_new, violation);
Gnorm1_new += violation;
// obtain Newton direction d
if (Gp < H * beta[i])
{
d = -Gp / H;
}
else if (Gn > H * beta[i])
{
d = -Gn / H;
}
else
{
d = -beta[i];
}
if (Math.Abs(d) < 1.0e-12)
continue;
double beta_old = beta[i];
beta[i] = Math.Min(Math.Max(beta[i] + d, -upper_bound), upper_bound);
d = beta[i] - beta_old;
if (d != 0)
{
xi = x[i];
for (int j = 0; j < xi.Length; j++)
w[j] += d * xi[j];
}
}
if (iter == 0)
Gnorm1_init = Gnorm1_new;
iter++;
if (iter % 10 == 0)
Debug.WriteLine(".");
if (Gnorm1_new <= eps * Gnorm1_init)
{
if (active_size == x.Length)
{
break;
}
else
{
active_size = x.Length;
Debug.WriteLine("*");
Gmax_old = Double.PositiveInfinity;
continue;
}
}
Gmax_old = Gmax_new;
}
Debug.WriteLine("optimization finished, #iter = " + iter);
if (iter >= max_iter)
{
Debug.WriteLine("WARNING: reaching max number of iterations");
Debug.WriteLine("Using -s 11 may be faster (also see FAQ)");
}
// calculate objective value
double v = 0;
int nSV = 0;
for (int i = 0; i < w.Length; i++)
v += w[i] * w[i];
v = 0.5 * v;
for (int i = 0; i < x.Length; i++)
{
v += p * Math.Abs(beta[i]) - y[i] * beta[i] + 0.5 * lambda * beta[i] * beta[i];
if (beta[i] != 0)
nSV++;
}
Debug.WriteLine("Objective value = " + v);
Debug.WriteLine("nSV = " + nSV);
Machine.Weights = new double[Machine.Inputs];
for (int i = 0; i < Machine.Weights.Length; i++)
Machine.Weights[i] = w[i];
Machine.Threshold = bias;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.ComponentModel;
using Apergies.Model;
using Microsoft.Phone.Tasks;
using System.Windows.Threading;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Scheduler;
namespace Apergies
{
public delegate void NotifyDataList();
public delegate void NotifyAttn();
public partial class MainPage : PhoneApplicationPage
{
StrikeLoader today;
StrikeLoader tomorrow;
AllStrikesLoader allstrikes;
DispatcherTimer overlayTimer;
AppSettings storedSettings;
int todayStrikes;
int loadingCounter;
// Constructor
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
// Load data for the ViewModel Items
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
storedSettings = new AppSettings();
DataRefresh();
RegisterScheduledTask();
}
private void RegisterScheduledTask()
{
// A unique name for your task. It is used to
// locate it in from the service.
var taskName = "ApergiesTileUpdate";
// If the task exists
var oldTask = ScheduledActionService.Find(taskName) as PeriodicTask;
if (oldTask != null)
{
ScheduledActionService.Remove(taskName);
}
if (this.storedSettings.UseTileToggleSwitchSetting && this.storedSettings.UpdateTileToggleSwitchSetting)
{
// Create the Task
PeriodicTask task = new PeriodicTask(taskName);
// Description is required
task.Description = "Ανανεώνει τις πληροφορίες για τις απεργίες στο πλακίδιο (tile) της εφαρμογής, όταν η εφαρμογή δε λειτουργεί";
// Add it to the service to execute
try
{
ScheduledActionService.Add(task);
}
catch (Exception ex)
{
}
}
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
if (NavigationService.CanGoBack)
{
e.Cancel = true;
NavigationService.GoBack();
}
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
}
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
DataRefresh();
}
private void DataRefresh()
{
progressOverlay.Show();
attnButton.Visibility = System.Windows.Visibility.Collapsed;
loadingCounter = 3;
today = new StrikeLoader();
tomorrow = new StrikeLoader();
allstrikes = new AllStrikesLoader();
allstrikes.attnNotifier = attnNotifier;
today.dataNotifier = todayNotifier;
tomorrow.dataNotifier = tomorrowNotifier;
allstrikes.dataNotifier = allstrikesNotifier;
today.LoadStrikes("http://apergia.gr/q/index.php?id=today");
tomorrow.LoadStrikes("http://apergia.gr/q/index.php?id=tomorrow");
allstrikes.LoadStrikes("http://feeds.feedburner.com/apergiagr?format=xml");
}
private void todayNotifier()
{
bool empty = false;
List<StrikeRecord> todayStrikesList = today.GetStrikes();
todayList.ItemsSource = todayStrikesList;
foreach (StrikeRecord item in todayStrikesList)
{
if (item.title.Contains("Δεν έχουν καταγραφεί"))
{
empty = true;
}
if (item.title.Contains("Δεν ήταν δυνατή η ανάκτηση"))
{
empty = true;
}
}
if (empty)
{
todayStrikes = 0;
}
else
{
todayStrikes = todayStrikesList.Count;
}
if (this.storedSettings.UseTileToggleSwitchSetting) UpdateLiveTile();
else RemoveLiveTile();
loadingTaskComplete();
}
private void RemoveLiveTile()
{
ShellTile TileToFind = ShellTile.ActiveTiles.First();
if (TileToFind != null)
{
StandardTileData data = new StandardTileData
{
Count = 0,
BackBackgroundImage = new Uri("Empty", UriKind.Relative),
BackContent = string.Empty,
BackTitle = string.Empty
};
// Update the Application Tile
TileToFind.Update(data);
}
}
private void UpdateLiveTile()
{
String tilebackContent = "";
if (todayStrikes == 0)
{
tilebackContent = "Καμμία απεργία σήμερα";
}
else if (todayStrikes == 1)
{
tilebackContent = todayStrikes.ToString() + " απεργία σήμερα";
}
else
{
tilebackContent = todayStrikes.ToString() + " απεργίες σήμερα";
}
// Update Tile
ShellTile TileToFind = ShellTile.ActiveTiles.First();
if (TileToFind != null)
{
StandardTileData NewTileData = new StandardTileData
{
Title = "Απεργίες",
Count = todayStrikes,
BackTitle = "Απεργίες",
//BackBackgroundImage = new Uri(textBoxBackBackgroundImage.Text, UriKind.Relative),
BackContent = tilebackContent
};
// Update the Application Tile
TileToFind.Update(NewTileData);
}
}
private void tomorrowNotifier()
{
tomorrowList.ItemsSource = tomorrow.GetStrikes();
loadingTaskComplete();
}
private void allstrikesNotifier()
{
allList.ItemsSource = allstrikes.GetStrikes();
loadingTaskComplete();
}
private void attnNotifier()
{
attnButton.Visibility = System.Windows.Visibility.Visible;
}
private void loadingTaskComplete()
{
loadingCounter--;
if (loadingCounter == 0) progressOverlay.Hide();
}
private void ApplicationBarItemAbout_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/About.xaml", UriKind.Relative));
}
private void allList_Hold(object sender, System.Windows.Input.GestureEventArgs e)
{
FrameworkElement element = (FrameworkElement)e.OriginalSource;
StrikeRecord item = (StrikeRecord)element.DataContext;
WebBrowserTask browsertask = new WebBrowserTask();
browsertask.Uri = new Uri(item.link);
browsertask.Show();
}
private void attnButton_Click(object sender, RoutedEventArgs e)
{
overlayTimer = new System.Windows.Threading.DispatcherTimer();
overlayTimer.Interval = new TimeSpan(0, 0, 0, 4, 0);
overlayTimer.Tick += new EventHandler(overlayTimer_Tick);
overlayTimer.Start();
noConnOverlay.Show();
}
void overlayTimer_Tick(object sender, EventArgs e)
{
overlayTimer.Stop();
noConnOverlay.Hide();
}
private void ApplicationBarItemSettings_Click(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
}
}
} |
using Ninject;
using SimpleVisioBL;
using SimpleVisioDataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleVisioService
{
public static class SimpleVisioServiceConfig
{
public static void Configure(IKernel kernel)
{
kernel.Bind<ISimpleVisio>().To<SimpleVisio>();
kernel.Bind<ISimpleVisioSaver>().To<FileSimpleVisioSaver>();
kernel.Bind<ISimpleVisioLoader>().To<FileSimpleVisioLoader>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
namespace WebApi.Controllers.Cotizacion
{
public class DolarController : ApiController, IDinero
{
public Task<IEnumerable<string>> GetCotizacion()
{
throw new HttpResponseException(HttpStatusCode.Unauthorized);
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Serilog.Ui.Core;
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Serilog.Ui.Web
{
public class SerilogUiMiddleware
{
private const string EmbeddedFileNamespace = "Serilog.Ui.Web.wwwroot.dist";
private readonly UiOptions _options;
private readonly StaticFileMiddleware _staticFileMiddleware;
private readonly JsonSerializerSettings _jsonSerializerOptions;
private readonly ILogger<SerilogUiMiddleware> _logger;
public SerilogUiMiddleware(
RequestDelegate next,
IWebHostEnvironment hostingEnv,
ILoggerFactory loggerFactory,
UiOptions options,
ILogger<SerilogUiMiddleware> logger
)
{
_options = options;
_logger = logger;
_staticFileMiddleware = CreateStaticFileMiddleware(next, hostingEnv, loggerFactory);
_jsonSerializerOptions = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.None
};
}
public async Task Invoke(HttpContext httpContext)
{
var httpMethod = httpContext.Request.Method;
var path = httpContext.Request.Path.Value;
// If the RoutePrefix is requested (with or without trailing slash), redirect to index URL
if (httpMethod == "GET" && Regex.IsMatch(path, $"^/{Regex.Escape(_options.RoutePrefix)}/api/logs/?$", RegexOptions.IgnoreCase))
{
try
{
httpContext.Response.ContentType = "application/json;charset=utf-8";
if (!CanAccess(httpContext))
{
httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
return;
}
var result = await FetchLogsAsync(httpContext);
httpContext.Response.StatusCode = (int)HttpStatusCode.OK;
await httpContext.Response.WriteAsync(result);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
var errorMessage = httpContext.Request.IsLocal()
? JsonConvert.SerializeObject(new { errorMessage = ex.Message })
: JsonConvert.SerializeObject(new { errorMessage = "Internal server error" });
await httpContext.Response.WriteAsync(JsonConvert.SerializeObject(new { errorMessage }));
}
return;
}
if (httpMethod == "GET" && Regex.IsMatch(path, $"^/?{Regex.Escape(_options.RoutePrefix)}/?$", RegexOptions.IgnoreCase))
{
var indexUrl = httpContext.Request.GetEncodedUrl().TrimEnd('/') + "/index.html";
RespondWithRedirect(httpContext.Response, indexUrl);
return;
}
if (httpMethod == "GET" && Regex.IsMatch(path, $"^/{Regex.Escape(_options.RoutePrefix)}/?index.html$", RegexOptions.IgnoreCase))
{
await RespondWithIndexHtml(httpContext.Response);
return;
}
await _staticFileMiddleware.Invoke(httpContext);
}
private StaticFileMiddleware CreateStaticFileMiddleware(
RequestDelegate next,
IWebHostEnvironment hostingEnv,
ILoggerFactory loggerFactory)
{
var staticFileOptions = new StaticFileOptions
{
RequestPath = $"/{_options.RoutePrefix}",
FileProvider = new EmbeddedFileProvider(typeof(SerilogUiMiddleware).GetTypeInfo().Assembly, EmbeddedFileNamespace),
};
return new StaticFileMiddleware(next, hostingEnv, Options.Create(staticFileOptions), loggerFactory);
}
private void RespondWithRedirect(HttpResponse response, string location)
{
response.StatusCode = 301;
response.Headers["Location"] = location;
}
private async Task RespondWithIndexHtml(HttpResponse response)
{
response.StatusCode = 200;
response.ContentType = "text/html;charset=utf-8";
await using var stream = IndexStream();
var htmlBuilder = new StringBuilder(await new StreamReader(stream).ReadToEndAsync());
htmlBuilder.Replace("%(Configs)", JsonConvert.SerializeObject(
new { _options.RoutePrefix, _options.AuthType }, _jsonSerializerOptions));
await response.WriteAsync(htmlBuilder.ToString(), Encoding.UTF8);
}
private Func<Stream> IndexStream { get; } = () => typeof(AuthorizationOptions).GetTypeInfo().Assembly
.GetManifestResourceStream("Serilog.Ui.Web.wwwroot.index.html");
private async Task<string> FetchLogsAsync(HttpContext httpContext)
{
httpContext.Request.Query.TryGetValue("page", out var pageStr);
httpContext.Request.Query.TryGetValue("count", out var countStr);
httpContext.Request.Query.TryGetValue("level", out var levelStr);
httpContext.Request.Query.TryGetValue("search", out var searchStr);
httpContext.Request.Query.TryGetValue("startDate", out var startDateStar);
httpContext.Request.Query.TryGetValue("endDate", out var endDateStar);
int.TryParse(pageStr, out var currentPage);
int.TryParse(countStr, out var count);
DateTime.TryParse(startDateStar, out var startDate);
DateTime.TryParse(endDateStar, out var endDate);
if (endDate != default)
endDate = new DateTime(endDate.Year, endDate.Month, endDate.Day, 23, 59, 59);
currentPage = currentPage == default ? 1 : currentPage;
count = count == default ? 10 : count;
var provider = httpContext.RequestServices.GetService<IDataProvider>();
var (logs, total) = await provider.FetchDataAsync(currentPage, count, levelStr, searchStr,
startDate == default ? (DateTime?)null : startDate, endDate == default ? (DateTime?)null : endDate);
//var result = JsonSerializer.Serialize(logs, _jsonSerializerOptions);
var result = JsonConvert.SerializeObject(new { logs, total, count, currentPage }, _jsonSerializerOptions);
return result;
}
private static bool CanAccess(HttpContext httpContext)
{
if (httpContext.Request.IsLocal())
return true;
var authOptions = httpContext.RequestServices.GetService<AuthorizationOptions>();
if (!authOptions.Enabled)
return false;
if (!httpContext.User.Identity.IsAuthenticated)
return false;
var userName = httpContext.User.Identity.Name?.ToLower();
if (authOptions.Usernames != null &&
authOptions.Usernames.Any(u => u.ToLower() == userName))
return true;
if (authOptions.Roles != null &&
authOptions.Roles.Any(role => httpContext.User.IsInRole(role)))
return true;
return false;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LoadGaneData : MonoBehaviour
{
private DataBaseLoadGameData _dataBase = new DataBaseLoadGameData();
[SerializeField]
private Text _username;
[SerializeField]
private Text _goldTooth;
[SerializeField]
private Text _goldCoin;
[SerializeField]
private Text _exp;
private void Start()
{
_username.text = PlayerPrefs.GetString("userName");
}
}
|
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Waffles;
using Waffles.UserControls;
public partial class admin_modal_debug_data : AdminModal
{
public override void Build()
{
Modal.Size = WAdminModal.Sizes.Large;
Modal.Label.Append("Debug Data");
Modal.Body.Append("<div id='debug-data'><textarea style='display: none;'></textarea><p class='text-warning'>Loading Debug Data</p><pre></pre></div><script>w.admin.debug_print();</script>");
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using cn.jpush.api.common;
namespace cn.jpush.api.schedule
{
class ScheduleListResult : BaseResult
{
public int total_count;
public int total_pages;
public int page;
public SchedulePayload[] schedules;
public override bool isResultOK()
{
throw new NotImplementedException();
}
public SchedulePayload[] getSchedules()
{
return this.schedules;
}
public int getTotal_count()
{
return this.total_count;
}
public int getTotal_pages()
{
return this.total_pages;
}
public int getPage()
{
return this.page;
}
}
}
|
namespace AllNameToTxt.Models
{
public class FileName
{
public string CurrentFileName { get; set; }
public string OldFileName { get; set; }
public string Performer { get; set; }
public string Title { get; set; }
public string Time { get; set; }
public string Album { get; set; }
public string Genres { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Entities;
using ShareTradingModel;
namespace Entities.Test
{
public class AddressTest: EntityTest<Address>
{
}
}
|
using UnityEngine;
using System;
using System.Collections.Generic;
[RequireComponent(typeof(BoxCollider2D))]
public class RaycastController : MonoBehaviour {
public LayerMask collisionMask;
public const float skinWidth = .015f;
const float dstBetweenRays = .25f;
[HideInInspector]
public int horizontalRayCount;
[HideInInspector]
public int verticalRayCount;
[HideInInspector]
public float horizontalRaySpacing;
[HideInInspector]
public float verticalRaySpacing;
[HideInInspector]
public BoxCollider2D boxCollider;
public RaycastOrigins raycastOrigins;
public virtual void Awake() {
boxCollider = GetComponent<BoxCollider2D>();
}
public virtual void Start() {
CalculateRaySpacing();
}
public void UpdateRaycastOrigins() {
Bounds bounds = boxCollider.bounds;
bounds.Expand(skinWidth * -2);
//Calculate world space locations for corners
raycastOrigins.topRight = transform.TransformPoint(new Vector2(boxCollider.size.x, boxCollider.size.y) * 0.5f + boxCollider.offset);
raycastOrigins.topLeft = transform.TransformPoint(new Vector2(-boxCollider.size.x, boxCollider.size.y) * 0.5f + boxCollider.offset);
raycastOrigins.bottomRight = transform.TransformPoint(new Vector2(boxCollider.size.x, -boxCollider.size.y) * 0.5f + boxCollider.offset);
raycastOrigins.bottomLeft = transform.TransformPoint(new Vector2(-boxCollider.size.x, -boxCollider.size.y) * 0.5f + boxCollider.offset);
}
public void CalculateRaySpacing() {
Bounds bounds = boxCollider.bounds;
bounds.Expand(skinWidth * -2);
float boundsWidth = bounds.size.x;
float boundsHeight = bounds.size.y;
horizontalRayCount = Mathf.RoundToInt(boundsHeight / dstBetweenRays);
verticalRayCount = Mathf.RoundToInt(boundsWidth / dstBetweenRays);
horizontalRaySpacing = bounds.size.y / (horizontalRayCount - 1);
verticalRaySpacing = bounds.size.x / (verticalRayCount - 1);
}
/*void OnDrawGizmos() {
Gizmos.color = Color.red;
Gizmos.DrawSphere(raycastOrigins.bottomLeft, 0.1f);
Gizmos.DrawSphere(raycastOrigins.bottomRight, 0.1f);
Gizmos.DrawSphere(raycastOrigins.topLeft, 0.1f);
Gizmos.DrawSphere(raycastOrigins.topRight, 0.1f);
}*/
/*void OnDrawGizmos() {
BoxCollider2D b = GetComponent<BoxCollider2D>();
Gizmos.color = Color.red;
Gizmos.DrawSphere(transform.TransformPoint(b.offset + new Vector2(b.size.x, b.size.y) * 0.5f), 0.1f);
Gizmos.DrawSphere(transform.TransformPoint(b.offset + new Vector2(b.size.x, -b.size.y) * 0.5f), 0.1f);
Gizmos.DrawSphere(transform.TransformPoint(b.offset + new Vector2(-b.size.x, b.size.y) * 0.5f), 0.1f);
Gizmos.DrawSphere(transform.TransformPoint(b.offset + new Vector2(-b.size.x, -b.size.y) * 0.5f), 0.1f);
Gizmos.DrawSphere(transform.TransformPoint(b.offset + new Vector2(b.size.x, b.size.y) * 0.5f), 0.1f);
Gizmos.DrawSphere(transform.TransformPoint(b.offset + new Vector2(b.size.x, -b.size.y) * 0.5f), 0.1f);
Gizmos.DrawSphere(transform.TransformPoint(b.offset + new Vector2(-b.size.x, b.size.y) * 0.5f), 0.1f);
Gizmos.DrawSphere(transform.TransformPoint(b.offset + new Vector2(-b.size.x, -b.size.y) * 0.5f), 0.1f);
}*/
public struct RaycastOrigins {
public Vector2 topLeft, topRight;
public Vector2 bottomLeft, bottomRight;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Analytics;
using UnityEngine.EventSystems;
public class PopUp_Card_Hide : MonoBehaviour, IPointerClickHandler
{
public GameObject currentPopUp;
private PopUp_Reactivate reactivator;
private void Start()
{
reactivator = FindObjectOfType<PopUp_Reactivate>();
}
public void OnPointerClick(PointerEventData eventData)
{
Hide();
}
public void Hide()
{
Analytics.CustomEvent("Minimized PopUp");
currentPopUp.SetActive(false);
reactivator.SetSaved(currentPopUp);
}
}
|
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Spectre.Console;
using Spectre.Console.Cli;
namespace Proto.Commands
{
public class EnumsSettings : CommandSettings
{ }
public class EnumsCommand : AsyncCommand<EnumsSettings>
{
private ILogger Logger { get; }
public EnumsCommand(ILogger<ConsoleCommand> logger)
{
Logger = logger;
}
public override Task<int> ExecuteAsync(CommandContext context, EnumsSettings settings)
{
Logger.LogInformation($"Starting enums");
Dinges a = Dinges.een;
Logger.LogInformation($"{a}");
Logger.LogInformation($"{Enum.ToObject(typeof(Dinges), 2)}");
Logger.LogInformation(String.Join(',', Enum.GetNames(typeof(Dinges))));
StackingDebuff debuff = StackingDebuff.Slow;
Logger.LogInformation($"debuff: {debuff}");
debuff |= StackingDebuff.Confused;
Logger.LogInformation($"debuff after |=: {debuff}");
return Task.FromResult<int>(0);
}
enum Dinges : int
{
een = 1,
twee = 2
}
[Flags]
public enum StackingDebuff : UInt64
{
None = 0,
Bleeding = 1 << 1,
Poison = 1 << 2,
Slow = 1 << 3,
Confused = 1 << 4,
All = Bleeding | Poison | Slow | Confused
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Training_App.Classes
{
class square : Classes.shape
{
public override void theArea(int _l)
{
int area = _l*_l;
Console.WriteLine(area);
}
}
}
|
using Contoso.Domain.Entities;
using Contoso.Forms.Configuration;
using Contoso.Forms.Configuration.Bindings;
using Contoso.Forms.Configuration.DataForm;
using Contoso.XPlatform.Tests.Helpers;
using Contoso.XPlatform.Services;
using Contoso.XPlatform.ViewModels.Factories;
using Contoso.XPlatform.ViewModels.ReadOnlys;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Contoso.XPlatform.Tests
{
public class ReadOnlyCollectionCellPropertiesUpdaterTest
{
public ReadOnlyCollectionCellPropertiesUpdaterTest()
{
serviceProvider = ServiceProviderHelper.GetServiceProvider();
}
#region Fields
private readonly IServiceProvider serviceProvider;
#endregion Fields
[Fact]
public void MapInstructorModelToIReadOnlyList()
{
//arrange
InstructorModel instructor = new()
{
ID = 3,
FirstName = "John",
LastName = "Smith",
HireDate = new DateTime(2021, 5, 20),
OfficeAssignment = new OfficeAssignmentModel
{
Location = "Location1"
},
Courses = new List<CourseAssignmentModel>
{
new CourseAssignmentModel
{
CourseID = 1,
InstructorID = 2,
CourseTitle = "Chemistry"
},
new CourseAssignmentModel
{
CourseID = 2,
InstructorID = 3,
CourseTitle = "Physics"
},
new CourseAssignmentModel
{
CourseID = 3,
InstructorID = 4,
CourseTitle = "Mathematics"
}
}
};
List<ItemBindingDescriptor> itemBindings = new()
{
new TextItemBindingDescriptor
{
Name = "Header",
Property = "OfficeAssignment.Location",
StringFormat = "{0}",
TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "TextTemplate" }
},
new TextItemBindingDescriptor
{
Name = "Text",
Property = "HireDate",
StringFormat = "{0:MMMM dd, yyyy}",
TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "DateTemplate" }
},
new MultiSelectItemBindingDescriptor
{
Name = "Detail",
Property = "Courses",
StringFormat = "{0}",
MultiSelectTemplate = Descriptors.InstructorFormWithPopupOfficeAssignment.FieldSettings.OfType<MultiSelectFormControlSettingsDescriptor>().Single(f => f.Field == "Courses").MultiSelectTemplate
}
};
ICollection<IReadOnly> properties = GetCollectionCellItemsBuilder
(
itemBindings,
typeof(InstructorModel)
).CreateFields();
//act
serviceProvider.GetRequiredService<IReadOnlyCollectionCellPropertiesUpdater>().UpdateProperties
(
properties,
typeof(InstructorModel),
instructor,
itemBindings
);
//assert
IDictionary<string, object?> propertiesDictionary = properties.ToDictionary(property => property.Name, property => property.Value);
Assert.Equal("Location1", propertiesDictionary["OfficeAssignment.Location"]);
Assert.Equal(new DateTime(2021, 5, 20), propertiesDictionary["HireDate"]);
Assert.Equal(1, ((IEnumerable<CourseAssignmentModel>)propertiesDictionary["Courses"]!).First().CourseID);
}
[Fact]
public void MapCourseModelToIReadOnlyList()
{
//arrange
CourseModel course = new()
{
CourseID = 3,
Title = "Chemistry",
Credits = 5
};
List<ItemBindingDescriptor> itemBindings = new()
{
new TextItemBindingDescriptor
{
Name = "Header",
Property = "CourseID",
StringFormat = "{}",
TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "DateTemplate" }
},
new TextItemBindingDescriptor
{
Name = "Detail",
Property = "Title",
StringFormat = "{0",
TextTemplate = new TextFieldTemplateDescriptor { TemplateName = "DateTemplate" }
},
new DropDownItemBindingDescriptor
{
Name = "Detail",
Property = "Credits",
StringFormat = "{0}",
DropDownTemplate = Descriptors.CourseForm.FieldSettings.OfType<FormControlSettingsDescriptor>().Single(f => f.Field == "Credits").DropDownTemplate
}
};
ICollection<IReadOnly> properties = GetCollectionCellItemsBuilder
(
itemBindings,
typeof(CourseModel)
)
.CreateFields();
//act
serviceProvider.GetRequiredService<IReadOnlyCollectionCellPropertiesUpdater>().UpdateProperties
(
properties,
typeof(CourseModel),
course,
itemBindings
);
//assert
IDictionary<string, object?> propertiesDictionary = properties.ToDictionary(property => property.Name, property => property.Value);
Assert.Equal(3, propertiesDictionary["CourseID"]);
Assert.Equal("Chemistry", propertiesDictionary["Title"]);
Assert.Equal(5, propertiesDictionary["Credits"]);
}
private ICollectionCellItemsBuilder GetCollectionCellItemsBuilder(List<ItemBindingDescriptor> bindingDescriptors, Type modelType)
{
return serviceProvider.GetRequiredService<ICollectionBuilderFactory>().GetCollectionCellItemsBuilder
(
modelType,
bindingDescriptors
);
}
}
}
|
using System;
namespace Fernando
{
public class Estoque
{
public int Id { get; set; }
public int Quantidade { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
public abstract class InInput : MonoBehaviour
{
public static InInput controller;
void OnEnable()
{
if(controller == null)
{
controller = this;
DontDestroyOnLoad(gameObject);
}
else if(controller != this)
this.enabled = false;
}
public abstract float getPressure();
public abstract float getLC1();
public abstract float getLC2();
public abstract Pair<float,float> getTouchPosition();
public abstract bool isOnGlass();
public abstract Quaternion getRotation();
public abstract void UpdatePacket();
}
|
using Microsoft.AspNetCore.Http;
namespace FirstWebApp.ViewModels
{
public class Image
{
public string Path { get; set; }
public IFormFile fullInfo { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace JsonBAM.Data.Entities
{
public class Log
{
public int Id { get; set; }
public string Key { get; set; }
public string HeaderJson { get; set; }
public string LogJson { get; set; }
public DateTime DateCreated { get; set; }
public string Verb { get; set; }
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Item {
public enum Types { Revolver, Pendant, Helm, Tunic }
public enum Qualities { Common, Uncommon, Rare, Epic };
public Types itemType;
public Qualities itemQuality;
public int itemLevel;
public string itemName;
//this is for the purpose of the RandomlyGenerateStats function.
int[] stats = new int[5] { 1, 2, 3, 4, 5 };
//items can have the following stats
public int maximumHealth = 0;
public int maximumMana = 0;
public int healthRegen = 0;
public int manaRegen = 0;
public int dodgeChance = 0;
//base stat for revolvers, can only occur on revolvers.
public int chamberCapacity = 0;
//base stat for non-revolvers, can only occur on non-revolvers.
public int damageReduction = 0;
//the player starts with one item which is defined here.
public Item startingRevolver;
//This function is using a random number generator to decide the type of the item.
public void RollItemType()
{
int enumSize = Enum.GetNames(typeof(Types)).Length;
int temp = UnityEngine.Random.Range(0, enumSize);
itemType = (Types)temp;
}
//This function is using a random number generator to decide the quality of the item.
public void RollItemQuality()
{
int quality;
//initializing a temporary variable and settiing it's value to be random between the ranges of 1 and 100.
int temp = UnityEngine.Random.Range(1, 101);
//setting the quality of the item based on the temp variable's value.
if (temp <= 55) quality = 0; //55% chance for the item to be of common quality.
else if (temp <= 85) quality = 1; //30% chance for the item to be of uncommon quality.
else if (temp <= 95) quality = 2; //10% chance for the item to be of rare quality.
else quality = 3; //5% chance for the item to be of epic quality.
itemQuality = (Qualities)quality;
}
//Constructs a name for the item based on it's quality, type, and item level.
public void GenerateItemName()
{
//if the item's quality is epic, the name will be resolved in the following if statement.
if ((int)itemQuality == 3)
{
if ((int)itemType == 0) itemName = "Handgun of the Visually Impaired Marksman";
else if ((int)itemType == 1) itemName = "Pendant of the Visually Impaired Marksman";
else if ((int)itemType == 2) itemName = "Faceguard of the Visually Impaired Marksman";
else if ((int)itemType == 3) itemName = "Chestguard of the Visually Impaired Marksman";
else Debug.LogError("Not sure how to name item of type " + (int)itemType + ". Constructing the name for this epic item failed.");
return;
}
//If the item's quality isn't epic, the itemName string is constructed in the rest of this function, starting with an empty string.
string tempName = "";
//adding prefix based on quality
if ((int)itemQuality == 1) tempName += "Superior ";
else if ((int)itemQuality == 2) tempName += "Exceptional ";
//adding the middle of the itemName based on type
if ((int)itemType == 0) tempName += "Pistol";
else if ((int)itemType == 1) tempName += "Amulet";
else if ((int)itemType == 2) tempName += "Faceguard";
else if ((int)itemType == 3) tempName += "Chestpiece";
else Debug.LogError("Not sure how to name item of type " + (int)itemType + ". Constructing the name for this non-epic item failed.");
tempName += " ";
//adding the sufix based on item level
if (itemLevel < 5) tempName += "of the Apprentice";
else if (itemLevel < 10) tempName += "of the Novice";
else if (itemLevel < 15) tempName += "of the Adept";
else if (itemLevel < 20) tempName += "of the Expert";
else if (itemLevel >= 20) tempName += "of the Master";
else Debug.LogError("Not sure how to add sufix for this item level: " + itemLevel);
//the construction of the name is finished
itemName = tempName;
}
//The stats for the item depend on the item's quality. Common means the item only has a base stat, but the value of the base stat is increased (capacity for revolver, damage reduction for armor).
//Uncommon means base stat + 1 additional stat. Rare is +2 stats and Epic is +2 stats with increased base stat. Common and uncommon equipment should be at about the same power level, while rare should be higher than that,
//and epic should be best in slot. The game should be balanced without taking epics into consideration and they should be very rare. Epics should also scale with level, so if you get an epic you are done with that equipment slot.
public void GenerateItemStats()
{
//adds base stats to an item. adds additional base stats if the item's quality is normal or epic.
if (itemType == Types.Revolver)
{
chamberCapacity = 6 + itemLevel % 4;
if (itemQuality == Qualities.Common || itemQuality == Qualities.Epic)
{
chamberCapacity++;
}
}
else if (itemType != Types.Revolver)
{
damageReduction = 5 + (itemLevel * 2);
if (itemQuality == Qualities.Common || itemQuality == Qualities.Epic)
{
damageReduction += 2;
}
}
//if the item quality is higher than common, add additional stats.
if (itemQuality == Qualities.Uncommon)
{
RandomlyAddStats(1);
}
else if (itemQuality == Qualities.Rare || itemQuality == Qualities.Epic)
{
RandomlyAddStats(2);
}
}
private void RandomlyAddStats(int amountOfStatsToAdd)
{
FisherYatesShuffle(stats);
for (int i = 0; i < amountOfStatsToAdd; i++)
{
AddStat(stats[i]);
}
}
//shuffles the given int array using the Fisher-Yates algorithm.
private void FisherYatesShuffle(int[] stats)
{
// Loops through array
for (int i = stats.Length - 1; i > 0; i--)
{
// Randomize a number between 0 and i (so that the range decreases each time)
int rnd = UnityEngine.Random.Range(0, i);
// Save the value of the current i, otherwise it'll overright when we swap the values
int temp = stats[i];
// Swap the new and old values
stats[i] = stats[rnd];
stats[rnd] = temp;
}
}
//adds the stat n to an item.
private void AddStat(int n)
{
if (n == 1) AddMaximumHealthBasedOnItemLevel();
else if (n == 2) AddMaximumManaBasedOnItemLevel();
else if (n == 3) AddHealthRegenBasedOnItemLevel();
else if (n == 4) AddManaRegenBasedOnItemLevel();
else if (n == 5) AddDodgeChanceBasedOnItemLevel();
else Debug.LogError("Invalid stat number. Didn't add anything!");
}
//the following functions decide the value of the non-base stats for an item of a given itemLevel, and add that stat to the item.
private void AddMaximumHealthBasedOnItemLevel()
{
maximumHealth += 10 + (itemLevel * 3);
}
private void AddMaximumManaBasedOnItemLevel()
{
maximumMana += 8 + (itemLevel * 2);
}
private void AddHealthRegenBasedOnItemLevel()
{
healthRegen += 5 + (3 * itemLevel);
}
private void AddManaRegenBasedOnItemLevel()
{
manaRegen += 5 + (2 * itemLevel);
}
private void AddDodgeChanceBasedOnItemLevel()
{
dodgeChance += 3 + itemLevel;
}
//creates the starting revolver for the player.
public static Item StartingRevolver()
{
Item temp = new Item
{
itemName = "Rusty Revolver",
itemQuality = Qualities.Common,
itemType = Types.Revolver,
itemLevel = 1,
chamberCapacity = 6
};
return temp;
}
}
|
using LuaInterface;
using SLua;
using System;
public class Lua_UnityEngine_TexGenMode : LuaObject
{
public static void reg(IntPtr l)
{
LuaObject.getEnumTable(l, "UnityEngine.TexGenMode");
LuaObject.addMember(l, 0, "None");
LuaObject.addMember(l, 1, "SphereMap");
LuaObject.addMember(l, 2, "Object");
LuaObject.addMember(l, 3, "EyeLinear");
LuaObject.addMember(l, 4, "CubeReflect");
LuaObject.addMember(l, 5, "CubeNormal");
LuaDLL.lua_pop(l, 1);
}
}
|
// ************************************************************************
// Copyright (C) 2001, Patrick Charles and Jonas Lehmann *
// Distributed under the Mozilla Public License *
// http://www.mozilla.org/NPL/MPL-1.1.txt *
// *************************************************************************
using System;
using AnsiEscapeSequences_Fields = SharpPcap.Packets.Util.AnsiEscapeSequences_Fields;
using ArrayHelper = SharpPcap.Packets.Util.ArrayHelper;
using Timeval = SharpPcap.Packets.Util.Timeval;
namespace SharpPcap.Packets
{
/// <summary> An ICMP packet.
/// <p>
/// Extends an IP packet, adding an ICMP header and ICMP data payload.
/// </p>
/// </summary>
[Serializable]
public class ICMPPacket : IPPacket, ICMPFields
{
/// <summary> Fetch the ICMP header a byte array.</summary>
virtual public byte[] ICMPHeader
{
get
{
return PacketEncoding.extractHeader(_ipPayloadOffset, ICMPFields_Fields.ICMP_HEADER_LEN, Bytes);
}
}
/// <summary> Fetch the ICMP header as a byte array.</summary>
override public byte[] Header
{
get
{
return ICMPHeader;
}
}
/// <summary> Fetch the ICMP data as a byte array.</summary>
virtual public byte[] ICMPData
{
get
{
int dataLen = Bytes.Length - _ipPayloadOffset - ICMPFields_Fields.ICMP_HEADER_LEN;
return PacketEncoding.extractData(_ipPayloadOffset, ICMPFields_Fields.ICMP_HEADER_LEN, Bytes, dataLen);
}
}
/// <summary> Fetch the ICMP message type code. Formerly .getMessageType().</summary>
virtual public int MessageMajorCode
{
get
{
return ArrayHelper.extractInteger(Bytes, _ipPayloadOffset + ICMPFields_Fields.ICMP_CODE_POS, ICMPFields_Fields.ICMP_CODE_LEN);
}
set
{
ArrayHelper.insertLong(Bytes, value, _ipPayloadOffset + ICMPFields_Fields.ICMP_CODE_POS, ICMPFields_Fields.ICMP_CODE_LEN);
}
}
/// <deprecated> use getMessageMajorCode().
/// </deprecated>
virtual public int MessageType
{
get
{
return MessageMajorCode;
}
set
{
MessageMajorCode = value;
}
}
/// <summary> Fetch the ICMP message type, including subcode. Return value can be
/// used with ICMPMessage.getDescription().
/// </summary>
/// <returns> a 2-byte value containing the message type in the high byte
/// and the message type subcode in the low byte.
/// </returns>
virtual public int MessageCode
{
get
{
return ArrayHelper.extractInteger(Bytes, _ipPayloadOffset + ICMPFields_Fields.ICMP_SUBC_POS, ICMPFields_Fields.ICMP_SUBC_LEN);
}
set
{
ArrayHelper.insertLong(Bytes, value, _ipPayloadOffset + ICMPFields_Fields.ICMP_SUBC_POS, ICMPFields_Fields.ICMP_SUBC_LEN);
}
}
/// <summary> Fetch the ICMP message subcode.</summary>
virtual public int MessageMinorCode
{
get
{
return ArrayHelper.extractInteger(Bytes, _ipPayloadOffset + ICMPFields_Fields.ICMP_SUBC_POS, ICMPFields_Fields.ICMP_SUBC_LEN);
}
set
{
ArrayHelper.insertLong(Bytes, value, _ipPayloadOffset + ICMPFields_Fields.ICMP_SUBC_POS, ICMPFields_Fields.ICMP_SUBC_LEN);
}
}
virtual public int MessageKey
{
get
{
return (MessageType << 0x08) + MessageCode;
}
}
//UPGRADE_NOTE: Respective javadoc comments were merged. It should be changed in order to comply with .NET documentation conventions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1199'"
/// <summary> Fetch the ICMP header checksum.</summary>
/// <summary> Sets the ICMP header checksum.</summary>
virtual public int ICMPChecksum
{
get
{
return ArrayHelper.extractInteger(Bytes, _ipPayloadOffset + ICMPFields_Fields.ICMP_CSUM_POS, ICMPFields_Fields.ICMP_CSUM_LEN);
}
set
{
ArrayHelper.insertLong(Bytes, value, _ipPayloadOffset + ICMPFields_Fields.ICMP_CSUM_POS, ICMPFields_Fields.ICMP_CSUM_LEN);
}
}
virtual public bool ValidICMPChecksum
{
get
{
int onesSum = ChecksumUtils.OnesSum(base.IPData);
return (onesSum == 0xFFFF);
}
}
virtual public bool IsEchoRequestOrReply
{
get
{
return MessageKey == ICMPMessages_Fields.ECHO_REPLY ||
MessageKey == ICMPMessages_Fields.ECHO;
}
}
/// <summary> Fetch the ICMP message identifier.</summary>
virtual public int Id
{
get
{
return ArrayHelper.extractInteger(Bytes, _ipPayloadOffset + ICMPFields_Fields.ICMP_ID_POS, ICMPFields_Fields.ICMP_ID_LEN);
}
}
/// <summary> Fetch the ICMP message sequence number.</summary>
virtual public int SequenceNumber
{
get
{
return ArrayHelper.extractInteger(Bytes, _ipPayloadOffset + ICMPFields_Fields.ICMP_SEQ_POS, ICMPFields_Fields.ICMP_SEQ_LEN);
}
}
/// <summary> Fetch ascii escape sequence of the color associated with this packet type.</summary>
override public System.String Color
{
get
{
return AnsiEscapeSequences_Fields.LIGHT_BLUE;
}
}
public ICMPPacket(int lLen, byte[] bytes)
: base(lLen, bytes)
{
}
public ICMPPacket(int lLen, byte[] bytes, Timeval tv)
: this(lLen, bytes)
{
this._timeval = tv;
}
/// <summary> Fetch the ICMP data as a byte array.</summary>
public override byte[] Data
{
get
{
return ICMPData;
}
}
/// <summary> Fetch the ICMP header checksum.</summary>
public int Checksum
{
get
{
return ICMPChecksum;
}
set
{
ICMPChecksum = value;
}
}
/// <summary> Computes the ICMP checksum, optionally updating the ICMP checksum header.
///
/// </summary>
/// <param name="update">Specifies whether or not to update the ICMP checksum
/// header after computing the checksum. A value of true indicates
/// the header should be updated, a value of false indicates it
/// should not be updated.
/// </param>
/// <returns> The computed ICMP checksum.
/// </returns>
public int ComputeICMPChecksum(bool update)
{
//return base.ComputeTransportLayerChecksum(ICMPFields_Fields.ICMP_CSUM_POS, update, false);
throw new System.NotImplementedException();
}
/// <summary> Same as <code>computeICMPChecksum(true);</code>
///
/// </summary>
/// <returns> The computed ICMP checksum value.
/// </returns>
public int ComputeICMPChecksum()
{
return ComputeICMPChecksum(true);
}
/// <summary> Convert this ICMP packet to a readable string.</summary>
public override System.String ToString()
{
return ToColoredString(false);
}
/// <summary> Generate string with contents describing this ICMP packet.</summary>
/// <param name="colored">whether or not the string should contain ansi
/// color escape sequences.
/// </param>
public override System.String ToColoredString(bool colored)
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
buffer.Append('[');
if (colored)
buffer.Append(Color);
buffer.Append("ICMPPacket");
if (colored)
buffer.Append(AnsiEscapeSequences_Fields.RESET);
buffer.Append(": ");
buffer.Append(ICMPMessage.getDescription(MessageKey));
buffer.Append(", ");
buffer.Append(SourceAddress + " -> " + DestinationAddress);
buffer.Append(" l=" + ICMPFields_Fields.ICMP_HEADER_LEN + "," + (Bytes.Length - _ipPayloadOffset - ICMPFields_Fields.ICMP_HEADER_LEN));
buffer.Append(']');
return buffer.ToString();
}
}
}
|
namespace InfernoInfinity.Models.Weapons
{
public class Sword
{
}
} |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using HedgeHog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HedgeHog.Core;
namespace HedgeHog.Tests {
[TestClass()]
public class IEnumerableCoreTests {
[TestMethod()]
public void GetRangeByDates() {
var start = DateTime.Parse("1/2/2000");
var start2 = DateTime.Parse("1/2/1999");
var end = DateTime.Parse("1/3/2000");
var end2 = DateTime.Parse("1/30/2000");
var data = new[] {
new { d = DateTime.Parse("1/1/2000") },
new { d = start},
new { d = end },
new { d = DateTime.Parse("1/4/2000") }
}.ToList();
var range = data.GetRange(start, end, a => a.d);
Assert.AreEqual(start, range[0].d);
Assert.AreEqual(end, range[1].d);
Console.WriteLine(range.ToJson());
range = data.GetRange(start2, end, a => a.d);
Console.WriteLine(range.ToJson());
Assert.AreEqual(data[0].d, range[0].d);
Assert.AreEqual(end, range.Last().d);
range = data.GetRange(start, end2, a => a.d);
Console.WriteLine(range.ToJson());
Assert.AreEqual(start, range[0].d);
Assert.AreEqual(data.Last().d, range.Last().d);
range = data.GetRange(start2, end2, a => a.d);
Console.WriteLine(range.ToJson());
Assert.AreEqual(data[0].d, range[0].d);
Assert.AreEqual(data.Last().d, range.Last().d);
}
[TestMethod()]
public void SingleOrElse() {
Assert.AreEqual(3, new[] { 1, 2 }.SingleOrElse(() => 3));
Assert.AreEqual(3, new[] { 3 }.SingleOrElse(() => 3));
}
[TestMethod()]
public void AddBusinessDays() {
var start = DateTime.Now.Date.AddDays(4);
Assert.AreEqual(start.AddDays(2), start.AddBusinessDays(0));
Assert.AreEqual(start.AddDays(3), start.AddBusinessDays(1));
start = DateTime.Now.Date;
Assert.AreEqual(start.AddDays(2), start.AddBusinessDays(2));
Assert.AreEqual(start.AddDays(7), start.AddBusinessDays(5));
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity.ModelConfiguration;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RepositoryAndUnitOfWorkPatterns.Domain;
namespace RepositoryAndUnitOfWorkPatterns.EntityFramework.EntityConfigurations
{
public class OrderConfiguration : EntityTypeConfiguration<Order>
{
public OrderConfiguration()
{
HasRequired(c => c.Customer)
.WithMany(a => a.Orders)
.HasForeignKey(c => c.CustomerId)
.WillCascadeOnDelete(false);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Airfield_Simulator.Core.Models
{
public interface ISimulationProperties : INotifyPropertyChanged
{
double SimulationSpeed { get; set; }
int InstructionsPerMinute { get; set; }
int AircraftSpawnsPerMinute { get; set; }
int AircraftSpeed { get; set; }
}
}
|
using System;
namespace Py2Cs.Logging
{
public class Logger
{
public void Log(string str, LogLevel level)
{
var oldColor = Console.ForegroundColor;
Console.ForegroundColor = GetColor(level);
Console.WriteLine(str);
Console.ForegroundColor = oldColor;
}
public void LogHeading(string str, LogLevel level)
{
var oldColor = Console.ForegroundColor;
Console.ForegroundColor = GetColor(level);
Console.WriteLine();
Console.WriteLine(str);
Console.WriteLine(new string('-', str.Length));
Console.ForegroundColor = oldColor;
}
private ConsoleColor GetColor(LogLevel level)
{
switch (level)
{
case LogLevel.Info:
return ConsoleColor.Yellow;
case LogLevel.Error:
return ConsoleColor.Red;
default:
return Console.ForegroundColor;
}
}
}
} |
using UnityEngine;
using System.Collections;
using Jolly;
namespace Jolly
{
public class JollyDebug : MonoBehaviour
{
// Add strings to this array to make "GetFlag", "SetFlag", "ExecuteIf", "Log*If" work with these flags.
private string[] Flags = new string[] {
};
private bool[] FlagValues;
private void InitializeSortedFlags ()
{
System.Array.Sort(this.Flags);
this.FlagValues = new bool[this.Flags.Length];
for (int i = 0; i < this.Flags.Length; ++i)
{
this.FlagValues[i] = false;
}
}
public IEnumerator DisplayFlagsEnumerator ()
{
return this.Flags.GetEnumerator();
}
private int IndexOfFlag(string flag)
{
return System.Array.BinarySearch(this.Flags, flag);
}
public static bool GetFlag(string flag)
{
JollyDebug self = JollyDebug.Instance;
int index = self.IndexOfFlag(flag);
if (index < 0)
{
return false;
}
return !self.FlagValues[index];
}
public static void SetFlag(string flag, bool value)
{
JollyDebug self = JollyDebug.Instance;
int index = self.IndexOfFlag(flag);
if (index >= 0)
{
self.FlagValues[index] = value;
}
}
private bool EvaluateFlagExpression(string flagExpression)
{
string[] substrings = flagExpression.Split (new char[] {' '}, System.StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < substrings.Length; ++i)
{
int index = this.IndexOfFlag(substrings[i]);
JollyDebug.Assert (index > 0, "substring[{0}] == {1} not found in debug flags", i, substrings[i]);
if (this.FlagValues[i])
{
return true;
}
}
return false;
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void ExecuteIf(string flagExpression, System.Action callback)
{
JollyDebug self = JollyDebug.Instance;
if (self.EvaluateFlagExpression(flagExpression))
{
callback.Invoke ();
}
}
public class Expression
{
public string Name;
public string LastValue;
public System.Func<float> ReturnsFloat;
public System.Func<string> ReturnsString;
public System.Func<bool> ReturnsBool;
public Expression(string name)
{
this.Name = name;
}
public Expression(string name, System.Func<float> returnsFloat)
{
this.Name = name;
this.ReturnsFloat = returnsFloat;
}
public Expression(string name, System.Func<string> returnsString)
{
this.Name = name;
this.ReturnsString = returnsString;
}
public Expression(string name, System.Func<bool> returnsBool)
{
this.Name = name;
this.ReturnsBool = returnsBool;
}
public void Update()
{
if (null != this.ReturnsFloat)
{
this.SetLastValue(this.ReturnsFloat());
}
else if (null != this.ReturnsString)
{
this.SetLastValue(this.ReturnsString());
}
else if (null != this.ReturnsBool)
{
this.SetLastValue(this.ReturnsBool());
}
}
public void SetLastValue(float floatValue)
{
this.LastValue = floatValue.ToString("0.00");
}
public void SetLastValue(string stringValue)
{
this.LastValue = stringValue;
}
public void SetLastValue(bool boolValue)
{
this.LastValue = boolValue.ToString();
}
};
public class ExpressionsByOwner
{
public MonoBehaviour Owner;
public ArrayList Expressions = new ArrayList();
public bool Enabled = true;
public ExpressionsByOwner(MonoBehaviour owner)
{
this.Owner = owner;
}
public void Add(Expression expression)
{
this.Expressions.Add (expression);
}
public Expression GetExpression(string name)
{
foreach (Expression expression in this.Expressions)
{
if (expression.Name.Equals(name))
{
return expression;
}
}
Expression newExpression = new Expression(name);
this.Add (newExpression);
return newExpression;
}
public void Update()
{
if (!this.Enabled)
{
return;
}
JollyDebug.Assert(!this.OwnerIsMissing);
foreach (Expression expression in this.Expressions)
{
expression.Update();
}
}
public bool OwnerIsMissing
{
get
{
return null == this.Owner;
}
}
}
private ArrayList ExpressionsByOwnerList = new ArrayList();
public IEnumerator ExpressionsByOwnerEnumerator
{
get
{
return this.ExpressionsByOwnerList.GetEnumerator();
}
}
private static JollyDebug _instance = null;
public static JollyDebug Instance
{
get
{
if (null != JollyDebug._instance)
{
return JollyDebug._instance;
}
GameObject go = GameObject.Find("JollyDebug");
JollyDebug instance = null;
if (go)
{
instance = go.GetComponent<JollyDebug>();
}
else
{
go = new GameObject("JollyDebug");
}
if (!instance)
{
instance = go.AddComponent("JollyDebug") as JollyDebug;
}
JollyDebug._instance = instance;
return instance;
}
}
private ExpressionsByOwner GetExpressionsForOwner(MonoBehaviour owner)
{
foreach (ExpressionsByOwner expressionsByOwner in this.ExpressionsByOwnerList)
{
if (expressionsByOwner.Owner == owner)
{
return expressionsByOwner;
}
}
ExpressionsByOwner newExpressionsByOwner = new ExpressionsByOwner(owner);
this.ExpressionsByOwnerList.Add (newExpressionsByOwner);
return newExpressionsByOwner;
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void Watch (MonoBehaviour owner, string name, System.Func<float> returnsFloat)
{
JollyDebug self = JollyDebug.Instance;
self.GetExpressionsForOwner(owner).Add (new Expression(name, returnsFloat));
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void Watch (MonoBehaviour owner, string name, System.Func<string> returnsString)
{
JollyDebug self = JollyDebug.Instance;
self.GetExpressionsForOwner(owner).Add (new Expression(name, returnsString));
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void Watch (MonoBehaviour owner, string name, System.Func<bool> returnsBool)
{
JollyDebug self = JollyDebug.Instance;
self.GetExpressionsForOwner(owner).Add (new Expression(name, returnsBool));
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void Watch (MonoBehaviour owner, string name, float floatValue)
{
JollyDebug self = JollyDebug.Instance;
self.GetExpressionsForOwner(owner).GetExpression(name).SetLastValue(floatValue);
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void Watch (MonoBehaviour owner, string name, string stringValue)
{
JollyDebug self = JollyDebug.Instance;
self.GetExpressionsForOwner(owner).GetExpression(name).SetLastValue(stringValue);
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void Watch (MonoBehaviour owner, string name, bool boolValue)
{
JollyDebug self = JollyDebug.Instance;
self.GetExpressionsForOwner(owner).GetExpression(name).SetLastValue(boolValue);
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void Assert (bool expression, string message = "", params object[] args)
{
if (expression)
{
return;
}
string linewiseStackTrace = StackTraceUtility.ExtractStackTrace();
string firstLine = null;
{
string [] lines = linewiseStackTrace.Split(new char[] {'\n'});
{
string [] skippedFirstLine = new string [lines.Length - 1];
System.Array.Copy(lines, 1, skippedFirstLine, 0, skippedFirstLine.Length);
lines = skippedFirstLine;
}
firstLine = lines[0];
linewiseStackTrace = string.Join("\n", lines);
}
message = string.Format (message, args);
JollyDebug.LogException("ASSERTION FAILED in {0}\n{1}\n{2}", firstLine, message, linewiseStackTrace);
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void Log(string message, params object[] args)
{
string formattedMessage = string.Format(message, args);
Debug.Log(formattedMessage);
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void LogWarning(string message, params object[] args)
{
string formattedMessage = string.Format(message, args);
Debug.LogWarning(formattedMessage);
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void LogError(string message, params object[] args)
{
string formattedMessage = string.Format(message, args);
Debug.LogError(formattedMessage);
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void LogException(string message, params object[] args)
{
string formattedMessage = string.Format (message, args);
JollyDebug self = JollyDebug.Instance;
self.ExceptionToDisplayOnScreen = formattedMessage;
Debug.LogError(formattedMessage);
Debug.Break ();
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void LogIf(string flagExpression, string message, params object[] args)
{
JollyDebug self = JollyDebug.Instance;
if (self.EvaluateFlagExpression(flagExpression))
{
JollyDebug.Log (message, args);
}
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void LogWarningIf(string flagExpression, string message, params object[] args)
{
JollyDebug self = JollyDebug.Instance;
if (self.EvaluateFlagExpression(flagExpression))
{
JollyDebug.LogWarning (message, args);
}
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void LogErrorIf(string flagExpression, string message, params object[] args)
{
JollyDebug self = JollyDebug.Instance;
if (self.EvaluateFlagExpression(flagExpression))
{
JollyDebug.LogError (message, args);
}
}
[System.Diagnostics.Conditional("DEBUG"), System.Diagnostics.Conditional("UNITY_EDITOR")]
public static void LogExceptionIf(string flagExpression, string message, params object[] args)
{
JollyDebug self = JollyDebug.Instance;
if (self.EvaluateFlagExpression(flagExpression))
{
JollyDebug.LogException (message, args);
}
}
void Awake()
{
this.InitializeSortedFlags();
Application.RegisterLogCallback(HandleException);
}
void OnLevelWasLoaded()
{
Application.RegisterLogCallback(HandleException);
}
private void HandleException(string condition, string stackTrace, LogType type)
{
if (type == LogType.Exception)
{
JollyDebug.LogException("{0}: {1}\n{2}", type, condition, stackTrace);
}
}
void Update ()
{
for (int i = this.ExpressionsByOwnerList.Count - 1; i >= 0; --i)
{
ExpressionsByOwner expressionsByOwner = (ExpressionsByOwner)this.ExpressionsByOwnerList[i];
if (expressionsByOwner.OwnerIsMissing)
{
this.ExpressionsByOwnerList.RemoveAt (i);
}
else
{
expressionsByOwner.Update();
}
}
}
private string ExceptionToDisplayOnScreen;
void OnGUI ()
{
if (null == this.ExceptionToDisplayOnScreen)
{
return;
}
GUILayout.BeginArea (new Rect(0,0,Screen.width,Screen.height));
GUIStyle style = new GUIStyle("textArea");
style.normal.textColor = Color.white;
GUI.Label (new Rect(Screen.width/6.0f, Screen.height/6.0f, Screen.width*2/3.0f, Screen.height*2/3.0f), this.ExceptionToDisplayOnScreen, style);
float width = 100.0f;
if (GUI.Button (new Rect((Screen.width - width)/2.0f, Screen.height * 5.1f / 6.0f, width, 40.0f), "Reset"))
{
this.ExceptionToDisplayOnScreen = null;
}
GUILayout.EndArea ();
}
}
}
|
namespace Phonebook
{
public interface IPrinter
{
void Print(string text);
void Accept(IPrinterVisitor visitor);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using TestUser.Models;
namespace TestUser.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<TestUser.Models.User> User { get; set; }
public DbSet<TestUser.Models.Book> Book { get; set; }
public DbSet<TestUser.Models.UserBook> UserBook { get; set; }
}
}
|
using System;
static class Distance
{
public static double Calculation(Definition.Point first,Definition.Point second)
{
return Math.Sqrt(Math.Pow((second.x - first.x), 2) + Math.Pow((second.y - first.y), 2) + Math.Pow((second.z - first.z), 2));
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cubecraft.Net.Protocol.IO;
namespace Cubecraft.Net.Protocol.Packets
{
class ClientChatPacket : CubePacket
{
public string Text { get; private set; }
public ClientChatPacket(string text)
{
this.Text = text;
}
public override void Read(InputBuffer input)
{
throw new NotImplementedException();
}
public override void Write(OutputBuffer output)
{
output.WriteString(Text);
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace A2CourseWork.Gui
{
public partial class GeneratedReport : Form
{
DateTime Monday;
double revenue;
public GeneratedReport(DateTime Monday,double revenue)
{
InitializeComponent();
this.Monday = Monday;
this.revenue = revenue;
datelbl.Text = "Current Viewing: " + Monday.ToShortDateString();
}
private void GeneratedReport_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'crecheData.DataTable1' table. You can move, or remove it, as needed.
this.dataTable1TableAdapter.Fill(this.crecheData.DataTable1,Monday.ToShortDateString());
this.reportViewer1.RefreshReport();
}
private void btnback_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class CMD : MonoBehaviour {
[SerializeField]
private string playerPref;
public Text inputText;
private string outputText;
private Paper paper;
public bool correct;
public GameObject incorrectCanvas;
public GameObject correctCanvas;
private CheatMode cheat;
private GameObject music;
// Use this for initialization
void Start () {
paper = FindObjectOfType<Paper>();
playerPref = SceneManager.GetActiveScene().name.ToLower();
cheat = FindObjectOfType<CheatMode>();
}
void Update () {
if(Input.GetKeyDown(KeyCode.Return))
{
inputText.text = inputText.text + "\n";
}
}
// Update is called once per frame
public void Enter () {
outputText = inputText.text;
if((outputText == paper.command) && (cheat.cheatMode == false))
{
correct = true;
correctCanvas.SetActive(true);
PlayerPrefs.SetInt(playerPref, 1);
}
else if (cheat.cheatMode == true)
{
correct = true;
correctCanvas.SetActive(true);
PlayerPrefs.SetInt(playerPref, 1);
}
else if((outputText != paper.command) && (cheat.cheatMode == false))
{
correct = false;
incorrectCanvas.SetActive(true);
}
}
public void CloseIncorrect()
{
incorrectCanvas.SetActive(false);
inputText.text = "";
}
public void CloseCorrect()
{
if(playerPref == "scene06")
{
music = GameObject.FindWithTag("Audio");
Destroy(music);
}
StartCoroutine(NextLevel());
}
IEnumerator NextLevel()
{
float fadeTime = GameObject.Find("Level Manager").GetComponent<Fading>().BeginFade(1);
yield return new WaitForSeconds(fadeTime);
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spearmen : Unit {
public bool hasUpgrade;
// Use this for initialization
void Start () {
StartCoroutine(SlowUp());
DetectionRange = 5;
AttackRange = 1.5f;
}
// Update is called once per frame
void Update () {
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clase_12_Library_2
{
public abstract class Vehiculo
{
#region Enum
public enum EMarca
{
Yamaha, Chevrolet, Ford, Iveco, Scania, BMW
}
#endregion
protected EMarca _marca;
protected string _patente;
protected ConsoleColor _color;
#region Constructor
public Vehiculo (string patente, EMarca marca, ConsoleColor color)
{
this._color = color;
this._marca = marca;
this._patente = patente;
}
#endregion
#region Propiedades
/// <summary>
/// Retornará la cantidad de ruedas del vehículo
/// </summary>
public abstract short CantidadRuedas { get; set; }
/// <summary>
/// Retornará la patente
/// </summary>
public string Patente
{
get { return _patente; }
set { _patente = value; }
}
#endregion
#region Sobrecarga
/// <summary>
/// Metodo mostrar que se sobrecargara
/// </summary>
public virtual string Mostrar()
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("PATENTE: {0}\r\n", this._patente);
sb.AppendFormat("MARCA : {0}\r\n", this._marca.ToString());
sb.AppendFormat("COLOR : {0}\r\n", this._color.ToString());
sb.AppendLine("---------------------");
return sb.ToString();
}
/// <summary>
/// Dos vehículos son iguales si comparten la misma patente
/// </summary>
/// <param name="v1"></param>
/// <param name="v2"></param>
/// <returns></returns>
public static bool operator ==(Vehiculo v1, Vehiculo v2)
{
return (v1.Patente == v2.Patente);
}
/// <summary>
/// Dos vehículos son distintos si su patente es distinta
/// </summary>
/// <param name="v1"></param>
/// <param name="v2"></param>
/// <returns></returns>
public static bool operator !=(Vehiculo v1, Vehiculo v2)
{
return !(v1 == v2);
}
#endregion
}
}
|
using AssetHub.DAL;
using AssetHub.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AssetHub.ViewModels.Asset.Partial
{
public class EditAssetViewModel
{
public class PropertyEditor
{
public int ModelPropertyId { get; set; }
public string Name { get; set; }
public bool IsNumeric { get; set; }
public int AssetPropertyId { get; set; }
[Required(ErrorMessage = Models.Asset.Validator.PROPERTY_VALUE_REQUIRED)]
public string Value { get; set; }
}
AssetHubContext db = new AssetHubContext();
public EditAssetViewModel() { }
public EditAssetViewModel(int id)
{
var asset = db.Assets.Find(id);
Id = asset.Id;
Name = asset.Name;
SerialNumber = asset.SerialNumber;
Value = asset.Value;
SelectedAssetModelId = asset.AssetModelId;
AssetModels = db.AssetModelDropdown();
Properties = new List<PropertyEditor>();
foreach(var p in asset.AssetProperties)
{
Properties.Add(new PropertyEditor
{
ModelPropertyId = p.AssetModelPropertyId,
Name = p.AssetModelProperty.Name,
IsNumeric = p.AssetModelProperty.IsNumeric,
AssetPropertyId = p.Id,
Value = p.Value,
});
}
}
public int Id { get; set; }
[Required(ErrorMessage = Models.Asset.Validator.NAME_REQUIRED)]
public string Name { get; set; }
[Display(Name = "Serial number")]
[Required(ErrorMessage = Models.Asset.Validator.SERIAL_REQUIRED)]
public string SerialNumber { get; set; }
[Display(Name = "Value [$]")]
[Required(ErrorMessage = Models.Asset.Validator.VALUE_REQUIRED)]
public decimal Value { get; set; }
[Display(Name = "Asset model")]
[Required(ErrorMessage = Models.Asset.Validator.MODEL_REQUIRED)]
public int SelectedAssetModelId { get; set; }
public IEnumerable<SelectListItem> AssetModels { get; set; }
public List<PropertyEditor> Properties { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinForm.Model;
namespace WinForm.UI.WinUserControl
{
public partial class GridTable_ImageCell : UserControl, HZH_Controls.Controls.IDataGridViewCustomCell
{
public GridTable_ImageCell()
{
InitializeComponent();
}
public void SetBindSource(object obj)
{
if (obj is AssetsInformation)
{
var path = (obj as AssetsInformation).QdPath;
this.BackgroundImage = Image.FromFile(path);
}
}
}
}
|
using Assets.Scripts.Common.Interfaces;
using Assets.Scripts.Utilities;
using UnityEngine;
namespace Assets.Scripts.Player {
public class PlayerController : MonoBehaviour, ISteerable {
public Ship Ship { get; set; }
public GameObject Instance { get { return gameObject; } }
public Vector2 Position {
get { return transform.position; }
}
public float MaxSpeed { get { return 16f; } }
public Vector2 VelocityVector {
get { return GetComponent<Rigidbody2D>().velocity; }
set { VelocityVector = value; }
}
void Start() {
var rigidBody2D = GetComponent<Rigidbody2D>();
Ship = new Ship(rigidBody2D, MaxSpeed);
}
void Update() {
var input = new InputCollection() {
MoveUnitVector = InputHelper.InputUnitVector,
FireInput = InputHelper.FireInput,
ModifierButtonPressed = InputHelper.IsModifierButtonDown
};
Ship.Update(input);
}
}
} |
using Library.DataAccess.Interface;
using Library.DomainModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Threading.Tasks;
namespace Library.DataAccess
{
public class BookRepository : IBookRepository
{
private readonly LibraryDbContext _dbContext;
public BookRepository(LibraryDbContext dbContext)
{
_dbContext = dbContext;
}
//CREATE
public async Task<Book> AddBook(Book book)
{
_dbContext.Books.Add(book);
await _dbContext.SaveChangesAsync();
return book;
}
//READ
//Get Book using ID
public async Task<Book> GetBookById(int id)
{
return await _dbContext.Books.Include(a => a.Author).SingleOrDefaultAsync(d => d.Id == id);
}
//Get Book using title
public async Task<IEnumerable<Book>> GetBookByName(string title)
{
return await _dbContext.Books.Where(b => b.Title.Contains(title)).ToListAsync();
}
//Get all the books from authors whose name is like X
public async Task<IEnumerable<Book>> GetBooksWhereAuthorNameLike(string nameLike)
{
//Include author table in the query result
List<Book> books = await _dbContext.Books.Include(a => a.Author).Where(b => b.Author.Name.Contains(nameLike)).ToListAsync();
// Using Linq to SQL for explicit inner join
IQueryable<Book> query = (from b in _dbContext.Books
join a in _dbContext.Authors on b.AuthorId equals a.Id
where a.Name.Contains(nameLike)
select b);
return books;
}
//Get books between specified range
public async Task<IEnumerable<Book>> GetBookBetween(DateTime startDate, DateTime endDate)
{
List<Book> books = await _dbContext.Books.Where(d => d.CreatedOn.Date >= startDate.Date && d.CreatedOn.Date <= endDate.Date).ToListAsync();
return books;
}
//Get all books in list
public async Task<IEnumerable<Book>> GetAllBooks()
{
return await _dbContext.Books.ToListAsync();
}
//UPDATE
public async Task<Book> UpdateBook(Book book)
{
_dbContext.Books.Update(book);
await _dbContext.SaveChangesAsync();
return book;
}
//DELETE
public void RemoveBook(Book book)
{
_dbContext.Books.Remove(book);
}
public async Task CommitChange()
{
await _dbContext.SaveChangesAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using VolanTrans.Logic.Helpers;
namespace VolanTrans.Logic.Model
{
public class Renewables : List<RenewableModel>
{
private readonly List<RenewableModel> _renewableModels;
private readonly IRenewablesRepositoryHelper _renewablesRepositoryHelper;
public Renewables()
{
_renewableModels = new List<RenewableModel>();
_renewablesRepositoryHelper = new RenewablesRepositoryHelper();
}
public new bool Add(RenewableModel model)
{
bool result = true;
try
{
if (_renewableModels.Any(w => w.Id == model.Id))
{
_renewableModels.Remove(_renewableModels.FirstOrDefault(w => w.Id == model.Id));
result = _renewablesRepositoryHelper.UpdateRenewModel(model);
}
else
result = _renewablesRepositoryHelper.AddRenewModel(model);
if (!result) return result;
_renewableModels.Add(model);
return _renewableModels.Any(w => w.Id == model.Id);
}
catch
{
//do not handle
return false;
}
}
public new bool Remove(RenewableModel model)
{
try
{
if (_renewablesRepositoryHelper.DeleteRenewModel(model))
{
_renewableModels.Remove(model);
return true;
}
else return false;
}
catch
{
//do not handle
return false;
}
}
public bool Remove(Guid id)
{
try
{
if (_renewablesRepositoryHelper.DeleteRenewModel(id))
{
_renewableModels.Remove(_renewableModels.FirstOrDefault(w=> w.Id.Equals(id)));
return true;
}
else return false;
}
catch
{
//do not handle
return false;
}
}
public void InitAdd(RenewableModel model) => _renewableModels.Add(model);
public List<RenewableModel> GetList() => _renewableModels;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
//Bullet Property and The Size of the Screen
[SerializeField]
private Camera m_MainCamera;
private float m_verticalSpeed = 5.0f;
private float m_height = Screen.height;
//private float m_width = Screen.width;
void Awake()
{
m_MainCamera = Camera.main;
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Move();
}
void Move()
{
Vector3 screenPos = m_MainCamera.WorldToScreenPoint(this.transform.position);
//System.Console.WriteLine("balle.y = ", screenPos.y, ", position max_ecran = ", m_height);
if (screenPos.y >= m_height)
Destroy(gameObject, 0);
if (screenPos.y < m_height)
this.transform.position = new Vector3(transform.position.x, transform.position.y + (m_verticalSpeed * Time.deltaTime), transform.position.z);
}
}
|
// Copyright 2020 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace NtApiDotNet.Utilities.SafeBuffers
{
/// <summary>
/// Class to create a view. This never owns the handle.
/// </summary>
internal class SafeBufferView : SafeBufferGeneric
{
public SafeBufferView(IntPtr buffer, long length, bool writable)
: base(buffer, length, false, writable)
{
}
public SafeBufferView(SafeBufferGeneric buffer, bool writable)
: base(buffer.DangerousGetHandle(), buffer.LongLength, false, writable)
{
}
protected override bool ReleaseHandle()
{
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
public partial class Kampanya : System.Web.UI.Page
{
public DataTable _dtMenu;
Data _sysData = new Data();
string _idAl;
OleDbConnection _cnn;
OleDbCommand _cmd;
DataTable _dtKampanya;
string Baglan = "Provider=Microsoft.jet.OLEDB.4.0; data source=" + HttpContext.Current.Server.MapPath("~/App_Data\\MercanYazilimDataBase.mdb");
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
_idAl = Request.QueryString["MercanYaziliM"];
_fncMenuGetir();
_fncVeriDoldur(_idAl);
}
}
private void _fncMenuGetir()
{
_dtMenu = _sysData._fncSelect("SELECT idKampanya,Baslik FROM Kampanya");
}
private void _fncVeriDoldur(string id)
{
try
{
_dtKampanya = _sysData._fncSelect("SELECT Baslik,Aciklama,Fiyat FROM Kampanya WHERE idKampanya =" + Convert.ToInt32(id));
_lblAdi.Text = _dtKampanya.Rows[0]["Baslik"].ToString();
_lblPaketAdi.Text = _dtKampanya.Rows[0]["Baslik"].ToString();
_lblFiyat.Text = _dtKampanya.Rows[0]["Fiyat"].ToString();
_lblDetay.Text = _dtKampanya.Rows[0]["Aciklama"].ToString();
}
catch (Exception)
{
Response.Redirect("Hata.aspx");
}
}
protected void Button3_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
_cnn = new OleDbConnection(Baglan);
_cnn.Open();
_cmd = _cnn.CreateCommand();
_cmd.CommandText = "INSERT INTO KampanyaForm ([KampanyaAdi],[Ad],[Soyad],[Telefon],[Email],[Aciklama],[Tarih]) VALUES (@KampanyaAdi,@Ad,@Soyad,@Telefon,@Email,@Aciklama,@Tarih)";
_cmd.Parameters.AddWithValue("KampanyaAdi", _lblPaketAdi.Text);
_cmd.Parameters.AddWithValue("Ad", TextBox1.Text);
_cmd.Parameters.AddWithValue("Soyad", TextBox2.Text);
_cmd.Parameters.AddWithValue("Telefon", TextBox3.Text);
_cmd.Parameters.AddWithValue("Email", TextBox4.Text);
_cmd.Parameters.AddWithValue("Aciklama", TextBox5.Text);
_cmd.Parameters.AddWithValue("Tarih", DateTime.Now.ToString());
_cmd.ExecuteNonQuery();
_cnn.Close();
}
catch (Exception)
{
Response.Redirect("Hata.aspx");
}
_lblDurum.Text = "Siparişiniz Alındı.";
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.