text stringlengths 13 6.01M |
|---|
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using bug_repro_3_1_15_success.Cadence;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Neon.Cadence;
namespace bug_repro_3_1_15_success
{
public class ExampleWorker : BackgroundService
{
private readonly IHostApplicationLifetime _appLifetime;
private readonly IOptions<CadenceSettings> _cadenceSettings;
private readonly ILogger<ExampleWorker> _logger;
public ExampleWorker(ILogger<ExampleWorker> logger, IHostApplicationLifetime appLifetime,
IOptions<CadenceSettings> cadenceSettings)
{
_logger = logger;
_appLifetime = appLifetime;
_cadenceSettings = cadenceSettings;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_appLifetime.ApplicationStarted.Register(OnStarted);
_appLifetime.ApplicationStarted.Register(OnStopping);
_appLifetime.ApplicationStarted.Register(OnStopped);
try
{
_logger.LogInformation($"Connecting to Cadence at {string.Join(",", _cadenceSettings.Value.Servers)}");
using var _cadenceClient = await CadenceClient.ConnectAsync(_cadenceSettings.Value);
_logger.LogInformation("Successfully connected to Cadence");
_logger.LogInformation("Registering Assembly");
await _cadenceClient.RegisterAssemblyAsync(Assembly.GetExecutingAssembly());
_logger.LogInformation("Starting ExampleWorker");
await _cadenceClient.StartWorkerAsync(_cadenceSettings.Value.DefaultTaskList);
_logger.LogInformation("Running ExampleWorkflow");
var stub = _cadenceClient.NewWorkflowStub<IExampleWorkflow>();
await stub.RunExampleWorkflowAsync();
}
catch (ConnectException e)
{
_logger.LogError(
$"Cannot connect to Cadence. Tried connecting to: {string.Join(",", _cadenceSettings.Value.Servers)}");
_logger.LogError(e.ToString());
}
catch (Exception e)
{
_logger.LogError($"Error: {e.Message}");
_logger.LogError(e.StackTrace);
}
_appLifetime.StopApplication();
}
private void OnStarted()
{
_logger.LogInformation("ExampleWorker Starting");
}
private void OnStopping()
{
_logger.LogInformation("ExampleWorker Stopping");
}
private void OnStopped()
{
_logger.LogInformation("ExampleWorker Stopped");
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(GenericFadeImageUIScript))]
public class SceneTransitionScript : MonoBehaviour {
public static SceneTransitionScript MainInstance;
GenericFadeImageUIScript fadeScript;
public bool Running => fadeScript.Running;
private void Awake() {
fadeScript = GetComponent<GenericFadeImageUIScript>();
MainInstance = this;
}
private void OnDestroy() {
MainInstance = null;
}
public void StartTransition() {
fadeScript.FadeIn();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EntMob.Models;
namespace EntMob.DAL
{
public interface ISessionRepository
{
Task<List<Session>> GetAllSessions(User user);
Task<Session> GetSessionById(User user, int id);
Task<Session> StartSession(Session session);
Task<Session> StopSession(Session session);
Task DeleteSessionForId(User user, int id);
Task<Dictionary<String, Double>> GetAveragesForSession(User user, int id);
}
}
|
using UnityEngine;
using System.Collections;
using DG.Tweening;
using UnityEngine.UI;
public class WindowFade : MonoBehaviour
{
public static bool BeginGame { get; private set; }
// Use this for initialization
void Start ()
{
if (!StartGame.First_In)
{
gameObject.SetActive(false);
return;
}
BeginGame = false;
StartCoroutine(Wait());
}
IEnumerator Wait()
{
//for (int i = 0; i < 3; i++)
//{
// transform.parent.GetChild(i).gameObject.SetActive(false);
//}
yield return new WaitForSeconds(1f);
transform.GetComponent<Image>().DOColor(Color.clear, 0.5f);
transform.GetComponent<Image>().DOPlay();
transform.GetComponentInChildren<Text>().DOColor(Color.clear, 0.5f);
transform.GetComponentInChildren<Text>().DOPlay();
// transform.parent.GetChild(2).gameObject.SetActive(true);
yield return new WaitForSeconds(0.5f);
gameObject.SetActive(false);
BeginGame = true;
//for (int i = 0; i < 3; i++)
//{
// transform.parent.GetChild(i).gameObject.SetActive(true);
//}
}
}
|
using BELCORP.GestorDocumental.BE.Comun;
using BELCORP.GestorDocumental.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BELCORP.GestorDocumental.DA.Comun
{
public class ErrorDA
{
#region Singleton
private static volatile ErrorDA _instance = null;
private static object lockAccessObject = new Object();
public static ErrorDA Instance
{
get
{
if (_instance == null)
{
lock (lockAccessObject)
{
_instance = new ErrorDA();
}
}
return _instance;
}
}
/// <summary>
/// Contructor por defecto
/// </summary>
private ErrorDA()
{
}
#endregion
public long RegistrarError(ErrorBE oError)
{
long idAcceso = 0;
using (SqlConnection oSqlConnection = ConexionDA.ObtenerConexionSQL(ConnectionStrings.BELCORP_GD_SQL))
{
try
{
SqlCommand oSqlCommand = new SqlCommand("USP_TBL_Error_Insertar", oSqlConnection);
oSqlCommand.CommandType = CommandType.StoredProcedure;
oSqlCommand.Parameters.AddWithValue("@pParametros", oError.Parametros);
oSqlCommand.Parameters.AddWithValue("@pDescripcion", oError.Descripcion);
oSqlCommand.Parameters.AddWithValue("@pFechaRegistro", oError.FechaRegistro);
idAcceso = long.Parse(oSqlCommand.ExecuteScalar().ToString());
}
catch (Exception)
{
//TODO: Implementar registro en block de notas cuando no haya conexión al servidor
}
finally
{
oSqlConnection.Close();
}
}
return idAcceso;
}
}
}
|
using System.Collections.Generic;
namespace SciVacancies.ReadModel.Pager
{
public interface IPagedList<T> : IPagedList
{
List<T> Items { get; set; }
}
public interface IPagedList
{
int TotalItems { get; set; }
int TotalPages { get; set; }
int CurrentPage { get; set; }
int PageSize { get; set; }
string SortField { get; set; }
string SortDirection { get; set; }
}
}
|
using UnityEngine;
using System.Collections;
/// <summary>
/// Attach this Script to Any Object that wishes to deal damage
/// </summary>
public class DamageDealer : MonoBehaviour {
//Attack Properties
[SerializeField]
public Attack Attack;
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AngularSPAWebAPI.Data;
using AngularSPAWebAPI.Models;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.EntityFrameworkCore;
using AngularSPAWebAPI.Models.DatabaseModels.Faq;
namespace AngularSPAWebAPI.Controllers
{
[Produces("application/json")]
[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = IdentityServerAuthenticationDefaults.AuthenticationScheme, Roles ="administrator")]
public class FaqController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly ILogger _logger;
private readonly ApplicationDbContext _context;
public FaqController(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
SignInManager<ApplicationUser> signInManager,
ILogger<IdentityController> logger, ApplicationDbContext context)
{
_userManager = userManager;
_roleManager = roleManager;
_signInManager = signInManager;
_logger = logger;
_context = context;
}
[AllowAnonymous]
[HttpGet("Question")]
public async Task<IActionResult> GetQuestions()
{
var questions = await _context.QuestionCategories.Include( i => i.Questions).ToListAsync();
return Ok(questions);
}
[HttpGet("QuestionsCategories")]
public async Task<IActionResult> GetQuestionCategories()
{
var qc = await _context.QuestionCategories.OrderBy(i => i.Title).ToListAsync();
return Ok(qc);
}
[HttpPost("Category")]
public async Task<IActionResult> PostCategory([FromBody] QuestionCategory qc)
{
qc.CreationDate = DateTime.Now;
await _context.QuestionCategories.AddAsync(qc);
await _context.SaveChangesAsync();
return Ok(_context.QuestionCategories);
}
[HttpPost("Question/{qcid}")]
public async Task<IActionResult> PostQuestion([FromRoute] int qcid ,[FromBody] Question q)
{
var qc = await _context.QuestionCategories.Include(i => i.Questions).FirstOrDefaultAsync(i => i.QuestionCategoryID == qcid);
if(qc == null)
{
return NotFound();
}
q.CreateDate = DateTime.Now;
qc.Questions.Add(q);
await _context.SaveChangesAsync();
return Ok();
}
[HttpPost("delete/Question/{qid}")]
public async Task<IActionResult> DeleteQuestion([FromRoute] int qid)
{
var question = await _context.Questions.FirstOrDefaultAsync(i => i.QuestionID == qid);
if(question == null)
{
return NotFound();
}
_context.Questions.Remove(question);
var result = await _context.SaveChangesAsync();
return Ok(result);
}
[HttpPost("delete/QuestionCategory/{qcid}")]
public async Task<IActionResult> DeleteQuestionCategory([FromRoute] int qcid)
{
var qc = await _context.QuestionCategories.Include(i => i.Questions).FirstOrDefaultAsync(i => i.QuestionCategoryID == qcid);
if (qc == null)
{
return NotFound();
}
_context.QuestionCategories.Remove(qc);
var result = await _context.SaveChangesAsync();
return Ok(result);
}
}
}
|
using System;
using System.Threading.Tasks;
using System.Web;
using Condor.Events;
using Condor.Web.Messages;
using Microsoft.AspNet.SignalR;
using NLog;
using Newtonsoft.Json;
namespace Condor.Web.Connections
{
public class ChatConnection: PersistentConnection
{
private static readonly Logger log = LogManager.GetCurrentClassLogger();
private readonly ChatQueue _chatQueue;
public ChatConnection(Condor.ChatQueue chatQueue)
{
log.Trace("ChatConnection");
_chatQueue = chatQueue;
}
protected override System.Threading.Tasks.Task OnReceived(IRequest request, string connectionId, string data)
{
log.Trace("OnReceived");
var message = JsonConvert.DeserializeObject<Messages.ChatMessage>(data);
var chattedEvent = ChattedEvent.Factory();
chattedEvent.Data = new ChattedEventData
{
Username = message.Username,
Text = message.Text,
Timestamp = DateTime.UtcNow, // TODO: client-side Timestamp?
};
_chatQueue.Push(chattedEvent);
return new Task(() => { });
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GhostCarScript : MonoBehaviour {
public static GhostCarScript MainInstance;
public GameObject[] Cars;
void Awake() {
MainInstance = this;
}
void Start() {
foreach (var item in Cars) {
item.SetActive(false);
}
}
void Update() {
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Hoteles_Servidor.Models
{
public class Hoteles
{
public int Id { get; set; }
public String Nombre { get; set; }
public String Direccion { get; set; }
public int CodigoPostal { get; set; }
public String Telefono { get; set; }
public int Puntuacion { get; set; }
public double PrecioBase { get; set; }
}
} |
using MinistryPlatform.Translation.Models.DTO;
using System.Collections.Generic;
namespace MinistryPlatform.Translation.Repositories.Interfaces
{
public interface IParticipantRepository
{
List<MpEventParticipantDto> GetChildParticipantsByEvent(int eventId, string search);
MpNewParticipantDto CreateParticipantWithContact(MpNewParticipantDto mpNewParticipantDto, string token = null);
List<MpGroupParticipantDto> CreateGroupParticipants(List<MpGroupParticipantDto> mpGroupParticipantDtos);
void UpdateEventParticipants(List<MpEventParticipantDto> mpEventParticipantDtos);
MpEventParticipantDto GetEventParticipantByEventParticipantId(int eventParticipantId);
List<MpEventParticipantDto> GetEventParticipantsByEventAndParticipant(int eventId, List<int> participantIds);
List<MpGroupParticipantDto> GetGroupParticipantsByParticipantAndGroupId(int groupId, List<int> participantIds);
List<MpGroupParticipantDto> GetGroupParticipantsByParticipantId(int participantId);
List<MpContactDto> GetFamiliesForSearch(string search);
MpHouseholdDto GetHouseholdByHouseholdId(int householdId);
void UpdateHouseholdInformation(MpHouseholdDto householdDto);
void DeleteGroupParticipants(List<MpGroupParticipantDto> groupParticipants);
}
}
|
using System;
namespace Matrix
{
class Program
{
static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int c = int.Parse(Console.ReadLine());
int d = int.Parse(Console.ReadLine());
for (int firstRowFirst = a; firstRowFirst <= b; firstRowFirst++)
{
for (int firstRowSecond = a; firstRowSecond <= b; firstRowSecond++)
{
for (int secondRowFirst = c; secondRowFirst <= d; secondRowFirst++)
{
for (int secondRowSecond = c; secondRowSecond <= d; secondRowSecond++)
{
if ((firstRowFirst + secondRowSecond) == (firstRowSecond + secondRowFirst) && (firstRowFirst != firstRowSecond) && (secondRowFirst != secondRowSecond))
{
Console.WriteLine($"{firstRowFirst}{firstRowSecond}");
Console.WriteLine($"{secondRowFirst}{ secondRowSecond}");
Console.WriteLine();
}
}
}
}
}
}
}
}
|
namespace BlazorShared.Models.Client
{
public class CreateClientRequest : BaseRequest
{
public string FullName { get; set; }
public string EmailAddress { get; set; }
public string Salutation { get; set; }
public string PreferredName { get; set; }
public int? PreferredDoctorId { get; set; }
//TODO: need to check
//public IList<int> Patients { get; set; } = new List<int>();
}
}
|
using System;
namespace TestApi.Domain
{
public class Class1
{
}
}
|
using PhotonInMaze.Common.Model;
namespace PhotonInMaze.Common.Controller {
public interface IMazeController {
bool IsWhiteHolePosition(IMazeCell newCell);
bool IsBlackHolePosition(IMazeCell newCell);
IMazeCell GetWormholeExit(int blackHoleId);
void Recreate(int rows, int columns, MazeGenerationAlgorithm algorithm);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Profiling2.Domain.DTO
{
public class ToBeConfirmedDTO
{
public string Type { get; set; }
public string Priority { get; set; }
public string Summary { get; set; }
public string Text { get; set; }
}
}
|
public enum SkillType
{
passivity,
initiaive,
}
public abstract class SkillBase
{
public SkillType skillType;
public int skillID;
public bool locked;
public int skillLevel;
public string skillDescript;
public abstract void SkillFunc();
public abstract void SkillLevelUp();
public abstract void Init();
}
|
using Microsoft.Extensions.Logging;
using System;
namespace ILoggerSamples
{
/// <summary>
/// A sample for using and testing ILogger
/// </summary>
public class LogTest
{
private readonly ILogger _logger;
public const string InformationMessage = "Test message";
public const string ErrorMessage = "Not implemented {recordId}";
public LogTest(ILogger<LogTest> logger)
{
_logger = logger;
}
public void Process()
{
_logger.LogInformation(InformationMessage);
}
public void ProcessWithException(Guid recordId)
{
try
{
throw new NotImplementedException(ErrorMessage);
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message, recordId);
}
}
}
}
|
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace aspnetcore
{
public class Datum
{
[JsonIgnore]
public int Id { get; set; }
public string Name { get; set; }
public string Job { get; set; }
public DateTime BirthDate { get; set; }
}
public static class Data
{
public static int NextId { get; set; } = 9;
public static List<Datum> Collection => new List<Datum>
{
new Datum
{
Id = 1,
Name = "Jim-Bob-Joe",
Job = "Mechanic",
BirthDate = DateTime.UtcNow
},
new Datum
{
Id = 2,
Name = "Mary Sue",
Job = "Mechanic",
BirthDate = DateTime.UtcNow
},
new Datum
{
Id = 3,
Name = "Hubert Cumberdale",
Job = "Friend",
BirthDate = DateTime.UtcNow
},
new Datum
{
Id = 4,
Name = "Margery Stewart-Baxter",
Job = "Friend",
BirthDate = DateTime.UtcNow
},
new Datum
{
Id = 5,
Name = "Jeremy Fisher",
Job = "Friend",
BirthDate = DateTime.UtcNow
},
new Datum
{
Id = 6,
Name = "Winnie-the-Pooh",
Job = "Pooh Bear",
BirthDate = DateTime.UtcNow
},
new Datum
{
Id = 7,
Name = "Dora-the-Explorer",
Job = "Explorer",
BirthDate = DateTime.UtcNow
},
new Datum
{
Id = 8,
Name = "Walter Cronkite",
Job = "News Anchor",
BirthDate = DateTime.UtcNow
}
};
}
}
|
using System.IO;
namespace SyncAppGUI
{
//Kind of redundant with PathGridMember class
struct DataHandling
{
internal string sourceDirectory;
string directoryName;
internal string targetDirectory;
string targetName;
public DataHandling(string path, string target)
{
sourceDirectory = path;
targetDirectory = target;
DirectoryInfo directoryInfo = new DirectoryInfo(sourceDirectory);
directoryName = directoryInfo.Name;
directoryInfo = new DirectoryInfo(targetDirectory);
targetName = directoryInfo.Name;
}
}
}
|
using Model.Migrations;
using Model.ResponseModels;
using Model.ViewModels;
using Repository.Repositories;
using Service.Interfaces.IChat;
using Service.Interfaces.IUsers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Service.Services
{
public class ChatService: IChatService
{
private readonly UsersRepository _userRepository;
private readonly ChatMessageRepository _chatMessageRepository;
public ChatService(UsersRepository userRepository, ChatMessageRepository chatMessageRepository)
{
_userRepository = userRepository;
_chatMessageRepository = chatMessageRepository;
}
/// <summary>
/// 發送訊息
/// </summary>
/// <param name="sendChatContentViewModel"></param>
/// <returns></returns>
public async Task<ChatContent> SendChatContentAsync(SendChatContentViewModel sendChatContentViewModel)
{
var chatContent = new ChatContent
{
Id = MongoDB.Bson.ObjectId.GenerateNewId().ToString(),
UsersId = sendChatContentViewModel.UsersId,
Content = sendChatContentViewModel.Content,
CreateTime = DateTime.Now
};
var chatMessage = new ChatMessage
{
ChatRoom = sendChatContentViewModel.ChatRoom,
ChatContents = new List<ChatContent> { chatContent },
BuketDate = DateTime.Now
};
await _chatMessageRepository.UpsertAsync(chatMessage);
return chatContent;
}
/// <summary>
/// 第一次進入聊天室取得所有訊息
/// </summary>
/// <param name="chatRoom"></param>
/// <returns></returns>
public async Task<ChatContentWithFirstEnterResModel> GetChatContentWithFirstEnterAsync(string chatRoom)
{
var chatMessages = await _chatMessageRepository.GetListChatMessageByChatRoomAsync(chatRoom);
var chatContens = chatMessages.SelectMany(x => x.ChatContents).ToList();
var usersIds = chatContens.Select(x => x.UsersId).Distinct().ToList();
var users = await _userRepository.GetListUserAsync(usersIds);
var result = new ChatContentWithFirstEnterResModel
{
ChatContents = chatContens,
Users = users
};
return result;
}
/// <summary>
/// 取得使用者曾經進入過的聊天室
/// </summary>
/// <param name="chatRoom"></param>
/// <returns></returns>
public async Task<List<ChatRoomWithEnterBeforeResModel>> GetListChatRoomWithEnterBeforeAsync(string usersId)
{
var chatMessages = await _chatMessageRepository.GetListUsersEnterBeforeChatRoomAsync(usersId);
var result = chatMessages.Select(x => new ChatRoomWithEnterBeforeResModel {
ChatRoom = x.ChatRoom,
UsersCount = x.ChatContents.Select(x => x.UsersId).Distinct().Count()
}).ToList();
return result;
}
/// <summary>
/// 取得群組成員
/// </summary>
/// <param name="chatRoom"></param>
/// <returns></returns>
public async Task<List<Users>> GetListChatRoomMemberAsync(string chatRoom)
{
var members = await _chatMessageRepository.GetListChatRoomMemberAsync(chatRoom);
return await _userRepository.GetListUserAsync(members);
}
}
}
|
using System;
namespace Vanara.PInvoke
{
public static partial class AdvApi32
{
/// <summary>Access mask values for the registry.</summary>
[PInvokeData("winnt.h")]
public enum RegAccessTypes
{
/// <summary>Required to query the values of a registry key.</summary>
KEY_QUERY_VALUE = 0x0001,
/// <summary>Required to create, delete, or set a registry value.</summary>
KEY_SET_VALUE = 0x0002,
/// <summary>Required to create a subkey of a registry key.</summary>
KEY_CREATE_SUB_KEY = 0x0004,
/// <summary>Required to enumerate the subkeys of a registry key.</summary>
KEY_ENUMERATE_SUB_KEYS = 0x0008,
/// <summary>Required to request change notifications for a registry key or for subkeys of a registry key.</summary>
KEY_NOTIFY = 0x0010,
/// <summary>Reserved for system use.</summary>
KEY_CREATE_LINK = 0x0020,
/// <summary>
/// Indicates that an application on 64-bit Windows should operate on the 32-bit registry view. This flag is ignored by 32-bit
/// Windows. For more information, see Accessing an Alternate Registry View.
/// <para>
/// This flag must be combined using the OR operator with the other flags in this table that either query or access registry values.
/// </para>
/// <note>Windows 2000: This flag is not supported.</note>
/// </summary>
KEY_WOW64_32KEY = 0x0200,
/// <summary>
/// Indicates that an application on 64-bit Windows should operate on the 64-bit registry view. This flag is ignored by 32-bit
/// Windows. For more information, see Accessing an Alternate Registry View.
/// <para>
/// This flag must be combined using the OR operator with the other flags in this table that either query or access registry values.
/// </para>
/// <note>Windows 2000: This flag is not supported.</note>
/// </summary>
KEY_WOW64_64KEY = 0x0100,
/// <summary></summary>
KEY_WOW64_RES = 0x0300,
/// <summary>Combines the STANDARD_RIGHTS_READ, KEY_QUERY_VALUE, KEY_ENUMERATE_SUB_KEYS, and KEY_NOTIFY values.</summary>
KEY_READ = 0x20019,
/// <summary>Combines the STANDARD_RIGHTS_WRITE, KEY_SET_VALUE, and KEY_CREATE_SUB_KEY access rights.</summary>
KEY_WRITE = 0x20006,
/// <summary>Equivalent to KEY_READ.</summary>
KEY_EXECUTE = 0x20019,
/// <summary>
/// Combines the STANDARD_RIGHTS_REQUIRED, KEY_QUERY_VALUE, KEY_SET_VALUE, KEY_CREATE_SUB_KEY, KEY_ENUMERATE_SUB_KEYS,
/// KEY_NOTIFY, and KEY_CREATE_LINK access rights.
/// </summary>
KEY_ALL_ACCESS = 0xF003F,
}
/// <summary>Filter for notifications reported by <see cref="RegNotifyChangeKeyValue"/>.</summary>
[Flags]
[PInvokeData("winnt.h")]
public enum RegNotifyChangeFilter
{
/// <summary>Notify the caller if a subkey is added or deleted.</summary>
REG_NOTIFY_CHANGE_NAME = 1,
/// <summary>Notify the caller of changes to the attributes of the key, such as the security descriptor information.</summary>
REG_NOTIFY_CHANGE_ATTRIBUTES = 2,
/// <summary>
/// Notify the caller of changes to a value of the key. This can include adding or deleting a value, or changing an existing value.
/// </summary>
REG_NOTIFY_CHANGE_LAST_SET = 4,
/// <summary>Notify the caller of changes to the security descriptor of the key.</summary>
REG_NOTIFY_CHANGE_SECURITY = 8,
/// <summary>
/// Indicates that the lifetime of the registration must not be tied to the lifetime of the thread issuing the
/// RegNotifyChangeKeyValue call. <note type="note">This flag value is only supported in Windows 8 and later.</note>
/// </summary>
REG_NOTIFY_THREAD_AGNOSTIC = 0x10000000
}
/// <summary>Options for <see cref="RegOpenKeyEx"/>.</summary>
[Flags]
[PInvokeData("winnt.h")]
public enum RegOpenOptions
{
/// <summary>Reserved.</summary>
REG_OPTION_RESERVED = 0x00000000,
/// <summary>
/// This key is not volatile; this is the default. The information is stored in a file and is preserved when the system is
/// restarted. The RegSaveKey function saves keys that are not volatile.
/// </summary>
REG_OPTION_NON_VOLATILE = 0x00000000,
/// <summary>
/// All keys created by the function are volatile. The information is stored in memory and is not preserved when the
/// corresponding registry hive is unloaded. For HKEY_LOCAL_MACHINE, this occurs only when the system initiates a full shutdown.
/// For registry keys loaded by the RegLoadKey function, this occurs when the corresponding RegUnLoadKey is performed. The
/// RegSaveKey function does not save volatile keys. This flag is ignored for keys that already exist. <note type="note">On a
/// user selected shutdown, a fast startup shutdown is the default behavior for the system.</note>
/// </summary>
REG_OPTION_VOLATILE = 0x00000001,
/// <summary>
/// <note type="note">Registry symbolic links should only be used for for application compatibility when absolutely necessary.</note>
/// <para>
/// This key is a symbolic link. The target path is assigned to the L"SymbolicLinkValue" value of the key. The target path must
/// be an absolute registry path.
/// </para>
/// </summary>
REG_OPTION_CREATE_LINK = 0x00000002,
/// <summary>
/// If this flag is set, the function ignores the samDesired parameter and attempts to open the key with the access required to
/// backup or restore the key. If the calling thread has the SE_BACKUP_NAME privilege enabled, the key is opened with the
/// ACCESS_SYSTEM_SECURITY and KEY_READ access rights. If the calling thread has the SE_RESTORE_NAME privilege enabled, beginning
/// with Windows Vista, the key is opened with the ACCESS_SYSTEM_SECURITY, DELETE and KEY_WRITE access rights. If both privileges
/// are enabled, the key has the combined access rights for both privileges. For more information, see Running with Special Privileges.
/// </summary>
REG_OPTION_BACKUP_RESTORE = 0x00000004,
/// <summary>The key is a symbolic link. Registry symbolic links should only be used when absolutely necessary.</summary>
REG_OPTION_OPEN_LINK = 0x00000008,
}
/// <summary>
/// Used by the <see cref="ChangeServiceConfig(SC_HANDLE, ServiceTypes, ServiceStartType, ServiceErrorControlType, string, string, out uint, string, string, string, string)"/> function.
/// </summary>
public enum ServiceErrorControlType : uint
{
/// <summary>Makes no change for this setting.</summary>
SERVICE_NO_CHANGE = 0xFFFFFFFF,
/// <summary>The startup program ignores the error and continues the startup operation.</summary>
SERVICE_ERROR_IGNORE = 0x00000000,
/// <summary>The startup program logs the error in the event log but continues the startup operation.</summary>
SERVICE_ERROR_NORMAL = 0x00000001,
/// <summary>
/// The startup program logs the error in the event log. If the last-known-good configuration is being started, the startup
/// operation continues. Otherwise, the system is restarted with the last-known-good configuration.
/// </summary>
SERVICE_ERROR_SEVERE = 0x00000002,
/// <summary>
/// The startup program logs the error in the event log, if possible. If the last-known-good configuration is being started, the
/// startup operation fails. Otherwise, the system is restarted with the last-known good configuration.
/// </summary>
SERVICE_ERROR_CRITICAL = 0x00000003
}
/// <summary>
/// Used by the <see cref="ChangeServiceConfig(SC_HANDLE, ServiceTypes, ServiceStartType, ServiceErrorControlType, string, string, out uint, string, string, string, string)"/> function.
/// </summary>
public enum ServiceStartType : uint
{
/// <summary>Makes no change for this setting.</summary>
SERVICE_NO_CHANGE = 0xFFFFFFFF,
/// <summary>A device driver started by the system loader. This value is valid only for driver services.</summary>
SERVICE_BOOT_START = 0x00000000,
/// <summary>A device driver started by the IoInitSystem function. This value is valid only for driver services.</summary>
SERVICE_SYSTEM_START = 0x00000001,
/// <summary>A service started automatically by the service control manager during system startup.</summary>
SERVICE_AUTO_START = 0x00000002,
/// <summary>A service started by the service control manager when a process calls the StartService function.</summary>
SERVICE_DEMAND_START = 0x00000003,
/// <summary>A service that cannot be started. Attempts to start the service result in the error code ERROR_SERVICE_DISABLED.</summary>
SERVICE_DISABLED = 0x00000004
}
/// <summary>
/// Used by the <see cref="ChangeServiceConfig(SC_HANDLE, ServiceTypes, ServiceStartType, ServiceErrorControlType, string, string, out uint, string, string, string, string)"/> function.
/// </summary>
[Flags]
public enum ServiceTypes : uint
{
/// <summary>Makes no change for this setting.</summary>
SERVICE_NO_CHANGE = 0xFFFFFFFF,
/// <summary>Driver service.</summary>
SERVICE_KERNEL_DRIVER = 0x00000001,
/// <summary>File system driver service.</summary>
SERVICE_FILE_SYSTEM_DRIVER = 0x00000002,
/// <summary>Reserved</summary>
SERVICE_ADAPTER = 0x00000004,
/// <summary>Reserved</summary>
SERVICE_RECOGNIZER_DRIVER = 0x00000008,
/// <summary>Combination of SERVICE_KERNEL_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_RECOGNIZER_DRIVER</summary>
SERVICE_DRIVER = SERVICE_KERNEL_DRIVER | SERVICE_FILE_SYSTEM_DRIVER | SERVICE_RECOGNIZER_DRIVER,
/// <summary>Service that runs in its own process.</summary>
SERVICE_WIN32_OWN_PROCESS = 0x00000010,
/// <summary>Service that shares a process with other services.</summary>
SERVICE_WIN32_SHARE_PROCESS = 0x00000020,
/// <summary>Combination of SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS</summary>
SERVICE_WIN32 = SERVICE_WIN32_OWN_PROCESS | SERVICE_WIN32_SHARE_PROCESS,
/// <summary>The service user service</summary>
SERVICE_USER_SERVICE = 0x00000040,
/// <summary>The service userservice instance</summary>
SERVICE_USERSERVICE_INSTANCE = 0x00000080,
/// <summary>Combination of SERVICE_USER_SERVICE | SERVICE_WIN32_SHARE_PROCESS</summary>
SERVICE_USER_SHARE_PROCESS = SERVICE_USER_SERVICE | SERVICE_WIN32_SHARE_PROCESS,
/// <summary>Combination of SERVICE_USER_SERVICE | SERVICE_WIN32_OWN_PROCESS</summary>
SERVICE_USER_OWN_PROCESS = SERVICE_USER_SERVICE | SERVICE_WIN32_OWN_PROCESS,
/// <summary>The service can interact with the desktop.</summary>
SERVICE_INTERACTIVE_PROCESS = 0x00000100,
/// <summary>The service PKG service</summary>
SERVICE_PKG_SERVICE = 0x00000200,
/// <summary>Combination of all service types</summary>
SERVICE_TYPE_ALL = SERVICE_WIN32 | SERVICE_ADAPTER | SERVICE_DRIVER | SERVICE_INTERACTIVE_PROCESS | SERVICE_USER_SERVICE | SERVICE_USERSERVICE_INSTANCE | SERVICE_PKG_SERVICE
}
}
} |
using Entities.Concrete;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Business.Constants
{
public static class Messages
{
public static string ProductAdded = "Ürün Eklendi";
public static string ProductNameInvalid = "Ürün ismi geçersiz";
public static string MaintenenceTime = "Sistem bakımda";
public static string ProductListed = "Ürünler eklendi";
public static string ProductCountOfCategoryError = "Bir kategoride en fazla 10 ürün olabilir.";
internal static string ProductNameAlreadyExists = "Bu isimde zaten başka bir ürün var";
internal static string CategoryLimitExceded = "Kategori limiti aşıldığı için yeni ürün eklenemiyor";
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Gauge : MonoBehaviour
{
public float nowLight;
public float nowSkill;
public Image nowLightBar;
public Image nowSkillBar;
private float speed = 10;
private GameObject player;
private GameObject trap;
private bool sUsed;
// Start is called before the first frame update
void Start()
{
sUsed = false;
player = GameObject.FindGameObjectWithTag("Player");
trap = GameObject.FindGameObjectWithTag("Trap");
nowLight = 100;
nowSkill = 100;
}
// Update is called once per frame
void Update()
{
if (nowLight / 100 != nowLightBar.fillAmount)
{
nowLightBar.fillAmount = Mathf.Lerp(nowLightBar.fillAmount, nowLight / 100, Time.deltaTime * speed);
}
if (nowSkill / 100 != nowSkillBar.fillAmount)
{
nowSkillBar.fillAmount = Mathf.Lerp(nowSkillBar.fillAmount, nowSkill / 100, Time.deltaTime * speed);
}
if (Input.GetKeyDown(KeyCode.Q) && player.activeSelf == true)
{
nowLight -= 5;
}
if (Input.GetKeyDown(KeyCode.W) && player.activeSelf == false && nowLight >= 10)
{
nowLight -= 10;
}
if (player.GetComponent<InvincibleSkill>().isSkill==true)
{
nowSkill -= 10;
player.GetComponent<InvincibleSkill>().isSkill = false;
}
if (player.GetComponent<DelaySkill>().isUsed == true && sUsed == false)
{
nowSkill -= 50;
sUsed = true;
}
if (nowLight < 0)
{
nowLight = 0;
}
if (nowSkill < 0)
{
nowSkill = 0;
}
}
}
|
using System.Net.Http;
using Microsoft.UnifiedRedisPlatform.Core.Services.Interfaces;
namespace Microsoft.UnifiedRedisPlatform.Core.Services
{
internal class HttpClientFactory: IHttpClientFactory
{
private static HttpClient _serviceClient;
private static readonly object _lock = new object();
private readonly int _maxRetry;
private readonly int _backoffInterval;
public HttpClientFactory(int maxRetry, int backOffInterval)
{
_maxRetry = maxRetry;
_backoffInterval = backOffInterval;
}
public HttpClient GetUnifiedPlatformClient()
{
lock (_lock)
{
if (_serviceClient == null)
{
var retryHandler = new RetryHttpHandler(new HttpClientHandler(), _maxRetry, _backoffInterval);
_serviceClient = new HttpClient(retryHandler);
}
}
return _serviceClient;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Dapper;
using Embraer_Backend.Models;
using Microsoft.Extensions.Configuration;
namespace Embraer_Backend.Models
{
public class StatusSensor
{
public long Id_Wise {get;set;}
public string Ip {get;set;}
public int Chanel {get;set;}
public string Url {get;set;}
public bool Enable{get;set;}
public DateTime? Dt_Status{get;set;}
}
public class StatusSensorModel
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(StatusSensorModel));
public IEnumerable<StatusSensor> SelectStatus(IConfiguration _configuration, long idSensor)
{
try
{
string sSql = string.Empty;
sSql = "EXEC SPI_SP_ULTIMO_STATUS_SENSOR " + idSensor;
IEnumerable <StatusSensor> _st;
using (IDbConnection db = new SqlConnection(_configuration.GetConnectionString("DB_Embraer_Sala_Limpa")))
{
_st = db.Query<StatusSensor>(sSql,commandTimeout:0);
}
return _st;
}
catch (Exception ex)
{
log.Error("Erro StatusSensorModel-SelectStatus:" + ex.Message.ToString());
return null;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CloudScript : MonoBehaviour
{
public float Speed
{
set { _speed = value; }
}
public float HideOffset
{
set { _hideOffset = value; }
}
private float _speed;
private float _hideOffset;
private CloudGenerator cloudGenerator;
void Start()
{
cloudGenerator = gameObject.GetComponentInParent<CloudGenerator>();
}
void FixedUpdate()
{
if (transform.position.x >= Camera.main.ScreenToWorldPoint(Vector3.zero).x - _hideOffset)
{
transform.Translate(new Vector3(-1,0,0) * _speed * Time.deltaTime);
}
else
{
gameObject.SetActive(false);
}
}
}
|
namespace SimpleShop.Helpers
{
public static class DbHelper
{
const string defaultConnetion = "Data Source=4YVA4OK;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
public static string DefaultConnection { get { return defaultConnetion; } }
}
}
|
// Copyright © 2020 Void-Intelligence All Rights Reserved.
using System;
using Vortex.Cost.Utility;
using Nomad.Core;
namespace Vortex.Cost.Kernels.Categorical
{
public class CategoricalCrossEntropy : BaseCost
{
public override double Evaluate(Matrix actual, Matrix expected)
{
return Forward(actual, expected);
}
public override double Forward(Matrix actual, Matrix expected)
{
var error = 0.0;
for (var i = 0; i < actual.Rows; i++)
for (var j = 0; j < actual.Columns; j++)
error += -expected[i, j] * Math.Log(actual[i, j] + double.Epsilon);
error /= actual.Rows * actual.Columns;
BatchCost += error;
return error;
}
public override Matrix Backward(Matrix actual, Matrix expected)
{
return (expected * -1).HadamardDivision(actual + actual.Fill(double.Epsilon));
}
public override ECostType Type()
{
return ECostType.CategoricalCorssEntropy;
}
}
} |
using DataAccesLayer.Repositories;
using Models;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BusinessLogicLayer
{
public class PcController
{
EController eController = new EController();
IPcRepository<Podcast> podcastRepository;
public PcController()
{
podcastRepository = new PcRepository();
}
//Returnerar antalet episoder
public int AmountOfEpisodes(string url)
{
int amountOfEpisodes = eController.GetEpisodes(url).Count();
return amountOfEpisodes;
}
//Raderar podcast
public void DeletePodcast(int curPodcast)
{
podcastRepository.Delete(curPodcast);
}
//Skapar en ny podcast och returnerar den
public Podcast CreatePodcast(string url, string namn, int frekvens, string kategori)
{
int amountOfEpisodes = AmountOfEpisodes(url);
Podcast podcast = new Podcast(url, amountOfEpisodes, namn, frekvens, kategori, eController.GetEpisodes(url));
return podcast;
}
//Skapar en podcast och lägger in den i ett xml dokument
public async void CreatePodcastToXML(string url, string namn, int frekvens, string kategori)
{
await Task.Run(() =>
{
Podcast podcast = CreatePodcast(url, namn, frekvens, kategori);
podcastRepository.New(podcast);
});
}
//Hämtar podcast listan
public List<Podcast> GetPCList()
{
return podcastRepository.GetAll();
}
//Hämtar podcast via ett namn
public Podcast GetPodcastByName(string name)
{
Podcast pc = podcastRepository.GetByNamn(name);
return pc;
}
//Hämtar podcast namn via ett index
public string GetPcNameByIndex(int index)
{
return podcastRepository.GetName(index);
}
//Uppdaterar podcast kategori
public void UpdatePodcastCategory(string name, string newName)
{
List<Podcast> podcasts = podcastRepository.GetAll();
foreach (var item in podcasts)
{
if (name.Equals(item.Kategori))
{
item.Kategori = newName;
}
}
podcastRepository.SetPodcastList(podcasts);
podcastRepository.SaveAllChanges();
}
//Raderar alla podcasts med samma kategori som den du raderar
public void DeletePodcastWhenDeleteingCategory(string categoryName)
{
for (int i = GetPCList().Count() - 1; i >= 0; i--)
{
if (GetPCList()[i].Kategori.Equals(categoryName))
{
podcastRepository.Delete(i);
}
}
}
//Spara podcast
public void SavePodcast(int index, Podcast pc)
{
podcastRepository.Save(index, pc);
}
//Hämtar den nya episoden om en sådan har släppts
public bool GetIfANewEpisodeIsOut(Podcast pc, string url)
{
bool aNewEpisodeIsOut = false;
if (AmountOfEpisodes(url) > pc.Avsnitt)
{
aNewEpisodeIsOut = true;
}
else
{
aNewEpisodeIsOut = false;
}
return aNewEpisodeIsOut;
}
}
}
|
using ScheduleService.Model;
using System;
using System.Collections.Generic;
namespace ScheduleService.Repository
{
public interface IDoctorRepository
{
Doctor Get(string id);
Doctor Get(string id, DateTime startDate, DateTime endDate);
ICollection<string> GetIdsBySpecialty(int specialtyId);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Welic.Dominio.Models.Users.Mapeamentos;
using Welic.Dominio.Models.Users.Servicos;
using Welic.Dominio.Patterns.Repository.Pattern.Repositories;
using Welic.Dominio.Patterns.Service.Pattern;
namespace Services.Users
{
public class AspNetUserService : Service<AspNetUser>, IAspNetUserService
{
public AspNetUserService(IRepositoryAsync<AspNetUser> repository)
: base(repository)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Olive.Data;
using Olive.Data.Uow;
using Olive.Web.MVC.Areas.Administration.ViewModels;
using Olive.Web.MVC.Areas.Administration.Models;
namespace Olive.Web.MVC.Areas.Administration.Controllers
{
public class CategoriesController : Controller
{
private IUowData db = new UowData();
public CategoriesController()
{
}
//
// GET: /Administration/Categories/
public ViewResult Index()
{
//var categories = db.Categories.AllChildrenCategories().Include(c => c.Category1);
//return View(categories.ToList());
AdminCategoriesIndexViewModel categoriesVM = new AdminCategoriesIndexViewModel()
{
ParentCategories = this.db.Categories.AllParentCategories(),
ChildrenCategories = this.db.Categories.AllChildrenCategories()
};
return View(categoriesVM);
}
#region Details/Create from scaffold
//public ViewResult Details(int id)
//{
// Category category = db.Categories.GetById(id);
// return View(category);
//}
//public ActionResult Create()
//{
// ViewBag.ParentCategoryID = new SelectList(db.Categories.AllParentCategories(), "CategoryID", "Name");
// return View();
//}
//[HttpPost]
//public ActionResult Create(Category category)
//{
// if (ModelState.IsValid)
// {
// db.Categories.Add(category);
// db.SaveChanges();
// return RedirectToAction("Index");
// }
// ViewBag.ParentCategoryID = new SelectList(db.Categories.AllParentCategories(), "CategoryID", "Name", category.ParentCategoryID);
// return View(category);
//}
#endregion
[HttpPost]
public ActionResult Create(AdminCategoriesIndexViewModel categoryiesModel)
{
Category newCategory = new Category();
newCategory.Name = categoryiesModel.Name;
if (categoryiesModel.NewCategoryType==CategoryType.Parent)
{
newCategory.ParentCategoryID = null;
}
else
{
newCategory.ParentCategoryID = categoryiesModel.SelectedParentCategoryID;
}
db.Categories.Add(newCategory);
db.SaveChanges();
categoryiesModel.ParentCategories = this.db.Categories.AllParentCategories();
return PartialView("_CategoriesListPartial", categoryiesModel.ParentCategories);
//ViewBag.ParentCategoryID = new SelectList(db.Categories.AllParentCategories(), "CategoryID", "Name", category.ParentCategoryID);
//return View("Index",categoryiesModel);
}
//
// GET: /Administration/Categories/Edit/5
//public ActionResult Edit(int id)
public ActionResult Edit(int id)
{
Category category = db.Categories.GetById(id);
AdminCategoriesIndexViewModel categoryVM = new AdminCategoriesIndexViewModel();
List<Category> parentsCategories = this.db.Categories.AllParentCategories().ToList();
categoryVM.CategoryID=category.CategoryID;
categoryVM.Name=category.Name;
if (category.Category1 == null)
{
categoryVM.NewCategoryType = CategoryType.Parent;
parentsCategories.Remove(category);
}
else
{
categoryVM.NewCategoryType = CategoryType.Child;
categoryVM.SelectedParentCategoryID = category.Category1.CategoryID;
}
//categoryVM.ParentCategories = this.db.Categories.AllParentCategories();
categoryVM.ParentCategories = parentsCategories;
return PartialView("Edit",categoryVM);
}
//
// POST: /Administration/Categories/Edit/5
[HttpPost]
public ActionResult Edit(AdminCategoriesIndexViewModel categoryVM)
{
Category category = db.Categories.GetById(categoryVM.CategoryID);
if (ModelState.IsValid)
{
category.Name = categoryVM.Name;
//children category become parent
if (categoryVM.NewCategoryType == CategoryType.Parent && category.Category1!=null)
{
category.ParentCategoryID = null;
}
if (categoryVM.NewCategoryType == CategoryType.Child && category.Category1 == null)
{
category.ParentCategoryID = categoryVM.SelectedParentCategoryID;
}
//else
//{
// newCategory.ParentCategoryID = categoryiesModel.SelectedParentCategoryID;
//}
db.Categories.Update(category);
db.SaveChanges();
}
//model.SourceID = id;
//return PartialView("_SourcePartial", model);
//return Json(new { categoryID = categoryVM.CategoryID, categoryName = categoryVM.Name});
categoryVM.ParentCategories = this.db.Categories.AllParentCategories();
return PartialView("_CategoriesListPartial", categoryVM.ParentCategories);
}
//
// GET: /Administration/Categories/Delete/5
public ActionResult Delete(int id)
{
Category category = db.Categories.GetById(id);
return PartialView(category);
}
//
// POST: /Administration/Categories/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Category category = db.Categories.GetById(id);
if (category.ParentCategoryID==null)
{
foreach (var childcategory in category.Categories1.ToList())
{
db.Categories.Delete(childcategory);
}
}
db.Categories.Delete(category);
db.SaveChanges();
return Content(id.ToString());
}
//all categories as JSON
public ActionResult GetAllParentCategories()
{
var parentCategories = db.Categories.AllParentCategories();
var parentCategoriesJSON = parentCategories.Select(x => new
{
CategoryID = x.CategoryID,
Name = x.Name
});
return Json(parentCategoriesJSON, JsonRequestBehavior.AllowGet);
}
}
} |
using System;
using Unity.Entities;
using UnityEngine;
namespace UnityECSTile
{
[Serializable]
public struct SpriteInstanceRendererComponent : ISharedComponentData
{
public Sprite Sprite;
}
public class SpriteInstanceRendererWrapper : SharedComponentDataWrapper<SpriteInstanceRendererComponent>
{
}
}
|
using DB_CQRS.Shared;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
namespace DB_CQRS.Web.Endpoints.Controller
{
[Route("[controller]")]
[ApiController]
public class OrderController : ControllerBase
{
private readonly ILogger<OrderController> _logger;
private readonly ICapPublisher _capPublisher;
public OrderController(ILogger<OrderController> logger, ICapPublisher capPublisher)
{
_logger = logger;
_capPublisher = capPublisher;
}
[HttpPost]
public async Task<string> Post()
{
var orderPlaced = new OrderPlaced
{
OrderId = Guid.NewGuid()
};
_logger.LogInformation($"publishing {nameof(orderPlaced.OrderId)}");
await _capPublisher.PublishAsync(nameof(OrderPlaced), orderPlaced);
_logger.LogInformation($"published {nameof(orderPlaced.OrderId)}");
return await Task.FromResult($"Order {orderPlaced.OrderId} has been placed.");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRL;
namespace WebTest.Page
{
public partial class Extension : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
var query = Code.ProductDataManage.Instance.GetLamadaQuery();
query.Where(b => b.ProductName.Contains("122"));//包含字符串
query.Where(b => b.ProductName.In("111", "222"));//string in
query.Where(b => b.AddTime.Between(DateTime.Now, DateTime.Now));//在时间段内
query.Where(b => b.AddTime.DateDiff(DatePart.dd, DateTime.Now) > 1);//时间比较
query.Where(b => b.ProductName.Substring(0, 3) == "222");//截取字符串
query.Where(b => b.Id.In(1, 2, 3));//in
query.Where(b => b.Id.NotIn(1, 2, 3));//not in
var list = Code.ProductDataManage.Instance.QueryList(query);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CamMovement : MonoBehaviour {
public Transform lookTarget;
public float targetHeight;
public Vector3 targetPoint;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.position = Vector3.MoveTowards(transform.position, lookTarget.position + targetPoint, 5f * Time.deltaTime);
transform.LookAt(lookTarget);
/*transform.LookAt(lookTarget);
float difference = Mathf.Abs (transform.position.y - lookTarget.position.y);
if (difference != targetHeight) {
Vector3 temp = transform.position;
temp.y = Mathf.MoveTowards(temp.y, targetHeight, 5f * Time.deltaTime);
transform.position = temp;
}
if (transform.position.x != lookTarget.position.x){
Vector3 temp = transform.position;
temp.x = Mathf.MoveTowards(temp.x, lookTarget, 5f * Time.deltaTime);
}*/
}
}
|
using UBaseline.Shared.DocumentLibraryPanel;
using Uintra.Core.Search.Converters.SearchDocumentPanelConverter;
using Uintra.Core.Search.Entities;
using Umbraco.Core;
namespace Uintra.Features.Search.Converters.Panel
{
public class DocumentLibraryPanelSearchConverter : SearchDocumentPanelConverter<DocumentLibraryPanelViewModel>
{
protected override SearchablePanel OnConvert(DocumentLibraryPanelViewModel panel)
{
return new SearchablePanel
{
Title = panel.Title,
Content = panel.RichTextEditor?.Value?.StripHtml()
};
}
}
} |
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace PermutationSet
{
public partial class PermutationSet
{
private List<int> basePermutation;
private Dictionary<int, int> translator;
private Node root;
private struct Transposition
{
public int i1;
public int i2;
}
private class Node
{
public List<Node> Children { get; }
public Transposition Value { get; }
public bool End { get; set; }
public Node(Transposition value)
{
Children = new List<Node>();
Value = value;
}
}
public IEnumerator<List<int>> GetEnumerator()
{
return new PermutationEnumerator(root, new List<int>(basePermutation));
}
private class PermutationEnumerator : IEnumerator<List<int>>
{
Node root;
List<int> permutation;
List<int> basePermutation;
List<int> result;
IEnumerator<List<int>> enumerator;
int s;
public PermutationEnumerator(Node root, List<int> basePermutation)
{
this.root = root;
this.basePermutation = basePermutation;
this.permutation = new List<int>(basePermutation);
s = -1;
}
public object Current => result;
List<int> IEnumerator<List<int>>.Current => result;
public void Dispose()
{
return;
}
public bool MoveNext()
{
if (s == -1)
{
Switch(root.Value);
result = permutation;
s = 0;
if (s < root.Children.Count)
enumerator = new PermutationEnumerator(root.Children[s], new List<int> (permutation));
if (!root.End)
{
return MoveNext();
}
else
return true;
}
else if (s < root.Children.Count)
{
if (enumerator.MoveNext())
{
result = enumerator.Current;
return true;
}
else
{
s++;
if (s < root.Children.Count)
{
enumerator = new PermutationEnumerator(root.Children[s], new List<int>(permutation));
}
return MoveNext();
}
}
else
return false;
}
public void Reset()
{
this.permutation = new List<int>(basePermutation);
s = -1;
}
private void Switch(Transposition trans)
{
int tmp = permutation[trans.i1 ];
permutation[trans.i1 ] = permutation[trans.i2 ];
permutation[trans.i2 ] = tmp;
}
}
}
}
|
namespace SimpleInjector.Tests.Unit
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class RegisterCollectionBatchTests
{
public interface ICommandHandler<T>
{
}
// This is the open generic interface that will be used as service type.
public interface IService<TA, TB>
{
}
// An non-generic interface that inherits from the closed generic IGenericService.
public interface INonGeneric : IService<float, double>
{
}
[TestMethod]
public void RegisterCollectionTypes_ConcreteTypeImplementingMultipleClosedVersions_CanResolveBoth()
{
// Arrange
var container = ContainerFactory.New();
// class Concrete3 : IService<float, double>, IService<Type, Type>
container.Collection.Register(typeof(IService<,>), new[] { typeof(Concrete3) });
// Act
container.GetAllInstances<IService<float, double>>().Single();
container.GetAllInstances<IService<Type, Type>>().Single();
}
[TestMethod]
public void RegisterCollectionTypes_SuppliedWithOpenGenericType_Succeeds()
{
// Arrange
var container = ContainerFactory.New();
var types = new[] { typeof(GenericHandler<>) };
container.Collection.Register(typeof(ICommandHandler<>), types);
// Act
var handler = container.GetAllInstances<ICommandHandler<int>>().Single();
// Assert
AssertThat.IsInstanceOfType(typeof(GenericHandler<int>), handler);
}
[TestMethod]
public void RegisterCollectionTypes_SuppliedWithOpenGenericType_ReturnsTheExpectedClosedGenericVersion()
{
// Arrange
var registeredTypes = new[] { typeof(DecimalHandler), typeof(GenericHandler<>) };
var expected = new[] { typeof(DecimalHandler), typeof(GenericHandler<decimal>) };
var container = ContainerFactory.New();
container.Collection.Register(typeof(ICommandHandler<>), registeredTypes);
// Act
var handlers = container.GetAllInstances<ICommandHandler<decimal>>();
// Assert
var actual = handlers.Select(handler => handler.GetType()).ToArray();
Assert.AreEqual(expected.ToFriendlyNamesText(), actual.ToFriendlyNamesText());
}
[TestMethod]
public void RegisterCollectionTypes_SuppliedWithOpenGenericTypeWithCompatibleTypeConstraint_ReturnsThatGenericType()
{
// Arrange
var registeredTypes = new[] { typeof(FloatHandler), typeof(GenericStructHandler<>) };
var expected = new[] { typeof(FloatHandler), typeof(GenericStructHandler<float>) };
var container = ContainerFactory.New();
container.Collection.Register(typeof(ICommandHandler<>), registeredTypes);
// Assert
var handlers = container.GetAllInstances<ICommandHandler<float>>();
// Assert
var actual = handlers.Select(handler => handler.GetType()).ToArray();
Assert.AreEqual(expected.ToFriendlyNamesText(), actual.ToFriendlyNamesText());
}
[TestMethod]
public void RegisterCollectionTypes_SuppliedWithOpenGenericTypeWithIncompatibleTypeConstraint_DoesNotReturnThatGenericType()
{
// Arrange
var registeredTypes = new[] { typeof(ObjectHandler), typeof(GenericStructHandler<>) };
var expected = new[] { typeof(ObjectHandler) };
var container = ContainerFactory.New();
container.Collection.Register(typeof(ICommandHandler<>), registeredTypes);
// Assert
var handlers = container.GetAllInstances<ICommandHandler<object>>();
// Assert
var actual = handlers.Select(handler => handler.GetType()).ToArray();
Assert.AreEqual(expected.ToFriendlyNamesText(), actual.ToFriendlyNamesText());
}
#region IService
// Instance of this type should be returned on container.GetInstance<IService<float, double>>() and
// on container.GetInstance<IService<Type, Type>>()
public class Concrete3 : IService<Type, Type>, INonGeneric
{
}
public class DecimalHandler : ICommandHandler<decimal>
{
}
public class FloatHandler : ICommandHandler<float>
{
}
public class ObjectHandler : ICommandHandler<object>
{
}
public class GenericHandler<T> : ICommandHandler<T>
{
}
public class GenericStructHandler<T> : ICommandHandler<T> where T : struct
{
}
#endregion
}
} |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PeliculasAPI.DTOs;
using PeliculasAPI.Entidades;
namespace PeliculasAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class GenerosController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly IMapper _mapper;
//constructor
public GenerosController(ApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
[HttpGet]
public async Task<ActionResult<List<GeneroDTO>>> Get()
{
//retorno la lista de generos
var entidades = await _context.Generos.ToListAsync();
//se mapean las entidades a DTOs
var dtos = _mapper.Map<List<GeneroDTO>>(entidades);
return dtos;
}
[HttpGet("{id:int}", Name = "obtenerGenero")]
public async Task<ActionResult<GeneroDTO>> Get(int id)
{
//compara el id con el que esta en la base
var entidad = await _context.Generos.FirstOrDefaultAsync(x => x.Id.Equals(id));
//si no encuentra nada, enviar notfound de respuesta
if (entidad == null)
{
return NotFound();
}
var dto = _mapper.Map<GeneroDTO>(entidad);
return dto;
}
[HttpPost]
public async Task<ActionResult> Post([FromBody] GeneroCreacionDTO generoCreacionDTO)
{
//mapeamos los que nos mandan los usuarios hacia una entidad
var entidad = _mapper.Map<Genero>(generoCreacionDTO);
//agregamos un nuevo registro
_context.Add(entidad);
//guardamos los cambios asincronicamente
await _context.SaveChangesAsync();
//tenemos que volver a convertirlo en otro dto para una respuesta al usuario
var generoDTO = _mapper.Map<GeneroDTO>(entidad);
return new CreatedAtRouteResult("obtenerGenero", new { id = generoDTO.Id }, generoDTO);
}
[HttpPut("{id}")]
public async Task<ActionResult> Put(int id, [FromBody] GeneroCreacionDTO generoCreacionDTO)
{
var entidad = _mapper.Map<Genero>(generoCreacionDTO);
entidad.Id = id;
//se le dice que la entidad fue modificada
_context.Entry(entidad).State = EntityState.Modified;
//guardamos cambios
await _context.SaveChangesAsync();
return NoContent();
}
[HttpDelete("{id}")]
public async Task<ActionResult> Delete(int id)
{
var existe = await _context.Generos.AnyAsync(x => x.Id == id);
if (!existe)
{
return NotFound();
}
_context.Remove(new Genero() { Id = id});
await _context.SaveChangesAsync();
return NoContent();
}
}
}
|
using Alabo.Cloud.Support.Domain.Enum;
using Alabo.Domains.Enums;
using Alabo.Users.Entities;
using Alabo.Validations;
using Alabo.Web.Mvc.Attributes;
using Alabo.Web.Mvc.ViewModel;
using System;
using System.ComponentModel.DataAnnotations;
namespace Alabo.Cloud.Support.Domain.ViewModels
{
public class ViewWorkOrder : BaseViewModel
{
[Display(Name = "标题")]
[Required(ErrorMessage = ErrorMessage.NameNotCorrect)]
public string Title { get; set; }
[Display(Name = "问题描述")]
[Required(ErrorMessage = ErrorMessage.NameNotCorrect)]
public string Description { get; set; }
[Display(Name = "工单发起人")]
[Required(ErrorMessage = ErrorMessage.NameNotCorrect)]
public long UserId { get; set; }
public long AcceptUserId { get; set; }
[Display(Name = "工单状态")]
[Required(ErrorMessage = ErrorMessage.NameNotCorrect)]
public WorkOrderState State { get; set; }
[Display(Name = "工单类型")]
[Required(ErrorMessage = ErrorMessage.NameNotCorrect)]
public WorkOrderType Type { get; set; }
[Display(Name = "确认时间")]
[Field(ControlsType = ControlsType.TimePicker, ListShow = true, EditShow = false, SortOrder = 10003,
Width = "160")]
public DateTime ConfirmTime { get; set; } = DateTime.Now;
public User User { get; set; }
/// <summary>
/// /// 受理工单的用户
/// </summary>
[Display(Name = "受理工单的用户")]
public User AcceptUser { get; set; }
public long Id { get; set; }
}
} |
using System;
namespace Continuation
{
// implements continuation monad, see http://en.wikipedia.org/wiki/Monad_%28functional_programming%29#Continuation_monad
class Program
{
static void Main()
{
// build monad
var res = from x in 7.ToContinuation<int, string>()
from y in 5.ToContinuation<int, string>()
from z in 11.ToContinuation<int, string>()
select x + y + z;
// apply monad to a continuation
Console.WriteLine(res(x => x.ToString().Replace('2', '-')));
}
}
static class ContinuationExtensions
{
public delegate TAnswer K<out T, TAnswer>(Func<T, TAnswer> k);
public static K<T, TAnswer> ToContinuation<T, TAnswer>(this T value)
{
return c => c(value);
}
public static K<TU, TAnswer> Bind<T, TU, TAnswer>(this K<T, TAnswer> m, Func<T, K<TU, TAnswer>> k)
{
return c => m(x => k(x)(c));
}
public static K<TV, TAnswer> SelectMany<T, TU, TV, TAnswer>(this K<T, TAnswer> m, Func<T, K<TU, TAnswer>> k,
Func<T, TU, TV> s)
{
return c => m(x => k(x)(u => c(s(x, u))));
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.IO;
using System.Text.Json;
using TheMapToScrum.Back.BLL;
using TheMapToScrum.Back.BLL.Interfaces;
using TheMapToScrum.Back.DAL;
using TheMapToScrum.Back.Repositories.Contract;
using TheMapToScrum.Back.Repositories.Repo;
namespace TheMapToScrum.Back.API
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
string strConn = Configuration.GetConnectionString("DefaultConnection");
//Injections de dépendances
services.AddDbContext<ApplicationContext>(options =>
{
options.EnableSensitiveDataLogging(true);
options.UseSqlServer(strConn);
});
services.AddScoped<IProjectLogic, ProjectLogic>();
services.AddScoped<IProjectRepository, ProjectRepository>();
services.AddScoped<IProductOwnerLogic, ProductOwnerLogic>();
services.AddScoped<IProductOwnerRepository, ProductOwnerRepository>();
services.AddScoped<IScrumMasterLogic, ScrumMasterLogic>();
services.AddScoped<IScrumMasterRepository, ScrumMasterRepository>();
services.AddScoped<IDeveloperLogic, DeveloperLogic>();
services.AddScoped<IDeveloperRepository, DeveloperRepository>();
services.AddScoped<IUserStoryLogic, UserStoryLogic>();
services.AddScoped<IUserStoryRepository, UserStoryRepository>();
services.AddScoped<IDepartmentLogic, DepartmentLogic>();
services.AddScoped<IDepartmentRepository, DepartmentRepository>();
services.AddScoped<ITeamLogic, TeamLogic>();
services.AddScoped<ITeamRepository, TeamRepository>();
//services.AddControllers();
services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
//services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddMvc(x => x.EnableEndpointRouting = false)
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
//options.SerializerSettings.ContractResolver = new DefaultContractResolver();
options.SerializerSettings.StringEscapeHandling = StringEscapeHandling.EscapeHtml;
}
);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class ScoreManager : MonoBehaviour
{
private static ScoreManager instance;
public static ScoreManager Instance { get { return instance; } }
public Text scoreText;
public Transform popupText;
int score = 0;
private void Awake()
{
if ( instance != null && instance != this )
{
Destroy(this);
}
else
{
instance = this;
DontDestroyOnLoad(this);
}
}
private void Start()
{
AddScore(0);
}
private void Update()
{
if ( scoreText == null )
{
scoreText = GameObject.Find("Score Text").GetComponent<Text>();
scoreText.text = score.ToString();
}
}
public void AddScore(int scorePoint)
{
score += scorePoint;
if ( PlayerPrefs.GetInt("HighScore", 0) < score )
{
PlayerPrefs.SetInt("HighScore", score);
}
scoreText.text = score.ToString();
}
public void ResetScore() => score = 0;
public void PopupText(Vector3 position, string text)
{
Transform popup = Instantiate(popupText, position + Vector3.left, Quaternion.identity);
popup.GetComponent<PopupText>().displayText = text;
}
}
|
using System.Collections.Generic;
namespace Sfa.Poc.ResultsAndCertification.CsvHelper.Domain.Models
{
public partial class TlSpecialism : BaseEntity
{
public TlSpecialism()
{
TqSpecialismRegistrations = new HashSet<TqSpecialismRegistration>();
}
public int TlPathwayId { get; set; }
public string LarId { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public virtual TlPathway TlPathway { get; set; }
public virtual ICollection<TqSpecialismRegistration> TqSpecialismRegistrations { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RakNet;
namespace InternalSwigTestApp
{
public class UDPProxyClientResultHandlerCB : UDPProxyClientResultHandler
{
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace IoTSharp.Cicada
{
public partial class frmMain : DevExpress.XtraBars.Ribbon.RibbonForm
{
public frmMain()
{
InitializeComponent();
}
private void btnLogin_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
frmLogin fl = new frmLogin();
var result = fl.ShowDialog(this);
if (result == DialogResult.OK)
{
sessionBindingSource.DataSource = Sdk.SdkClient.Session;
}
else if (result == DialogResult.No)
{
frmInstaller installer = new frmInstaller();
if (installer.ShowDialog() == DialogResult.OK)
{
btnLogin.PerformClick();
}
}
else if (result == DialogResult.Cancel)
{
}
}
private void frmMain_Load(object sender, EventArgs e)
{
sessionBindingSource.DataSource = new Sdk.CSharp.Session(null);
}
private void SetMenuAndBar()
{
}
private void btnExit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
Application.Exit();
}
private void btnTen_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
this.ShowMdiChildren<frmTenantAdmin>();
}
private void btnDevices_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
this.ShowMdiChildren<frmDevices>(opt =>
{
var cust = IoTSharp.Sdk.SdkClient.Create<IoTSharp.Sdk.DevicesClient>();
opt.Customer = IoTSharp.Sdk.SdkClient.MyInfo.Customer;
opt.Text = $"设备管理-{opt.Customer.Name}";
});
}
}
} |
// -----------------------------------------------------------------------
// <copyright file="CameraParameters.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
namespace Microsoft.Kinect.Fusion
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// This class is used to store the intrinsic camera parameters.
/// These parameters describe the optical system of the camera lens and sensor.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class CameraParameters : IEquatable<CameraParameters>
{
/// <summary>
/// The Kinect For Windows parameters.
/// </summary>
private const float CameraDepthNominalFocalLengthInPixels = 367.0094f;
/// <summary>
/// The x value of the default normalized focal length.
/// </summary>
private const float DepthNormFocalLengthX = CameraDepthNominalFocalLengthInPixels / 512.0f;
/// <summary>
/// The y value of the default normalized focal length.
/// </summary>
private const float DepthNormFocalLengthY = CameraDepthNominalFocalLengthInPixels / 424.0f;
/// <summary>
/// The x value of the depth normalized principal point.
/// </summary>
private const float DepthNormPrincipalPointX = 0.511245f;
/// <summary>
/// The y value of the depth normalized principal point.
/// </summary>
private const float DepthNormPrincipalPointY = 0.489791f;
/// <summary>
/// The private member variable to cache the default camera parameters.
/// </summary>
private static CameraParameters defaultCameraParameters;
/// <summary>
/// Initializes a new instance of the CameraParameters class.
/// </summary>
/// <param name="focalLengthX">The focal length for X normalized by the camera width.</param>
/// <param name="focalLengthY">The focal length for Y normalized by the camera height.</param>
/// <param name="principalPointX">The principal point for X normalized by the camera width.</param>
/// <param name="principalPointY">The principal point for Y normalized by the camera height.</param>
public CameraParameters(float focalLengthX, float focalLengthY, float principalPointX, float principalPointY)
{
FocalLengthX = focalLengthX;
FocalLengthY = focalLengthY;
PrincipalPointX = principalPointX;
PrincipalPointY = principalPointY;
}
/// <summary>
/// Initializes a new instance of the CameraParameters class.
/// </summary>
/// <param name="sensor">The Kinect sensor to use to initialize the camera parameters.</param>
internal CameraParameters(KinectSensor sensor)
{
if (null == sensor)
{
throw new ArgumentNullException("sensor");
}
this.FocalLengthX = DepthNormFocalLengthX;
this.FocalLengthY = DepthNormFocalLengthY;
this.PrincipalPointX = DepthNormPrincipalPointX;
this.PrincipalPointY = DepthNormPrincipalPointY;
}
/// <summary>
/// Prevents a default instance of the CameraParameters class from being created.
/// The declaration of the default constructor is used for marshaling operations.
/// </summary>
private CameraParameters()
{
}
/// <summary>
/// Gets the default parameters.
/// </summary>
public static CameraParameters Defaults
{
get
{
if (null == defaultCameraParameters)
{
defaultCameraParameters = new CameraParameters(
DepthNormFocalLengthX,
DepthNormFocalLengthY,
DepthNormPrincipalPointX,
DepthNormPrincipalPointY);
}
return defaultCameraParameters;
}
}
/// <summary>
/// Gets the focal length for X normalized by the camera width.
/// </summary>
public float FocalLengthX { get; private set; }
/// <summary>
/// Gets the focal length for Y normalized by the camera height.
/// </summary>
public float FocalLengthY { get; private set; }
/// <summary>
/// Gets the principal point for X normalized by the camera width.
/// </summary>
public float PrincipalPointX { get; private set; }
/// <summary>
/// Gets the principal point for Y normalized by the camera height.
/// </summary>
public float PrincipalPointY { get; private set; }
/// <summary>
/// Calculates the hash code of the CameraParameters.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
// Note this method of hash code generation is similar to what the XNA framework does
return FocalLengthX.GetHashCode() + FocalLengthY.GetHashCode()
+ PrincipalPointX.GetHashCode() + PrincipalPointY.GetHashCode();
}
/// <summary>
/// Determines if the two objects are equal.
/// </summary>
/// <param name="other">The object to compare to.</param>
/// <returns>This method returns true if they are equal and false otherwise.</returns>
public bool Equals(CameraParameters other)
{
return null != other
&& FocalLengthX == other.FocalLengthX
&& FocalLengthY == other.FocalLengthY
&& PrincipalPointX == other.PrincipalPointX
&& PrincipalPointY == other.PrincipalPointY;
}
}
}
|
using System.Collections.Generic;
using LogFile.Analyzer.Core.LogModel;
namespace LogFile.Analyzer.Core.Statistic
{
public interface IStatisticGetter
{
Dictionary<string, double> GetStatistic(IList<LogString> logs);
}
}
|
using System.Data.Common;
using Microsoft.EntityFrameworkCore;
namespace DgKMS.Cube.EntityFrameworkCore
{
public static class CubeDbContextConfigurer
{
public static void Configure(DbContextOptionsBuilder<CubeDbContext> builder, string connectionString)
{
builder.UseNpgsql(connectionString);
}
public static void Configure(DbContextOptionsBuilder<CubeDbContext> builder, DbConnection connection)
{
builder.UseNpgsql(connection);
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Mio.TileMaster;
//using Framework;
using DG.Tweening;
public class NoteMulti : NoteSimple {
public const int MAX_COLLIDER_ADDITIONAL_SIZE = 240;
// Use this for initialization
LongNotePlayedData playData = null;
public SpriteRenderer headSprite;
public SpriteRenderer tailSprite;
public SpriteRenderer bgSprite;
[SerializeField]
private Animator blinkEffect;
public NoteTouchEffectManagement touchKeepEffect;
public Sprite sprite43Ratio;
public Sprite[] spriteHead;
public GameObject objActive;
private float cacheYHeight = 0;
private bool isMoveComplete = false;
private bool isActiveAuto = false;
[SerializeField]
//private TextMesh lbScoreLabel;
private NumericSprite lbScoreLabel;
//private static Color normal = Cor;
//private static Color colorSpriteActive = new Color(71.0f / 255f, 161.0f / 255.0f, 236.0f / 255.0f);
//private static Color colorTextNormal = Color.black;
private static Dictionary<int, string> listScoreText = new Dictionary<int, string>(100);
//private Tween tweenFadeOut;
// Update is called once per frame
void Update() {
if(isActiveAuto) {
if(!isMoveComplete) {
IncreaseActiveHeight(InGameUIController.Instance.cacheDeltaMove.y);
}
if(!isClickable) {
OnKeepTouch();
}
}
}
private string GetScoreText(int score) {
if(!listScoreText.ContainsKey(score)) {
//print("creating new key for score " + score);
listScoreText[score] = string.Format("+{0}", score);
}
return listScoreText[score];
}
public new void Setup(TileData _data, Vector3 _spawnPos, int _tileIndex, int _column, int _height) {
base.Setup(_data, _spawnPos, _tileIndex, _column, _height);
//if(colorTextNormal == Color.black) {
// colorTextNormal = lbScoreLabel.color;
//}
//hide score label
lbScoreLabel.text = GetScoreText(_data.score);
Color t = lbScoreLabel.color;
t.a = 1;
lbScoreLabel.color = t;
lbScoreLabel.gameObject.SetActive(false);
//Debug.Log("Current scale: " + InGameUIController.scale);
//swap sprite for screen ratio of 4:3 (iPad)
if(InGameUIController.scale <= 0.8f) {
bgSprite.sprite = sprite43Ratio;
}
this.height = _height;
if (box == null) {
box = gameObject.GetComponent<BoxCollider2D>();
}
float speedRatio = InGameUIController.Instance.gameplay.GetSpeedRatio();
float addY = 0;
float colliderX = BASE_COLLIDER_WIDTH;
if(speedRatio > 0) {
addY = (speedRatio - 1) * MAX_COLLIDER_ADDITIONAL_SIZE;
if(addY > MAX_COLLIDER_ADDITIONAL_SIZE) {
addY = MAX_COLLIDER_ADDITIONAL_SIZE;
}
addY += 100;
colliderX = speedRatio < MAX_COLLIDER_EXPAND ? speedRatio * BASE_COLLIDER_WIDTH : BASE_COLLIDER_WIDTH * MAX_COLLIDER_EXPAND;
}
box.size = new Vector2(colliderX, 700 + addY);
box.offset = colliderOffset + new Vector2(0, addY * 0.25f);
Vector3 scale = sprite.transform.localScale;
scale.y = (int)(_height / 4.80f);
sprite.transform.localScale = scale;
lbScoreLabel.transform.localPosition = new Vector3(40, height);
playData = new LongNotePlayedData();
playData.timeStampBeginTouch = 0;
playData.noteDataPlayedIndex = -1;
objActive.SetActive(false);
headSprite.sprite = spriteHead[0];
cacheYHeight = 0;
isClickable = true;
isFinish = false;
isMoveComplete = false;
isActiveAuto = false;
//iTween[] listOld = gameObject.GetComponents<iTween>();
//for (int i = 0; i < listOld.Length; i++) {
// if (listOld[i] != null) {
// Destroy(listOld[i]);
// }
//}
sprite.DOKill();
//sprite.color = normal;
bgSprite.gameObject.SetActive(true);
//Color color = sprite.color;
//color.a = 1;
sprite.color = Color.white;
}
public override void Press(TouchCover _touchCover) {
this.touchCover = _touchCover;
if(!isClickable) {
return;
}
isClickable = false;
isFinish = true;
isMoveComplete = false;
if(touchCover != null) InGameUIController.Instance.CacheTouchForNote(touchCover, this);
MidiPlayer.Instance.PlayPianoNotes(data.notes, InGameUIController.Instance.gameplay.GetSpeedRatio(), true, data.soundDelay);
InGameUIController.Instance.gameplay.IncreaseAndShowScore();
InGameUIController.Instance.gameplay.TileFinished();
AchievementHelper.Instance.LogAchievement("totalNoteHit");
//isClickable = false;
if(GameConsts.isPlayAuto || InGameUIController.Instance.gameplay.isListenThisSong) {
isActiveAuto = true;
}
blinkEffect.gameObject.SetActive(true);
blinkEffect.StartPlayback();
if (!InGameUIController.Instance.gameplay.isListenThisSong) {
//Debug.Log("Is listen this song; " + InGameUIController.Instance.gameplay.isListenThisSong);
touchKeepEffect.OnTouchDown(gameObject, touchCover);
}
}
public void OnShowUIWhenPress(Vector3 posTouch) {
posTouch.y += 160;
//Debug.LogError ("Pos:"+posTouch+",Pos now:"+this.transform.localPosition+",touch:"+touchCover.position);
float yHeight = posTouch.y - this.transform.localPosition.y;
if(yHeight < 320) {
yHeight = 320;
}
//Debug.LogError ("Cache Height=" + yHeight);
cacheYHeight = yHeight;
SetupActiveHeight();
objActive.SetActive(true);
}
public void IncreaseActiveHeight(float addY) {
cacheYHeight += addY / InGameUIController.scale;
//Debug.LogError ("IncreaseActiveHeight:" + cacheYHeight);
if(cacheYHeight >= height) {
headSprite.sprite = spriteHead[1];
SetupActiveHeight();
OnReleaseTouch();
} else {
SetupActiveHeight();
}
}
public void SetupActiveHeight() {
float heightActive = cacheYHeight;
if(heightActive >= height) {
heightActive = height;
}
Vector3 scale = tailSprite.transform.localScale;
float scaleY = (heightActive / 4.8f) - 10 / InGameUIController.scale;
scale.y = scaleY;
tailSprite.transform.localScale = scale;
Vector3 posHead = headSprite.transform.localPosition;
//posHead.y = heightActive - 96 / InGameUIController.scale;
posHead.y = heightActive - 48 / InGameUIController.scale;
headSprite.transform.localPosition = posHead;
}
public bool IsMoveCompleted() {
return isMoveComplete;
}
public override float GetDistanceAcceptPass() {
return 700;
}
//private float lastUpdate = 0;
//if the tile is hold, prepare to play its music
//List<NoteData> notesToPlay = new List<NoteData>(15);
public override void OnKeepTouch() {
}
public override void OnReleaseTouch() {
//Debug.Log("OnReleaseTouch");
if(!isMoveComplete) {
//Debug.LogError ("OnReleaseTouch");
//int score = (int)System.Math.Round(height / 480.0f);
//if (score < 2) {
// score = 2;
//}
isMoveComplete = true;
lbScoreLabel.gameObject.SetActive(true);
//increase tile's score minus one because we have already increased it when first touched
InGameUIController.Instance.gameplay.IncreaseAndShowScore(data.score - 1);
EffectWhenFinish();
blinkEffect.StopPlayback();
blinkEffect.gameObject.SetActive(false);
}
//Debug.Log("hide");
//touchKeepEffect.transform.DOScale(new Vector3(0.1f, 0.1f, 0.1f), 0.9f).OnComplete(() => {
// touchKeepEffect.gameObject.SetActive(false);
//}).Play();
//touchNoteEffect.gameObject.SetActive(false);
}
public void OnKeepTouchEnd() {
blinkEffect.StopPlayback();
blinkEffect.gameObject.SetActive(false);
touchKeepEffect.OnTouchUp(gameObject);
//Debug.Log("OnKeepTouchEnd "+ isMoveComplete);
}
protected override void EffectWhenFinish() {
bgSprite.gameObject.SetActive(false);
objActive.SetActive(false);
sprite.DOFade(0.25f, 0.1f).Play();
DOTween.ToAlpha(() => lbScoreLabel.color, x => lbScoreLabel.color = x, 0.1f, 0.5f).Play();
}
public override void Reset() {
base.Reset();
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace SchemaChanger
{
public class NoteEntityConfiguration : IEntityTypeConfiguration<Note>
{
private readonly string? _schema;
public NoteEntityConfiguration(string? schema)
{
_schema = schema;
}
/// <inheritdoc />
public void Configure(EntityTypeBuilder<Note> builder)
{
if (!String.IsNullOrWhiteSpace(_schema))
builder.ToTable(nameof(SchemaChangeDbContext.Notes), _schema);
builder.HasKey(product => product.Id);
}
}
} |
namespace ExamWeb
{
public class Contracts
{
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
using System.Net.Http;
public partial class SignIn : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["USERNAME"] != null)
{
btnSignIn.Text = "Sign Out";
}
else if (Session["USERNAME"] != null)
{
btnSignIn.Text = "Sign Out";
}
}
protected void btnSignOut_Click(object sender, EventArgs e)
{
Session["USERNAME"] = null;
Response.Redirect("~/Default.aspx");
}
protected void Button1_Click(object sender, EventArgs e)
{
WCF.RestfulServiceClient client = new WCF.RestfulServiceClient("BasicHttpBinding_IRestfulService");
string user = UserName.Text;
string pass = Password.Text;
string result = client.GetLoginData(user, pass);
string userid = client.GetUserID(user);
Session["USERID"] = userid;
Console.WriteLine(userid);
if (result == "U")
{
Session["USERNAME"] = UserName.Text;
Response.Redirect("~/Default.aspx");
}
if (result == "A")
{
Session["ADMIN"] = UserName.Text;
Response.Redirect("~/AdminHome.aspx");
}
else
{
lblError.Text = "Invalid Username or Password!";
}
}
protected void Button2_Click(object sender, EventArgs e)
{
WCF.RestfulServiceClient client = new WCF.RestfulServiceClient("BasicHttpBinding_IRestfulService");
string user = UserName.Text;
string userid = client.GetUserID(user);
Session["USERID"] = userid;
Response.Redirect("~/History.aspx");
}
protected void btnSignIn_Click(object sender, EventArgs e)
{
if (Session["USERNAME"] != null)
{
btnSignIn.Text = "Sign Out";
Session["USERNAME"] = null;
Response.Redirect("~/Default.aspx");
}
else
{
btnSignIn.Text = "Sign In";
Response.Redirect("~/SignIn.aspx");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Description résumée de CommandeRepository
/// </summary>
public class CommandeRepository
{
public CommandeRepository()
{
//
// TODO: Add constructor logic here
//
}
public void Add(Commande commande)
{
COMMANDE entity = new COMMANDE();
entity.COMMANDE_DATE = commande.Date;
entity.COMMANDE_ID = commande.Id;
entity.COMMANDE_STATUT = commande.Statut;
using (var db = new maderaEntities())
{
db.COMMANDE.Add(entity);
db.SaveChanges();
}
}
public Commande GetById(int id)
{
Commande dto;
using (var db = new maderaEntities())
{
var query = from a in db.COMMANDE where a.COMMANDE_ID.Equals(id) select a;
dto = new Commande(query.First().COMMANDE_ID, query.First().COMMANDE_DATE, query.First().COMMANDE_STATUT);
}
return dto;
}
} |
using System;
using System.Collections.Generic;
using Hl7.Fhir.Support;
using System.Xml.Linq;
/*
Copyright (c) 2011-2012, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 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 COPYRIGHT HOLDER 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.
*/
//
// Generated on Mon, Apr 15, 2013 13:14+1000 for FHIR v0.08
//
namespace Hl7.Fhir.Model
{
/// <summary>
/// Insurance or medical plan
/// </summary>
[FhirResource("Coverage")]
public partial class Coverage : Resource
{
/// <summary>
/// null
/// </summary>
[FhirComposite("CoveragePlanHolderComponent")]
public partial class CoveragePlanHolderComponent : Element
{
/// <summary>
/// PolicyHolder name
/// </summary>
public HumanName Name { get; set; }
/// <summary>
/// PolicyHolder address
/// </summary>
public Address Address { get; set; }
/// <summary>
/// PolicyHolder date of birth
/// </summary>
public Date Birthdate { get; set; }
}
/// <summary>
/// An identifier for the plan issuer
/// </summary>
public ResourceReference Issuer { get; set; }
/// <summary>
/// Coverage start and end dates
/// </summary>
public Period Period { get; set; }
/// <summary>
/// Type of coverage
/// </summary>
public Coding Type { get; set; }
/// <summary>
/// The primary coverage ID
/// </summary>
public Identifier Identifier { get; set; }
/// <summary>
/// An identifier for the plan
/// </summary>
public Identifier Plan { get; set; }
/// <summary>
/// An identifier for the subsection of the plan
/// </summary>
public Identifier Subplan { get; set; }
/// <summary>
/// The dependent number
/// </summary>
public Integer Dependent { get; set; }
/// <summary>
/// The plan instance or sequence counter
/// </summary>
public Integer Sequence { get; set; }
/// <summary>
/// Planholder information
/// </summary>
public CoveragePlanHolderComponent PlanHolder { get; set; }
}
}
|
using CarRental.API.Common.SettingsOptions;
using CarRental.API.DAL.Entities;
using CarRental.API.DAL.CustomEntities;
using Dapper;
using Dapper.FastCrud;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading.Tasks;
namespace CarRental.API.DAL.DataServices.Prices
{
class PriceDataService : BaseDataService , IPriceDataService
{
private const string SpReadAll = "dbo.GetAllPrices";
private const string GetCarPrice = "dbo.GetPriceForSelectedCar";
private const string ReadDetailedPrices = "dbo.GetDetailedPrices";
public PriceDataService(IOptions<DatabaseOptions> databaseOptions)
: base(databaseOptions)
{
}
/// <summary>
/// Dapper.FastCrud example
/// </summary>
public async Task<PriceItem> GetAsync(Guid id)
{
using (var conn = await GetOpenConnectionAsync())
{
return await conn.GetAsync(new PriceItem() { Id = id });
}
}
/// <summary>
/// Dapper with stored procedure
/// </summary>
public async Task<IEnumerable<PriceItem>> GetAllAsync()
{
using (var conn = await GetOpenConnectionAsync())
{
return await conn.QueryAsync<PriceItem>(
sql: SpReadAll,
commandType: CommandType.StoredProcedure);
}
}
public async Task<IEnumerable<DetailedPriceItem>> GetDetailedPrices()
{
using (var conn = await GetOpenConnectionAsync())
{
return await conn.QueryAsync<DetailedPriceItem>(
sql: ReadDetailedPrices,
commandType: CommandType.StoredProcedure);
}
}
public async Task<IEnumerable<PriceItem>> GetCarPriceAsync(Guid id)
{
using (var conn = await GetOpenConnectionAsync())
{
return await conn.QueryAsync<PriceItem>(
param: new { CarId = id },
sql: GetCarPrice,
commandType: CommandType.StoredProcedure);
}
}
public async Task<PriceItem> CreateAsync(PriceItem price)
{
using (var conn = await GetOpenConnectionAsync())
{
price.Id = Guid.NewGuid();
conn.Insert(price);
}
return price;
}
public async Task<PriceItem> DeleteAsync(Guid id)
{
using (var conn = await GetOpenConnectionAsync())
{
conn.Delete<PriceItem>(new PriceItem { Id = id });
}
return null;
}
public async Task<PriceItem> UpsertAsync(PriceItem price)
{
using (var conn = await GetOpenConnectionAsync())
{
conn.Update<PriceItem>(price);
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace FundTransfer
{
public class Customer
{
#region enums
enum currencytype
{
USD,
MXN,
CAD
}
enum acctype
{
chequing = 1,
saving = 1,
multiple = 2,
joint = 3
}
enum transactiontype
{
deposit = 1,
withdrawal = 2
}
#endregion
CustomerInfo cust = new CustomerInfo();
#region balanceinformation
private double getbalance(string usercurreny, double depositamount)
{
double amount = 0.0;
if (usercurreny == Convert.ToString(currencytype.USD))
{
amount += (depositamount / cust.USDexchangerate);
}
else if (usercurreny == Convert.ToString(currencytype.MXN))
{
amount += (depositamount / cust.MXNexchangerate);
}
else if (usercurreny == Convert.ToString(currencytype.CAD))
{
amount = depositamount;
}
return amount;
}
private double getaccountbalance(string usercurreny, double accountbalance, double depositamount, int type)
{
switch (type)
{
case 1:
accountbalance += getbalance(usercurreny, depositamount);
break;
case 2:
accountbalance -= getbalance(usercurreny, depositamount);
break;
}
return accountbalance;
}
public double depositamount(string usercurreny, double accountbalance = 0.0, double depositamount = 0.0)
{
return getaccountbalance(usercurreny, accountbalance, depositamount, (int)transactiontype.deposit);
}
public double withdrawalamount(string usercurreny, double accountbalance = 0.0, double depositamount = 0.0)
{
return getaccountbalance(usercurreny, accountbalance, depositamount, (int)transactiontype.withdrawal);
}
public List<CustomerInfo> getuserdetails()
{
List<CustomerInfo> cust = new List<CustomerInfo>();
cust.Add(new CustomerInfo { customername = "Stewie Griffin", accounttype = "chequing", customerId = 777, accountbalance = 100.00, accountnumber = 1234 });
cust.Add(new CustomerInfo { customername = "Glenn Quagmire", accounttype = "chequing", customerId = 504, accountbalance = 35000.00, accountnumber = 2001 });
cust.Add(new CustomerInfo { customername = "Joe Swanson", accounttype = "chequing", customerId = 002, accountbalance = 7425.00, accountnumber = 1010 });
cust.Add(new CustomerInfo { customername = "Joe Swanson", accounttype = "chequing", customerId = 002, accountbalance = 15000.00, accountnumber = 5500 });
cust.Add(new CustomerInfo { customername = "Peter Griffin", accounttype = "chequing", customerId = 123, accountbalance = 150.00, accountnumber = 0123 });
cust.Add(new CustomerInfo { customername = "Lois Griffin", accounttype = "chequing", customerId = 456, accountbalance = 65000.00, accountnumber = 0456 });
return cust;
}
public List<CustomerInfo> filterdata(int acctno, List<CustomerInfo> cust)
{
return cust.FindAll(e => e.accountnumber == acctno);
}
#endregion
}
}
|
using CarsIsland.Core.Entities;
using CarsIsland.Core.Interfaces;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CarsIsland.API.Controllers
{
[AllowAnonymous]
[ApiController]
[Route("api/[controller]")]
public class CarController : ControllerBase
{
private readonly IDataRepository<Car> _carRepository;
public CarController(IDataRepository<Car> carRepository)
{
_carRepository = carRepository
?? throw new ArgumentNullException(nameof(carRepository));
}
/// <summary>
/// Gets list with available cars for rent
/// </summary>
/// <returns>
/// List with available cars for rent
/// </returns>
/// <response code="200">List with cars</response>
/// <response code="401">Access denied</response>
/// <response code="404">Cars list not found</response>
/// <response code="500">Oops! something went wrong</response>
[ProducesResponseType(typeof(IReadOnlyList<Car>), 200)]
[HttpGet("all")]
public async Task<IActionResult> GetAllCarsAsync()
{
var allCars = await _carRepository.GetAllAsync();
return Ok(allCars);
}
/// <summary>
/// Gets details about specific car
/// </summary>
/// <returns>
/// Details about specific car
/// </returns>
/// <response code="200">Details about specific car</response>
/// <response code="401">Access denied</response>
/// <response code="404">Car not found</response>
/// <response code="500">Oops! something went wrong</response>
[ProducesResponseType(typeof(IReadOnlyList<Car>), 200)]
[HttpGet("{id}")]
public async Task<IActionResult> GetCarDetailsAsync(string id)
{
var carDetails = await _carRepository.GetAsync(id);
return Ok(carDetails);
}
}
}
|
using System.Collections.Generic;
using System.Web.Http;
using ILogging;
using ServiceDeskSVC.Domain.Entities.ViewModels.HelpDesk.Tickets;
using ServiceDeskSVC.Managers;
namespace ServiceDeskSVC.Controllers.API
{
public class TicketCommentController:ApiController
{
private readonly IHelpDeskTicketCommentManager _helpDeskTicketCommentManager;
private readonly ILogger _logger;
public TicketCommentController(IHelpDeskTicketCommentManager helpDeskTicketCommentManager, ILogger logger)
{
_helpDeskTicketCommentManager = helpDeskTicketCommentManager;
_logger = logger;
}
/// <summary>
/// Gets the specified identifier.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns></returns>
public List<HelpDesk_TicketComments_vm> Get(int id)
{
_logger.Info("Getting all comments for ticket with id " + id);
return _helpDeskTicketCommentManager.GetAllTicketComments(id);
}
/// <summary>
/// Posts the specified identifier.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public int Post(int id, [FromBody]HelpDesk_TicketComments_vm value)
{
_logger.Info("Adding a new comment for ticket with id " + id);
return _helpDeskTicketCommentManager.CreateTicketComment(id, value);
}
/// <summary>
/// Puts the specified identifier.
/// </summary>
/// <param name="id">The identifier.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public int Put(int id, [FromBody]HelpDesk_TicketComments_vm value)
{
_logger.Info("Editing the comment with id " + id);
return _helpDeskTicketCommentManager.EditTicketCommentById(id, value);
}
/// <summary>
/// Deletes the specified identifier.
/// </summary>
/// <param name="id">The identifier.</param>
/// <returns></returns>
public bool Delete(int id)
{
_logger.Info("Deleting the comment with id " + id);
return _helpDeskTicketCommentManager.DeleteTicketCommentById(id);
}
}
} |
public class Button3DSign : Class3DButton<Operation>
{
}
|
using System;
using Microsoft.Xna.Framework;
namespace VoxelSpace {
public struct VoxelRaycastResult {
public Voxel Voxel;
public Coords Coords;
public VoxelVolume Volume;
public VoxelChunk Chunk;
public Vector3 Normal;
}
} |
using Unity.Collections;
using Unity.Entities;
using Unity.Physics;
[UpdateBefore(typeof(TriggerVolumeSystem))]
public class WeaponPickupSystem : ComponentSystem
{
protected override void OnUpdate()
{
var withMeleeGroup = GetComponentDataFromEntity<WithMelee>(true);
var weaponComponentGroup = GetComponentDataFromEntity<WeaponComponent>(true);
Entities
.WithAllReadOnly<OverlappingTriggerVolume, OverlappingWeaponPickup, PlayerIndex, PlayerComponent, EquippedWeapon>()
.ForEach((Entity entity, ref OverlappingTriggerVolume overlappingTriggerVolume, ref PlayerIndex playerIndex, ref EquippedWeapon equippedWeapon) =>
{
Entity weaponPickupEntity = overlappingTriggerVolume.VolumeEntity;
if (!overlappingTriggerVolume.HasJustEntered) return;
if (weaponComponentGroup.Exists(equippedWeapon.Entity))
{
WeaponComponent weaponComponent = weaponComponentGroup[equippedWeapon.Entity];
weaponComponent.AmmoCount = 0;
PostUpdateCommands.SetComponent<WeaponComponent>(equippedWeapon.Entity, weaponComponent);
if (!withMeleeGroup.Exists(equippedWeapon.Entity) && !withMeleeGroup.Exists(weaponPickupEntity))
{
PostUpdateCommands.AddComponent<KeepMeleeRemovedOnPickup>(equippedWeapon.Entity);
}
}
PostUpdateCommands.RemoveComponent<PhysicsCollider>(weaponPickupEntity);
PostUpdateCommands.RemoveComponent<TriggerVolume>(weaponPickupEntity);
PostUpdateCommands.RemoveComponent<Lifetime>(weaponPickupEntity);
PostUpdateCommands.AddComponent(weaponPickupEntity, new PlayerIndex
{
Value = playerIndex.Value
});
equippedWeapon.Entity = weaponPickupEntity;
if (!withMeleeGroup.Exists(weaponPickupEntity))
{
EntityQuery meleeQuery = GetEntityQuery(ComponentType.ReadOnly<MeleeComponent>(), ComponentType.ReadOnly<PlayerIndex>());
NativeArray<Entity> meleeEntities = meleeQuery.ToEntityArray(Allocator.TempJob);
NativeArray<PlayerIndex> meleePlayerIndexComponents = meleeQuery.ToComponentDataArray<PlayerIndex>(Allocator.TempJob);
for (int i = 0; i < meleeEntities.Length; i++)
{
if (meleePlayerIndexComponents[i].Value == playerIndex.Value) PostUpdateCommands.AddComponent<Inactive>(meleeEntities[i]);
}
meleeEntities.Dispose();
meleePlayerIndexComponents.Dispose();
}
});
}
} |
using System.Windows.Controls;
using CODE.Framework.Wpf.Mvvm;
namespace CODE.Framework.Wpf.Theme.Geek.Controls
{
/// <summary>
/// Special button to close notifications
/// </summary>
public class CloseNotificationsButton : Button
{
/// <summary>
/// Called when a <see cref="T:System.Windows.Controls.Button" /> is clicked.
/// </summary>
protected override void OnClick()
{
base.OnClick();
Shell.Current.ClearNotifications();
}
}
}
|
using System;
namespace FitnessStore.API.Models.Projecoes
{
public class ProjecaoDeRefeicao
{
/// <summary>
/// Descrição da refeição.
/// </summary>
public string Descricao { get; set; }
/// <summary>
/// Total de calorias fornecidos pela refeição.
/// </summary>
public int Calorias { get; set; }
/// <summary>
/// Data na qual a refeição foi realizada.
/// </summary>
public DateTimeOffset DataRealizada { get; set; }
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityTerraforming.GameAi
{
public abstract class DecisionTreeNode : MonoBehaviour
{
public abstract DecisionTreeNode MakeDecision();
}
} |
namespace PADIbookCommonLib
{
public enum Interest
{
Cars,
Comics,
Finance,
Games,
Hobbies,
Jobs,
Literatures,
Life,
Medicine,
Movies,
Music,
Nature,
Painting,
Personal,
Politics,
Religion,
Science,
Sports,
Travel
}
} |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
namespace AmazonReloader
{
public class CreditCard
{
public static string GetMonthYearKeyForPurchases(DateTime date)
{
return $"{date.ToString("MMMM", CultureInfo.InvariantCulture)}_{date.Year}";
}
public string GetThisCardFileLocation()
{
return $"{ConfigurationManager.AppSettings["encrypted_info_folder"]}\\{Bank}.json";
}
private readonly string SecretKeyPath;
private byte[] Key => File.ReadAllBytes(SecretKeyPath);
public CreditCard()
{
SecretKeyPath = ConfigurationManager.AppSettings["secret_key_location"];
}
public Dictionary<string, int> NumberOfPurchasesForEachMonth { get; set; }
public string EncryptedNumber { get; set; }
public string EncryptedName { get; set; }
public string EncryptedExpires { get; set; }
public string Bank { get; set; }
public int NumberOfNeededPurchasesPerMonth { get; set; }
public string GetCcNumber()
{
return AESGCM.SimpleDecrypt(EncryptedNumber, Key);
}
public string GetNameOnCc()
{
return AESGCM.SimpleDecrypt(EncryptedName, Key);
}
public string GetExpiration()
{
return AESGCM.SimpleDecrypt(EncryptedExpires, Key);
}
}
} |
using System;
using System.Collections.Generic;
using System.Windows.Media;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using DmxController.ViewModels;
using System.Configuration;
using System.ComponentModel.DataAnnotations;
namespace DmxController.StoryBoards
{
public class StoryBoardElement : INotifyPropertyChanged
{
private const double MIN_TIME_VALUE = 0.1;
private const double MAX_TIME_VALUE = 3600;
private byte r;
private byte g;
private byte b;
private double time;
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyProperty ([CallerMemberName] string str = "")
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(str));
}
public Color RedBalance
{
get
{
return Color.FromRgb(r, 0, 0);
}
}
public Color BlueBalance
{
get
{
return Color.FromRgb(0, 0, b);
}
}
public Color GreenBalance
{
get
{
return Color.FromRgb(0, g, 0);
}
}
public Color ElementColor
{
get
{
return Color.FromRgb(r, g, b);
}
}
public double Time
{
get
{
return time;
}
set
{
if (time != value)
{
if (value < MIN_TIME_VALUE) time = MIN_TIME_VALUE;
else if (value > MAX_TIME_VALUE) time = MAX_TIME_VALUE;
else time = value;
NotifyProperty();
}
}
}
[IntegerValidator(MinValue = 0, MaxValue = 255)]
public int B
{
get
{
return b;
}
set
{
if (b != value)
{
b = (byte)value;
NotifyProperty();
NotifyProperty("BlueBalance");
NotifyProperty("ElementColor");
}
}
}
[IntegerValidator(MinValue = 0, MaxValue = 255)]
public int G
{
get
{
return g;
}
set
{
if (g != value)
{
g = (byte)value;
NotifyProperty();
NotifyProperty("GreenBalance");
NotifyProperty("ElementColor");
}
}
}
[IntegerValidator(MinValue = 0, MaxValue = 255)]
public int R
{
get
{
return r;
}
set
{ if (value != r)
{
r = (byte)value;
NotifyProperty();
NotifyProperty("RedBalance");
NotifyProperty("ElementColor");
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Web.Compilation;
namespace Atomic
{
/// <summary>
/// 类型发现接口默认实现类
/// </summary>
public sealed class TypeDefaultFinder : ITypeFinder
{
#region Variable
/// <summary>
/// 已跳过的程序集的策略正则表达式集合
/// </summary>
private readonly List<string> _skipedAssemblyPatterns = new List<string>();
/// <summary>
/// 指定扫描的DLL必须满足的条件约定,默认 .*
/// </summary>
private string _assemblyRestrictToLoadingPattern = ".*";
/// <summary>
/// 约定额外的程序集【不在AppDomain中的程序集】
/// </summary>
private readonly List<Assembly> _extraAssembliesDLL = new List<Assembly>();
/// <summary>
/// 排除的程序集的FullName
/// </summary>
private readonly List<string> _excludeAssembliesName = new List<string>();
/// <summary>
/// 反射程序集缓存object
/// </summary>
private static readonly object s_cacheKey = new object();
/// <summary>
/// 缓存程序集集合(提供效率 仅反射一次)
/// </summary>
private static readonly List<Assembly> s_cacheAssemblies = new List<Assembly>();
#endregion
#region Constructor
/// <summary>
/// 构造函数
/// </summary>
public TypeDefaultFinder()
{
//Skip DOTNET DLL Patterns
this.AddSkipAssemblyPattern("^System.");
this.AddSkipAssemblyPattern("^mscorlib");
this.AddSkipAssemblyPattern("^Microsoft");
this.AddSkipAssemblyPattern("^EntityFramework");
this.AddSkipAssemblyPattern("^WebGrease");
//Skip Thrid Parts DLL Patterns
this.AddSkipAssemblyPattern("^Autofac");
this.AddSkipAssemblyPattern("^AutoMapper");
this.AddSkipAssemblyPattern("^FluentValidation");
this.AddSkipAssemblyPattern("^log4net");
this.AddSkipAssemblyPattern("^Newtonsoft");
this.AddSkipAssemblyPattern("^ChnCharInfo");
this.AddSkipAssemblyPattern("^Owin");
//adds matched assemblies
this.LoadMatchingBinAssemblies();
}
#endregion
#region Propertys
/// <summary>
/// 当前接口实例下已加载的额外DLL
/// </summary>
public System.Collections.ObjectModel.ReadOnlyCollection<Assembly> ExtraAssembliesDLL
{
get { return this._extraAssembliesDLL.AsReadOnly(); }
}
/// <summary>
/// 已排除的程序集名称集合
/// </summary>
public System.Collections.ObjectModel.ReadOnlyCollection<string> ExcludeAssembliesName
{
get { return this._excludeAssembliesName.AsReadOnly(); }
}
#endregion
#region ITypeFinder
/// <summary>
/// 追加一个额外的程序集
/// </summary>
/// <param name="assembly"></param>
public void AppendAssembly(Assembly assembly)
{
if (null == assembly)
return;
if (this._extraAssembliesDLL.Any(d => d.FullName == assembly.FullName))
return;
if (!this.Matches(assembly.FullName))
return;
//如果追加的程序集在排除范围内,则将排除项进行清空
if (this._excludeAssembliesName.Exists(d => d.Equals(assembly.FullName)))
this._excludeAssembliesName.Remove(assembly.FullName);
bool exists = false;
foreach (var item in this.ScanAssemblies())
{
if (item.FullName.Equals(assembly.FullName))
{
exists = true;
break;
}
}
if (exists)
return;
this._extraAssembliesDLL.Add(assembly);
//清除缓存
lock (s_cacheKey)
{
s_cacheAssemblies.Clear();
}
}
/// <summary>
/// 移除一个额外的程序集
/// </summary>
/// <param name="assembly"></param>
public void RemoveAssembly(Assembly assembly)
{
if (null == assembly)
return;
if (!this._extraAssembliesDLL.Any(d => d.FullName == assembly.FullName))
return;
//尝试从额外DLL中移除
bool isReturn = false;
foreach (var item in this._extraAssembliesDLL)
{
if (item.FullName.Equals(assembly.FullName))
{
this._extraAssembliesDLL.Remove(assembly);
isReturn = true;
break;
}
}
if (isReturn)
return;
//检索BuildManager中的程序集,如果存在标记为不扫描DLL
Assembly[] existedAssemblys = null;
if (AppDomain.CurrentDomain.ShadowCopyFiles)
existedAssemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
else
{
Assembly entryAssembly = Assembly.GetEntryAssembly();
if (null != entryAssembly)
existedAssemblys = (from name in entryAssembly.GetReferencedAssemblies()
select Assembly.Load(name)).ToArray();
else
existedAssemblys = new Assembly[] { };
}
foreach (var item in existedAssemblys)
{
if (item.FullName.Equals(assembly.FullName) && this.Matches(assembly.FullName))
{
this._excludeAssembliesName.Add(item.FullName);
break;
}
}
//清除缓存
lock (s_cacheKey)
{
s_cacheAssemblies.Clear();
}
}
/// <summary>
/// 从所有的DLL进行筛选出匹配的类型
/// </summary>
/// <param name="assignTypeFrom">指定接口类型</param>
/// <param name="onlyConcreteClasses">True:不包含抽象类型,False:包含抽象类型</param>
/// <returns></returns>
public IEnumerable<Type> FindClassesOfType(Type assignTypeFrom, bool onlyConcreteClasses)
{
return this.FindClassesOfType(assignTypeFrom, null, onlyConcreteClasses);
}
/// <summary>
/// 从指定的程序集中筛选出匹配的类型
/// </summary>
/// <typeparam name="T">指定接口类型</typeparam>
/// <param name="assemblies">指定的查询的程序集范围(默认:null 指从所有的程序集进行筛选)</param>
/// <param name="onlyConcreteClasses">True:不包含抽象类型,False:包含抽象类型</param>
/// <returns></returns>
public IEnumerable<Type> FindClassesOfType<T>(IEnumerable<System.Reflection.Assembly> assemblies, bool onlyConcreteClasses)
{
return this.FindClassesOfType(typeof(T), assemblies, onlyConcreteClasses);
}
/// <summary>
/// 从指定的程序集中筛选出匹配的类型
/// </summary>
/// <param name="assignTypeFrom">指定接口类型</param>
/// <param name="assemblies">指定的查询的程序集范围</param>
/// <param name="onlyConcreteClasses">True:不包含抽象类型,False:包含抽象类型</param>
/// <returns></returns>
public IEnumerable<Type> FindClassesOfType(Type assignTypeFrom, IEnumerable<Assembly> assemblies, bool onlyConcreteClasses)
{
List<Assembly> assemblyList = null == assemblies ? new List<Assembly>() : new List<Assembly>(assemblies);
//优先检测外部传入参数
if (assemblyList.Count == 0)
{
//获取当前允许检测的程序集
assemblyList = new List<Assembly>(this.GetAssemblies());
if (assemblyList.Count == 0)
{
yield break;
}
}
foreach (var item in assemblyList)
{
Type[] types = null;
try
{
types = item.GetTypes();
}
catch (Exception ex)
{
throw ex;
}
if (null != types)
{
foreach (var t in types)
{
if (assignTypeFrom.IsAssignableFrom(t) || (assignTypeFrom.IsGenericTypeDefinition && DoesTypeImplementOpenGeneric(t, assignTypeFrom)))
{
if (!t.IsInterface)
{
if (onlyConcreteClasses)
{
if (t.IsClass && !t.IsAbstract)
{
yield return t;
}
}
else
{
yield return t;
}
}
}
}
}
}
}
/// <summary>
/// 获取所有的符合条件的程序集(嵌套缓存集合,加快速度)
/// </summary>
/// <returns></returns>
public IEnumerable<Assembly> GetAssemblies()
{
if (s_cacheAssemblies.Count <= 0)
{
lock (s_cacheKey)
{
if (s_cacheAssemblies.Count <= 0)
{
s_cacheAssemblies.AddRange(this.ScanAssemblies());
}
}
}
return s_cacheAssemblies;
}
#endregion
#region Virtual Protected Methods
/// <summary>
/// 判断指定的程序集是否满足验证规则【1.不包含在跳过配置,2.满足限制约束】
/// </summary>
/// <param name="assemblyFullName">程序集名称</param>
/// <returns></returns>
private bool Matches(string assemblyFullName)
{
if (string.IsNullOrEmpty(assemblyFullName))
{
return false;
}
string regPattern = string.Join("|", this._skipedAssemblyPatterns);
return !Regex.IsMatch(assemblyFullName, regPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled) && Regex.IsMatch(assemblyFullName, this._assemblyRestrictToLoadingPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
}
/// <summary>
/// 是否表示可以用来构造其他泛型类型的泛型类型
/// </summary>
/// <param name="type"></param>
/// <param name="openGeneric"></param>
/// <returns></returns>
private bool DoesTypeImplementOpenGeneric(Type type, Type openGeneric)
{
try
{
var genericTypeDefinition = openGeneric.GetGenericTypeDefinition();
foreach (var implementedInterface in type.FindInterfaces((objType, objCriteria) => true, null))
{
if (!implementedInterface.IsGenericType)
continue;
var isMatch = genericTypeDefinition.IsAssignableFrom(implementedInterface.GetGenericTypeDefinition());
return isMatch;
}
return false;
}
catch
{
return false;
}
}
/// <summary>
/// 扫描符合条件的程序集(不使用缓存,真实扫描,速度会慢)
/// </summary>
/// <returns></returns>
private IEnumerable<Assembly> ScanAssemblies()
{
List<Assembly> assemblies = new List<Assembly>();
List<string> addedAssemblyNames = new List<string>();
/* add assembly from buildManager or entry bin path */
Assembly[] existedAssemblys = null;
if (AppDomain.CurrentDomain.ShadowCopyFiles)
existedAssemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
else
{
Assembly entryAssembly = Assembly.GetEntryAssembly();
if (null != entryAssembly)
existedAssemblys = (from name in entryAssembly.GetReferencedAssemblies()
select Assembly.Load(name)).ToArray();
else
existedAssemblys = new Assembly[] { };
}
foreach (Assembly assembly in existedAssemblys)
{
if (this.Matches(assembly.FullName) && !addedAssemblyNames.Contains(assembly.FullName) && !this._excludeAssembliesName.Exists(d => d.Equals(assembly.FullName)))
{
assemblies.Add(assembly);
addedAssemblyNames.Add(assembly.FullName);
}
}
/* add assembly from extraAssemblies */
foreach (Assembly extraDLL in this._extraAssembliesDLL)
{
if (this.Matches(extraDLL.FullName) && !addedAssemblyNames.Contains(extraDLL.FullName) && !this._excludeAssembliesName.Exists(d => d.Equals(extraDLL.FullName)))
{
assemblies.Add(extraDLL);
addedAssemblyNames.Add(extraDLL.FullName);
}
}
return assemblies;
}
/// <summary>
/// 新增需要跳过的程序集正则
/// </summary>
/// <param name="assemblyPattern">程序集正则</param>
private void AddSkipAssemblyPattern(string assemblyPattern)
{
if (string.IsNullOrEmpty(assemblyPattern) || this._skipedAssemblyPatterns.Exists(d => d.Equals(assemblyPattern)))
return;
this._skipedAssemblyPatterns.Add(assemblyPattern);
}
/// <summary>
/// 删除需要跳过的程序集正则
/// </summary>
/// <param name="assemblyPattern">程序集正则</param>
private void RemoveSkipAssemblyPattern(string assemblyPattern)
{
if (string.IsNullOrEmpty(assemblyPattern) || !this._skipedAssemblyPatterns.Exists(d => d.Equals(assemblyPattern)))
return;
this._skipedAssemblyPatterns.Remove(assemblyPattern);
}
/// <summary>
/// 设置限制加载的正则表达式
/// </summary>
/// <param name="restrictToLoadingPattern">限制加载的表达式</param>
private void SetRestrictPattern(string restrictToLoadingPattern)
{
this._assemblyRestrictToLoadingPattern = restrictToLoadingPattern;
}
/// <summary>
/// 获取App应用程序的Bin目录
/// </summary>
/// <returns></returns>
private string BinDirectory()
{
string path = AppDomain.CurrentDomain.BaseDirectory;
if (AppDomain.CurrentDomain.ShadowCopyFiles)
{
if (path.Contains("bin"))
return path;
else
path = string.Format("{0}{1}{2}{1}", path, Path.DirectorySeparatorChar, "bin");
}
return path;
}
/// <summary>
/// 默认加载主应用程序Bin目录中的DLL(构造函数中最后一步调用)
/// </summary>
private void LoadMatchingBinAssemblies()
{
string directoryPath = this.BinDirectory();
Assembly[] existsed = null;
if (AppDomain.CurrentDomain.ShadowCopyFiles)
existsed = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToArray();
else
{
Assembly entryAssembly = Assembly.GetEntryAssembly();
if (null != entryAssembly)
existsed = (from name in entryAssembly.GetReferencedAssemblies()
select Assembly.Load(name)).ToArray();
else
existsed = new Assembly[] { };
}
//通常情况是是Bin中的所有dll进行筛选
foreach (string dllPath in System.IO.Directory.GetFiles(directoryPath, "*.dll"))
{
try
{
var an = AssemblyName.GetAssemblyName(dllPath);
if (!existsed.Any(d => null != an && d.FullName == an.FullName))
{
this.AppendAssembly(Assembly.Load(an));
}
}
catch (Exception ex)
{
throw ex;
}
}
//若为控制台或WINForm程序执行如下
if (!AppDomain.CurrentDomain.ShadowCopyFiles)
{
foreach (string exePath in System.IO.Directory.GetFiles(directoryPath, "*.exe"))
{
try
{
var an = AssemblyName.GetAssemblyName(exePath);
if (!existsed.Any(d => null != an && d.FullName == an.FullName))
{
this.AppendAssembly(Assembly.Load(an));
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
#endregion
}
}
|
using System;
using Nancy.Hosting.Self;
namespace NancyDemo
{
class Program
{
static void Main(string[] args)
{
var host = new NancyHost(new Uri("http://localhost:8080"));
host.Start();
Console.ReadLine();
}
}
}
|
using System;
using System.IO;
using Newtonsoft.Json;
namespace workspace.workshops
{
class ExpensesRequestParser
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
ExpenseRequest request = JsonConvert.DeserializeObject<ExpenseRequest>(File.ReadAllText(@"input/request.json"));
Console.WriteLine(request.expenses.Count);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Timer : MonoBehaviour
{
Text timerText;
Coroutine countdown;
int seconds;
void Start()
{
timerText = GetComponent<Text>();
}
private string SecondsToString(int seconds)
{
int minutes = seconds / 60;
int remaining = seconds % 60;
return string.Format("{0:D2}:{1:D2}", minutes, remaining);
}
public void Initialize(int seconds)
{
this.seconds = seconds;
timerText.text = SecondsToString(seconds);
}
public void StartCountdown()
{
countdown = StartCoroutine(Countdown());
}
public void StopCountdown()
{
StopCoroutine(countdown);
}
IEnumerator Countdown()
{
while (seconds > 0)
{
yield return new WaitForSeconds(1f);
--seconds;
timerText.text = SecondsToString(seconds);
}
TimerExpired();
}
private void TimerExpired()
{
Debug.Log("Timer Expired!");
}
}
|
using System;
using HtmlTags;
using FubuCore;
namespace FubuMVC.CodeSnippets
{
public class SnippetTag : HtmlTag
{
public SnippetTag(Snippet snippet) : base("pre")
{
Text(Environment.NewLine + snippet.Text);
AddClass("prettyprint");
if (snippet.Class.IsNotEmpty())
{
AddClass(snippet.Class);
}
if (snippet.Start > 0)
{
Data("linenums", snippet.Start);
}
}
}
} |
using System.Collections;
using UnityEngine;
public class WaterContact : MonoBehaviour
{
public FishingRod fishingRod;
public FishyManager fishM;
public bool fishing;
public AudioSource splop;
public bool hasLandedInWater;
public void Start()
{
fishM = FindObjectOfType<FishyManager>();
}
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Water")
{
splop.Play();
if (fishing && !hasLandedInWater)
{
hasLandedInWater = true;
if (Vector3.Distance(transform.position, fishingRod.transform.position) > 7f)
{
fishM.StartFishing(transform);
}
else
{
StartCoroutine(CheckDistance());
}
}
}
}
private IEnumerator CheckDistance()
{
while (fishing && Vector3.Distance(transform.position, fishingRod.transform.position) < 7f)
{
yield return null;
}
fishM.StartFishing(transform);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Thingy.WebServerLite.Api
{
public interface IControllerProvider
{
IController GetControllerForRequest(IWebServerRequest request);
IController GetNextControllerForRequest(IWebServerRequest request, Priorities previousPiority);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
using OnlineShopping.Models;
namespace OnlineShopping.Controllers
{
[EnableCors(origins: "http://localhost:4200", headers: "*", methods: "*")]
public class OrdersController : ApiController
{
Project_ShoppingEntities entities = new Project_ShoppingEntities();
public HttpResponseMessage GetOrders(int id)
{
List<Order> orders = new List<Order>();
var res = entities.sp_getOrders1(id).ToList();
foreach(var item in res.ToList())
{
orders.Add(new Order { Order_Id = item.Order_Id, Prod_Quantity = item.Prod_Quantity, Prod_Name = item.Prod_Name, Prod_Price = item.Prod_Price,Prod_Image=item.Prod_Image });
}
return Request.CreateResponse(HttpStatusCode.OK, orders);
}
}
}
|
using System;
using System.Collections.Generic;
namespace HospitalSystem.Models
{
public partial class approve_record
{
public long ApproveRecordID { get; set; }
public Nullable<long> MedicineID { get; set; }
public Nullable<long> ApplyDoctorID { get; set; }
public Nullable<long> ApproveDoctorID { get; set; }
public Nullable<int> MedicineNumber { get; set; }
public string ApplyReason { get; set; }
public Nullable<System.DateTime> ApplyTime { get; set; }
public Nullable<System.DateTime> ApproveTime { get; set; }
public Nullable<bool> Pass { get; set; }
public virtual doctor doctor { get; set; }
public virtual doctor doctor1 { get; set; }
public virtual medicine medicine { get; set; }
}
}
|
namespace CS.EntityFramework.Models
{
public class OrderStatus
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*******************************
* Created By franco
* Description: log type
*******************************/
namespace Kingdee.CAPP.Common.Logger
{
class ColorLogger: ILog,IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
public void Error(string message, params object[] args)
{
throw new NotImplementedException();
}
public void Warning(string message, params object[] args)
{
throw new NotImplementedException();
}
public void Info(string message, params object[] args)
{
throw new NotImplementedException();
}
public void Debug(string message, params object[] args)
{
throw new NotImplementedException();
}
}
}
|
using System;
namespace SelectionMover.Models
{
public static class ArrayWorker
{
public static int[,] NewArray(uint frame_width, uint frame_height)
{
Random random = new Random();
int[,] array = new int[frame_height, frame_width];
for (uint i = 0; i < frame_height; i++)
{
for (uint j = 0; j < frame_width; j++)
{
array[i,j] = random.Next(int.MinValue, int.MaxValue);
}
}
return array;
}
public static int[,] MoveSelection(int[,] array, uint x, uint y, uint width, uint height)
{
for (uint i = 0; i < height; i++)
{
for (uint j = 0; j < width; j++)
{
array[i, j] = array[i + y, j + x];
}
}
return array;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UFO.Server.Data {
public class Performance {
public Performance(uint id, DateTime date, uint artistId, uint venueId) {
Id = id;
Date = date;
ArtistId = artistId;
VenueId = venueId;
}
public Performance()
{
}
public uint Id {
get; set;
}
public DateTime Date {
get; set;
}
public uint ArtistId {
get; set;
}
public uint VenueId {
get; set;
}
public override string ToString() {
return String.Format("Performance(id={0}, date={1}, artistId={2}, venueId={3}) ", Id, Date, ArtistId, VenueId);
}
public override bool Equals(object obj) {
Performance per = obj as Performance;
if (per == null) {
return false;
}
return Id.Equals(per.Id) && Date.Equals(per.Date) && ArtistId.Equals(per.ArtistId) && VenueId.Equals(per.VenueId);
}
public override int GetHashCode() {
return (int)Id;
}
}
public interface IPerformanceDao {
List<Performance> GetAllPerformances();
Performance GetPerformanceById(uint id);
bool UpdatePerformance(Performance performance);
bool DeletePerformance(Performance performance);
Performance CreatePerformance(DateTime date, uint artistId, uint venueId);
void DeleteAllPerformances();
uint CountOfPerformancesAtVenue(Venue venue);
uint CountOfPerformancesOfArtist(Artist artist);
Performance GetPerformanceByVenueAndDate(uint venueId, DateTime date);
List<Performance> GetPerformancesByArtistBeforeDate(uint artistId, DateTime date);
List<Performance> GetPerformancesByArtistAfterDate(uint artistId, DateTime date);
List<Performance> GetPerformancesForDay(DateTime day);
}
public class PerformanceDao : IPerformanceDao {
private const string CREATE_CMD = "INSERT INTO Performance(date, artistId, venueId) VALUES (@date, @artistId, @venueId)";
private const string DELETE_CMD = "DELETE FROM Performance WHERE performanceId = @id";
private const string GETALL_CMD = "SELECT * FROM Performance";
private const string GETALLBYARTISTAFTERDATE = "SELECT * FROM Performance WHERE artistId=@artistId AND date > @date";
private const string GETALLBYARTISTBEFOREDATE = "SELECT * FROM Performance WHERE artistId=@artistId AND date < @date";
private const string GETALLPERFORMANCESFORDAY = "SELECT * FROM Performance WHERE date >= @beginDay AND date < @endDay ORDER BY date" ;
private const string GETBYID_CMD = "SELECT * FROM Performance WHERE performanceId = @id";
private const string UPDATE_CMD = "UPDATE Performance SET date=@date, artistId=@artistId, venueId=@venueId WHERE performanceId=@id";
private const string COUNTVENUES_CMD = "SELECT COUNT(*) AS count FROM Performance WHERE venueId=@venueId";
private const string COUNTARTISTS_CMD = "SELECT COUNT(*) AS count FROM Performance WHERE artistId=@artistId";
private const string GETBYVENUEDATE_CMD = "SELECT * FROM Performance WHERE date=@date AND venueId=@venueId";
private IDatabase db;
private Performance readOne(IDataReader reader) {
uint id = (uint)reader["performanceId"];
DateTime date = db.ConvertDateTimeFromDbFormat(reader["date"]);
uint artistId = (uint)reader["artistId"];
uint venueId = (uint)reader["venueId"];
return new Performance(id, date, artistId, venueId);
}
public PerformanceDao(IDatabase db) {
this.db = db;
}
public Performance CreatePerformance(DateTime date, uint artistId, uint venueId) {
DbCommand cmd = db.CreateCommand(CREATE_CMD);
db.DefineParameter(cmd, "@date", System.Data.DbType.DateTime, db.ConvertDateTimeToDbFormat(date));
db.DefineParameter(cmd, "@artistId", System.Data.DbType.UInt32, artistId);
db.DefineParameter(cmd, "@venueId", System.Data.DbType.UInt32, venueId);
uint id = (uint)db.ExecuteNonQuery(cmd);
return new Performance(id, date, artistId, venueId);
}
public void DeleteAllPerformances() {
db.TruncateTable("Performance");
}
public bool DeletePerformance(Performance performance) {
DbCommand cmd = db.CreateCommand(DELETE_CMD);
db.DefineParameter(cmd, "@id", System.Data.DbType.UInt32, performance.Id);
return cmd.ExecuteNonQuery() >= 1;
}
public List<Performance> GetAllPerformances() {
List<Performance> performances = new List<Performance>();
DbCommand cmd = db.CreateCommand(GETALL_CMD);
db.doSynchronized(() => {
using (IDataReader reader = db.ExecuteReader(cmd)) {
while (reader.Read()) {
performances.Add(readOne(reader));
}
}
});
return performances;
}
public Performance GetPerformanceById(uint id) {
DbCommand cmd = db.CreateCommand(GETBYID_CMD);
db.DefineParameter(cmd, "@id", System.Data.DbType.UInt32, id);
Performance perf = null;
db.doSynchronized(() => {
using (IDataReader reader = db.ExecuteReader(cmd)) {
if (reader.Read()) {
perf = readOne(reader);
}
}
});
return perf;
}
public bool UpdatePerformance(Performance performance) {
DbCommand cmd = db.CreateCommand(UPDATE_CMD);
db.DefineParameter(cmd, "@id", System.Data.DbType.UInt32, performance.Id);
db.DefineParameter(cmd, "@date", System.Data.DbType.DateTime, db.ConvertDateTimeToDbFormat(performance.Date));
db.DefineParameter(cmd, "@artistId", System.Data.DbType.UInt32, performance.ArtistId);
db.DefineParameter(cmd, "@venueId", System.Data.DbType.UInt32, performance.VenueId);
return db.ExecuteNonQuery(cmd) >= 1;
}
public uint CountOfPerformancesAtVenue(Venue venue) {
DbCommand cmd = db.CreateCommand(COUNTVENUES_CMD);
db.DefineParameter(cmd, "@venueId", System.Data.DbType.UInt32, venue.Id);
uint count = 0;
db.doSynchronized(() => {
using (IDataReader reader = db.ExecuteReader(cmd)) {
reader.Read();
count = (uint)((long)reader["count"]);
}
});
return count;
}
public uint CountOfPerformancesOfArtist(Artist artist) {
DbCommand cmd = db.CreateCommand(COUNTARTISTS_CMD);
db.DefineParameter(cmd, "@artistId", System.Data.DbType.UInt32, artist.Id);
uint count = 0;
db.doSynchronized(() => {
using (IDataReader reader = db.ExecuteReader(cmd)) {
reader.Read();
count = (uint)((long)reader["count"]);
}
});
return count;
}
public Performance GetPerformanceByVenueAndDate(uint venueId, DateTime date) {
DbCommand cmd = db.CreateCommand(GETBYVENUEDATE_CMD);
db.DefineParameter(cmd, "@date", System.Data.DbType.DateTime, date);
db.DefineParameter(cmd, "@venueId", System.Data.DbType.UInt32, venueId);
Performance perf = null;
db.doSynchronized(() => {
using (IDataReader reader = db.ExecuteReader(cmd)) {
if (reader.Read()) {
perf = readOne(reader);
}
}
});
return perf;
}
public List<Performance> GetPerformancesByArtistBeforeDate(uint artistId, DateTime date) {
List<Performance> performances = new List<Performance>();
DbCommand cmd = db.CreateCommand(GETALLBYARTISTBEFOREDATE);
db.DefineParameter(cmd, "@artistId", System.Data.DbType.UInt32, artistId);
db.DefineParameter(cmd, "@date", System.Data.DbType.DateTime, date);
db.doSynchronized(() => {
using (IDataReader reader = db.ExecuteReader(cmd)) {
while (reader.Read()) {
performances.Add(readOne(reader));
}
}
});
return performances;
}
public List<Performance> GetPerformancesByArtistAfterDate(uint artistId, DateTime date) {
List<Performance> performances = new List<Performance>();
DbCommand cmd = db.CreateCommand(GETALLBYARTISTAFTERDATE);
db.DefineParameter(cmd, "@artistId", System.Data.DbType.UInt32, artistId);
db.DefineParameter(cmd, "@date", System.Data.DbType.DateTime, date);
db.doSynchronized(() => {
using (IDataReader reader = db.ExecuteReader(cmd)) {
while (reader.Read()) {
performances.Add(readOne(reader));
}
}
});
return performances;
}
public List<Performance> GetPerformancesForDay(DateTime day) {
List<Performance> performances = new List<Performance>();
DbCommand cmd = db.CreateCommand(GETALLPERFORMANCESFORDAY);
var beginDay = new DateTime(day.Year, day.Month, day.Day);
var endDay = beginDay.AddDays(1);
db.DefineParameter(cmd, "@beginDay", System.Data.DbType.DateTime, beginDay);
db.DefineParameter(cmd, "@endDay", System.Data.DbType.DateTime, endDay);
db.doSynchronized(() => {
using (IDataReader reader = db.ExecuteReader(cmd)) {
while (reader.Read()) {
performances.Add(readOne(reader));
}
}
});
return performances;
}
}
}
|
namespace _07.FixEmails
{
using System;
using System.Collections.Generic;
public class FixEmails
{
public static void Main()
{
Dictionary<string, string> nameAndEmailsDictionary = new Dictionary<string, string>();
while (true)
{
string inputName = Console.ReadLine();
if (inputName == "stop")
{
break;
}
string inputEmail = Console.ReadLine();
string tmpStr = inputEmail.Substring(inputEmail.Length - 2).ToLower();
if (tmpStr != "us" && tmpStr != "uk")
{
if (!nameAndEmailsDictionary.ContainsKey(inputName))
{
nameAndEmailsDictionary.Add(inputName,"");
}
nameAndEmailsDictionary[inputName] = inputEmail;
}
}
foreach (KeyValuePair<string, string> keyValuePair in nameAndEmailsDictionary)
{
Console.WriteLine($"{keyValuePair.Key} -> {keyValuePair.Value}");
}
}
}
}
|
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Atc.CodeAnalysis.CSharp.SyntaxFactories
{
public static class SyntaxNameEqualsFactory
{
public static NameEqualsSyntax Create(string value)
{
return SyntaxFactory.NameEquals(
SyntaxFactory.IdentifierName(
SyntaxFactory.Identifier(
SyntaxFactory.TriviaList(),
value,
new SyntaxTriviaList(SyntaxFactory.Space))));
}
}
} |
using System.Collections.Generic;
using System.Linq;
namespace Nono.Engine
{
public ref struct CollapseCollector
{
private Box[]? _boxes;
private decimal _combinationsCount;
public void Add(IEnumerable<Box> line, decimal combinationsCount)
{
if (_boxes == null)
{
_boxes = line.ToArray();
_combinationsCount = combinationsCount;
return;
}
using (IEnumerator<Box> lineEnum = line.GetEnumerator())
{
int i = -1;
while (++i < _boxes.Length && lineEnum.MoveNext())
{
if (_boxes[i] != lineEnum.Current)
_boxes[i] = Box.Empty;
}
}
_combinationsCount += combinationsCount;
}
public CollapseLine ToCollapseLine()
=> _boxes != null
? new CollapseLine(_boxes, _combinationsCount)
: new CollapseLine();
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace UnityTerraforming.GameAi
{
[RequireComponent(typeof(Seek))]
[RequireComponent(typeof(Arrive))]
[RequireComponent(typeof(Wander))]
[RequireComponent(typeof(AvoidAgents))]
[RequireComponent(typeof(AvoidWall))]
public class Guardian : MonoBehaviour
{
public Spawner GuardianDestination;
public float GuardRadius;
public float LookRadius;
public float AttacRadius;
public Transform PlayerTransform;
private int _playerLayer;
public Seek SeekRef;
public Arrive ArriveRef;
private void Awake()
{
_playerLayer = LayerMask.NameToLayer("Player");
}
public bool PlayerInAttackRange()
{
if (PlayerTransform == null) return false;
return (transform.position - PlayerTransform.position).magnitude <= AttacRadius;
}
public bool InsideGuardRadius()
{
if (GuardianDestination == null) return false;
return (transform.position - GuardianDestination.transform.position).magnitude < GuardRadius;
}
public bool CheckPlayerInSight()
{
Collider[] coliders = Physics.OverlapSphere(transform.position, LookRadius);
foreach (Collider col in coliders)
{
if (col.gameObject.layer == _playerLayer)
{
PlayerTransform = col.gameObject.transform;
SeekRef.Target = PlayerTransform.gameObject;
return true;
}
}
return false;
}
}
} |
using System;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using i18n;
using Infra.Context;
using Infra.Migrations;
using Registrators;
using Unity;
using Welic.Dominio.Patterns.Repository.Pattern.DataContext;
using WebApi.Binders;
using WebApi.Themes;
namespace WebApi
{
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//http://stackoverflow.com/questions/1718501/asp-net-mvc-best-way-to-trim-strings-after-data-entry-should-i-create-a-custo
ModelBinders.Binders.Add(typeof(string), new TrimModelBinder());
// Use theme razor if database is installed
if (ConnectionStringHelper.IsDatabaseInstalled())
{
//remove all view engines
ViewEngines.Engines.Clear();
//except the themeable razor view engine we use
ViewEngines.Engines.Add(new ThemeableRazorViewEngine());
}
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["Language"];
if (cookie != null && cookie.Value != null)
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cookie.Value);
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(cookie.Value);
}
else
{
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
}
// ensure database is installed
if (!ConnectionStringHelper.IsDatabaseInstalled())
{
//TODO REvisar
//HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
//RouteData rd = RouteTable.Routes.GetRouteData(context);
////http://stackoverflow.com/questions/16819585/get-absolute-url-path-of-an-action-from-within-global-asax
//// Check if the current controller is Install
//if (rd != null)
//{
// string controllerName = rd.Values.ContainsKey("controller") ? rd.GetRequiredString("controller") : string.Empty;
// string actionName = rd.Values.ContainsKey("action") ? rd.GetRequiredString("action") : string.Empty;
// // check if it's bundles or content or set language
// if (!(controllerName.Equals("bundles", StringComparison.InvariantCultureIgnoreCase) ||
// controllerName.Equals("content", StringComparison.InvariantCultureIgnoreCase)))
// {
// if (!controllerName.Equals("install", StringComparison.InvariantCultureIgnoreCase))
// {
// Response.RedirectToRoute("Install");
// }
// }
//}
}
//TODO: Revisar
// ensure database is installed
//if (!ConnectionStringHelper.IsDatabaseInstalled())
//{
// HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
// RouteData rd = RouteTable.Routes.GetRouteData(context);
// //http://stackoverflow.com/questions/16819585/get-absolute-url-path-of-an-action-from-within-global-asax
// // Check if the current controller is Install
// if (rd != null)
// {
// string controllerName = rd.Values.ContainsKey("controller") ? rd.GetRequiredString("controller") : string.Empty;
// string actionName = rd.Values.ContainsKey("action") ? rd.GetRequiredString("action") : string.Empty;
// // check if it's bundles or content or set language
// if (!(controllerName.Equals("bundles", StringComparison.InvariantCultureIgnoreCase) ||
// controllerName.Equals("content", StringComparison.InvariantCultureIgnoreCase)))
// {
// if (!controllerName.Equals("install", StringComparison.InvariantCultureIgnoreCase))
// {
// Response.RedirectToRoute("Install");
// }
// }
// }
//}
if (ConnectionStringHelper.IsDatabaseInstalled())
{
var dbContext = ContainerManager.GetConfiguredContainer()
.Resolve<IDataContextAsync>() as AuthContext;
var language = Context.GetPrincipalAppLanguageForRequest().GetLanguage();
// Set date time format only if the database is ready
if (dbContext.Database.Exists())
{
// Short Date and time pattern
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo(language);
culture.DateTimeFormat.ShortDatePattern = CacheHelper.Settings.DateFormat;
culture.DateTimeFormat.ShortTimePattern = CacheHelper.Settings.TimeFormat;
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
//// Check if language from the url is enabled, if not, redirect to the default language
//if (!LanguageHelper.AvailableLanguges.Languages.Any(x => x.Culture == language && x.Enabled))
//{
// var returnUrl = LocalizedApplication.Current.UrlLocalizerForApp.SetLangTagInUrlPath(
// Request.RequestContext.HttpContext, Request.Url.PathAndQuery, UriKind.RelativeOrAbsolute,
// string.IsNullOrEmpty(LanguageHelper.DefaultCulture) ? null : LanguageHelper.DefaultCulture).ToString();
// Response.Redirect(returnUrl);
//}
}
}
protected void Application_Error(object sender, EventArgs e)
{
// Skip error processing if debugging
if (HttpContext.Current.IsDebuggingEnabled)
return;
Exception exception = Server.GetLastError();
HttpException httpException = exception as HttpException;
Elmah.ErrorSignal.FromCurrentContext().Raise(exception);
if (httpException != null)
{
string action = null;
switch (httpException.GetHttpCode())
{
case 404:
// page not found
action = "NotFound";
break;
case 500:
// server error
action = "Index";
break;
}
if (!string.IsNullOrEmpty(action))
{
// clear error on server
Response.Clear();
Server.ClearError();
Response.TrySkipIisCustomErrors = true;
// Call target Controller and pass the routeData.
IController errorController = new Controllers.ErrorController();
var routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", action);
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
}
}
public void Application_OnAuthorizeRequest()
{
var cookie = FormsAuthentication.FormsCookieName;
if (cookie == null)
return;
HttpCookie httpCookie = Context.Request.Cookies[cookie];
if (httpCookie == null)
return;
try
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(httpCookie.Value);
FormsIdentity identity = new FormsIdentity(ticket);
GenericPrincipal principal = new GenericPrincipal(identity, new[] { "role1" });
HttpContext.Current.User = principal;
}
catch (CryptographicException cex)
{
FormsAuthentication.SignOut();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Web;
using VandelayIndustries.DAL.Models;
namespace VandelayIndustries.DAL
{
public class DataContext : DbContext
{
public DataContext() : base("DefaultConnection")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, VandelayIndustries.Migrations.Configuration>());
}
public static DataContext Create()
{
return new DataContext();
}
public DbSet<Transaction> Transactions { get; set; }
public DbSet<Item> Items { get; set; }
public DbSet<SalesPerson> SalesPersons { get; set; }
public DbSet<Buyer> Buyers { get; set; }
public DbSet<Seller> Sellers { get; set; }
}
} |
using System;
namespace _9_Class_Constr_Prop
{
public class Person
{
//private string _name;
public string SecondName { get; set; }
public string Name { get; set; }
public Person(string secondName, string name)
{
SecondName = secondName;
Name = name;
}
//public string Name
//{
// get
// {
// return _name;
// }
// set
// {
// if (string.IsNullOrWhiteSpace(value))
// {
// throw new ArgumentNullException("Имя не может быть пустым");
// }
// _name = value + "+Maick";
// }
//}
//public string FullName
//{
// get
// {
// return SecondName + " " + Name;
// }
//}
//public string ShortName
//{
// get
// {
// return $"{SecondName} {Name.Substring(0, 1)}.";
// }
//}
///тоже что и вверху
//public string GetName()
//{
// return _name;
//}
//public void SetName(string name)
//{
// if (string.IsNullOrWhiteSpace(name))
// {
// throw new ArgumentNullException("Имя не может быть пустым");
// }
// _name = name;
//}
}
}
|
using System;
using System.Linq;
using StackExchange.Redis;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace Microsoft.UnifiedRedisPlatform.Core.Database
{
public partial class UnifiedRedisDatabase
{
public bool StringSet(RedisKey key, RedisValue value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None) =>
Execute(() => _baseDatabase.StringSet(CreateAppKey(key), value, expiry, when, flags));
public bool StringSet(KeyValuePair<RedisKey, RedisValue>[] values, When when = When.Always, CommandFlags flags = CommandFlags.None)
{
var appValues = values.Select(pair => new KeyValuePair<RedisKey, RedisValue>(CreateAppKey(pair.Key), pair.Value));
return Execute(() => _baseDatabase.StringSet(appValues.ToArray(), when, flags));
}
public Task<bool> StringSetAsync(RedisKey key, RedisValue value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None) =>
ExecuteAsync(() => _baseDatabase.StringSetAsync(CreateAppKey(key), value, expiry, when, flags));
public Task<bool> StringSetAsync(KeyValuePair<RedisKey, RedisValue>[] values, When when = When.Always, CommandFlags flags = CommandFlags.None)
{
var appValues = values.Select(pair => new KeyValuePair<RedisKey, RedisValue>(CreateAppKey(pair.Key), pair.Value));
return ExecuteAsync(() => _baseDatabase.StringSetAsync(appValues.ToArray(), when, flags));
}
public bool StringSetBit(RedisKey key, long offset, bool bit, CommandFlags flags = CommandFlags.None) =>
Execute(() => _baseDatabase.StringSetBit(CreateAppKey(key), offset, bit, flags));
public Task<bool> StringSetBitAsync(RedisKey key, long offset, bool bit, CommandFlags flags = CommandFlags.None) =>
ExecuteAsync(() => _baseDatabase.StringSetBitAsync(CreateAppKey(key), offset, bit, flags));
public RedisValue StringSetRange(RedisKey key, long offset, RedisValue value, CommandFlags flags = CommandFlags.None) =>
Execute(() => _baseDatabase.StringSetRange(CreateAppKey(key), offset, value, flags));
public Task<RedisValue> StringSetRangeAsync(RedisKey key, long offset, RedisValue value, CommandFlags flags = CommandFlags.None) =>
ExecuteAsync(() => _baseDatabase.StringSetRangeAsync(CreateAppKey(key), offset, value, flags));
public RedisValue StringGetSet(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) =>
Execute(() => _baseDatabase.StringGetSet(CreateAppKey(key), value, flags));
public Task<RedisValue> StringGetSetAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) =>
ExecuteAsync(() => _baseDatabase.StringGetSetAsync(key, value, flags));
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DFC.ServiceTaxonomy.PageLocation.Indexes;
using DFC.ServiceTaxonomy.Taxonomies.Helper;
using DFC.ServiceTaxonomy.Taxonomies.Validation;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Utilities;
using YesSql;
namespace DFC.ServiceTaxonomy.PageLocation.Validators
{
public class PageLocationUrlValidator : ITaxonomyTermValidator
{
private readonly ISession _session;
private readonly IContentManager _contentManager;
private readonly ITaxonomyHelper _taxonomyHelper;
public PageLocationUrlValidator(ISession session, IContentManager contentManager, ITaxonomyHelper taxonomyHelper)
{
_session = session;
_contentManager = contentManager;
_taxonomyHelper = taxonomyHelper;
}
public async Task<(bool, string)> ValidateCreate(JObject term, JObject taxonomy)
{
if (!term.ContainsKey("PageLocation"))
{
return (true, string.Empty);
}
string url = _taxonomyHelper.BuildTermUrl(term, taxonomy);
//TODO: check whether or not we only care about published pages, but I think we care about both
IEnumerable<ContentItem> contentItems = await _session.Query<ContentItem, PageLocationPartIndex>().ListAsync();
foreach (var contentItem in contentItems)
{
ContentItem? draftContentItem = await _contentManager.GetAsync(contentItem.ContentItemId, VersionOptions.Draft);
ContentItem? publishedContentItem = await _contentManager.GetAsync(contentItem.ContentItemId, VersionOptions.Published);
//TODO: use nameof, but doing so would introduce a circular dependency between the page location and taxonomies projects
string? draftUrl = ((string?)draftContentItem?.Content.PageLocationPart.FullUrl)?.Trim('/') ?? null;
string? pubUrl = ((string?)publishedContentItem?.Content.PageLocationPart.FullUrl)?.Trim('/') ?? null;
string[]? draftRedirectLocations = draftContentItem?.Content.PageLocationPart.RedirectLocations?.ToObject<string?>()?.Split("\r\n");
string[]? publishedRedirectLocations = publishedContentItem?.Content.PageLocationPart.RedirectLocations?.ToObject<string?>()?.Split("\r\n");
if ((draftUrl?.Equals(url, StringComparison.OrdinalIgnoreCase) ?? false) || (pubUrl?.Equals(url, StringComparison.OrdinalIgnoreCase) ?? false))
{
return (false, $"The generated URL for '{term["DisplayText"]}' has already been used as a {draftContentItem?.ContentType.CamelFriendly() ?? publishedContentItem!.ContentType.CamelFriendly()} URL.");
}
if ((draftRedirectLocations?.Any(x => x.Trim('/').Equals(url, StringComparison.OrdinalIgnoreCase)) ?? false) || (publishedRedirectLocations?.Any(x => x.Trim('/').Equals(url, StringComparison.OrdinalIgnoreCase)) ?? false))
{
return (false, $"The generated URL for '{term["DisplayText"]}' has already been used as a {draftContentItem?.ContentType.CamelFriendly() ?? publishedContentItem!.ContentType.CamelFriendly()} Redirect Location");
}
}
return (true, string.Empty);
}
public Task<(bool, string)> ValidateUpdate(JObject term, JObject taxonomy)
{
return ValidateCreate(term, taxonomy);
}
public Task<(bool, string)> ValidateDelete(JObject term, JObject taxonomy)
{
return Task.FromResult((true, string.Empty));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace AimaTeam.WebFormLightAPI.httpCore
{
/// <summary>
/// http_service_module.cs 调用某些函数的参数对象 add by OceanHo 2015-08-25 17:41:15
/// </summary>
public class RunModuleEvent
{
/// <summary>
/// 获取或者设置一个值,该值表示当前请求的是否已经处理过此次请求。将此属性设置为True(代码将不再往下执行,结束当前请求),反之继续
/// </summary>
public bool Handled { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddAmmo : MonoBehaviour
{
public AmmoCounter ammoCounter;
public GameObject Canvas;
private void Start()
{
Canvas = GameObject.FindGameObjectWithTag("Canvas");
ammoCounter = Canvas.GetComponentInChildren<AmmoCounter>();
}
void OnTriggerStay2D(Collider2D collision)
{
if (collision.gameObject.tag == "Player")
{
Destroy(gameObject);
ammoCounter.AddMag();
}
}
}
|
using CWI.Desafio2.Domain.Entities.Common;
using System.Collections.Generic;
namespace CWI.Desafio2.Domain.Entities
{
public class Sale : Entity
{
public int SalesmanId { get; set; }
public ICollection<Item> Items { get; set; }
}
}
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Web.Routing;
namespace System.Web.Mvc.Html
{
public static class TextBoxForExtensions
{
public enum TextCase { none, toUpper, toLower };
public static MvcHtmlString TextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
object htmlAttributes,
TextCase textcase)
{
var values = new RouteValueDictionary(htmlAttributes);
switch (textcase)
{
case TextCase.toLower:
values.Add("case", "lower");
break;
case TextCase.toUpper:
values.Add("case", "upper");
break;
default:
break;
}
return htmlHelper.TextBoxFor<TModel, TProperty>(expression, values);
}
}
}
|
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using Content.Client.GameObjects.EntitySystems;
using Content.Client.Utility;
using Content.Shared.Construction;
using Content.Shared.GameObjects.Components;
using Content.Shared.GameObjects.Components.Interactable;
using Content.Shared.Materials;
using Robust.Client.Graphics;
using Robust.Client.Interfaces.Placement;
using Robust.Client.Interfaces.ResourceManagement;
using Robust.Client.Placement;
using Robust.Client.ResourceManagement;
using Robust.Client.UserInterface;
using Robust.Client.UserInterface.Controls;
using Robust.Client.UserInterface.CustomControls;
using Robust.Client.Utility;
using Robust.Shared.Enums;
using Robust.Shared.GameObjects.Systems;
using Robust.Shared.Interfaces.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Prototypes;
namespace Content.Client.Construction
{
public class ConstructionMenu : SS14Window
{
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly IResourceCache _resourceCache = default!;
[Dependency] private readonly IEntitySystemManager _systemManager = default!;
[Dependency] private readonly IPlacementManager _placementManager = default!;
protected override Vector2? CustomSize => (720, 320);
private ConstructionPrototype? _selected;
private string[] _categories = Array.Empty<string>();
private readonly ItemList _recipes;
private readonly ItemList _stepList;
private readonly Button _buildButton;
private readonly Button _eraseButton;
private readonly LineEdit _searchBar;
private readonly OptionButton _category;
private readonly TextureRect _targetTexture;
private readonly RichTextLabel _targetName;
private readonly RichTextLabel _targetDescription;
public ConstructionMenu()
{
IoCManager.InjectDependencies(this);
_placementManager.PlacementChanged += PlacementChanged;
Title = "Construction";
var hbox = new HBoxContainer() {SizeFlagsHorizontal = SizeFlags.FillExpand};
var recipeContainer = new VBoxContainer() {SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.45f};
var searchContainer = new HBoxContainer() {SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.1f};
_searchBar = new LineEdit() {PlaceHolder = "Search", SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.6f};
_category = new OptionButton() {SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.4f};
_recipes = new ItemList() {SelectMode = ItemList.ItemListSelectMode.Single, SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.9f};
var spacer = new Control() {SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.05f};
var stepsContainer = new VBoxContainer() {SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.45f};
var targetContainer = new HBoxContainer() {Align = BoxContainer.AlignMode.Center, SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.25f};
_targetTexture = new TextureRect() {SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.15f, Stretch = TextureRect.StretchMode.KeepCentered};
var targetInfoContainer = new VBoxContainer() {SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.85f};
_targetName = new RichTextLabel() {SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.1f};
_targetDescription = new RichTextLabel() {SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.9f};
_stepList = new ItemList() {SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.75f, SelectMode = ItemList.ItemListSelectMode.None};
var buttonContainer = new VBoxContainer() {SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.1f};
_buildButton = new Button() {Disabled = true, ToggleMode = true, Text = Loc.GetString("Place construction ghost"), SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.5f};
var eraseContainer = new HBoxContainer() {SizeFlagsVertical = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.5f};
_eraseButton = new Button() {Text = Loc.GetString("Eraser Mode"), ToggleMode = true, SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.7f};
var clearButton = new Button() {Text = Loc.GetString("Clear All"), SizeFlagsHorizontal = SizeFlags.FillExpand, SizeFlagsStretchRatio = 0.3f};
recipeContainer.AddChild(searchContainer);
recipeContainer.AddChild(_recipes);
searchContainer.AddChild(_searchBar);
searchContainer.AddChild(_category);
targetInfoContainer.AddChild(_targetName);
targetInfoContainer.AddChild(_targetDescription);
targetContainer.AddChild(_targetTexture);
targetContainer.AddChild(targetInfoContainer);
stepsContainer.AddChild(targetContainer);
stepsContainer.AddChild(_stepList);
eraseContainer.AddChild(_eraseButton);
eraseContainer.AddChild(clearButton);
buttonContainer.AddChild(_buildButton);
buttonContainer.AddChild(eraseContainer);
stepsContainer.AddChild(buttonContainer);
hbox.AddChild(recipeContainer);
hbox.AddChild(spacer);
hbox.AddChild(stepsContainer);
Contents.AddChild(hbox);
_recipes.OnItemSelected += RecipeSelected;
_recipes.OnItemDeselected += RecipeDeselected;
_searchBar.OnTextChanged += SearchTextChanged;
_category.OnItemSelected += CategorySelected;
_buildButton.OnToggled += BuildButtonToggled;
clearButton.OnPressed += ClearAllButtonPressed;
_eraseButton.OnToggled += EraseButtonToggled;
PopulateCategories();
PopulateAll();
}
private void PlacementChanged(object? sender, EventArgs e)
{
_buildButton.Pressed = false;
_eraseButton.Pressed = false;
}
private void PopulateAll()
{
foreach (var recipe in _prototypeManager.EnumeratePrototypes<ConstructionPrototype>())
{
_recipes.Add(GetItem(recipe, _recipes));
}
}
private static ItemList.Item GetItem(ConstructionPrototype recipe, ItemList itemList)
{
return new(itemList)
{
Metadata = recipe,
Text = recipe.Name,
Icon = recipe.Icon.Frame0(),
TooltipEnabled = true,
TooltipText = recipe.Description,
};
}
private void PopulateBy(string search, string category)
{
_recipes.Clear();
foreach (var recipe in _prototypeManager.EnumeratePrototypes<ConstructionPrototype>())
{
if (!string.IsNullOrEmpty(search))
{
if (!recipe.Name.ToLowerInvariant().Contains(search.Trim().ToLowerInvariant()))
continue;
}
if (!string.IsNullOrEmpty(category) && category != Loc.GetString("All"))
{
if (recipe.Category != category)
continue;
}
_recipes.Add(GetItem(recipe, _recipes));
}
}
private void PopulateCategories()
{
var uniqueCategories = new HashSet<string>();
// hard-coded to show all recipes
uniqueCategories.Add(Loc.GetString("All"));
foreach (var prototype in _prototypeManager.EnumeratePrototypes<ConstructionPrototype>())
{
var category = Loc.GetString(prototype.Category);
if (!string.IsNullOrEmpty(category))
uniqueCategories.Add(category);
}
_category.Clear();
var array = uniqueCategories.ToArray();
Array.Sort(array);
for (var i = 0; i < array.Length; i++)
{
var category = array[i];
_category.AddItem(category, i);
}
_categories = array;
}
private void PopulateInfo(ConstructionPrototype prototype)
{
ClearInfo();
var isItem = prototype.Type == ConstructionType.Item;
_buildButton.Disabled = false;
_buildButton.Text = Loc.GetString(!isItem ? "Place construction ghost" : "Craft");
_targetName.SetMessage(prototype.Name);
_targetDescription.SetMessage(prototype.Description);
_targetTexture.Texture = prototype.Icon.Frame0();
if (!_prototypeManager.TryIndex(prototype.Graph, out ConstructionGraphPrototype graph))
return;
var startNode = graph.Nodes[prototype.StartNode];
var targetNode = graph.Nodes[prototype.TargetNode];
var path = graph.Path(startNode.Name, targetNode.Name);
var current = startNode;
var stepNumber = 1;
Texture? GetTextureForStep(ConstructionGraphStep step)
{
switch (step)
{
case MaterialConstructionGraphStep materialStep:
switch (materialStep.Material)
{
case StackType.Metal:
return _resourceCache.GetTexture("/Textures/Objects/Materials/sheets.rsi/metal.png");
case StackType.Glass:
return _resourceCache.GetTexture("/Textures/Objects/Materials/sheets.rsi/glass.png");
case StackType.Plasteel:
return _resourceCache.GetTexture("/Textures/Objects/Materials/sheets.rsi/plasteel.png");
case StackType.Phoron:
return _resourceCache.GetTexture("/Textures/Objects/Materials/sheets.rsi/phoron.png");
case StackType.Cable:
return _resourceCache.GetTexture("/Textures/Objects/Tools/cables.rsi/coil-30.png");
case StackType.MetalRod:
return _resourceCache.GetTexture("/Textures/Objects/Materials/materials.rsi/rods.png");
}
break;
case ToolConstructionGraphStep toolStep:
switch (toolStep.Tool)
{
case ToolQuality.Anchoring:
return _resourceCache.GetTexture("/Textures/Objects/Tools/wrench.rsi/icon.png");
case ToolQuality.Prying:
return _resourceCache.GetTexture("/Textures/Objects/Tools/crowbar.rsi/icon.png");
case ToolQuality.Screwing:
return _resourceCache.GetTexture("/Textures/Objects/Tools/screwdriver.rsi/screwdriver-map.png");
case ToolQuality.Cutting:
return _resourceCache.GetTexture("/Textures/Objects/Tools/wirecutters.rsi/cutters-map.png");
case ToolQuality.Welding:
return _resourceCache.GetTexture("/Textures/Objects/Tools/welder.rsi/welder.png");
case ToolQuality.Multitool:
return _resourceCache.GetTexture("/Textures/Objects/Tools/multitool.rsi/multitool.png");
}
break;
case ComponentConstructionGraphStep componentStep:
return componentStep.Icon?.Frame0();
case PrototypeConstructionGraphStep prototypeStep:
return prototypeStep.Icon?.Frame0();
case NestedConstructionGraphStep _:
return null;
}
return null;
}
foreach (var node in path)
{
var edge = current.GetEdge(node.Name);
var firstNode = current == startNode;
if (firstNode)
{
_stepList.AddItem(isItem
? Loc.GetString($"{stepNumber++}. To craft this item, you need:")
: Loc.GetString($"{stepNumber++}. To build this, first you need:"));
}
foreach (var step in edge.Steps)
{
var icon = GetTextureForStep(step);
switch (step)
{
case MaterialConstructionGraphStep materialStep:
_stepList.AddItem(
!firstNode
? Loc.GetString(
"{0}. Add {1}x {2}.", stepNumber++, materialStep.Amount, materialStep.Material)
: Loc.GetString(" {0}x {1}", materialStep.Amount, materialStep.Material), icon);
break;
case ToolConstructionGraphStep toolStep:
_stepList.AddItem(Loc.GetString("{0}. Use a {1}.", stepNumber++, toolStep.Tool.GetToolName()), icon);
break;
case PrototypeConstructionGraphStep prototypeStep:
_stepList.AddItem(Loc.GetString("{0}. Add {1}.", stepNumber++, prototypeStep.Name), icon);
break;
case ComponentConstructionGraphStep componentStep:
_stepList.AddItem(Loc.GetString("{0}. Add {1}.", stepNumber++, componentStep.Name), icon);
break;
case NestedConstructionGraphStep nestedStep:
var parallelNumber = 1;
_stepList.AddItem(Loc.GetString("{0}. In parallel...", stepNumber++));
foreach (var steps in nestedStep.Steps)
{
var subStepNumber = 1;
foreach (var subStep in steps)
{
icon = GetTextureForStep(subStep);
switch (subStep)
{
case MaterialConstructionGraphStep materialStep:
if (!isItem)
_stepList.AddItem(Loc.GetString(" {0}.{1}.{2}. Add {3}x {4}.", stepNumber, parallelNumber, subStepNumber++, materialStep.Amount, materialStep.Material), icon);
break;
case ToolConstructionGraphStep toolStep:
_stepList.AddItem(Loc.GetString(" {0}.{1}.{2}. Use a {3}.", stepNumber, parallelNumber, subStepNumber++, toolStep.Tool.GetToolName()), icon);
break;
case PrototypeConstructionGraphStep prototypeStep:
_stepList.AddItem(Loc.GetString(" {0}.{1}.{2}. Add {3}.", stepNumber, parallelNumber, subStepNumber++, prototypeStep.Name), icon);
break;
case ComponentConstructionGraphStep componentStep:
_stepList.AddItem(Loc.GetString(" {0}.{1}.{2}. Add {3}.", stepNumber, parallelNumber, subStepNumber++, componentStep.Name), icon);
break;
}
}
parallelNumber++;
}
break;
}
}
current = node;
}
}
private void ClearInfo()
{
_buildButton.Disabled = true;
_targetName.SetMessage(string.Empty);
_targetDescription.SetMessage(string.Empty);
_targetTexture.Texture = null;
_stepList.Clear();
}
private void RecipeSelected(ItemList.ItemListSelectedEventArgs obj)
{
_selected = (ConstructionPrototype) obj.ItemList[obj.ItemIndex].Metadata!;
PopulateInfo(_selected);
}
private void RecipeDeselected(ItemList.ItemListDeselectedEventArgs obj)
{
_selected = null;
ClearInfo();
}
private void CategorySelected(OptionButton.ItemSelectedEventArgs obj)
{
_category.SelectId(obj.Id);
PopulateBy(_searchBar.Text, _categories[obj.Id]);
}
private void SearchTextChanged(LineEdit.LineEditEventArgs obj)
{
PopulateBy(_searchBar.Text, _categories[_category.SelectedId]);
}
private void BuildButtonToggled(BaseButton.ButtonToggledEventArgs args)
{
if (args.Pressed)
{
if (_selected == null) return;
var constructSystem = EntitySystem.Get<ConstructionSystem>();
if (_selected.Type == ConstructionType.Item)
{
constructSystem.TryStartItemConstruction(_selected.ID);
_buildButton.Pressed = false;
return;
}
_placementManager.BeginPlacing(new PlacementInformation()
{
IsTile = false,
PlacementOption = _selected.PlacementMode,
}, new ConstructionPlacementHijack(constructSystem, _selected));
}
else
{
_placementManager.Clear();
}
_buildButton.Pressed = args.Pressed;
}
private void EraseButtonToggled(BaseButton.ButtonToggledEventArgs args)
{
if (args.Pressed) _placementManager.Clear();
_placementManager.ToggleEraserHijacked(new ConstructionPlacementHijack(_systemManager.GetEntitySystem<ConstructionSystem>(), null));
_eraseButton.Pressed = args.Pressed;
}
private void ClearAllButtonPressed(BaseButton.ButtonEventArgs obj)
{
var constructionSystem = EntitySystem.Get<ConstructionSystem>();
constructionSystem.ClearAllGhosts();
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing)
{
_placementManager.PlacementChanged -= PlacementChanged;
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpikesOnExplode : MonoBehaviour
{
private Explodable _explodable;
public GameObject spikePrefab;
public Team originTeam;
public float spikeRadius = 5f;
public LayerMask obstacleLayer;
private void Awake()
{
_explodable = GetComponent<Explodable>();
_explodable.OnFragmentsGenerated += HandleFragments;
if(_explodable)
_explodable.OnExplode.AddListener(OnExplode);
}
public void HandleFragments(List<GameObject> fragments)
{
print($"Handling {fragments.Count} Fragments");
foreach (var fragment in fragments)
{
SpikeFragment spikeFragment = fragment.AddComponent<SpikeFragment>();
spikeFragment.originTeam = originTeam;
spikeFragment.spikePrefab = spikePrefab;
}
}
public void OnExplode()
{
Vector3 position = transform.position;
List<RaycastHit2D> hits = BendHelper.StarCast(Vector2.up, position, 15, spikeRadius, obstacleLayer);
foreach (var hit in hits)
{
if(!hit)
continue;
GameObject spikeObj = Instantiate(spikePrefab, hit.point, Quaternion.identity);
spikeObj.transform.parent = hit.collider.transform;
Vector2 diff = (hit.point - (Vector2) position);
Vector2 spikeDir = Vector2.Reflect(-diff.normalized, hit.normal);
spikeObj.transform.right = spikeDir;
Debug.DrawRay(hit.point, spikeDir*10,Color.yellow,10f);
SpikeDamage spikeDamage = spikeObj.GetComponent<SpikeDamage>();
if(!spikeDamage)
continue;
spikeDamage.originTeam = originTeam;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class VulnerablePip : MonoBehaviour
{
// Use this for initialization
void Start ()
{
gameObject.transform.parent.tag = "Vulnerable";
}
// Update is called once per frame
void Update ()
{
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.