text stringlengths 13 6.01M |
|---|
using System.ComponentModel;
namespace Properties.Core.Objects
{
public enum AdvertiseActionType
{
Unknown = 0,
[Description("Advertise Single")]
AdvertiseSingle = 1,
[Description("Advertise All")]
AdvertiseAll = 2,
[Description("Remove Single")]
RemoveSingle = 3
}
}
|
using UnityEditor;
using UnityEngine;
namespace EditorExtensions
{
public class LayoutTest : ScriptableWizard
{
private static LayoutTest window;
private Vector2 firstPos;
private Vector2 secondPos;
private bool isExpand;
[MenuItem("Tools/窗口布局测试/展开折叠")]
public static void Init()
{
window = DisplayWizard<LayoutTest>("展开折叠");
window.maxSize = window.minSize = new Vector2(400, 400);
window.Show();
}
private void OnGUI()
{
EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(false));
GUILayout.Space(10);
firstPos = EditorGUILayout.BeginScrollView(firstPos, GUILayout.Width(340), GUILayout.ExpandWidth(false));
GUILayout.Button("左侧内容", GUILayout.Width(2000), GUILayout.Height(500), GUILayout.ExpandWidth(false));
EditorGUILayout.EndScrollView();
GUILayout.Space(5);
if (!isExpand)
{
if (GUILayout.Button("展开", GUILayout.Width(40), GUILayout.MaxHeight(2000), GUILayout.ExpandWidth(false)))
{
isExpand = true;
window.maxSize = window.minSize = new Vector2(800, 400);
}
}
else
{
if (GUILayout.Button("折叠", GUILayout.Width(40), GUILayout.MaxHeight(2000), GUILayout.ExpandWidth(false)))
{
isExpand = false;
window.maxSize = window.minSize = new Vector2(400, 400);
}
GUILayout.Space(5);
secondPos = EditorGUILayout.BeginScrollView(secondPos, GUILayout.Width(390), GUILayout.MaxWidth(2000), GUILayout.ExpandWidth(false));
GUILayout.Button("右侧内容", GUILayout.Width(2000), GUILayout.Height(500), GUILayout.ExpandWidth(false));
EditorGUILayout.EndScrollView();
}
EditorGUILayout.EndHorizontal();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EmployeeDeactivation.Interface
{
public interface IPdfDataOperation
{
void SendPdfAsEmailAttachmentDeactivation(string memoryStream, string employeeName, string teamName);
void SendPdfAsEmailAttachmentActivation(string memoryStream, string employeeName, string teamName, string sponsorGID, string siemensGid);
byte[] FillPdfForm(string GId);
byte[] FillActivationPdfForm(string GId);
void SendReminderEmail();
void SendEmailDeclined(string gid, string employeeName);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FSWatcher.Models;
using System.Data.SQLite;
namespace FSWatcher.Services {
class SQLiteLoggerService : ILoggerService {
private SQLiteConnection sql;
private string tableName;
public SQLiteLoggerService(string pathToDbFile, string tableName) {
this.sql = new SQLiteConnection("Data Source=FileSystemWatcher.db;Version=3;New=True;Compress=True");
this.sql.Open();
this.tableName = tableName;
// TODO add error handling here...
using(SQLiteCommand cmd = this.sql.CreateCommand()) {
cmd.CommandText = "CREATE TABLE IF NOT EXISTS " + tableName + " (Id varchar(128) primary key, FileName varchar(128), FilePath varchar(256), EventType integer, Timestamp datetime, ObjType integer, Extension varchar(15));";
cmd.ExecuteNonQuery();
}
}
public void DeleteFileEvent(FileEvent f) {
throw new NotImplementedException();
}
public List<FileEvent> GetFileEvents(List<string> extensions) {
return GetFileEvents(DateTime.MinValue, DateTime.MinValue, extensions);
}
public List<FileEvent> GetFileEvents(DateTime start, DateTime end, List<string> extensions) {
List<FileEvent> toReturn = new List<FileEvent>();
string extStr = string.Join(",", extensions.Select(x => "'" + x.ToString() + "'").ToArray());
try {
using(SQLiteCommand cmd = this.sql.CreateCommand()) {
cmd.CommandText = $"SELECT * FROM {tableName}";
if(extensions.Count > 0) cmd.CommandText += $" WHERE Extension IN ({extStr})";
using(SQLiteDataReader reader = cmd.ExecuteReader()) {
while(reader.Read()) {
toReturn.Add(new FileEvent(
reader["FileName"].ToString(),
reader["FilePath"].ToString(),
(FileEventTypes) Enum.Parse(typeof(FileEventTypes), (reader["EventType"]).ToString()),
DateTime.Parse(reader["Timestamp"].ToString()),
(ObjectTypes) Enum.Parse(typeof(ObjectTypes), (reader["ObjType"]).ToString())
));
}
}
}
} catch {
return null;
}
return toReturn;
}
public List<FileEvent> GetFileEvents() {
List<string> temp = new List<string>();
temp.Add("*");
return this.GetFileEvents(temp);
}
public bool LogFileEvent(FileEvent f) {
List<FileEvent> temp = new List<FileEvent>();
temp.Add(f);
return this.LogFileEvents(temp);
}
public bool LogFileEvents(List<FileEvent> data) {
try {
using(SQLiteCommand cmd = this.sql.CreateCommand()) {
cmd.CommandText = @"INSERT INTO fs_events(Id, FileName, FilePath, EventType, Timestamp, ObjType, Extension) VALUES (@Id, @FileName, @FilePath, @EventType, @Timestamp, @ObjType, @Extension)";
cmd.Prepare();
foreach(FileEvent item in data) {
// Skip files that have already been logged (if liveLogging is on)
if(item.HasBeenSavedToLog) continue;
cmd.Parameters.AddWithValue("@Id", item.Id.ToString());
cmd.Parameters.AddWithValue("@FileName", item.FileName);
cmd.Parameters.AddWithValue("@FilePath", item.FilePath);
cmd.Parameters.AddWithValue("@EventType", item.EventType);
cmd.Parameters.AddWithValue("@Timestamp", item.Timestamp);
cmd.Parameters.AddWithValue("@ObjType", item.ObjType);
cmd.Parameters.AddWithValue("@Extension", item.Extension);
cmd.ExecuteNonQuery();
item.HasBeenSavedToLog = true;
}
}
} catch {
return false;
}
return true;
}
public bool EraseData() {
try {
using(SQLiteCommand cmd = this.sql.CreateCommand()) {
cmd.CommandText = $"DELETE FROM {tableName};";
cmd.ExecuteNonQuery();
}
} catch {
return false;
}
return true;
}
}
}
|
using Discord;
using JhinBot.Conversation;
using JhinBot.DiscordObjects;
using JhinBot.Utils;
using System.Collections.Generic;
namespace JhinBot.Services
{
public interface IEmbedService : IService
{
EmbedBuilder CreateEmbed(string title, string colorCode, IUser author = null, string desc = "", string thumbnailURL = "", string footerText = "");
EmbedBuilder CreateEmbedWithList(string resxTitle, string colorCode, IEnumerable<(string, string)> list, IUser author = null, string resxDesc = "",
string thumbnailURL = "", params string[] descArgs);
EmbedBuilder CreateInfoEmbed(string resxTitle, string resxDesc, IUser author, params string[] descArgs);
PagedEmbed CreatePagedEmbed(string resxTitle, string colorCode, List<(string, string)> list, IOwnerLogger ownerLogger, IBotConfig botConfig,
IUser author, string resxDesc = "", params string[] descArgs);
EmbedBuilder CreateTagEmbed(Dictionary<string, string> tagBody);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public interface IMenu
{
void CheckForPressing();
}
public class Menu : MonoBehaviour
{
public bool pressed = false;
public MenuElement Notes;
public MenuElement Pause;
public MenuElement currentMenu;
public CircleInt choice;
public virtual void OpenMenu(MenuElement menu)
{
MenuElement temp = currentMenu;
currentMenu = menu;
currentMenu.GObj.SetActive(true);
temp.GObj.SetActive(false);
}
public virtual void OnChoiceChange()
{
foreach (Image child in currentMenu.Grid.GetComponentsInChildren<Image>())
{
child.color = new Color32(255, 255, 255, 255);
}
currentMenu.Grid.transform.GetChild(choice).GetComponent<Image>().color = new Color32(255, 30, 0, 255);
pressed = true;
}
public void FixPressing()
{
if (Input.GetAxisRaw("Horizontal") == 0 && Input.GetAxisRaw("UpDown") == 0)
{
pressed = false;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Simulator.Utils;
namespace Simulator.Instructions {
internal class CpuInstructionManager {
internal CpuInstructionManager(IEnumerable<CpuInstruction> instructions) {
Instructions = new Dictionary<CpuValue, CpuInstruction>();
foreach (var instruction in instructions) {
if (Instructions.ContainsKey(instruction.OpCode))
throw new CpuInstructionNameDuplicationException();
Instructions.Add(instruction.OpCode, instruction);
}
}
private Dictionary<CpuValue, CpuInstruction> Instructions { get; }
internal CpuInstruction GetInstruction(CpuValue opCode) {
if (Instructions.ContainsKey(opCode)) return Instructions[opCode];
throw new IncorrectCpuInstructionCallException();
}
internal CpuInstruction GetInstruction(string name) {
var instructions = Instructions.Values.Where(x => x.Name == name);
return instructions.FirstOrDefault();
}
internal CpuValue NameToOpcode(string name) {
var instruction = GetInstruction(name);
if (instruction?.OpCode != null) return instruction.OpCode;
throw new InvalidOpcodeException();
}
}
} |
using Arduino_Alarm.SetAlarm;
using Arduino_Alarm.SetAlarm.GetSchedule;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Arduino_Alarm
{
public class Factory
{
public static string Time { get; set; }
public static DayOfWeek Day { get; set; }
private static FinalSchedule _schedule;
internal static Settings _set;
internal static Settings GetSettings()
{
if (_set == null)
_set = new Settings();
return _set;
}
internal static FinalSchedule GetIt()
{
if (_schedule == null)
_schedule = new FinalSchedule();
return _schedule;
}
internal static void Update()
{
_schedule = null;
GetIt();
}
}
}
|
using Arduino_Alarm.Manual_Settings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Arduino_Alarm.SetAlarm;
using Arduino_Alarm.SetAlarm.GetSchedule;
using Arduino_Alarm.EnterSettings;
namespace Arduino_Alarm
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Window _iwindow;
MainWindowModel mv = new MainWindowModel();
public MainWindow()
{
InitializeComponent();
DataContext = mv;
}
private void Manual_Set_Click(object sender, RoutedEventArgs e)
{
(_iwindow = new ManualView()).ShowDialog();
}
private void Set_priorities_Click(object sender, RoutedEventArgs e)
{
(_iwindow = new PrioritiesView()).ShowDialog();
}
private void Initial_Set_Click(object sender, RoutedEventArgs e)
{
(_iwindow = new SettingsView()).ShowDialog();
}
private async void Set_Alarm_Click(object sender, RoutedEventArgs e)
{
if (Factory.Time== null)
MessageBox.Show("Wait a second...We need to check your schedule!", "Checking...", MessageBoxButton.OK, MessageBoxImage.Information);
var start = new CalculateTime();
start.OnReady += Message;
try
{
await start.Calculate();
}
catch { MessageBox.Show("Connection with Arduino is not established.Please connect your Arduino to the computer.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); }
}
public void Message()
{
MessageBox.Show("Be sure that you have connected arduino.\n\nYour alarm will be set. Good night!", "All right", MessageBoxButton.OK, MessageBoxImage.Information);
this.WindowState = WindowState.Minimized;
}
private void button_Click(object sender, RoutedEventArgs e)
{
string info = "The program is developed by Higher School of Economics students\n\n1. Set initial settings or set the time manually\n2. Set important subjects by choosing them in priority list. For these subjects alarm will work twice.\n3. Click Set Alarm button.";
MessageBox.Show(info, "Help", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class firstTimerUser : MonoBehaviour {
public int position;
public Button next,previous;
public GameObject gambarback,storyGO;
public GameObject[] story;
// Use this for initialization
void Start () {
position = 3;
if(PlayerPrefs.GetString ("SummonTutor")== "UDAH")
{
End();
}
}
// Update is called once per frame
void Update () {
// if (position == 0) {
// previous.gameObject.SetActive (false);
//
// if (position == 4) {
// next.gameObject.SetActive (false);
// }
//else {
// previous.gameObject.SetActive (true);
// next.gameObject.SetActive (true);
// }
switch (position) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
story [0].SetActive (true);
story [1].SetActive (false);
next.gameObject.SetActive (false);
// storyGO.SetActive (false);
break;
case 4:
story[0].SetActive(false);
story[2].SetActive(true);
story[3].SetActive(false);
break;
case 5:
gambarback.SetActive (false);
story[3].SetActive(false);
story[0].SetActive(false);
story[1].SetActive(true);
break;
//
}
}
public void Next(){
if (position <= 3) {
position += 1;
}
if (PlayerPrefs.HasKey ("SummonTutor")) {
if (PlayerPrefs.GetString ("SummonTutor") == "UDAH") {
//storyGO.SetActive (false);
position = 5;
next.gameObject.SetActive (false);
}
}
}
public void End()
{
position = 5;
}
}
|
namespace Flux.src.Flux.Renderer
{
public class CubeShapeFactory : IShapeFactory
{
public IShape Create()
{
return new Platform.OpenGL.OpenGLCube(Platform.OpenGL.OpenGLCube.VAODataType.VERTS);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using DTO;
namespace DAO
{
public class TuKhoaDuongDAO : AbstractDAO
{
//Tim duong
//return maDuong
public static int TimDuong(List<string> dsCumTu)
{
OleDbConnection ketNoi = null;
int maDuong = 0;
try
{
ketNoi = MoKetNoi();
string chuoiLenh = "SELECT MaDuong FROM TUKHOADUONG WHERE TuKhoaDuong Like @CumTu";
foreach (string cumTu in dsCumTu)
{
OleDbCommand lenh = new OleDbCommand(chuoiLenh, ketNoi);
OleDbParameter thamSo = new OleDbParameter("@CumTu", OleDbType.VarChar);
thamSo.Value = cumTu;
lenh.Parameters.Add(thamSo);
OleDbDataReader boDoc = lenh.ExecuteReader();
if (boDoc.Read())
{
maDuong = boDoc.GetInt32(0);
break;
}
}
}
catch
{
maDuong = 0;
}
finally
{
if (ketNoi != null && ketNoi.State == System.Data.ConnectionState.Open)
ketNoi.Close();
}
return maDuong;
}
}
}
|
namespace DotNetBrightener.LinQToSqlBuilder.Adapter
{
class SqlServerAdapter : SqlServerAdapterBase, ISqlAdapter
{
public string QueryStringPage(string source, string selection, string conditions, string order,
int pageSize, int pageIndex = 0)
{
if (pageIndex == 0)
return $"SELECT TOP({pageSize}) {selection} FROM {source} {conditions} {order}";
return
$@"SELECT {selection} FROM {source} {conditions} {order} OFFSET {pageSize * pageIndex} ROWS FETCH NEXT {pageSize} ROWS ONLY";
}
}
} |
using Cs_Gerencial.Aplicacao.Interfaces;
using Cs_Gerencial.Dominio.Entities;
using Cs_Gerencial.Dominio.Interfaces.Servicos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Gerencial.Aplicacao.ServicosApp
{
public class AppServicoAdicional: AppServicoBase<Adicional>, IAppServicoAdicional
{
private readonly IServicoAdicional _servicoAdicional;
public AppServicoAdicional(IServicoAdicional servicoAdicional)
:base(servicoAdicional)
{
_servicoAdicional = servicoAdicional;
}
}
}
|
using System;
using System.Collections.Generic;
using FunctionalProgramming.Basics;
namespace FunctionalProgramming.Monad
{
public interface IWriter<TLog, TValue>
{
Tuple<TLog, TValue> ValueWithLog();
TValue Value();
}
public static class Writer
{
public static IWriter<TLog, TValue> WithLog<TLog, TValue>(this TValue v, TLog log)
{
return new WriterImpl<TLog, TValue>(log, v);
}
public static IWriter<TLog, TValue> WithLog<TLog, TValue>(this TValue v, Func<TValue, TLog> f)
{
return new WriterImpl<TLog, TValue>(f(v), v);
}
public static IWriter<IEnumerable<TLog>, TValue> WithLogs<TLog, TValue>(this TValue v, TLog log)
{
return new WriterImpl<IEnumerable<TLog>, TValue>(log.LiftEnumerable(), v);
}
public static IWriter<IEnumerable<TLog>, TValue> WithLogs<TLog, TValue>(this TValue v, Func<TValue, TLog> f)
{
return new WriterImpl<IEnumerable<TLog>, TValue>(f(v).LiftEnumerable(), v);
}
public static IWriter<TLog, Unit> LogOnly<TLog>(this TLog log)
{
return new WriterImpl<TLog, Unit>(log, Unit.Only);
}
public static IWriter<IEnumerable<TLog>, Unit> LogsOnly<TLog>(this TLog log)
{
return new WriterImpl<IEnumerable<TLog>, Unit>(log.LiftEnumerable(), Unit.Only);
}
public static IWriter<TLog, TValue> NoLog<TLog, TValue>(this TValue v, IMonoid<TLog> m)
{
return new WriterImpl<TLog, TValue>(m.MZero, v);
}
public static IWriter<TLog, TResult> Select<TLog, TInitial, TResult>(this IWriter<TLog, TInitial> m,
Func<TInitial, TResult> f)
{
var logAndValue = m.ValueWithLog();
return new WriterImpl<TLog, TResult>(logAndValue.Item1, f(logAndValue.Item2));
}
public static IWriter<IEnumerable<TLog>, TResult> SelectMany<TLog, TInitial, TResult>(
this IWriter<IEnumerable<TLog>, TInitial> m, Func<TInitial, IWriter<IEnumerable<TLog>, TResult>> f)
{
var logAndValue = m.ValueWithLog();
var newLogAndValue = f(logAndValue.Item2).ValueWithLog();
return new WriterImpl<IEnumerable<TLog>, TResult>(EnumerableMonoid<TLog>.Only.MAppend(logAndValue.Item1, newLogAndValue.Item1), newLogAndValue.Item2);
}
public static IWriter<IEnumerable<TLog>, TSelect> SelectMany<TLog, TInitial, TResult, TSelect>(
this IWriter<IEnumerable<TLog>, TInitial> m, Func<TInitial, IWriter<IEnumerable<TLog>, TResult>> f,
Func<TInitial, TResult, TSelect> selector)
{
return m.SelectMany(a => f(a).SelectMany(b => selector(a, b).NoLog(EnumerableMonoid<TLog>.Only)));
}
private class WriterImpl<TLog, TValue> : IWriter<TLog, TValue>
{
private readonly TLog _log;
private readonly TValue _value;
public WriterImpl(TLog log, TValue value)
{
_log = log;
_value = value;
}
public Tuple<TLog, TValue> ValueWithLog()
{
return Tuple.Create(_log, _value);
}
public TValue Value()
{
return _value;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using GrubTime.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using GrubTime.Middleware;
using Microsoft.AspNetCore.Routing;
using Microsoft.DotNet.PlatformAbstractions;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Swashbuckle.AspNetCore.Swagger;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using Microsoft.Extensions.PlatformAbstractions;
namespace GrubTime
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
});
services.AddLogging();
string domain = $"https://{Configuration["Auth0:Domain"]}/";
services.AddAuthorization();
services.AddOptions();
services.Configure<Google>(Configuration.GetSection("Google"));
services.AddSwaggerGen(c =>
{
c.OperationFilter<AddRequiredHeaderParameter>();
c.SwaggerDoc("v1", new Info
{
Version = "v1",
Title = "Grubtime API",
Description = "An app used to search restuarants open near you.",
TermsOfService = "None",
Contact = new Contact { Name = "Hanna Bernard", Email = "Hlbernard124@gmail.com", Url = "https://github.com/hann-b" }
});
c.DescribeAllEnumsAsStrings();
var basepath = PlatformServices.Default.Application.ApplicationBasePath;
c.IncludeXmlComments(basepath + "\\.xml");
});
services.AddRouting();
services.AddDbContext<GrubTimeContext>(options =>
options.UseSqlServer(Configuration["Database:DefaultConnection"]));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
var Jwtoptions = new JwtBearerOptions
{
Audience = Configuration["Auth0:ApiIdentifier"],
Authority = $"https://{Configuration["Auth0:Domain"]}/",
Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
//context.Ticket.Principle.Identity
var claimsIdentity = context.Ticket.Principal.Identity as ClaimsIdentity;
if (claimsIdentity != null)
{
string userId = claimsIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value;
string name = claimsIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
}
return Task.FromResult(0);
}
}
};
app.UseJwtBearerAuthentication(Jwtoptions);
app.UseCors("AllowAll");
//Middleware
var GoogleApi = Configuration.GetSection("Google").Get<Google>();
//Search Middelware
app.UseReqParseMiddleware();
// app.UseValuesMiddleware();
app.UseValuesMiddleware(GoogleApi);
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}");
});
app.UseSwagger(null);
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Grubtime API V1");
});
}
}
}
|
using LocusNew.Core.Models;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Description;
using LocusNew.Core;
namespace LocusNew.Areas.Admin.Controllers.ApiControllers
{
[Authorize]
public class PropertyTypesController : ApiController
{
private readonly IUnitOfWork _unitOfWork;
public PropertyTypesController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public IQueryable<PropertyType> GetPropertyTypes()
{
return _unitOfWork.PropertyTypes.GetPropertyTypes();
}
[ResponseType(typeof(PropertyType))]
public IHttpActionResult GetPropertyType(int id)
{
PropertyType propertyType = _unitOfWork.PropertyTypes.GetPropertyType(id);
if (propertyType == null)
{
return NotFound();
}
return Ok(propertyType);
}
[ResponseType(typeof(PropertyType))]
public IHttpActionResult AddNewPropertyType(PropertyType propertyType)
{
_unitOfWork.PropertyTypes.AddPropertyType(propertyType);
_unitOfWork.Complete();
return CreatedAtRoute("DefaultApi", new { id = propertyType.Id }, propertyType);
}
[HttpPost]
public IHttpActionResult DeletePropertyType(int id)
{
if (!_unitOfWork.PropertyTypes.RemovePropertyType(id))
{
return BadRequest();
}
_unitOfWork.Complete();
return Ok();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MissionScript : MonoBehaviour
{
public GameObject PanelText;
public bool Locked;
// Use this for initialization
void Start ()
{
HideTextPanel ();
}
public void HideTextPanel ()
{
StartCoroutine (HidePanel ());
}
IEnumerator HidePanel()
{
yield return new WaitForSeconds (10f);
PanelText.SetActive (false);
}
}
|
using System.Collections.Generic;
using LocusNew.Core.Models;
namespace LocusNew.Core.Repositories
{
public interface ISellerLeadsRepository
{
void AddSellerLead(SellerLead lead);
SellerLead GetSellerLead(int id);
IEnumerable<SellerLead> GetSellerLeadsWithPropertyType();
void RemoveSellerLead(int id);
}
} |
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private TreeNode Helper(int[] inorder, int iStart, int iEnd, int[] postorder, int pStart, int pEnd) {
if (iStart>iEnd || pStart>pEnd) return null;
TreeNode root = new TreeNode(postorder[pEnd]);
int i;
for (i=iStart; i<=iEnd; i++) {
if (inorder[i] == postorder[pEnd]) break;
}
root.left = Helper(inorder, iStart, i-1, postorder, pStart, pStart+i-1-iStart);
root.right = Helper(inorder, i+1, iEnd, postorder, pEnd-(iEnd-i), pEnd-1);
return root;
}
public TreeNode BuildTree(int[] inorder, int[] postorder) {
if (inorder.Length == 0) return null;
TreeNode root = Helper(inorder, 0, inorder.Length-1, postorder, 0, postorder.Length-1);
return root;
}
} |
using System;
namespace AppStore.Streaming.Handlers
{
public class ProcessPaymentHandler
{
public int OrderId { get; set; }
public Guid? InstantBuyKey { get; set; }
public CreditCardBrand? Brand { get; set; }
public string Number { get; set; }
public int? ExpMonth { get; set; }
public int? ExpYear { get; set; }
public string SecurityCode { get; set; }
public string HolderName { get; set; }
public bool? SaveCreditCard { get; set; }
}
}
|
using Microsoft.Azure.Cosmos.Table;
using System;
using System.Threading.Tasks;
namespace AzureTableStorage
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Table storage sample");
var storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=apithreelayerarchstorage;AccountKey=QERpGqXXMGMLOlG1zCHdJAeANoFpdSiTm7YRc+IhrDobHoD61S7HLZXx2SfXN/ASGoqskVjKLmIx5hzWFHLmAg==;EndpointSuffix=core.windows.net";
var tableName = "tsmtable";
CloudStorageAccount storageAccount;
storageAccount = CloudStorageAccount.Parse(storageConnectionString);
CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration());
CloudTable table = tableClient.GetTableReference(tableName);
CustomerEntity customer = new CustomerEntity("Tarun", "Singh Mahar")
{
Email = "tarun@gmail.com",
PhoneNumber = "+91-7777766666"
};
//CreateCustomer(table, customer).Wait();
//ReadCustomer(table, "Tarun", "Singh Mahar").Wait();
//UpdateCustomer(table, customer).Wait();
DeleteCustomer(table, "Tarun", "Singh Mahar").Wait();
}
public static async Task CreateCustomer(CloudTable table, CustomerEntity customer)
{
TableOperation createOperation = TableOperation.Insert(customer);
// Execute the operation.
TableResult result = await table.ExecuteAsync(createOperation);
CustomerEntity createdCustomer = result.Result as CustomerEntity;
Console.WriteLine("Created customer.");
}
public static async Task ReadCustomer(CloudTable table, string firstName, string lastName)
{
TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>(firstName, lastName);
TableResult result = await table.ExecuteAsync(retrieveOperation);
CustomerEntity customer = result.Result as CustomerEntity;
if (customer != null)
{
Console.WriteLine("Fetched \t{0}\t{1}\t{2}\t{3}",
customer.PartitionKey, customer.RowKey, customer.Email, customer.PhoneNumber);
}
}
public static async Task UpdateCustomer(CloudTable table, CustomerEntity customer)
{
TableOperation updateOperation = TableOperation.InsertOrMerge(customer);
// Execute the operation.
TableResult result = await table.ExecuteAsync(updateOperation);
CustomerEntity updatedCustomer = result.Result as CustomerEntity;
Console.WriteLine("Updated user.");
}
public static async Task DeleteCustomer(CloudTable table, string firstName, string lastName)
{
TableOperation retrieveOperation = TableOperation.Retrieve<CustomerEntity>(firstName, lastName);
TableResult result = await table.ExecuteAsync(retrieveOperation);
CustomerEntity customer = result.Result as CustomerEntity;
TableBatchOperation batchOperation = new TableBatchOperation();
customer.ETag = "*";
batchOperation.Delete(customer);
table.ExecuteBatch(batchOperation);
Console.WriteLine("Deleted customer");
}
}
public class CustomerEntity : TableEntity
{
public CustomerEntity() { }
public CustomerEntity(string lastName, string firstName)
{
PartitionKey = lastName;
RowKey = firstName;
}
public string Email { get; set; }
public string PhoneNumber { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
namespace TheQuest.Models
{
public class Character
{
public Character()
{
this.Stats = new HashSet<Stats>();
this.Friends = new HashSet<Character>();
this.Items = new HashSet<Item>();
}
[Key]
public int CharacterId { get; set; }
public string CharacterName { get; set; }
public int Level { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public ICollection<Stat> Stats { get; set; }
public ICollection<Character> Friends { get; set; }
public ICollection<Item> Items { get; set; }
public int Currency { get; set; }
}
}
|
using System.Collections.Generic;
using com.Sconit.Entity.SYS;
using com.Sconit.Entity.INV;
using com.Sconit.Entity.MD;
using com.Sconit.Entity.ORD;
using com.Sconit.Entity.VIEW;
using System;
using com.Sconit.Entity.PRD;
using com.Sconit.Entity.INP;
namespace com.Sconit.Service
{
public interface ILocationDetailMgr
{
LocationLotDetail GetHuLocationLotDetail(string huId);
IList<LocationLotDetail> GetHuLocationLotDetails(IList<string> huIdList);
IList<InventoryTransaction> InventoryOut(IpDetail ipDetail);
IList<InventoryTransaction> InventoryOut(IpDetail ipDetail, DateTime effectiveDate);
//IList<InventoryTransaction> CancelInventoryOut(IpDetail ipDetail);
//IList<InventoryTransaction> CancelInventoryOut(IpDetail ipDetail, DateTime effectiveDate);
IList<InventoryTransaction> InventoryIn(ReceiptDetail receiptDetail);
IList<InventoryTransaction> InventoryIn(ReceiptDetail receiptDetail, DateTime effectiveDate);
IList<InventoryTransaction> FeedProductRawMaterial(FeedInput feedInput);
IList<InventoryTransaction> FeedProductRawMaterial(FeedInput feedInput, DateTime effectiveDate);
IList<InventoryTransaction> ReturnProductRawMaterial(ReturnInput returnInput);
IList<InventoryTransaction> ReturnProductRawMaterial(ReturnInput returnInput, DateTime effectiveDate);
IList<InventoryTransaction> BackflushProductWeightAverageRawMaterial(IList<WeightAverageBackflushInput> backFlushInputList);
IList<InventoryTransaction> BackflushProductWeightAverageRawMaterial(IList<WeightAverageBackflushInput> backFlushInputList, DateTime effectiveDate);
IList<InventoryTransaction> BackflushProductMaterial(IList<BackflushInput> backflushInputList);
IList<InventoryTransaction> BackflushProductMaterial(IList<BackflushInput> backflushInputList, DateTime effectiveDate);
IList<InventoryTransaction> CancelBackflushProductMaterial(IList<BackflushInput> backflushInputList);
IList<InventoryTransaction> CancelBackflushProductMaterial(IList<BackflushInput> backflushInputList, DateTime effectiveDate);
IList<InventoryTransaction> InventoryInspect(InspectMaster inspectMaster);
IList<InventoryTransaction> InventoryInspect(InspectMaster inspectMaster, DateTime effectiveDate);
IList<InventoryTransaction> InspectJudge(InspectMaster inspectMaster, IList<InspectResult> inspectResultList);
IList<InventoryTransaction> InspectJudge(InspectMaster inspectMaster, IList<InspectResult> inspectResultList, DateTime effectiveDate);
IList<InventoryTransaction> ConcessionToUse(ConcessionMaster consessionMaster);
IList<InventoryTransaction> ConcessionToUse(ConcessionMaster consessionMaster, DateTime effectiveDate);
IList<InventoryTransaction> InventoryPack(IList<InventoryPack> inventoryPackList);
IList<InventoryTransaction> InventoryPack(IList<InventoryPack> inventoryPackList, DateTime effectiveDate);
IList<InventoryTransaction> InventoryUnPack(IList<InventoryUnPack> inventoryUnPackList);
IList<InventoryTransaction> InventoryUnPack(IList<InventoryUnPack> inventoryUnPackList, DateTime effectiveDate);
IList<InventoryTransaction> InventoryRePack(IList<InventoryRePack> inventoryRePackList);
IList<InventoryTransaction> InventoryRePack(IList<InventoryRePack> inventoryRePackList, DateTime effectiveDate);
IList<InventoryTransaction> StockTakeAdjust(StockTakeMaster stockTakeMaster, IList<StockTakeResult> stockTakeResultList);
IList<InventoryTransaction> StockTakeAdjust(StockTakeMaster stockTakeMaster, IList<StockTakeResult> stockTakeResultList, DateTime effectiveDate);
void InventoryPick(IList<InventoryPick> inventoryPickList);
void InventoryPut(IList<InventoryPut> inventoryPutList);
void InventoryPut(IList<StockTakeDetail> stockTakeDetailList);
IList<LocationLotDetail> InventoryOccupy(IList<InventoryOccupy> inventoryOccupyList);
IList<LocationLotDetail> CancelInventoryOccupy(CodeMaster.OccupyType occupyType, string occupyReferenceNo);
IList<LocationLotDetail> CancelInventoryOccupy(CodeMaster.OccupyType occupyType, string occupyReferenceNo, IList<string> huIdList);
IList<InventoryTransaction> InventoryOtherInOut(MiscOrderMaster miscOrderMaster, MiscOrderDetail miscOrderDetail);
IList<InventoryTransaction> InventoryOtherInOut(MiscOrderMaster miscOrderMaster, MiscOrderDetail miscOrderDetail, DateTime effectiveDate);
IList<InventoryTransaction> CancelInventoryOtherInOut(MiscOrderMaster miscOrderMaster);
IList<InventoryTransaction> CancelInventoryOtherInOut(MiscOrderMaster miscOrderMaster, DateTime effectiveDate);
//IList<HistoryInventory> GetHistoryLocationDetails(string locatoin, IList<string> itemList, DateTime historyDate, string SortDesc, int PageSize, int Page);
//IList<HuHistoryInventory> GetHuHistoryLocationDetails(string locatoin, IList<string> itemList, DateTime historyDate);
IList<InventoryTransaction> InventoryExchange(IList<ItemExchange> itemExchangeList);
IList<InventoryTransaction> CancelInventoryExchange(IList<ItemExchange> itemExchangeList);
void InventoryFreeze(IList<string> huIdList);
void InventoryFreeze(IList<string> huIdList,string reason);
void InventoryFreeze(string item, string location, string lotNo, string manufactureParty);
void InventoryUnFreeze(IList<string> huIdList);
void InventoryUnFreeze(IList<string> huIdList, string reason);
void InventoryUnFreeze(string item, string location, string lotNo, string manufactureParty);
#region 客户化代码
IList<InventoryTransaction> InventoryRePack(IList<InventoryRePack> inventoryRePackList, Boolean isCheckOccupy, DateTime effectiveDate);
#endregion
IList<LocationDetailIOB> GetLocationDetailIOB(string location, string item, DateTime startDate, DateTime endDate);
Dictionary<string, decimal> GetInvATPQty(string location, List<string> items);
Dictionary<string, decimal> GetPurchaseInTransQty(string location, List<string> items);
void SettleLocaitonLotDetail(List<Int64> locationLotDetIdList);
IList<Hu> Repack(string huId, IList<ProductBarCode> checkedProductBarCodeList, IList<ProductBarCode> uncheckedProductBarCodeList);
List<Hu> DevanningHu(Hu hu);
void DeleteLocationBin(string id);
}
}
|
namespace UniNode
{
public class Node
{
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace OSRSClientSide.Models
{
public class PaymentDTO
{
public string nameOnCard { get; set; }
public int? cardNumber { get; set; }
public int? cvv { get; set; }
public string netBankingName { get; set; }
[ScaffoldColumn(false)]
public int order_id { get; set; }
[ScaffoldColumn(false)]
public int userid { get; set; }
public DateTime? expiryDate { get; set; }
public double amount { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EX_4A_Farm
{
class Rabbit
{
public Rabbit(string name)
{
string animalName = name;
Console.WriteLine($"Hello, my name is {animalName}. ");
}
public string speak()
{
string sound = "squeek";
return sound;
}
public string eat()
{
string food = "carrots";
return food;
}
public string movie()
{
string film = "Roger Rabbit";
return film;
}
public string product()
{
string service = "fur";
return service;
}
}
}
|
using System.Web.Mvc;
namespace DevExpress.Web.Demos {
public partial class TreeListController : DemoController {
[HttpGet]
public ActionResult Export() {
TreeListExportDemoOptions options = new TreeListExportDemoOptions() {
EnableAutoWidth = false,
ExpandAllNodes = false,
ShowTreeButtons = false
};
Session["TreeListExportOptions"] = options;
return DemoView("Export", DepartmentsProvider.GetDepartments());
}
[HttpPost]
public ActionResult Export([Bind] TreeListExportDemoOptions options) {
Session["TreeListExportOptions"] = options;
foreach(string typeName in TreeListDemoHelper.ExportTypes.Keys) {
if(Request.Params[typeName] != null) {
return TreeListDemoHelper.ExportTypes[typeName].Method(
TreeListDemoHelper.CreateExportTreeListSettings(options),
DepartmentsProvider.GetDepartments()
);
}
}
return DemoView("Export", DepartmentsProvider.GetDepartments());
}
public ActionResult ExportPartial() {
return PartialView("ExportPartial", DepartmentsProvider.GetDepartments());
}
}
}
|
using System;
using Xunit;
namespace EmailChecker_Test
{
public class UnitTest1
{
[Fact]
public void Test1()
{
string mailaddress = "irgendwas@web.de";
bool result = Program.IsEmailAdress(mailaddress);
Assert.True(result, "Expected " + mailaddress + " to be a valid email address.");
}
[Fact]
public void Test2()
{
string mailaddress = "@web.de";
bool result = Program.IsEmailAdress(mailaddress);
Assert.False(result, "Expected " + mailaddress + " to be an invalid email address.");
}
[Fact]
public void Test3()
{
string mailaddress = "test@eins.zwei.de";
bool result = Program.IsEmailAdress(mailaddress);
Assert.True(result, "Expected " + mailaddress + " to be a valid email address.");
}
[Fact]
public void Test4()
{
string mailaddress = "a.b@eins.zwei.de";
bool result = Program.IsEmailAdress(mailaddress);
Assert.True(result, "Expected " + mailaddress + " to be a valid email address.");
}
[Fact]
public void Test5()
{
string mailaddress = "a@.";
bool result = Program.IsEmailAdress(mailaddress);
Assert.False(result, "Expected " + mailaddress + " to be an invalid email address.");
}
}
}
|
using LoowooTech.Stock.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LoowooTech.Stock.Rules
{
public class SplinterRule:IRule
{
public string RuleName { get { return "面层是否存在不符合上图要求的碎片多边形"; } }
public string ID { get { return "4201"; } }
public bool Space { get { return false; } }
public void Check()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TCPClient
{
class Client
{
public TcpClient client = new TcpClient();
public string name;
public string status = "off";
static void Main(string[] args)
{
Form menu = new StartUI();
menu.ShowDialog();
}
public bool connectAtemp()
{
try
{
client.Connect("127.0.0.1", 8888);
}
catch (Exception e)
{
return false;
}
return true;
}
public string whatAmI = "";
public void main()
{
status = "waiting";
try
{
client.ReceiveBufferSize = 256;
string sReceive = "";
sReceive = receive();
//waiting
while (true)
{
sReceive = this.receive();
whatAmI = sReceive;
if (status != "matched")
{
//send("ok");
}
else break;
if (this.whatAmI == "Black"||this.whatAmI=="White")
{
Console.WriteLine("gamemodel " + whatAmI + "_");
status = "matched";
break;
}
}
}
catch (Exception e)
{
status = "off";
}
}
public void createStartScreen()
{
Form a = new ChessUI(client.GetStream(), whatAmI);
a.ShowDialog();
}
public string receive()
{
NetworkStream stream = client.GetStream();
string result= "";
byte[] buffer = new byte[client.ReceiveBufferSize];
stream.Read(buffer, 0, buffer.Length);
result = Encoding.ASCII.GetString(buffer);
//
for (int i = 0; i < result.Length; i++)
{
if (result[i] == '.')
{
result = result.Substring(0, i);
}
}
return result;
}
public void send(string message)
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
buffer = Encoding.ASCII.GetBytes(message);
stream.Write(buffer, 0, buffer.Length);
stream.Flush();
}
}
} |
using AsNum.XFControls.Behaviors;
using AsNum.XFControls.Binders;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using Xamarin.Forms;
namespace AsNum.XFControls {
/// <summary>
///
/// </summary>
[System.Obsolete("请使用 TabView 替换")]
public class TabbedView : ContentView {
#region itemsSource 数据源
public static readonly BindableProperty ItemsSourceProperty =
BindableProperty.Create("ItemsSource",
typeof(IEnumerable<ISelectable>),
typeof(TabbedView),
Enumerable.Empty<ISelectable>(),//保证 ItemsSource 不为NULL
propertyChanged: ItemsSourceChanged);
public IEnumerable<ISelectable> ItemsSource {
get {
return (IEnumerable<ISelectable>)this.GetValue(ItemsSourceProperty);
}
set {
if (value != null) {
//保证数据源中,没有 null
var source = value.Cast<object>().Where(s => s != null);
this.SetValue(ItemsSourceProperty, source);
} else {
//保证数据源不为 NULL
SetValue(ItemsSourceProperty, Enumerable.Empty<object>());
}
}
}
private static void ItemsSourceChanged(BindableObject bindable, object oldValue, object newValue) {
var tv = (TabbedView)bindable;
tv.UpdateTabs();
tv.UpdateChildren();
if (newValue is INotifyCollectionChanged) {
var newCollection = (INotifyCollectionChanged)newValue;
tv.InitCollection(newCollection);
}
}
#endregion
#region TabContainerTemplate
public static readonly BindableProperty TabContainerTemplateProperty =
BindableProperty.Create("TabContainerTemplate",
typeof(ControlTemplate),
typeof(TabbedView),
null,
BindingMode.Default,
propertyChanged: TabContainerChanged);
public ControlTemplate TabContainerTemplate {
get {
return (ControlTemplate)this.GetValue(TabContainerTemplateProperty);
}
set {
this.SetValue(TabContainerTemplateProperty, value);
}
}
private static void TabContainerChanged(BindableObject bindable, object oldValue, object newValue) {
var tv = (TabbedView)bindable;
tv.TabContainer.ControlTemplate = (ControlTemplate)newValue;
}
#endregion
#region TabTemplate 标签模板
public static readonly BindableProperty TabTemplateProperty =
BindableProperty.Create("TabTemplate",
typeof(DataTemplate),
typeof(TabbedView),
null,
propertyChanged: TabTemplateChanged);
public DataTemplate TabTemplate {
get {
return (DataTemplate)GetValue(TabTemplateProperty);
}
set {
SetValue(TabTemplateProperty, value);
}
}
private static void TabTemplateChanged(BindableObject bindable, object oldValue, object newValue) {
var tv = (TabbedView)bindable;
tv.UpdateTabs();
}
#endregion
#region ItemTemplate 数据模板
public static readonly BindableProperty ItemTemplateProperty =
BindableProperty.Create("ItemTemplate",
typeof(DataTemplate),
typeof(TabbedView),
null);
public DataTemplate ItemTemplate {
get {
return (DataTemplate)GetValue(ItemTemplateProperty);
}
set {
SetValue(ItemTemplateProperty, value);
}
}
#endregion
#region itemTemplateSelector 模板选择器
public static readonly BindableProperty ItemTemplateSelectorProperty =
BindableProperty.Create("ItemTemplateSelector",
typeof(DataTemplateSelector),
typeof(TabbedView),
null);
public DataTemplateSelector ItemTemplateSelector {
get {
return (DataTemplateSelector)GetValue(ItemTemplateSelectorProperty);
}
set {
SetValue(ItemTemplateSelectorProperty, value);
}
}
#endregion
#region TabTemplateSelector 标签模板选择器
public static readonly BindableProperty TabTemplateSelectorProperty =
BindableProperty.Create("TabTemplateSelector",
typeof(DataTemplateSelector),
typeof(TabbedView),
null);
public DataTemplateSelector TabTemplateSelector {
get {
return (DataTemplateSelector)GetValue(TabTemplateSelectorProperty);
}
set {
SetValue(TabTemplateSelectorProperty, value);
}
}
#endregion
#region selectedItem 选中的数据
public static readonly BindableProperty SelectedItemProperty =
BindableProperty.Create("SelectedItem",
typeof(ISelectable),
typeof(TabbedView),
null,
BindingMode.TwoWay,
propertyChanged: SelectedItemChanged);
public ISelectable SelectedItem {
get {
return (ISelectable)GetValue(SelectedItemProperty);
}
set {
SetValue(SelectedItemProperty, value);
}
}
private static void SelectedItemChanged(BindableObject bindable, object oldValue, object newValue) {
var tv = (TabbedView)bindable;
var flag = true;
if (oldValue == null) {
//重新进入的时候,oldValue 为 null, 但是 itemsSource 中有 IsSelected 为 true 的
// Bug ??
var restoreSelected = tv.ItemsSource.FirstOrDefault(t => t.IsSelected);
if (restoreSelected != null) {
flag = false;
restoreSelected.IsSelected = true;
restoreSelected.NotifyOfPropertyChange("IsSelected");
if (newValue != null && !restoreSelected.Equals(newValue)) {
((ISelectable)newValue).IsSelected = false;
((ISelectable)newValue).NotifyOfPropertyChange("IsSelected");
//更新选中项,必须
tv.SelectedItem = restoreSelected;
}
}
}
if (flag) {
if (oldValue != null) {
((ISelectable)oldValue).IsSelected = false;
((ISelectable)oldValue).NotifyOfPropertyChange("IsSelected");
}
if (newValue != null) {
((ISelectable)newValue).IsSelected = true;
((ISelectable)newValue).NotifyOfPropertyChange("IsSelected");
}
}
}
#endregion
#region tabPosition 标签位置
public static readonly BindableProperty TabPositionProperty =
BindableProperty.Create("TabPosition",
typeof(TabPositions),
typeof(TabbedView),
TabPositions.Top,
propertyChanged: TabPositionChanged);
public TabPositions TabPosition {
get {
return (TabPositions)(this.GetValue(TabPositionProperty));
}
set {
this.SetValue(TabPositionProperty, value);
}
}
private static void TabPositionChanged(BindableObject bindable, object oldValue, object newValue) {
var tv = (TabbedView)bindable;
tv.UpdateTabPosition();
}
#endregion
/// <summary>
/// 子视图容器
/// </summary>
private Grid ChildrenContainer = null;
private ContentView TabContainer = null;
/// <summary>
/// 标签容器的父容器
/// </summary>
private ScrollView TabScroller = null;
/// <summary>
/// 内层标签容器
/// </summary>
private StackLayout TabInnerContainer = null;
/// <summary>
/// 选中命令
/// </summary>
private Command SelectedCmd = null;
public TabbedView() {
this.SelectedCmd = new Command(o => {
var model = (ISelectable)o;
this.SelectedItem = model;
if (model != null && model.SelectedCommand != null)
model.SelectedCommand.Execute(null);
});
this.PrepareLayout();
}
/// <summary>
/// 布局
/// </summary>
private void PrepareLayout() {
#region
var grid = new Grid();
this.Content = grid;
grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
grid.RowDefinitions.Add(new RowDefinition());
grid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
grid.ColumnDefinitions.Add(new ColumnDefinition());
grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
this.ChildrenContainer = new Grid();
grid.Children.Add(this.ChildrenContainer);
this.TabContainer = new ContentView();
grid.Children.Add(this.TabContainer);
this.TabScroller = new ScrollView();
this.TabContainer.Content = this.TabScroller;
this.TabInnerContainer = new StackLayout() {
Spacing = 0
};
this.TabScroller.Content = this.TabInnerContainer;
this.UpdateTabPosition();
this.UpdateChildrenPosition();
#endregion
}
/// <summary>
/// 更新标签位置
/// </summary>
private void UpdateTabPosition() {
int row = 0, col = 0, colSpan = 1, rowSpan = 1;
ScrollOrientation orientation = ScrollOrientation.Horizontal;
StackOrientation orientation2 = StackOrientation.Horizontal;
switch (this.TabPosition) {
case TabPositions.Top:
row = 0;
col = 0;
colSpan = 3;
rowSpan = 1;
orientation = ScrollOrientation.Horizontal;
orientation2 = StackOrientation.Horizontal;
break;
case TabPositions.Bottom:
row = 2;
col = 0;
colSpan = 3;
rowSpan = 1;
orientation = ScrollOrientation.Horizontal;
orientation2 = StackOrientation.Horizontal;
break;
case TabPositions.Left:
row = 0;
col = 0;
rowSpan = 3;
colSpan = 1;
orientation = ScrollOrientation.Vertical;
orientation2 = StackOrientation.Vertical;
break;
case TabPositions.Right:
row = 0;
col = 2;
rowSpan = 3;
colSpan = 1;
orientation = ScrollOrientation.Vertical;
orientation2 = StackOrientation.Vertical;
break;
}
this.TabScroller.Orientation = orientation;
this.TabScroller.HorizontalOptions = LayoutOptions.Fill;
this.TabScroller.VerticalOptions = LayoutOptions.Fill;
this.TabInnerContainer.Orientation = orientation2;
if (this.TabInnerContainer.Orientation == StackOrientation.Horizontal) {
this.TabInnerContainer.HorizontalOptions = LayoutOptions.Center;
this.TabInnerContainer.VerticalOptions = LayoutOptions.Center;
} else {
this.TabInnerContainer.HorizontalOptions = LayoutOptions.Center;
this.TabInnerContainer.VerticalOptions = LayoutOptions.Start;
}
Grid.SetRow(this.TabContainer, row);
Grid.SetColumn(this.TabContainer, col);
Grid.SetRowSpan(this.TabContainer, rowSpan);
Grid.SetColumnSpan(this.TabContainer, colSpan);
}
/// <summary>
/// 更新主体位置
/// </summary>
private void UpdateChildrenPosition() {
int row = 0, col = 0, colSpan = 0, rowSpan = 0;
switch (this.TabPosition) {
case TabPositions.Top:
row = 1;
col = 0;
colSpan = 3;
rowSpan = 2;
break;
case TabPositions.Bottom:
row = 0;
col = 0;
colSpan = 3;
rowSpan = 2;
break;
case TabPositions.Left:
row = 0;
col = 1;
rowSpan = 3;
colSpan = 2;
break;
case TabPositions.Right:
row = 0;
col = 0;
rowSpan = 3;
colSpan = 2;
break;
}
Grid.SetRow(this.ChildrenContainer, row);
Grid.SetColumn(this.ChildrenContainer, col);
Grid.SetRowSpan(this.ChildrenContainer, rowSpan);
Grid.SetColumnSpan(this.ChildrenContainer, colSpan);
}
public enum TabPositions {
Top,
Bottom,
Left,
Right
}
/// <summary>
///
/// </summary>
/// <param name="collection"></param>
private void InitCollection(INotifyCollectionChanged collection) {
if (collection != null)
collection.CollectionChanged += Collection_CollectionChanged;
}
private void Collection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
switch (e.Action) {
case NotifyCollectionChangedAction.Add:
this.InsertChildren(e.NewItems, e.NewStartingIndex);
break;
case NotifyCollectionChangedAction.Remove:
this.RemoveChildren(e.OldItems, e.OldStartingIndex);
break;
case NotifyCollectionChangedAction.Move:
Debugger.Break();
break;
case NotifyCollectionChangedAction.Replace:
Debugger.Break();
break;
case NotifyCollectionChangedAction.Reset:
this.UpdateTabs();
this.UpdateChildren();
break;
}
}
/// <summary>
/// 更新子元素
/// </summary>
private void UpdateChildren() {
this.ChildrenContainer.Children.Clear();
var source = this.ItemsSource.Cast<object>();
foreach (var d in source) {
View view = this.GetChildView(d);
this.ChildrenContainer.Children.Add(view);
}
if (this.SelectedItem == null) {
this.SelectedCmd.Execute(source.FirstOrDefault());
}
}
/// <summary>
/// 更新标签
/// </summary>
private void UpdateTabs() {
this.TabInnerContainer.Children.Clear();
foreach (var d in this.ItemsSource) {
View tabView = this.GetTabView(d);
this.TabInnerContainer.Children.Add(tabView);
}
}
/// <summary>
/// 数据源更新(插入)
/// </summary>
/// <param name="datas"></param>
/// <param name="startIdx"></param>
private void InsertChildren(IEnumerable datas, int startIdx = 0) {
if (datas == null)
return;
foreach (var d in datas) {
var view = this.GetChildView(d);
var tabView = this.GetTabView(d);
this.ChildrenContainer.Children.Insert(startIdx, view);
this.TabInnerContainer.Children.Insert(startIdx, tabView);
startIdx++;
}
}
/// <summary>
/// 数据源更新(删除)
/// </summary>
/// <param name="datas"></param>
/// <param name="startIdx"></param>
private void RemoveChildren(IList datas, int startIdx) {
if (datas == null)
return;
foreach (var d in datas) {
this.ChildrenContainer.Children.RemoveAt(startIdx);
this.TabInnerContainer.Children.RemoveAt(startIdx);
startIdx++;
}
}
/// <summary>
/// 从模板/模板选择器创建子视图
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private View GetChildView(object data) {
View view = null;
if (this.ItemTemplate != null || this.ItemTemplateSelector != null) {
if (this.ItemTemplateSelector != null)
view = (View)this.ItemTemplateSelector.SelectTemplate(data, null).CreateContent();
else if (this.ItemTemplate != null)
view = (View)this.ItemTemplate.CreateContent();
if (view != null) {
view.BindingContext = data;
}
}
if (view == null)
view = new Label() { Text = "111" };
//this.ChildrenContainer.Children.Add(view);
this.SetFade(view, data);
return view;
}
/// <summary>
/// 设置淡入淡出
/// </summary>
/// <param name="view"></param>
/// <param name="data"></param>
private void SetFade(View view, object data) {
var behavior = new FadeBehavior();
behavior.SetBinding(FadeBehavior.IsSelectedProperty, "IsSelected", BindingMode.TwoWay);
view.Behaviors.Add(behavior);
}
/// <summary>
/// 从模板/模板选择器创建标签
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private View GetTabView(object data) {
View view = null;
if (this.TabTemplate != null || this.TabTemplateSelector != null) {
//优先使用 TemplateSelector
if (this.TabTemplateSelector != null) {
// SelectTemplate 的第二个参数,即 TemplateSelector 的 OnSelectTemplate 方法的 container 参数
view = (View)this.TabTemplateSelector.SelectTemplate(data, this).CreateContent();
} else if (this.TabTemplate != null)
view = (View)this.TabTemplate.CreateContent();
if (view != null) {
//上下文
view.BindingContext = data;
}
}
if (view == null)
view = new Label() { Text = "Tab" };
TapBinder.SetCmd(view, this.SelectedCmd);
TapBinder.SetParam(view, data);
return view;
}
}
}
|
using System;
using Net01_1.Model;
namespace Net01_1.Extensions
{
public static class BaseEntityGuidExtention
{
public static void CreateEntityGuid(this BaseEntity entity)
{
entity.Id = Guid.NewGuid();
}
}
}
|
using System;
namespace AdventCode4
{
class Program
{
static void Main(string[] args)
{
int lower = 153517;
int upper = 630395;
int count = 0;
for(int x = lower;x<= upper; x++)
{
if (DupCheck(x.ToString()) && IncCheck(x.ToString()))
count++;
}
Console.WriteLine(count);
//Console.WriteLine(DupCheck("111111"));
//Console.WriteLine(IncCheck("111111"));
//Console.WriteLine(DupCheck("223450"));
//Console.WriteLine(IncCheck("223450"));
//Console.WriteLine(DupCheck("123789"));
//Console.WriteLine(IncCheck("123789"));
}
public static bool DupCheck(string x)
{
int[] counts = new int[10];
foreach (char z in x)
{
counts[Int32.Parse(z.ToString())] += 1;
}
foreach(int z in counts)
{
if (z == 2)
return true;
}
return false;
}
public static bool IncCheck(string x)
{
int y = x[0];
foreach(int z in x.Substring(1))
{
if (z < y)
return false;
y = z;
}
return true;
}
}
}
|
using System;
using System.Collections.Generic;
public class QuickUnionUF
{
private List<int> id = new List<int>();
private List<int> sz = new List<int>();
public QuickUnionUF(int N)
{
for (int i = 0; i < N; ++i)
{
id[i] = i;
sz[i] = 1;
}
}
public int Root(int i)
{
while (id[i] != i)
{
++i;
}
return id[i];
}
public bool Connected(int i, int j)
{
return Root(i) == Root(j);
}
public bool Union(int p, int q)
{
int i = Root(p);
int j = Root(q);
if (i == j) return false;
if (sz[p] > sz[q])
{
id[j] = id[i];
sz[p] += sz[q];
}
else
{
id[i] = id[j];
sz[q] += sz[p];
}
return true;
}
public void DoRandomConnections()
{
Random rnd = new Random();
while (true)
{
//int p = rnd.Next(0, );
}
}
}
|
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;
using Kingdee.CAPP.BLL;
using Kingdee.CAPP.Model;
namespace Kingdee.CAPP.UI.ProcessDataManagement
{
/// <summary>
/// 类型说明:典型工艺分类界面
/// 作 者:jason.tang
/// 完成时间:2013-07-23
/// </summary>
public partial class TypicalCategoryFrm : BaseSkinForm
{
#region 属性
public string ProcessCardId { get; set; }
public string ProcessCardName { get; set; }
public Dictionary<string,string> ProcessCardIds { get; set; }
#endregion
#region 变量
private DataTable dt = null;
#endregion
#region 构造函数
public TypicalCategoryFrm()
{
InitializeComponent();
}
#endregion
#region 窗体控件事件
private void txtName_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
e.SuppressKeyPress = true;
}
}
private void btnSearch_Click(object sender, EventArgs e)
{
DataRow[] rows = dt.Select(string.Format("Type = 4 And Name like '%{0}%'", txtName.Text));
DataTable table = dt.Clone();
foreach (DataRow dr in rows)
{
DataRow row = table.NewRow();
row = dr;
table.Rows.Add(row.ItemArray);
}
dgvTypicalCategory.DataSource = table;
}
private void TypicalCategoryFrm_Load(object sender, EventArgs e)
{
dgvTypicalCategory.AutoGenerateColumns = false;
GetTypicalCategory();
if (!string.IsNullOrEmpty(ProcessCardName))
txtName.Text = ProcessCardName;
else if (dgvTypicalCategory.Rows.Count > 0)
{
if (dgvTypicalCategory.Rows[0].Cells["colName"] != null &&
dgvTypicalCategory.Rows[0].Cells["colName"].Value != null &&
!string.IsNullOrEmpty(dgvTypicalCategory.Rows[0].Cells["colName"].Value.ToString()))
{
txtName.Text = dgvTypicalCategory.Rows[0].Cells["colName"].Value.ToString();
}
}
}
private void btnConfirm_Click(object sender, EventArgs e)
{
string name = string.Empty;
string parentNode = string.Empty;
foreach (DataGridViewRow row in dgvTypicalCategory.Rows)
{
if ((bool)row.Cells[0].EditedFormattedValue == true &&
row.Cells["colName"].Value != null)
{
name = row.Cells["colName"].Value.ToString();
parentNode = row.Cells["colCurrentNode"].Value.ToString();
break;
}
}
if(string.IsNullOrEmpty(name))
return;
try
{
if (ProcessCardIds != null && ProcessCardIds.Count > 0)
{
foreach (string key in ProcessCardIds.Keys)
{
Guid cardid = new Guid(key);
bool result = TypicalProcessBLL.ExistTypcialProcessCard(cardid, int.Parse(parentNode));
if (!result)
{
TypicalProcess typical = new TypicalProcess();
typical.Name = ProcessCardIds[key];
typical.CurrentNode = dt.Rows.Count + 1;
typical.BusinessId = cardid;
typical.BType = BusinessType.Card;
typical.ParentNode = int.Parse(parentNode);
TypicalProcessBLL.AddTypicalProcess(typical);
}
}
}
else
{
Guid cardid = new Guid(ProcessCardId);
bool result = TypicalProcessBLL.ExistTypcialProcessCard(cardid, int.Parse(parentNode));
if (!result)
{
TypicalProcess typical = new TypicalProcess();
typical.Name = ProcessCardName;
typical.CurrentNode = dt.Rows.Count + 1;
typical.BusinessId = cardid;
typical.BType = BusinessType.Card;
typical.ParentNode = int.Parse(parentNode);
TypicalProcessBLL.AddTypicalProcess(typical);
}
}
if (TypicalProcessFrm.typicalProcessForm != null)
{
TypicalProcessFrm.typicalProcessForm.ChangeToTypical();
}
MessageBox.Show("卡片转为典型成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
catch
{
MessageBox.Show("卡片转为典型失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void dgvTypicalCategory_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (e.ColumnIndex == 0 && dgv.Rows.Count > 0)
{
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dgv.Rows[e.RowIndex].Cells[e.ColumnIndex];
bool value = (bool)checkCell.Value;
foreach (DataGridViewRow row in dgv.Rows)
{
if (row.Index != e.RowIndex && value)
{
row.Cells[e.ColumnIndex].Value = false;
}
}
dgv.Invalidate();
}
}
private void dgvTypicalCategory_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.IsCurrentCellDirty)
{
dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dgvTypicalCategory_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dgvTypicalCategory.CurrentRow != null)
{
if (dgvTypicalCategory.CurrentRow.Cells["colName"] != null &&
dgvTypicalCategory.CurrentRow.Cells["colName"].Value != null &&
!string.IsNullOrEmpty(dgvTypicalCategory.CurrentRow.Cells["colName"].Value.ToString()))
{
txtName.Text = dgvTypicalCategory.CurrentRow.Cells["colName"].Value.ToString();
}
}
}
#endregion
#region 方法
private void GetTypicalCategory()
{
dt = TypicalProcessBLL.GetTypicalCategory(string.Empty);
DataRow[] rows = dt.Select("Type = 4 ");
DataTable table = dt.Clone();
foreach (DataRow dr in rows)
{
DataRow row = table.NewRow();
row = dr;
table.Rows.Add(row.ItemArray);
}
dgvTypicalCategory.DataSource = table;
}
#endregion
}
}
|
using System;
using com.Sconit.Entity.SYS;
using System.ComponentModel.DataAnnotations;
//TODO: Add other using statements here
namespace com.Sconit.Entity.MRP.MD
{
public partial class ProductType
{
#region Non O/R Mapping Properties
[CodeDetailDescriptionAttribute(CodeMaster = com.Sconit.CodeMaster.CodeMaster.ScheduleType, ValueField = "SubType")]
[Display(Name = "OrderMaster_SubType", ResourceType = typeof(Resources.ORD.OrderMaster))]
public string OrderSubTypeDescription { get; set; }
public string CodeDescription
{
get
{
if (string.IsNullOrWhiteSpace(this.Description))
{
return this.Code;
}
else
{
return this.Code + " [" + this.Description + "]";
}
}
}
public double IslandQty { get; set; }
public string IslandDescription { get; set; }
#endregion
}
} |
using System;
using System.Collections.ObjectModel;
using MVVM_WPF_HelloWorld.DataAccess;
using System.Windows.Input;
using System.Windows.Media;
namespace MVVM_WPF_HelloWorld.ViewModel
{
public class EmployeeListViewModel : ViewModelBase
{
readonly EmployeeRepository _employeeRepository;
RelayCommand _invasionCommand;
private Brush _bgBrush;
public Brush BackgroundBrush
{
get
{
return _bgBrush;
}
set
{
_bgBrush = value;
OnPropertyChaged("BackgroundBrush");
}
}
public ObservableCollection<Model.Employee> AllEmployees
{
get;
private set;
}
public EmployeeListViewModel(EmployeeRepository employeeRepository)
{
if (employeeRepository == null)
{
throw new ArgumentNullException("employeeRepository");
}
_employeeRepository = employeeRepository;
this.AllEmployees = new ObservableCollection<Model.Employee>(_employeeRepository.GetEmployees());
}
protected override void OnDispose()
{
this.AllEmployees.Clear();
}
public ICommand InvasionCommand
{
get
{
if(_invasionCommand == null)
{
_invasionCommand = new RelayCommand(param => this.InvasionCommandExecute(), param => this.InvasionCommandCanExecute);
}
return _invasionCommand;
}
}
public bool InvasionCommandCanExecute {
get
{
if (this.AllEmployees.Count == 0)
{
return false;
}
else
return true;
}
}
private void InvasionCommandExecute()
{
bool isinvasion = true;
foreach(Model.Employee emp in this.AllEmployees)
if (emp.LastName.Trim().ToLower() != "smith")
{
isinvasion = false;
}
if (isinvasion)
{
BackgroundBrush = new SolidColorBrush(Colors.Green);
}
else
BackgroundBrush = new SolidColorBrush(Colors.White);
}
}
}
|
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using System;
using System.Collections.Generic;
using System.Text;
namespace PiwoBack.Services.Services
{
public class PictureService
{
public static int Save(string srcPath, string destPath)
{
int savedImage = 0;
using (Image<Rgba32> image = Image.Load(srcPath))
{
image.Save(destPath);
savedImage = 1;
}
return savedImage;
}
}
}
|
using System;
namespace Equal_Sums_Even_Odd_Position
{
class Program
{
static void Main(string[] args)
{
int firstInterval = int.Parse(Console.ReadLine());
int secondInterval = int.Parse(Console.ReadLine());
for (int number = firstInterval; number <= secondInterval; number++)
{
int firstDigit = number % 10;
int secondDigit = number / 10 % 10;
int thirdDigit = number / 100 % 10;
int fourthDigit = number / 1000 % 10;
int fifthDigit = number / 10000 % 10;
int sumLeft = firstDigit + secondDigit;
int sumRight = fourthDigit + fifthDigit;
if (sumLeft == sumRight)
{
Console.Write(number + " ");
}
else
{
if (sumRight > sumLeft)
{
sumLeft = sumLeft + thirdDigit;
if (sumLeft == sumRight)
{
Console.Write(number + " ");
}
}
else
{
sumRight = sumRight + thirdDigit;
if (sumLeft == sumRight)
{
Console.Write(number + " ");
}
}
}
}
}
}
}
|
using gView.Framework.Data;
using gView.Framework.Data.Cursors;
using gView.Framework.Geometry;
using System.Text;
using System.Threading.Tasks;
using gView.Framework.Extensions;
using gView.Framework.OGC.Extensions;
namespace gView.Framework.OGC.GML
{
public class FeatureTranslator
{
#region Feature To GML
public static void Feature2GML(IFeature feature, IFeatureClass fc, string fcID, StringBuilder sb, string srsName, IGeometricTransformer transformer, GmlVersion version)
{
if (feature == null || fc == null)
{
return;
}
sb.Append(@"
<gml:featureMember>
<gv:" + fcID + " gml:id=\"" + fcID + "." + feature.OID + "\">");
// Shape
IGeometry shape = (transformer != null) ? transformer.Transform2D(feature.Shape) as IGeometry : feature.Shape;
if (shape != null)
{
sb.Append(@"
<gml:boundedBy>");
sb.Append(GeometryTranslator.Geometry2GML(shape.Envelope, srsName, version));
sb.Append(@"
</gml:boundedBy>");
sb.Append(@"
<gv:" + fc.ShapeFieldName.Replace("#", "") + ">");
sb.Append(GeometryTranslator.Geometry2GML(shape, srsName, version));
sb.Append(@"
</gv:" + fc.ShapeFieldName.Replace("#", "") + ">");
}
// Fields
foreach (FieldValue fv in feature.Fields)
{
if (fv.Name == fc.ShapeFieldName)
{
continue;
}
sb.Append(@"
<gv:" + fv.Name.ToValidXmlTag() + ">" + fv.Value?.ToString().XmlEncoded() + "</gv:" + fv.Name.ToValidXmlTag() + ">");
}
sb.Append(@"
</gv:" + fcID + @">
</gml:featureMember>");
}
async public static Task Features2GML(IFeatureCursor cursor, IFeatureClass fc, string fcID, StringBuilder sb, string srsName, IGeometricTransformer transformer, GmlVersion version)
{
await Features2GML(cursor, fc, fcID, sb, srsName, transformer, version, -1);
}
async public static Task Features2GML(IFeatureCursor cursor, IFeatureClass fc, string fcID, StringBuilder sb, string srsName, IGeometricTransformer transformer, GmlVersion version, int maxFeatures)
{
if (cursor == null || fc == null)
{
return;
}
int count = 0;
IFeature feature = null;
while ((feature = await cursor.NextFeature()) != null)
{
Feature2GML(feature, fc, fcID, sb, srsName, transformer, version);
count++;
if (maxFeatures > 0 && count > maxFeatures)
{
break;
}
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Model.ViewModel
{
public class QAGroupLineLineViewModel
{
public int QAGroupLineId { get; set; }
public int? JobReceiveQAAttributeId { get; set; }
public int QAGroupId { get; set; }
public string Name { get; set; }
public bool IsMandatory { get; set; }
public string DataType { get; set; }
public string ListItem { get; set; }
public string DefaultValue { get; set; }
public string Value { get; set; }
public string Remarks { get; set; }
public bool IsActive { get; set; }
public string CreatedBy { get; set; }
public string ModifiedBy { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
public string OMSId { get; set; }
}
}
|
using mec.Database.Presentees;
using mec.Model;
using mec.Model.Apps;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Filters;
namespace mec.Cleint.Portal.Controllers
{
public class SystemController : ApiController
{
private SystemPresenter presenter;
public SystemPresenter Presenter
{
get
{
if (this.presenter == null)
{
this.presenter = new SystemPresenter();
}
return this.presenter;
}
}
public SystemController()
{
}
[HttpPost]
public HttpResponseMessage GetUsers(BaseParam param)
{
//this.Presenter = new SystemPresenter();
var vms = this.Presenter.GetUsers(param);
if (vms != null)
{
return Request.CreateResponse(HttpStatusCode.OK, vms);
}
return Request.CreateErrorResponse(HttpStatusCode.NotModified, "讀取 User 錯誤!!");
}
[HttpPost]
public HttpResponseMessage GetUser(UserParam param)
{
//SystemPresenter p = new SystemPresenter();
var vm = this.Presenter.GetUser(param);
if (vm != null)
{
return Request.CreateResponse(HttpStatusCode.OK, vm);
}
return Request.CreateErrorResponse(HttpStatusCode.NotModified, "讀取 User 錯誤!!");
}
[HttpPost]
public HttpResponseMessage GetMenus(UserParam param)
{
var vms = this.Presenter.GetMenus(param);
if (vms != null)
{
return Request.CreateResponse(HttpStatusCode.OK, vms);
}
return Request.CreateErrorResponse(HttpStatusCode.NotModified, "讀取 User 錯誤!!");
}
[HttpGet]
[BasicAuthorization]
public HttpResponseMessage Get()
{
return Request.CreateResponse(HttpStatusCode.OK, "dannis");
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class BasicAuthorization : AuthorizationFilterAttribute
{
private const string _authorizedToken = "AuthorizedToken";
private const string _userAgent = "User-Agent";
//private UserAuthorizations objAuth = null;
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext filterContext)
{
string authorizedToken = string.Empty;
string userAgent = string.Empty;
try
{
var headerToken = filterContext.Request.Headers.SingleOrDefault(x => x.Key == _authorizedToken);
if (headerToken.Key != null)
{
authorizedToken = Convert.ToString(headerToken.Value.SingleOrDefault());
userAgent = Convert.ToString(filterContext.Request.Headers.UserAgent);
if (IsAuthorize(authorizedToken, userAgent) == false)
{
filterContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
return;
}
}
else
{
filterContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
return;
}
}
catch (Exception)
{
filterContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
return;
}
base.OnAuthorization(filterContext);
}
private bool IsAuthorize(string authorizedToken, string userAgent)
{
return true;
/*
objAuth = new UserAuthorizations();
bool result = false;
try
{
result = objAuth.ValidateToken(authorizedToken, userAgent);
}
catch (Exception)
{
result = false;
}
return result;
*/
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class End : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = Session["MSG"].ToString();
}
protected void Button1_Click1(object sender, EventArgs e)
{
if(Session["ADMIN"]==null || Session["ADMIN"].ToString().Length<1)
{
Response.Redirect("Default.aspx");
}
else
{
Response.Redirect("AdminHome.aspx");
}
}
} |
using UnityEngine;
using System.Collections;
public class LightGem : MonoBehaviour {
//variable declaration
protected RaycastHit hitInfo;
public float f_RayLength;
protected bool b_IsOn;
public GameObject lightObject;
public GameObject sunGem;
private PlayerStates player;
// Use this for initialization
void Start () {
f_RayLength = 5.0f;
player = GameObject.FindWithTag("Player").GetComponent<PlayerStates>();
b_IsOn = false;
}
// Update is called once per frame
void Update () {
if(player.getSunGem() == true) {
sunGem.renderer.enabled = true;
b_IsOn = true;
//sunLight.light.enabled = true;
Debug.DrawRay (transform.position, Camera.mainCamera.transform.TransformDirection(Vector3.forward) * f_RayLength);
//If Object collides with other object that is lightObject, send message
if(Physics.Raycast(transform.position, Camera.mainCamera.transform.TransformDirection(Vector3.forward), out hitInfo, f_RayLength)) {
if(hitInfo.collider.gameObject.tag == "LightObject") {
//send a message to switch states
lightObject = hitInfo.collider.gameObject;
lightObject.SendMessage("ActivateLight");
}// End IF block
} // End Raycast
}// End of player.getSunGem() == true block
else if(player.getSunGem() == false) {
sunGem.renderer.enabled = false;
}//end of Player.getSunGem() condition
}// End Update
public bool GetIsOn() {return b_IsOn;}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleDestroy : MonoBehaviour {
private void OnTriggerEnter2D(Collider2D collision)
{
//Debug.Log(collision.collider.name);
if (collision.tag == "Player" || collision.tag == "Projectile")
{
//if (collision.gameObject.GetComponent<Player>().MyLastState == Player.State.Attacking)
//{
Debug.Log(collision.name);
Destroy(gameObject);
//}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ClientApp
{
public partial class ClientForm : Form
{
SynchronousSocketClient ssc = new SynchronousSocketClient();
public ClientForm()
{
InitializeComponent();
}
/// <summary>
/// nothing, but he didnt delete it in the video so I didnt either.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ClientForm_Load(object sender, EventArgs e)
{
//he cut out the code that was here and placed it at the top of the class
}
/// <summary>
/// establishes stream and sends the users input to the server
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void BtnSubmit_Click(object sender, EventArgs e)
{
TxtBoxResponse.Text = ssc.ContactServer(TxtBoxRequest.Text);
}
}
}
|
using Xunit;
namespace DotNetCross.Memory.Tests
{
public class Unsafe_AsPointer_Test
{
[Fact]
public unsafe void Int()
{
var ptr = stackalloc int[1];
*ptr = 42;
var actualPtr = Unsafe.AsPointer<int>(ref *ptr);
Assert.True(ptr == actualPtr);
}
[Fact]
public unsafe void Double()
{
var ptr = stackalloc double[1];
*ptr = 42;
var actualPtr = Unsafe.AsPointer<double>(ref *ptr);
Assert.True(ptr == actualPtr);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;
using System.Web;
using WebApplication11.Models;
using Microsoft.Ajax.Utilities;
using System.Web.Script.Serialization;
namespace WebApplication11.Controllers
{
public class sm9Controller : ApiController
{
SM9_MANTISEntities sm = new SM9_MANTISEntities();
public IHttpActionResult Getsm9()
{
var results = sm.SM9.ToList(); //.Take(3000)
return Ok(results);
}
[HttpPost]
public IHttpActionResult sm9Insert(SM9 sm9Insert)
{
sm.SM9.Add(sm9Insert);
sm.SaveChanges();
return Ok();
}
//get by id
[HttpGet]
public IHttpActionResult sm9GetId(int id)
{
sm9Class sm9Details = null;
sm9Details = sm.SM9.Where(x => x.Id == id).Select(x => new sm9Class()
{
Id = x.Id,
Responsable = x.Responsable,
Date_Heure_d_ouverture = x.Date_Heure_d_ouverture,
Date_Heure_de_résolution = x.Date_Heure_de_résolution,
Date_Heure_de_clôture = x.Date_Heure_de_clôture,
ID_Incident = x.ID_Incident,
Priorité = x.Priorité,
État_de_l_alerte = x.État_de_l_alerte,
État = x.État,
CI_concerné = x.CI_concerné,
Service_concerné_principal = x.Service_concerné_principal,
Titre = x.Titre,
Application = x.Application,
Catégorie = x.Catégorie,
New_Cat = x.New_Cat,
Start_Date_Cal = x.Start_Date_Cal,
End_Date_Cal = x.End_Date_Cal,
week_in = x.week_in,
week_out = x.week_out,
year_in = x.year_in,
year_out = x.year_out,
Year___Week_in = x.Year___Week_in,
Year___Week_Out = x.Year___Week_Out,
P = x.P,
Slo = x.Slo,
Realisation = x.Realisation,
SLA = x.SLA,
SR = x.SR,
Best_effort = x.Best_effort,
M_D = x.M_D,
}).FirstOrDefault<sm9Class>();
if (sm9Details==null)
{
return NotFound();
}
return Ok(sm9Details);
}
//update
public IHttpActionResult put(sm9Class sc)
{
var updatesm9 = sm.SM9.Where(x => x.Id == sc.Id).FirstOrDefault<SM9>();
if(updatesm9!=null)
{
updatesm9.Id = sc.Id;
updatesm9.Responsable = sc.Responsable;
updatesm9.Date_Heure_d_ouverture = sc.Date_Heure_d_ouverture;
updatesm9.Date_Heure_de_résolution = sc.Date_Heure_de_résolution;
updatesm9.Date_Heure_de_clôture = sc.Date_Heure_de_clôture;
updatesm9.ID_Incident = sc.ID_Incident;
updatesm9.Priorité = sc.Priorité;
updatesm9.État_de_l_alerte = sc.État_de_l_alerte;
updatesm9.État = sc.État;
updatesm9.CI_concerné = sc.CI_concerné;
updatesm9.Service_concerné_principal = sc.Service_concerné_principal;
updatesm9.Titre = sc.Titre;
updatesm9.Application = sc.Application;
updatesm9.Catégorie = sc.Catégorie;
updatesm9.New_Cat = sc.New_Cat;
updatesm9.Start_Date_Cal = sc.Start_Date_Cal;
updatesm9.End_Date_Cal = sc.End_Date_Cal;
updatesm9.week_in = sc.week_in;
updatesm9.week_out = sc.week_out;
updatesm9.year_in = sc.year_in;
updatesm9.year_out = sc.year_out;
updatesm9.Year___Week_in = sc.Year___Week_in;
updatesm9.Year___Week_Out = sc.Year___Week_Out;
updatesm9.P = sc.P;
updatesm9.Slo = sc.Slo;
updatesm9.Realisation = sc.Realisation;
updatesm9.SLA = sc.SLA;
updatesm9.SR = sc.SR;
updatesm9.Best_effort = sc.Best_effort;
updatesm9.M_D = sc.M_D;
sm.SaveChanges();
}
else
{
return NotFound();
}
return Ok();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Clase3.Ejercicio3.ContadorPalabras
{
/// <summary>
/// Realizar un software que solicite al usuario que ingrese un párrafo por teclado y el software
/// cuente la cantidad de ocurrencias de cada palabra.Asimismo, deberá indicar la cantidad de
/// palabras distintas que existen en el párrafo ingresado por el usuario
/// </summary>
class Program
{
static void Main(string[] args)
{
Dictionary <string, int> diccionario = new Dictionary <string, int>();
int contador = 0;
Console.WriteLine("Ingrese un párrafo: ");
string[] parrafo = Console.ReadLine().Split(' ');
foreach (string palabra in parrafo)
{
foreach (string palabrarepetida in parrafo)
{
if (palabra.Equals(palabrarepetida))
{
contador++;
}
}
if (diccionario.Count == 0)
{
diccionario.Add(palabra, contador);
}
else
{
bool repetido = false;
for (int i = 0; i < diccionario.Count; i++)
{
if (diccionario.ElementAt(i).Key.Equals(palabra) && diccionario.ElementAt(i).Value.Equals(contador))
{
repetido = true;
break;
}
}
if (repetido == false)
{
diccionario.Add(palabra, contador);
}
}
contador = 0;
}
Console.WriteLine("Contenido del diccionario: ");
foreach (KeyValuePair<string, int> elemento in diccionario)
{
Console.WriteLine(elemento.Key + " " + elemento.Value);
contador++;
}
Console.WriteLine("Tamaño del diccionario: " + contador);
Console.WriteLine("Presione enter para salir . . ");
Console.Read();
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Soul", menuName = "Soul Hunter/Soul")]
public class SoulData : ScriptableObject // Mort
{
public Color color;
public int soulPower;
[SerializeField] GameObject particle;
public void SpawnParticle(Vector3 position)
{
GameObject p = Instantiate(particle, position, Quaternion.identity);
p.GetComponent<Rigidbody2D>().AddForce(new Vector2(Random.Range(-100, 100), 200));
p.GetComponent<Loot>().soulPower = soulPower;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace test {
public class EnemyController : MonoBehaviour
{
public static EnemyController instance;
public bool horizontal;
public float health = 20f;
public float healthMax = 20f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (horizontal)
{
transform.position = new Vector2(Mathf.Sin(GameController.instance.timeElapsed) * 6f, transform.position.y);
}
}
public void TakeDamage(float damageAmount)
{
health -= damageAmount;
if (health <= 0)
{
Die();
PlayerController.instance.EarnPoints(25);
}
}
void Die()
{
Destroy(gameObject);
}
}
}
|
using Unity;
using Unity.Extension;
using Unity.Lifetime;
namespace Motherload.Factories
{
/// <summary>
/// Classe que lida com o DI
/// </summary>
public static class DependencyInjector
{
/// <summary>
/// Unity Container
/// </summary>
private static readonly UnityContainer UnityContainer = new UnityContainer();
/// <summary>
/// Registra uma interface e classe juntas
/// </summary>
/// <typeparam name="I">Interface</typeparam>
/// <typeparam name="T">Classe</typeparam>
public static void Register<I, T>() where T : I
{
UnityContainer.RegisterType<I, T>(new ContainerControlledLifetimeManager());
}
/// <summary>
/// Registra uma intância de uma interface
/// </summary>
/// <typeparam name="I">Interface</typeparam>
/// <param name="instance">Instância</param>
public static void InjectStub<I>(I instance)
{
UnityContainer.RegisterInstance(instance, new ContainerControlledLifetimeManager());
}
/// <summary>
/// Retorna uma interface registrada pelo DI
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Retrieve<T>()
{
return UnityContainer.Resolve<T>();
}
/// <summary>
/// Adiciona uma extensão para executar o registro de um serviço sem necessáriamente chamar pelo
/// <see cref="Register{I, T}"/> diretamente.
/// </summary>
/// <typeparam name="T">Classe que herda <see cref="UnityContainerExtension"/></typeparam>
public static void AddExtension<T>() where T : UnityContainerExtension
{
UnityContainer.AddNewExtension<T>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ServiceLayer
{
public interface IValidationService
{
bool IsValidRequestInformationFormSubmission(
string name,
string emailAddress,
string phoneNumber,
string description);
}
}
|
using System.Collections.Generic;
using Properties.Core.Objects;
namespace Properties.Core.Interfaces
{
public interface IPropertyCheckService
{
List<PropertyCheck> GetChecksForProperty(string propertyReference);
PropertyCheck GetCheckForProperty(string propertyReference, string propertyCheckReference);
string CreateCheck(string propertyReference, PropertyCheck check);
bool UpdateCheck(string propertyReference, string propertyCheckReference, PropertyCheck check);
bool DeleteCheck(string propertyReference, string propertyCheckReference);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GatewayEDI.Logging;
namespace NLogFacade
{
/// <summary>
/// An implementation of the <see cref="ILogFactory"/> interface which creates <see cref="ILog"/> instances that use the NLog framework as the underlying logging mechanism.
/// </summary>
public class NLogLogFactory : ILogFactory
{
public ILog GetLog(string name)
{
return new NLogLog(NLog.LogManager.GetLogger(name));
}
}
}
|
using System;
namespace UKPR.Hermes.Models
{
public class AggregatedContract
{
public Guid ContractId { get; set; }
public decimal AverageValue { get; set; }
public DateTime WindowEndUtc { get; set; }
public string ClientContractId { get; set; }
public WindowType ServiceType { get; set; }
public override string ToString()
{
return $"{WindowEndUtc.ToString("o")} {ContractId} {ClientContractId} {AverageValue}";
}
}
}
|
using System;
// ReSharper disable once CheckNamespace
namespace Atc
{
/// <summary>
/// Enum Guid Attribute.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate)]
public sealed class EnumGuidAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="EnumGuidAttribute" /> class.
/// </summary>
/// <param name="value">The GUID.</param>
public EnumGuidAttribute(string value)
{
this.GlobalIdentifier = new Guid(value);
}
/// <summary>
/// Gets the global identifier.
/// </summary>
/// <value>
/// The global identifier.
/// </value>
public Guid GlobalIdentifier { get; }
}
} |
using System;
using System.Text;
using System.Collections;
namespace AgileVisions.IndexManager.DocumentManagement
{
/// <summary>
/// Created by Mayukh Dutta (mayukh_dutta@homail.com)
/// Date: 8/31/2006
/// </summary>
[Serializable]
public class Documents : CollectionBase
{
public void Add(Document document)
{
List.Add(document);
}
public void Remove(Document document)
{
List.Remove(document);
}
public Document this[int index]
{
get { return (Document) List[index];}
set { List[index] = value;}
}
}
/// <summary>
/// Created by Mayukh Dutta (mayukh_dutta@homail.com)
/// Date: 8/31/2006
/// </summary>
[Serializable]
public class Document
{
private string _name = string.Empty;
private string _filename = string.Empty;
private string _applicationdirectory = string.Empty;
private string _virtualdirectory = string.Empty;
private Hashtable _index;
public Document(){}
public void SetContent(string sContent){}
public Hashtable Index
{
get { return _index;}
set { _index = value;}
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public string FileName
{
get { return _filename; }
set { _filename = value; }
}
public string ApplicationDirectory
{
set {_applicationdirectory = value;}
get { return _applicationdirectory;}
}
public string VirtualDirectory
{
get { return _virtualdirectory;}
set { _virtualdirectory = value;}
}
}
}
|
using Microsoft.Xna.Framework;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewValley;
using System.Collections.Generic;
namespace MultiplayerEmotes.Framework {
/// <summary>
/// TEST - Animation trough sprite broadcast.
/// Issue: Sprite position does not change for other players.
/// </summary>
public class EmoteTemporaryAnimation {
private readonly IReflectionHelper Reflection;
List<TemporaryAnimatedSprite> temporaryAnimationList = new List<TemporaryAnimatedSprite>();
public EmoteTemporaryAnimation(IReflectionHelper reflectionHelper, IModEvents events) {
Reflection = reflectionHelper;
events.Display.Rendered += OnRendered;
}
/// <summary>Raised after the game draws to the sprite patch in a draw tick, just before the final sprite batch is rendered to the screen.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event data.</param>
private void OnRendered(object sender, RenderedEventArgs e) {
foreach(TemporaryAnimatedSprite animatedSprite in temporaryAnimationList) {
//animatedSprite.update(Game1.currentGameTime);
animatedSprite.Position = new Vector2(Game1.player.Position.X, Game1.player.Position.Y - 160);
}
}
public void BroadcastEmote(int whichEmote) {
TemporaryAnimatedSprite emoteStart = new TemporaryAnimatedSprite("TileSheets\\emotes", new Rectangle(0, 0, 16, 16), new Vector2(Game1.player.Position.X, Game1.player.Position.Y - 160), false, 0f, Color.White) {
interval = 80f,
animationLength = 4,
scale = 4f,
layerDepth = 0.9f,
local = false,
timeBasedMotion = true,
attachedCharacter = Game1.player,
extraInfoForEndBehavior = 0,
endFunction = FinishedAnimation
};
TemporaryAnimatedSprite emote = new TemporaryAnimatedSprite("TileSheets\\emotes", new Rectangle(0, whichEmote * 16, 16, 16), new Vector2(Game1.player.Position.X, Game1.player.Position.Y - 160), false, 0f, Color.White) {
delayBeforeAnimationStart = 100,
interval = 250f,
animationLength = 4,
scale = 4f,
layerDepth = 1f,
local = false,
timeBasedMotion = true,
attachedCharacter = Game1.player,
extraInfoForEndBehavior = 1,
endFunction = FinishedAnimation
};
TemporaryAnimatedSprite emoteEnding = new TemporaryAnimatedSprite("TileSheets\\emotes", new Rectangle(0, 0, 16, 16), new Vector2(Game1.player.Position.X, Game1.player.Position.Y - 160), false, 0f, Color.White) {
delayBeforeAnimationStart = 800,
interval = 80f,
animationLength = 4,
scale = 4f,
layerDepth = 0.9f,
local = false,
timeBasedMotion = true,
pingPong = true, // This makes the animation play, forwards, and when finished backwards
sourceRect = new Rectangle(48, 0, 16, 16), // Set the current sprite position to the last animation image
currentParentTileIndex = 3, // To play the animation backwards, we tell it that its in the last frame
attachedCharacter = Game1.player,
extraInfoForEndBehavior = 2,
endFunction = FinishedAnimation
};
temporaryAnimationList = new List<TemporaryAnimatedSprite>() {
emoteStart,
emote,
emoteEnding
};
Multiplayer multiplayer = Reflection.GetField<Multiplayer>(typeof(Game1), "multiplayer").GetValue();
multiplayer.broadcastSprites(Game1.player.currentLocation, temporaryAnimationList);
}
private void FinishedAnimation(int extraInfo) {
switch(extraInfo) {
case 0:
ModEntry.ModMonitor.Log($"Finished animation 0!");
break;
case 1:
ModEntry.ModMonitor.Log($"Finished animation 1!");
break;
case 2:
ModEntry.ModMonitor.Log($"Finished animation 2!");
break;
}
temporaryAnimationList[extraInfo].delayBeforeAnimationStart = 0;
}
}
}
|
using System;
using System.Drawing;
using System.Drawing.Imaging;
using GeoAPI.Geometries;
using GisSharpBlog.NetTopologySuite.Geometries;
using SharpMap.UI.Forms;
using SharpMap.Styles;
using GeometryFactory = SharpMap.Converters.Geometries.GeometryFactory;
namespace SharpMap.UI.Helpers
{
public class MapControlHelper // TODO: it looks more like Map helper in SharpMap ?
{
/// <summary>
/// Modifies a Vectorstyle to "highlight" during operation (eg. moving features)
/// </summary>
/// <param name="vectorStyle"></param>
/// <param name="good"></param>
public static void PimpStyle(VectorStyle vectorStyle, bool good)
{
vectorStyle.Line.Color = Color.FromArgb(128, vectorStyle.Line.Color);
SolidBrush solidBrush = vectorStyle.Fill as SolidBrush;
if (null != solidBrush)
vectorStyle.Fill = new SolidBrush(Color.FromArgb(127, solidBrush.Color));
else // possibly a multicolor brush
vectorStyle.Fill = new SolidBrush(Color.FromArgb(63, Color.DodgerBlue));
if (null != vectorStyle.Symbol)
{
Bitmap bitmap = new Bitmap(vectorStyle.Symbol.Width, vectorStyle.Symbol.Height);
Graphics graphics = Graphics.FromImage(bitmap);
ColorMatrix colorMatrix;
if (good)
{
colorMatrix = new ColorMatrix(new float[][]
{
new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // red scaling of 1
new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, // green scaling of 1
new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, // blue scaling of 1
new float[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, // alpha scaling of 0.5
new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}
});
}
else
{
colorMatrix = new ColorMatrix(new float[][]
{
new float[] {2.0f, 0.0f, 0.0f, 0.0f, 0.0f}, // red scaling of 2
new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, // green scaling of 1
new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, // blue scaling of 1
new float[] {0.0f, 0.0f, 0.0f, 0.5f, 0.0f}, // alpha scaling of 0.5
new float[] {1.0f, 0.0f, 0.0f, 0.0f, 1.0f}
});
}
ImageAttributes imageAttributes = new ImageAttributes();
imageAttributes.SetColorMatrix(colorMatrix);
graphics.DrawImage(vectorStyle.Symbol,
new Rectangle(0, 0, vectorStyle.Symbol.Width, vectorStyle.Symbol.Height), 0, 0,
vectorStyle.Symbol.Width, vectorStyle.Symbol.Height, GraphicsUnit.Pixel, imageAttributes);
graphics.Dispose();
vectorStyle.Symbol = bitmap;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using DFC.ServiceTaxonomy.GraphSync.Exceptions;
using DFC.ServiceTaxonomy.GraphSync.Interfaces;
using DFC.ServiceTaxonomy.GraphSync.Models;
using DFC.ServiceTaxonomy.GraphSync.Extensions;
using DFC.ServiceTaxonomy.GraphSync.Interfaces.Queries;
using DFC.ServiceTaxonomy.GraphSync.CosmosDb.Queries.Models;
using DFC.ServiceTaxonomy.GraphSync.Helpers;
namespace DFC.ServiceTaxonomy.GraphSync.CosmosDb.Queries
{
public class CosmosDbGetIncomingContentPickerRelationshipsQuery : IGetIncomingContentPickerRelationshipsQuery
{
public IEnumerable<string> NodeLabels { get; set; } = Enumerable.Empty<string>();
public string? IdPropertyName { get; set; }
public object? IdPropertyValue { get; set; }
public List<string> ValidationErrors()
{
var validationErrors = new List<string>();
if (IdPropertyName == null)
validationErrors.Add($"{nameof(IdPropertyName)} is null.");
if (IdPropertyValue == null)
validationErrors.Add($"{nameof(IdPropertyValue)} is null.");
if(!NodeLabels.Any())
{
validationErrors.Add("At least one NodeLabel must be provided.");
}
return validationErrors;
}
public Query Query
{
get
{
this.CheckIsValid();
(_, Guid id) = DocumentHelper.GetContentTypeAndId(IdPropertyValue?.ToString() ?? string.Empty);
var contentType = NodeLabels.First(nodeLabel =>
!nodeLabel.Equals("Resource", StringComparison.InvariantCultureIgnoreCase));
return new Query(id.ToString(), contentType);
}
}
public INodeWithOutgoingRelationships? ProcessRecord(IRecord record)
{
var results = (Dictionary<string, object>)record["sourceNodeWithOutgoingRelationships"];
if (results == null)
throw new QueryResultException($"{nameof(CosmosDbGetIncomingContentPickerRelationshipsQuery)} results not in expected format.");
if (!(results["sourceNode"] is INode sourceNode))
return null;
IEnumerable<(IRelationship, INode)> outgoingRelationships =
((IEnumerable<object>)results["outgoingRelationships"])
.Cast<IDictionary<string, object>>()
.Select(or =>
((IRelationship)or["relationship"], (INode)or["destinationNode"]));
if (outgoingRelationships.Count() == 1 && outgoingRelationships.First().Item1 == null)
outgoingRelationships = Enumerable.Empty<(IRelationship, INode)>();
CosmosDbNodeWithOutgoingRelationships nodeWithOutgoingRelationships =
//todo: check all combos of missing data
new CosmosDbNodeWithOutgoingRelationships(sourceNode, outgoingRelationships);
return nodeWithOutgoingRelationships;
}
}
}
|
using NetEscapades.AspNetCore.SecurityHeaders.Headers;
// ReSharper disable once CheckNamespace
namespace Microsoft.AspNetCore.Builder
{
/// <summary>
/// Extension methods for adding a <see cref="ReferrerPolicyHeader" /> to a <see cref="HeaderPolicyCollection" />
/// </summary>
public static class ReferrerPolicyHeaderExtensions
{
/// <summary>
/// Indicates that the site doesn't want to set a Referrer Policy
/// here and the browser should fallback to a Referrer Policy defined
/// via other mechanisms elsewhere
/// </summary>
/// <param name="policies">The collection of policies</param>
/// <returns>The <see cref="HeaderPolicyCollection"/> for method chaining</returns>
public static HeaderPolicyCollection AddReferrerPolicyNone(this HeaderPolicyCollection policies)
{
return policies.ApplyPolicy(new ReferrerPolicyHeader(string.Empty));
}
/// <summary>
/// Instructs the browser to never send the referrer header with requests
/// that are made from your site. This also include links to pages on your own site.
/// </summary>
/// <param name="policies">The collection of policies</param>
/// <returns>The <see cref="HeaderPolicyCollection"/> for method chaining</returns>
public static HeaderPolicyCollection AddReferrerPolicyNoReferrer(this HeaderPolicyCollection policies)
{
return policies.ApplyPolicy(new ReferrerPolicyHeader("no-referrer"));
}
/// <summary>
/// The browser will not send the referrer header when navigating from HTTPS to HTTP,
/// but will always send the full URL in the referrer header when navigating
/// from HTTP to any origin.
/// </summary>
/// <param name="policies">The collection of policies</param>
/// <returns>The <see cref="HeaderPolicyCollection"/> for method chaining</returns>
public static HeaderPolicyCollection AddReferrerPolicyNoReferrerWhenDowngrade(this HeaderPolicyCollection policies)
{
return policies.ApplyPolicy(new ReferrerPolicyHeader("no-referrer-when-downgrade"));
}
/// <summary>
/// The browser will only set the referrer header on requests to the same origin.
/// If the destination is another origin then no referrer information will be sent.
/// </summary>
/// <param name="policies">The collection of policies</param>
/// <returns>The <see cref="HeaderPolicyCollection"/> for method chaining</returns>
public static HeaderPolicyCollection AddReferrerPolicySameOrigin(this HeaderPolicyCollection policies)
{
return policies.ApplyPolicy(new ReferrerPolicyHeader("same-origin"));
}
/// <summary>
/// The browser will always set the referrer header to the origin from which the request was made.
/// This will strip any path information from the referrer information.
/// </summary>
/// <param name="policies">The collection of policies</param>
/// <returns>The <see cref="HeaderPolicyCollection"/> for method chaining</returns>
public static HeaderPolicyCollection AddReferrerPolicyOrigin(this HeaderPolicyCollection policies)
{
return policies.ApplyPolicy(new ReferrerPolicyHeader("origin"));
}
/// <summary>
/// The browser will always set the referrer header to the origin from which the request was made, as
/// long as the destination is HTTPS, otherwise no refer will not be sent.
/// This will strip any path information from the referrer information.
/// </summary>
/// <param name="policies">The collection of policies</param>
/// <returns>The <see cref="HeaderPolicyCollection"/> for method chaining</returns>
public static HeaderPolicyCollection AddReferrerPolicyStrictOrigin(this HeaderPolicyCollection policies)
{
return policies.ApplyPolicy(new ReferrerPolicyHeader("strict-origin"));
}
/// <summary>
/// The browser will send the full URL to requests to the same origin but
/// only send the origin when requests are cross-origin.
/// </summary>
/// <param name="policies">The collection of policies</param>
/// <returns>The <see cref="HeaderPolicyCollection"/> for method chaining</returns>
public static HeaderPolicyCollection AddReferrerPolicyOriginWhenCrossOrigin(this HeaderPolicyCollection policies)
{
return policies.ApplyPolicy(new ReferrerPolicyHeader("origin-when-cross-origin"));
}
/// <summary>
/// The browser will send the full URL to requests to the same origin but
/// only send the origin when requests are cross-origin, as long as a scheme
/// downgrade has not happened (i.e. you are not moving from HTTPS to HTTP)
/// </summary>
/// <param name="policies">The collection of policies</param>
/// <returns>The <see cref="HeaderPolicyCollection"/> for method chaining</returns>
public static HeaderPolicyCollection AddReferrerPolicyStrictOriginWhenCrossOrigin(this HeaderPolicyCollection policies)
{
return policies.ApplyPolicy(new ReferrerPolicyHeader("strict-origin-when-cross-origin"));
}
/// <summary>
/// The browser will always send the full URL with any request to any origin.
/// </summary>
/// <param name="policies">The collection of policies</param>
/// <returns>The <see cref="HeaderPolicyCollection"/> for method chaining</returns>
public static HeaderPolicyCollection AddReferrerPolicyUnsafeUrl(this HeaderPolicyCollection policies)
{
return policies.ApplyPolicy(new ReferrerPolicyHeader("unsafe-url"));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Threading;
using IRAP.Global;
using IRAP.Client.User;
using IRAP.Entity.SSO;
using IRAP.Entities.MDM;
using IRAP.WCF.Client.Method;
namespace IRAP.Client.SubSystem
{
public class CurrentOptions
{
private static string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
private static CurrentOptions _instance = null;
private int indexOfOptionTwo = -1;
private WIPStation optionOne = new WIPStation();
private ProductViaStation optionTwo = new ProductViaStation();
private List<ProductViaStation> optionTwos = new List<ProductViaStation>();
private CurrentOptions()
{
}
public static CurrentOptions Instance
{
get
{
if (_instance == null)
_instance = new CurrentOptions();
return _instance;
}
}
/// <summary>
/// 获取/设置当前选择的产品/流程在产品/流程列表中的索引号
/// </summary>
public int IndexOfOptionTwo
{
get { return indexOfOptionTwo; }
set
{
if (value > optionTwos.Count)
{
if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en")
throw new Exception("Index is out of range.");
else
throw new Exception("索引超出列表的范围");
}
if (indexOfOptionTwo != value)
{
if (indexOfOptionTwo < 0)
{
indexOfOptionTwo = -1;
optionTwo = null;
}
else
{
optionTwo = OptionTwos[value];
indexOfOptionTwo = value;
}
}
}
}
/// <summary>
/// 获取/设置当前的工位/工作流结点
/// </summary>
public WIPStation OptionOne
{
get
{
if (optionOne != null)
return optionOne;
else
return new WIPStation();
}
set
{
if (value != null)
{
if (value != null)
{
optionOne = value.Clone();
try
{
GetProductsWithCurrentStatioin();
}
catch
{
indexOfOptionTwo = -1;
optionTwo = new ProductViaStation();
return;
}
if (OptionTwos.Count > 0)
{
foreach (ProductViaStation prdt in optionTwos)
{
if (prdt.T102LeafID == optionTwo.T102LeafID)
{
optionTwo = prdt;
indexOfOptionTwo = optionTwos.IndexOf(prdt);
return;
}
}
indexOfOptionTwo = 0;
optionTwo = optionTwos[0];
}
else
{
indexOfOptionTwo = -1;
OptionTwo = new ProductViaStation();
}
}
else
{
optionOne = new WIPStation();
}
}
}
}
/// <summary>
/// 获取/设置当前选择的产品/流程
/// </summary>
public ProductViaStation OptionTwo
{
get
{
if (optionTwo != null)
return optionTwo;
else
return new ProductViaStation();
}
set
{
if (optionTwo == null ||
optionTwo.T102LeafID != value.T102LeafID)
{
for (int i = 0; i < optionTwos.Count; i++)
{
if (optionTwos[i].T102LeafID == value.T102LeafID)
{
optionTwo = optionTwos[i];
indexOfOptionTwo = i;
return;
}
}
if (value.T102LeafID != 0)
{
if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en")
throw new Exception("The product/process to switch is not in the list of the current position/process");
else
throw new Exception("要切换产品/流程的不在当前工位/工序允许的列表中");
}
else
{
optionTwo = value;
indexOfOptionTwo = -1;
}
}
if (optionTwo == null)
{
optionTwo = new ProductViaStation();
}
}
}
public List<ProductViaStation> OptionTwos
{
get { return optionTwos; }
}
private void GetProductsWithCurrentStatioin()
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
WriteLog.Instance.WriteBeginSplitter(strProcedureName);
try
{
optionTwos.Clear();
AvailableProducts.Instance.GetProducts(
IRAPUser.Instance.CommunityID,
IRAPUser.Instance.SysLogID,
optionOne.T107LeafID,
optionOne.IsWorkFlowNode);
foreach (ProductViaStation prod in AvailableProducts.Instance.Products)
optionTwos.Add(prod.Clone());
}
catch (Exception error)
{
WriteLog.Instance.Write(error.Message, strProcedureName);
WriteLog.Instance.Write(error.StackTrace, strProcedureName);
throw error;
}
finally
{
WriteLog.Instance.WriteEndSplitter(strProcedureName);
}
}
}
} |
using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace AsNum.XFControls {
/// <summary>
/// 左右滑动幻灯片
/// </summary>
[ContentProperty("Children")]
public class Flip : View {
/// <summary>
/// 下一侦
/// </summary>
public event EventHandler NextRequired;
/// <summary>
/// 请求指定侦
/// </summary>
public event EventHandler<IndexRequestEventArgs> IndexRequired;
#region ItemsSource
/// <summary>
/// 源
/// </summary>
public static readonly BindableProperty ItemsSourceProperty =
BindableProperty.Create("ItemsSource",
typeof(IEnumerable),
typeof(Flip),
null,
propertyChanged: ItemsSourceChanged);
/// <summary>
/// 数据源
/// </summary>
public IEnumerable ItemsSource {
get {
return (IEnumerable)this.GetValue(ItemsSourceProperty);
}
set {
this.SetValue(ItemsSourceProperty, value);
}
}
private static void ItemsSourceChanged(BindableObject bindable, object oldValue, object newValue) {
var flip = (Flip)bindable;
flip.WrapItemsSource();
}
#endregion
#region Orientation
///// <summary>
/////
///// </summary>
//public static readonly BindableProperty OrientationProperty =
// BindableProperty.Create(
// "Orientation",
// typeof(ScrollOrientation),
// typeof(Flip),
// ScrollOrientation.Horizontal);
//public ScrollOrientation Orientation {
// get {
// return (ScrollOrientation)this.GetValue(OrientationProperty);
// }
// set {
// this.SetValue(OrientationProperty, value);
// }
//}
#endregion
#region ItemTemplate
/// <summary>
/// 数据模板
/// </summary>
public static readonly BindableProperty ItemTemplateProperty =
BindableProperty.Create(
"ItemTemplate",
typeof(DataTemplate),
typeof(Flip),
null
);
/// <summary>
/// 数据模板
/// </summary>
public DataTemplate ItemTemplate {
get {
return (DataTemplate)this.GetValue(ItemTemplateProperty);
}
set {
this.SetValue(ItemTemplateProperty, value);
}
}
#endregion
#region AutoPlay
/// <summary>
/// 是否自动播放
/// </summary>
public static readonly BindableProperty AutoPlayProperty =
BindableProperty.Create(
"AutoPlay",
typeof(bool),
typeof(Flip),
false,
propertyChanged: AutoPlayChanged
);
/// <summary>
/// 是否自动播放
/// </summary>
public bool AutoPlay {
get {
return (bool)this.GetValue(AutoPlayProperty);
}
set {
this.SetValue(AutoPlayProperty, value);
}
}
private static void AutoPlayChanged(BindableObject bindable, object oldValue, object newValue) {
var flip = (Flip)bindable;
if ((bool)newValue) {
flip.Play();
} else {
flip.Stop();
}
}
#endregion
#region Interval
/// <summary>
/// 播放间隔, 单位毫秒,默认2000
/// </summary>
public static readonly BindableProperty IntervalProperty =
BindableProperty.Create("Interval",
typeof(int),
typeof(Flip),
2000);
/// <summary>
/// 播放间隔, 单位毫秒,默认2000
/// </summary>
public int Interval {
get {
return (int)this.GetValue(IntervalProperty);
}
set {
this.SetValue(IntervalProperty, value);
}
}
#endregion
#region ShowIndicator
/// <summary>
/// 是否显示指示点
/// </summary>
public static readonly BindableProperty ShowIndicatorProperty =
BindableProperty.Create(
"ShowIndicator",
typeof(bool),
typeof(Flip),
true
);
/// <summary>
/// 是否显示指示点
/// </summary>
public bool ShowIndicator {
get {
return (bool)this.GetValue(ShowIndicatorProperty);
}
set {
this.SetValue(ShowIndicatorProperty, value);
}
}
#endregion
#region Current
/// <summary>
/// 当前侦序号,从0开始
/// </summary>
public static readonly BindableProperty CurrentProperty =
BindableProperty.Create("Current",
typeof(int),
typeof(Flip),
0,
propertyChanged: CurrentChanged,
defaultBindingMode: BindingMode.TwoWay
);
/// <summary>
/// 当前侦序号,从0开始
/// </summary>
public int Current {
get {
return (int)this.GetValue(CurrentProperty);
}
set {
this.SetValue(CurrentProperty, value);
}
}
/// <summary>
/// 从1开始,区别于 Current, 为了方便在界面上显示序号
/// </summary>
public int Index {
get {
if (this.Children.Count > 0)
return (int)Current + 1;
else
return 0;
}
}
private static void CurrentChanged(BindableObject bindable, object oldValue, object newValue) {
var flip = (Flip)bindable;
flip.OnPropertyChanged("Index");
if (flip.IndexRequired != null && !oldValue.Equals(newValue)) {
flip.IndexRequired.Invoke(flip, new IndexRequestEventArgs((int)newValue));
}
}
#endregion
#region Total
//https://developer.xamarin.com/api/type/Xamarin.Forms.BindablePropertyKey/
/// <summary>
/// 条目总数
/// </summary>
public static readonly BindablePropertyKey TotalPropertyKey =
BindableProperty.CreateReadOnly("Total",
typeof(int),
typeof(Flip),
0);
/// <summary>
/// 条目总数,为了方便界面显示
/// </summary>
public int Total {
get {
//注意: TotalPropertyKey.BindableProperty
return (int)this.GetValue(TotalPropertyKey.BindableProperty);
}
private set {
//注意: TotalPropertyKey
this.SetValue(TotalPropertyKey, value);
}
}
#endregion
public ObservableCollection<View> Children {
get;
} = new ObservableCollection<View>();
#region 数据源变动事件
/// <summary>
/// 订阅数据源变化通知
/// </summary>
private void WrapItemsSource() {
new NotifyCollectionWrapper(this.ItemsSource,
add: (datas, idx) => this.Add(datas, idx),
remove: (datas, idx) => this.Remove(datas, idx),
reset: () => this.Reset(),
finished: () => {
this.Total = this.ItemsSource?.Cast<object>().Count() ?? 0;
});
}
private void Add(IList datas, int idx) {
var c = this.Children.Count();
foreach (var d in datas) {
var i = idx++;
var v = this.GetChild(d);
if (i < c) {
this.Children.Insert(i, v);
} else {
this.Children.Add(v);
}
}
}
private void Remove(IList datas, int idx) {
var headers = this.Children.Skip(idx).Take(datas.Count);
for (var i = idx; i < datas.Count; i++) {
this.Children.RemoveAt(i);
}
}
private void Reset() {
this.Children.Clear();
if (this.ItemsSource != null) {
var idx = 0;
foreach (var d in this.ItemsSource) {
var i = idx++;
var v = this.GetChild(d);
this.Children.Add(v);
}
}
}
#endregion
/// <summary>
/// 根据数据模板,生成子元素
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private View GetChild(object data) {
View view = null;
if (this.ItemTemplate != null) {
view = (View)this.ItemTemplate.CreateContent();
view.BindingContext = data;
view.Parent = this;
} else {
view = new Label() { Text = "Not Set ItemTemplate" };
}
return view;
}
protected override void OnSizeAllocated(double width, double height) {
base.OnSizeAllocated(width, height);
foreach (var c in this.Children) {
if (c.Parent == null)
c.Parent = this;
c.Layout(new Rectangle(0, 0, width, height));
}
}
public void Play() {
this.AutoPlay = true;
this.InnerPlay();
}
public void Stop() {
this.AutoPlay = false;
}
private void InnerPlay() {
if (this.AutoPlay)
Task.Delay(this.Interval)
.ContinueWith(t => {
if (this.NextRequired != null)
this.NextRequired.Invoke(this, new EventArgs());
this.InnerPlay();
});
}
public class IndexRequestEventArgs : EventArgs {
public int Index { get; }
public IndexRequestEventArgs(int idx) {
this.Index = idx;
}
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Arduino_Alarm.EnterSettings;
namespace UnitTestProject1
{
[TestClass]
public class Enter_settings_Tests
{
[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void Should_be_int()
{
SettingsViewModel sv = new SettingsViewModel();
sv.TimeToReady = "reyerh";
sv.Check();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Moveplatform : MonoBehaviour {
private Vector3 startPosition;
bool up=true;
// Use this for initialization
void Start () {
//maxSpeed = 3;
startPosition = transform.position;
}
// Update is called once per frame
void Update () {
MoveVertical ();
}
void MoveVertical() {
var temp=transform.position;
print (up);
if(up==true) {
temp.y += 0.02f;
transform.position= temp;
if(transform.position.y >=0.39f) {
up=false;
}
}
if(up == false) {
temp.y -= 0.02f;
transform.position=temp;
if(transform.position.y <=-6.08f) {
up = true;
}
}
}
}
|
using System;
using System.ComponentModel.Design;
using System.Dynamic;
namespace Present_Delivery
{
class Program
{
private static int countOfPresents;
private static int happyKids = 0;
static void Main(string[] args)
{
var m = int.Parse(Console.ReadLine());
countOfPresents = m;
var n = int.Parse(Console.ReadLine());
var matrix = new string[n, n];
var santaPos = ReadMatrix(matrix);
var santaRow = santaPos[0];
var santaCol = santaPos[1];
var command = Console.ReadLine();
while (true)
{
if (command == "Christmas morning")
{
break;
}
if (command == "up")
{
matrix[santaRow, santaCol] = "-";
santaRow--;
CheckForCookie(matrix,santaRow,santaCol);
CheckForNice(matrix, santaRow, santaCol);
CheckForNaughty(matrix, santaRow, santaCol);
matrix[santaRow, santaCol] = "S";
}
else if (command == "down")
{
matrix[santaRow, santaCol] = "-";
santaRow++;
CheckForCookie(matrix, santaRow, santaCol);
CheckForNice(matrix, santaRow, santaCol);
CheckForNaughty(matrix, santaRow, santaCol);
matrix[santaRow, santaCol] = "S";
}
else if (command == "left")
{
matrix[santaRow, santaCol] = "-";
santaCol--;
CheckForCookie(matrix, santaRow, santaCol);
CheckForNice(matrix, santaRow, santaCol);
CheckForNaughty(matrix, santaRow, santaCol);
matrix[santaRow, santaCol] = "S";
}
else if (command == "right")
{
matrix[santaRow, santaCol] = "-";
santaCol++;
CheckForCookie(matrix, santaRow, santaCol);
CheckForNice(matrix, santaRow, santaCol);
CheckForNaughty(matrix, santaRow, santaCol);
matrix[santaRow, santaCol] = "S";
}
if (countOfPresents == 0)
{
Console.WriteLine("Santa ran out of presents!");
break;
}
command = Console.ReadLine();
}
PrintMatrix(matrix);
var numberOfKids = GetUnhappy(matrix);
if (numberOfKids > 0)
{
Console.WriteLine($"No presents for {numberOfKids} nice kid/s.");
}
else
{
Console.WriteLine($"Good job, Santa! {happyKids} happy nice kid/s.");
}
}
private static int GetUnhappy(string[,] matrix)
{
var count = 0;
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
if (matrix[i, j] == "V")
{
count++;
}
}
}
return count;
}
private static void CheckForNaughty(string[,] matrix, int santaRow, int santaCol)
{
if (matrix[santaRow,santaCol] == "X")
{
matrix[santaRow, santaCol] = "-";
}
}
private static void CheckForNice(string[,] matrix, int santaRow, int santaCol)
{
if (matrix[santaRow,santaCol] == "V")
{
countOfPresents--;
happyKids++;
matrix[santaRow, santaCol] = "-";
}
}
private static void CheckForCookie(string[,] matrix, int santaRow, int santaCol)
{
if (matrix[santaRow,santaCol] == "C")
{
CheckForAny(matrix,santaRow + 1,santaCol);
CheckForAny(matrix,santaRow - 1,santaCol);
CheckForAny(matrix,santaRow,santaCol + 1);
CheckForAny(matrix,santaRow,santaCol - 1);
}
}
private static void CheckForAny(string[,] matrix, in int santaRow, int santaCol)
{
if (matrix[santaRow, santaCol] == "V" || matrix[santaRow, santaCol] == "X")
{
countOfPresents--;
happyKids++;
matrix[santaRow, santaCol] = "-";
}
}
private static int[] ReadMatrix(string[,] matrix)
{
var santaRow = -1;
var santaCol = -1;
var arr = new int[2];
for (int i = 0; i < matrix.GetLength(0); i++)
{
var row = Console.ReadLine().Split();
for (int j = 0; j < matrix.GetLength(1); j++)
{
matrix[i, j] = row[j];
if (matrix[i,j] == "S")
{
arr[0] = i;
arr[1] = j;
}
}
}
return arr;
}
private static void PrintMatrix(string[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Comp2007_Assignment2.Models
{
public class Pokemenu : DropCreateDatabaseIfModelChanges<PokemonBytesContext>
{
protected override void Seed(PokemonBytesContext context)
{
var Types = new List<Type>
//Pokemon types for users to choose food style
{
new Type { Name = "Fire" },
new Type { Name = "Water" },
new Type { Name = "Grass" },
new Type { Name = "Ice" },
new Type { Name = "Ground" },
new Type { Name = "Rock" },
new Type { Name = "Electric" },
new Type { Name = "Ghost" },
new Type { Name = "Normal" },
};
//List of pokemon for users to then pick dish based on their favorite pokemon
var Pokemons = new List<Pokemon>
{
new Pokemon { Name = "Bulbasaur" },
new Pokemon { Name = "Charmander" },
new Pokemon { Name = "Flareon" },
new Pokemon { Name = "Squirtle" },
new Pokemon { Name = "Lapras" },
new Pokemon { Name = "Sandshrew" },
new Pokemon { Name = "Geodude" },
new Pokemon { Name = "Pikachu" },
new Pokemon { Name = "Gastly" },
new Pokemon { Name = "Rattata" },
};
// Github Fix
new List<Dish>
{
new Dish { Name = "Spicy En'Charmad'as", Type = Types.Single(t => t.Name == "Fire"), Price = 8.99, Pokemon = Pokemons.Single(p => p.Name == "Charmander"), DishImageUrl = "~/Assets/images/Pokeball.PNG" },
new Dish { Name = "Flareon Fettuccini", Type = Types.Single(t => t.Name == "Fire"), Price = 8.99, Pokemon = Pokemons.Single(p => p.Name == "Flareon"), DishImageUrl = "~/Assets/images/Pokeball.PNG" },
new Dish { Name = "Bubble Blast Soup", Type = Types.Single(t => t.Name == "Water"), Price = 8.99, Pokemon = Pokemons.Single(p => p.Name == "Squirtle"), DishImageUrl = "~/Assets/images/Pokeball.PNG" },
new Dish { Name = "Vine Whipped Salad", Type = Types.Single(t => t.Name == "Grass"), Price = 8.99, Pokemon = Pokemons.Single(p => p.Name == "Bulbasaur"), DishImageUrl = "~/Assets/images/Pokeball.PNG" },
new Dish { Name = "IceBeam Icecream", Type = Types.Single(t => t.Name == "Ice"), Price = 8.99, Pokemon = Pokemons.Single(p => p.Name == "Lapras"), DishImageUrl = "/Assets/images/Pokeball.PNG" },
new Dish { Name = "Earthquake Pound Cake", Type = Types.Single(t => t.Name == "Ground"), Price = 8.99, Pokemon = Pokemons.Single(p => p.Name == "Sandshrew"), DishImageUrl = "/Assets/images/Pokeball.PNG" },
new Dish { Name = "Stone Edge Martini", Type = Types.Single(t => t.Name == "Rock"), Price = 8.99, Pokemon = Pokemons.Single(p => p.Name == "Geodude"), DishImageUrl = "/Assets/images/Pokeball.PNG" },
new Dish { Name = "Pika Pizza", Type = Types.Single(t => t.Name == "Electric"), Price = 8.99, Pokemon = Pokemons.Single(p => p.Name == "Pikachu"), DishImageUrl = "/Assets/images/Pokeball.PNG" },
new Dish { Name = "Cursed Panini", Type = Types.Single(t => t.Name == "Ghost"), Price = 8.99, Pokemon = Pokemons.Single(p => p.Name == "Gastly"), DishImageUrl = "/Assets/images/Pokeball.PNG" },
new Dish { Name = "Tail Whip Tacos", Type = Types.Single(t => t.Name == "Normal"), Price = 8.99, Pokemon = Pokemons.Single(p => p.Name == "Rattata"), DishImageUrl = "/Assets/images/Pokeball.PNG" },
}.ForEach(d => context.Dishes.Add(d));
}
}
} |
using System;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StarlightRiver.Abilities;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace StarlightRiver.Projectiles.Dummies
{
class BouncerDummy : ModProjectile
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("");
}
public override string Texture => "StarlightRiver/Invisible";
public override void SetDefaults()
{
projectile.width = 22;
projectile.height = 22;
projectile.aiStyle = -1;
projectile.timeLeft = 2;
projectile.tileCollide = false;
}
public override void AI()
{
foreach (Player player in Main.player.Where(player => Vector2.Distance(player.Center, projectile.Center) <= 100))
{
AbilityHandler mp = player.GetModPlayer<AbilityHandler>();
if (AbilityHelper.CheckDash(player, projectile.Hitbox))
{
mp.dash.Active = false;
if (player.velocity.Length() != 0)
{
player.velocity = Vector2.Normalize(player.velocity) * -18f;
player.wingTime = player.wingTimeMax;
player.rocketTime = player.rocketTimeMax;
player.jumpAgainCloud = true;
player.jumpAgainBlizzard = true;
player.jumpAgainSandstorm = true;
player.jumpAgainFart = true;
player.jumpAgainSail = true;
}
Main.PlaySound(SoundID.Shatter, projectile.Center);
for (int k = 0; k <= 30; k++)
{
int dus = Dust.NewDust(projectile.position, 48, 32, mod.DustType("Glass"), Main.rand.Next(-16, 15), Main.rand.Next(-16, 15), 0, default, 1.3f);
Main.dust[dus].customData = projectile.Center;
}
}
}
projectile.timeLeft = 2;
if(Main.tile[(int)projectile.Center.X / 16, (int)projectile.Center.Y / 16].type != mod.TileType("Bounce"))
{
projectile.timeLeft = 0;
}
}
}
}
|
using System.Collections;
using UnityEngine;
using UnityEngine.Assertions;
namespace RPG.Characters
{
public class WeaponSystem : MonoBehaviour
{
[SerializeField] float baseDamage = 10f;
[Range ( .1f, 1.0f )] [SerializeField] float criticalHitChance = .1f;
[SerializeField] float criticalHitMultiplier = 1.25f;
[SerializeField] ParticleSystem criticalHitParticle;
[SerializeField] WeaponConfig getCurrentWeapon;
const string ATTACK_TRIGGER = "Attack";
const string DEFAULT_ATTACK = "DEFAULT ATTACK";
Animator animator;
Character character;
GameObject target;
GameObject weaponObject;
float lastHitTime;
public void StopAttacking()
{
animator.StopPlayback ();
StopAllCoroutines();
}
void Start()
{
animator = GetComponent<Animator>();
character = GetComponent<Character>();
PutWeaponInHand( getCurrentWeapon );
SetAttackAnimation();
}
void Update()
{
bool targetIsDead;
bool targetIsOutOfRange;
if ( target == null )
{
targetIsDead = false;
targetIsOutOfRange = false;
}
else
{
var targetHealth = target.GetComponent<HealthSystem>().healthAsPercentage;
targetIsDead = targetHealth <= Mathf.Epsilon;
var distanceToTarget = Vector3.Distance( transform.position, target.transform.position );
targetIsOutOfRange = distanceToTarget > currentWeapon.GetMaxAttackRange();
}
float characterHealth = GetComponent<HealthSystem>().healthAsPercentage;
bool characterIsDead = ( characterHealth <= Mathf.Epsilon );
if ( characterIsDead || targetIsOutOfRange || targetIsDead )
{
StopAllCoroutines();
}
}
public WeaponConfig currentWeapon { get { return getCurrentWeapon; } }
public void PutWeaponInHand ( WeaponConfig weaponToUse )
{
getCurrentWeapon = weaponToUse;
var weaponPrefab = weaponToUse.GetWeaponPrefab ();
GameObject dominantHand = RequestDominantHand ();
Destroy ( weaponObject );
weaponObject = Instantiate ( weaponPrefab, dominantHand.transform );
weaponObject.transform.localPosition = weaponToUse.gripTransform.localPosition;
weaponObject.transform.localRotation = weaponToUse.gripTransform.localRotation;
}
public void AttackTarget ( GameObject targetToAttack )
{
target = targetToAttack;
StartCoroutine( AttackTargetRepeatedly() );
}
IEnumerator AttackTargetRepeatedly()
{
bool attackerStillAlive = GetComponent<HealthSystem>().healthAsPercentage >= Mathf.Epsilon;
bool targetStillAlive = target.GetComponent<HealthSystem>().healthAsPercentage >= Mathf.Epsilon;
while ( attackerStillAlive && targetStillAlive )
{
var animationClip = currentWeapon.GetAttackAnimClip ();
float animationClipTime = animationClip.length / character.getAnimSpeedMultiplier;
float timeToWait = animationClipTime * currentWeapon.GetTimeBetweenAnimationCycles();
bool isTimeToHitAgain = Time.time - lastHitTime > timeToWait;
if ( isTimeToHitAgain )
{
AttackTargetOnce();
lastHitTime = Time.time;
}
yield return new WaitForSeconds( timeToWait );
}
}
void AttackTargetOnce()
{
transform.LookAt( target.transform );
animator.SetTrigger( ATTACK_TRIGGER );
float damageDelay = currentWeapon.GetDamageDelay ();
SetAttackAnimation();
StartCoroutine( DamageAfterDelay( damageDelay ) );
}
IEnumerator DamageAfterDelay( float delay )
{
yield return new WaitForSecondsRealtime( delay );
target.GetComponent<HealthSystem>().TakeDamage( CalculateDamage() );
}
void SetAttackAnimation()
{
if ( !character.getOverrideController )
{
Debug.Break();
Debug.LogAssertion( "Please provide " + gameObject + " with an animator override controller." );
}
var animatorOverrideController = character.getOverrideController;
animator.runtimeAnimatorController = animatorOverrideController;
animatorOverrideController[DEFAULT_ATTACK] = getCurrentWeapon.GetAttackAnimClip(); // TODO remove paramater
}
float CalculateDamage()
{
float totalDamage = baseDamage + getCurrentWeapon.GetAdditionalDamage();
if ( UnityEngine.Random.Range( 0f, 1.0f ) <= criticalHitChance )
{
criticalHitParticle.Play();
totalDamage *= criticalHitMultiplier;
}
return totalDamage;
}
GameObject RequestDominantHand ()
{
var dominantHands = GetComponentsInChildren<DominantHand> ();
int numberOfDominantHands = dominantHands.Length;
Assert.IsFalse ( numberOfDominantHands <= 0, "No dominant hand found on " + gameObject.name + ", please add one." );
Assert.IsFalse ( numberOfDominantHands > 1, "Multiple dominant hand scripts on player, please remove one." );
return dominantHands [0].gameObject;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgorithmProblems.matrix_problems
{
class SumOfMatrixElementsFormedByRectangleWithCoordinates
{
public int[,] PreProcessMatrix(int[,] mat)
{
int rowLength = mat.GetLength(0);
int colLength = mat.GetLength(1);
for (int r = 0; r < rowLength; r++ )
{
for(int c = 0; c < colLength; c++)
{
int rowSum = 0;
int columnSum = 0;
int diagSum = 0;
if(r-1 >= 0)
{
columnSum = mat[r - 1, c];
}
if (c-1 >= 0)
{
rowSum = mat[r, c - 1];
}
if(r-1 >= 0 && c-1 >= 0)
{
diagSum = mat[r - 1, c - 1];
}
mat[r, c] += rowSum + columnSum - diagSum;
}
}
return mat;
}
public int GetArea(int r1, int c1, int r2, int c2, int[,] mat)
{
int area = mat[r2, c2] - mat[r1 - 1, c2] - mat[r2, c1 - 1] + mat[r1 - 1, c1 - 1];
return area;
}
public static void TestSumOfMatrixElements()
{
int[,] mat = MatrixProblemHelper.CreateMatrix(4, 5);
Console.WriteLine("The actual matrix");
MatrixProblemHelper.PrintMatrix(mat);
Console.WriteLine("Sum of matrix elements in the rectangle");
SumOfMatrixElementsFormedByRectangleWithCoordinates sumMat = new SumOfMatrixElementsFormedByRectangleWithCoordinates();
mat = sumMat.PreProcessMatrix(mat);
MatrixProblemHelper.PrintMatrix(mat);
Console.WriteLine("the area is: " + sumMat.GetArea(2, 2, 3, 4, mat));
}
}
}
|
using System.Collections.Generic;
using CSConsoleRL.Entities;
using CSConsoleRL.Events;
using CSConsoleRL.Game.Managers;
using CSConsoleRL.Helpers;
namespace CSConsoleRL.GameSystems
{
public class DebugSystem : GameSystem
{
private readonly GameStateHelper _gameStateHelper;
public DebugSystem(GameSystemManager manager, GameStateHelper gameStateHelper)
{
SystemManager = manager;
_systemEntities = new List<Entity>();
_gameStateHelper = gameStateHelper;
}
public override void InitializeSystem()
{
}
public override void AddEntity(Entity entity)
{
}
public override void HandleMessage(IGameEvent gameEvent)
{
switch (gameEvent.EventName)
{
case "ToggleDebugMode":
ToggleDebugMode((ToggleDebugModeEvent)gameEvent);
break;
}
}
private void ToggleDebugMode(ToggleDebugModeEvent gameEvent)
{
bool? debugMode = null;
if (gameEvent.EventParams.Count > 0) debugMode = (bool?)gameEvent.EventParams[0];
if (debugMode == null)
{
_gameStateHelper.SetDebugMode(!_gameStateHelper.DebugMode);
return;
}
_gameStateHelper.SetDebugMode(debugMode.Value);
}
}
} |
using System;
using Argentini.HalideLite;
namespace Notification
{
class Program
{
static void Main(string[] args)
{
// Use Halide within your own code here...
// Do something...
Console.Write("Hello, world.");
// EXIT CONSOLE SESSION
Environment.Exit(0);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamageZone : MonoBehaviour
{
void OnTriggerEnter2D(Collider2D other)
{
PlayerMovementController controller = other.GetComponent<PlayerMovementController>();
if (controller != null)
{
controller.ChangeHealth(-1);
}
Debug.Log("Object that is damaged from entering the trigger : " + other);
}
}
|
using HiLoSocket.Compressor;
namespace HiLoSocket.Builder.Client
{
/// <summary>
/// ISetCompressType.
/// </summary>
/// <typeparam name="T"></typeparam>
public interface ISetCompressType<T>
where T : class
{
/// <summary>
/// Sets the type of the compress.
/// </summary>
/// <param name="compressType">Type of the compress.</param>
/// <returns>ISetTimeoutTime</returns>
ISetTimeoutTime<T> SetCompressType( CompressType? compressType );
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerManager : MonoBehaviour {
// Singleton
public static PlayerManager Instance { get; private set; }
// Player's info
[Header("Name")]
public string PlayerName;
[Header("Components")]
public int PlayerMaxHealth;
public int PlayerCurrHealth;
public int PlayerMaxHunger;
public int PlayerCurrHunger;
public int PlayerMaxThirst;
public int PlayerCurrThirst;
[Header("Movement")]
public float PlayerMoveSpeed;
public float PlayerJumpHeight;
private float playerMoveVelocity;
private float _scaleX;
private float _scaleY;
private float _scaleZ;
private float _posX;
private float _posY;
private float _posZ;
[Header("Ground Check")]
// player jump to check on ground
public Transform GroundCheck;
public LayerMask WhatIsGround;
public float GroundCheckRadius;
public bool isGrounded;
[Header("Attack")]
public int PlayerMeleeDamage;
public GameObject MeleeAttackPos;
[Header("Cool Downs")]
public float ChangeSceneCD;
// player death
[HideInInspector]
public bool IsDead;
[Header("Knock Back")]
public float KnockBack;
public float KnockBackLength;
[HideInInspector]
public float KnockBackCount;
[HideInInspector]
public bool KnockFromRight; // check if enemy is on the right or left
// sprite animation
private Animator _playerAnim;
// This is called before Start()
private void Awake()
{
if(Instance == null) // if instance doesn't contain anything, this script is running for the first time
{
Instance = this; // set this curr instance to be contained inside ^ the static instance
DontDestroyOnLoad(gameObject); // don't detroy the first instance
}
else
{
Destroy(gameObject); // destory other duplicated instances
}
}
// Use this for initialization
void Start ()
{
// store player's x and y scale
_scaleX = transform.localScale.x;
_scaleY = transform.localScale.y;
// store player's x and y and z pos
_posX = transform.position.x;
_posY = transform.position.y;
_posZ = transform.position.z;
// player animation
_playerAnim = GetComponent<Animator>();
// player components
PlayerCurrHealth = PlayerMaxHealth;
PlayerCurrHunger = PlayerMaxHunger;
PlayerCurrThirst = PlayerMaxThirst;
// player not dead
IsDead = false;
}
void FixedUpdate()
{
isGrounded = Physics2D.OverlapCircle(GroundCheck.position, GroundCheckRadius, WhatIsGround);
}
// Update is called once per frame
void Update ()
{
// player direction flip
if (playerMoveVelocity > 0)
{
// player flip to right
transform.localScale = new Vector3(_scaleX, _scaleY, 1f);
}
else if (playerMoveVelocity < 0)
{
// player flip to left
transform.localScale = new Vector3(-_scaleX, _scaleY, 1f);
}
if (IsDead == true)
PlayerCurrHealth = 0;
// player walking
PlayerWalk();
// player jumping
PlayerJump();
// player melee attacking
PlayerMelee();
// player death
PlayerDeath();
// player knock back
PlayerKnockBack();
// Debugging
AddHealth();
}
// Player walk
void PlayerWalk()
{
if(!IsDead)
{
playerMoveVelocity = PlayerMoveSpeed * Input.GetAxisRaw("Horizontal");
GetComponent<Rigidbody2D>().velocity = new Vector2(playerMoveVelocity, GetComponent<Rigidbody2D>().velocity.y);
// walking animation
_playerAnim.SetFloat("Speed", Mathf.Abs(GetComponent<Rigidbody2D>().velocity.x));
}
}
// Player jump
void PlayerJump()
{
if(!IsDead)
{
// player jumping
if (Input.GetButtonDown("Jump") && isGrounded)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(GetComponent<Rigidbody2D>().velocity.x, PlayerJumpHeight);
}
// jumping animation
// the jump anim boolean is set to the same value as the isGrounded value in here
_playerAnim.SetBool("Grounded", isGrounded);
}
}
// Player melee
void PlayerMelee()
{
if(!IsDead)
{
// player attacking
if (_playerAnim.GetBool("Melee") == true)
{
_playerAnim.SetBool("Melee", false);
}
else if (_playerAnim.GetBool("Melee") == false && isGrounded == true)
{
MeleeAttackPos.SetActive(false); // toggle off melee attack
_playerAnim.SetBool("JumpMelee", false);
}
// melee attack when standing still
if (Input.GetButtonDown("Fire1") && playerMoveVelocity == 0 && isGrounded == true) //if(Input.GetKeyDown(KeyCode.X))
{
_playerAnim.SetBool("Melee", true);
MeleeAttackPos.SetActive(true); // toggle on melee attack pos
}
else if (Input.GetButtonDown("Fire1") && isGrounded == false) // jump melee attack animation
{
_playerAnim.SetBool("JumpMelee", true);
MeleeAttackPos.SetActive(true); // toggle on melee attack pos
}
}
}
// Player death
void PlayerDeath()
{
if (PlayerCurrHealth <= 0)
{
//Debug.Log("this ding dong xi kiao kiao alr");
IsDead = true;
_playerAnim.SetBool("Dead", IsDead);
ChangeSceneCD -= Time.deltaTime;
if (ChangeSceneCD < 0)
{
// back to character select
SceneManager.LoadScene("02_CharacterSelection");
Destroy(gameObject);
}
}
}
// Player knock back
void PlayerKnockBack()
{
if(!IsDead)
{
if (KnockBackCount <= 0)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(playerMoveVelocity, GetComponent<Rigidbody2D>().velocity.y);
}
else
{
if (KnockFromRight)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(-KnockBack, KnockBack);
}
if (!KnockFromRight)
{
GetComponent<Rigidbody2D>().velocity = new Vector2(KnockBack, KnockBack);
}
KnockBackCount -= Time.deltaTime;
}
}
}
// Add health
void AddHealth()
{
if(Input.GetKeyDown(KeyCode.R) && !IsDead)
{
PlayerCurrHealth += 20;
}
}
// Getters
public int GetPlayerCurrHealth()
{
return PlayerCurrHealth;
}
public int GetPlayerCurrHunger()
{
return PlayerCurrHunger;
}
public int GetPlayerCurrThirst()
{
return PlayerCurrThirst;
}
//// Collision
//void OnTriggerEnter2D(Collider2D other)
//{
// if (other.tag == "Item")
// {
// InventoryManager.Instance.AddItem(other.GetComponent<ItemDatabase);
// }
//}
}
|
using System;
using System.Linq;
namespace Task_09
{
class LinearEquation
{
private double a;
private double b;
private double c;
public double X
{
get
{
return a != 0 ? (c - b) / a : double.PositiveInfinity;
}
}
public LinearEquation()
{
Random random = new Random();
a = random.Next(-10, 10) + random.NextDouble();
b = random.Next(-10, 10) + random.NextDouble();
c = random.Next(-10, 10) + random.NextDouble();
}
public LinearEquation(double a, double b, double c)
{
this.a = a;
this.b = b;
this.c = c;
}
public override string ToString()
{
return $"{a}x + ({b}) = {c}{Environment.NewLine}x = {X}";
}
}
class Program
{
static void Main()
{
do
{
Console.Clear();
Console.Write("Enter the value of N: ");
if (!uint.TryParse(Console.ReadLine(), out uint N))
{
Console.WriteLine("Incorrect input.");
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
continue;
}
LinearEquation[] equations = new LinearEquation[N];
for (int index = 0; index < equations.Length; index++)
{
Console.WriteLine();
equations[index] = new LinearEquation();
Console.WriteLine(equations[index].ToString());
}
equations = equations.OrderBy(item => item.X).ToArray();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\nSort is complete.");
Console.ResetColor();
Array.ForEach(equations, item => Console.WriteLine($"\n{item}"));
Console.WriteLine("\nPress Esc to exit or another key to continue");
} while (Console.ReadKey().Key != ConsoleKey.Escape);
}
}
}
|
using UnityEngine;
using System.Diagnostics;
using Debug = UnityEngine.Debug;
public class Log {
[Conditional("ENABLE_LOG")]
public static void Info(object message) {
Debug.Log("Info : " + message);
}
[Conditional("ENABLE_LOG")]
public static void Warning(object message) {
Debug.LogWarning("Warning : " + message);
}
[Conditional("ENABLE_LOG")]
public static void Error(object message) {
Debug.LogError("Error : " + message);
}
} |
using University.Data;
using University.Service;
using University.UI.Areas.Admin.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using University.Service.Interface;
using University.UI.Models;
using System.Web.Security;
using University.UI.Utilities;
using System.Net.Mail;
using System.Net;
using System.Configuration;
namespace University.UI.Areas.Admin.Controllers
{
public class UserController : Controller
{
private IUseradminService _UseradminService;
// string CategoryImagePath = WebConfigurationManager.AppSettings["CategoryImagePath"];
public UserController()
{
_UseradminService = new UseradminService();
}
// GET: Admin/Category
public ActionResult index()
{
var res = _UseradminService.GetUserList().ToList();
var viewModel = AutoMapper.Mapper.Map<List<Login_tbl>, List<Login_tbl>>(res);
Session["UserList"] = viewModel;
return View(viewModel);
}
//public ActionResult AddEditCategory(Login_tbl model)
//{
//var res = AutoMapper.Mapper.Map<Login_tbl>(model);
// var isSuccess = _UseradminService.AddOrUpdateCategory(res);
// return Json(isSuccess, JsonRequestBehavior.AllowGet);
// return View();
//}
//private string UploadFileOnServer(string location, HttpPostedFileBase file)
//{
// string extension = Path.GetExtension(file.FileName);
// string fileId = Guid.NewGuid().ToString().Replace("-", "");
// string filename = fileId + extension;
// var path = Path.Combine(Server.MapPath(location), filename);
// file.SaveAs(path);
// return filename;
//}
//public ActionResult GetCategory(string Id)
//{
// CategoryViewModel model;
// if (!string.IsNullOrEmpty(Id))
// {
// var res = _categoryMasterService.GetCategory(Convert.ToDecimal(Id));
// model = AutoMapper.Mapper.Map<CategoryMaster, CategoryViewModel>(res);
// }
// else
// {
// model = new CategoryViewModel();
// }
// return PartialView("AddEditCategory",model);
//}
//[HttpDelete]
public ActionResult DeleteUser(string Id)
{
var res = _UseradminService.DeleteUser(Convert.ToDecimal(Id));
return Json(new { url = "/Admin/User" });
// return Json(true, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Register()
{
var res = _UseradminService.GetCustomerList();
if (TempData["EditUserId"] != null)
{
Login_tbl Login_tbl = _UseradminService.EditUser(Convert.ToInt32(TempData["EditUserId"]));
return View("Register", new RegistrationVM
{
ID = Login_tbl.ID,
FirstName = Login_tbl.FirstName,
LastName = Login_tbl.LastName,
Email = Login_tbl.UserName,
Password = UrlSecurityManager.Decrypt(Login_tbl.Password, ConfigurationManager.AppSettings["SecurityKey"]),
ConfirmPassword = UrlSecurityManager.Decrypt(Login_tbl.Password, ConfigurationManager.AppSettings["SecurityKey"]),
MobileNo = Login_tbl.MobileNo,
CustomerId = Login_tbl.CustomerId,
CustomerList = res
});
}
else
{
return View("Register", new RegistrationVM { CustomerList = res });
}
}
[HttpPost]
public ActionResult Register(RegistrationVM p_RegistrationVM)
{
if (p_RegistrationVM.ID != 0)
{
var res = _UseradminService.SaveEditUserDetails(new Login_tbl
{
ID = p_RegistrationVM.ID,
FirstName = p_RegistrationVM.FirstName,
LastName = p_RegistrationVM.LastName,
UserName = p_RegistrationVM.Email,
Password = UrlSecurityManager.Encrypt(p_RegistrationVM.Password, ConfigurationManager.AppSettings["SecurityKey"]), //p_RegistrationVM.Password,
CustomerId = p_RegistrationVM.CustomerId,
MobileNo = p_RegistrationVM.MobileNo,
RoleID = 5,
CreatedDate = DateTime.Now,
CreatedBy = Convert.ToDecimal(Session["RoleID"]),
IsDeleted = false,
AdminId = Convert.ToInt32(Session["AdminLoginID"])
});
if (res.Item1 == true)
{
//bool success = SendEmail(p_RegistrationVM.Email, p_RegistrationVM.Password, p_RegistrationVM.FirstName);
//if (success)
//{
return Json(new { result = true, Message = "User Update Successful", url = "/Admin/User" });
//}
//else
//{
// return Json(new { result = true, Message = "User Registration Successful but Email not sent", url = "/Admin/User" });
//}
}
else
{
//if (res.Item2 == true)
//{
// return Json(new { result = false, Message = "Email already Exists.", url = "/Admin/User/Register" });
//}
//else
//{
return Json(new { result = false, Message = "something went wrong,please try again.", url = "/Admin/User/Register" });
//}
}
}
else
{
var res = _UseradminService.RegisterUser(new Login_tbl
{
FirstName = p_RegistrationVM.FirstName,
LastName = p_RegistrationVM.LastName,
UserName = p_RegistrationVM.Email,
Password = UrlSecurityManager.Encrypt(p_RegistrationVM.Password, ConfigurationManager.AppSettings["SecurityKey"]), //p_RegistrationVM.Password,
CustomerId = p_RegistrationVM.CustomerId,
MobileNo = p_RegistrationVM.MobileNo,
RoleID = 5,
CreatedDate = DateTime.Now,
CreatedBy = Convert.ToDecimal(Session["RoleID"]),
IsDeleted = false,
AdminId = Convert.ToInt32(Session["AdminLoginID"])
});
if (res.Item1 == true)
{
bool success = SendEmail(p_RegistrationVM.Email, p_RegistrationVM.Password, p_RegistrationVM.FirstName);
if (success)
{
return Json(new { result = true, Message = "User Registration Successful and Email Sent", url = "/Admin/User" });
}
else
{
return Json(new { result = true, Message = "User Registration Successful but Email not sent", url = "/Admin/User" });
}
}
else
{
if (res.Item2 == true)
{
return Json(new { result = false, Message = "Email already Exists.", url = "/Admin/User/Register" });
}
else
{
return Json(new { result = false, Message = "something went wrong,please try again.", url = "/Admin/User/Register" });
}
}
}
}
public bool SendEmail(string p_Email, string p_Password, string FirstName)
{
try
{
var smtp = new SmtpClient
{
Host = ConfigurationManager.AppSettings["Host"],
Port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]),
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(ConfigurationManager.AppSettings["AdminId"], ConfigurationManager.AppSettings["AdminPassword"])
};
using (var message = new MailMessage(new MailAddress(ConfigurationManager.AppSettings["AdminId"], "Admin"), new MailAddress(p_Email, "user"))
{
Subject = "Login Credentials",
Body = "Hello " + FirstName + ",<br/><br/>Welcome to LearnX. Below are the login credentials for the system. <br/><br/>UserName: " + p_Email + " <br/>Password: " + p_Password + "<br/><br/>Please <a href=" + ConfigurationManager.AppSettings["LoginUrl"] + ">Click Here</a> to login. <br/><br/><br/>Regards,<br/>Admin"
})
{
message.IsBodyHtml = true;
smtp.Send(message);
}
return true;
}
catch (Exception e)
{
return false;
}
}
[HttpGet]
public ActionResult EditUser(int id)
{
TempData["EditUserId"] = id;
return RedirectToAction("Register");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cache.Core
{
public interface ICache<TKey, TValue> : IDisposable
{
bool Add(TKey key, TValue value);
bool AddOrUpdate(TKey key, TValue value);
void Clear();
bool Exists(TKey key);
TValue Get(TKey key);
void Put(TKey key, TValue value);
bool Remove(TKey key);
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bot : MonoBehaviour
{
public GameObject player;
public float speed, rotSpeed;
private Rigidbody rb;
float FindRotation()
{
Vector3 v1 = new Vector3(0f, 0f, 0f);//transform.rotation.eulerAngles;
Vector3 v2 = player.transform.position - transform.position;
float tag = v2.z / v2.x;
float angle;
switch(Math.Sign(v2.x))
{
case -1:
switch(Math.Sign(v2.z))
{
case -1:
angle = -(float)Math.Atan(tag) * 360f / (float)Math.PI - 90f;
break;
default:
angle = -(float)Math.Atan(tag) * 360f / (float)Math.PI;
break;
}
break;
default:
switch(Math.Sign(v2.z))
{
case -1:
angle = (float)Math.Atan(tag) * 360f / (float)Math.PI + 90f;
break;
default:
angle = (float)Math.Atan(tag) * 360f / (float)Math.PI;
break;
}
break;
}
Debug.Log(angle);
return angle;
}
void Start()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
transform.rotation = Quaternion.Euler(0f, FindRotation(), 0f);
Vector3 v = transform.TransformVector(0f, 0f, speed);
rb.velocity = new Vector3(v.x, rb.velocity.y, v.z);
}
}
|
using UnityEngine;
using System.Collections;
public class RatingsHelper : MonoBehaviour {
string iosAppID = "1049415206";
string androidPackageName = "com.snackfortgames.lazyangus_android";
public static RatingsHelper instance;
void Awake() {
instance = this;
}
public string GetStorePageURL() {
if (Application.platform == RuntimePlatform.IPhonePlayer) {
float iOSVersion = Utilities.GetIOSVersion ();
if (iOSVersion >= 8f) {
return "itms-apps://itunes.apple.com/app/id" + iosAppID;
} else {
return "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=" +
iosAppID +
"&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software";
}
} else if (Application.platform == RuntimePlatform.Android) {
return "market://details?id=" + androidPackageName;
} else {
return "http://itunes.apple.com/app/id" + iosAppID;
}
}
public void ShowRatingsPage() {
string rateThisURL = GetStorePageURL ();
Application.OpenURL (rateThisURL);
}
}
|
namespace Sales.Models
{
using System;
using System.Collections.Generic;
using System.Text;
public class ChatMessage
{
public string Text { get; set; }
public DateTime MessageDateTime { get; set; }
public bool IsIncoming { get; set; }
public string Image { get; set; }
}
}
|
using System;
using EPI.DynamicProgramming;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EPI.UnitTests.DynamicProgramming
{
[TestClass]
public class MaxSubarrayUnitTest
{
[TestMethod]
public void FindMaxSubarray()
{
MaxSubarray.FindMaximumSubarray(new[] { 0, 5, -3, 7, 1, 0, -2 }).ShouldBeEquivalentTo( new Tuple<int, int>(0,6));
MaxSubarray.FindMaximumSubarray(new[] { 0, -5, -2, 7, 3, -3 }).ShouldBeEquivalentTo(new Tuple<int, int>(3,5));
MaxSubarray.FindMaximumSubarray(new[] { -1, -5, -2, -7, -3, 0 }).ShouldBeEquivalentTo(new Tuple<int, int>(5, 6));
MaxSubarray.FindMaximumSubarray(new[] { 0, -1, -5, -2, -7, -3 }).ShouldBeEquivalentTo(new Tuple<int, int>(6, 6));
}
}
}
|
using Unity.Entities;
using Unity.Mathematics;
public struct OverlappingMovementPickup : IComponentData { }
public struct Dash : IComponentData
{
public float Timer;
public bool Active;
public float3 PlayerVelocityBeforeDash;
}
public struct OverlappingRocketPickup : IComponentData { }
public struct Rocket : IComponentData
{
public Entity AttachmentEntity;
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BudgetApp.Domain.Abstract;
using BudgetApp.Domain.Concrete;
using BudgetApp.Domain.Entities;
using BudgetApp.Domain.DAL;
namespace BudgetApp.Domain.Concrete
{
public class EFPaymentPlanEntries : IPaymentPlanEntries
{
private LedgerDBContext context;
public EFPaymentPlanEntries(LedgerDBContext context)
{
this.context = context;
}
public IQueryable<PaymentPlanEntry> PaymentPlanEntries
{
get { return context.PaymentPlanEntries; }
}
public void Add(PaymentPlanEntry entry)
{
context.PaymentPlanEntries.Add(entry);
}
public void Modify(PaymentPlanEntry entry)
{
context.Entry(entry).State = System.Data.EntityState.Modified;
// Clean up, if necessary
if (entry.Charges.Count < 1)
Delete(entry);
}
public void Delete(PaymentPlanEntry entry)
{
context.PaymentPlanEntries.Remove(entry);
}
}
}
|
using AppExercise.Core.ViewModels;
using AppExercise.iOS.Theme;
using Cirrious.FluentLayouts.Touch;
using Foundation;
using MvvmCross.Platforms.Ios.Presenters.Attributes;
using MvvmCross.Platforms.Ios.Views;
using UIKit;
namespace AppExercise.iOS.Views
{
[Register(nameof(UsersView))]
[MvxRootPresentation(WrapInNavigationController = true)]
public class UsersView : MvxViewController<UserListViewModel>
{
public override void ViewDidLoad()
{
View.BackgroundColor = UIColor.White;
View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints();
NavigationController.NavigationBar.BarTintColor = Colors.StrongBlue;
NavigationItem.TitleView = new UILabel
{
Text = "Exercise",
TextColor = UIColor.White,
Font = UIFont.BoldSystemFontOfSize(17)
};
var HeaderView = new UIView
{
TranslatesAutoresizingMaskIntoConstraints = false,
};
var LabelTitle = new UILabel()
{
Text = "Exercise",
TextAlignment = UITextAlignment.Center,
TextColor = UIColor.White,
AdjustsFontSizeToFitWidth = true,
TranslatesAutoresizingMaskIntoConstraints = false
};
}
}
}
|
using UnityEngine;
using System.Collections;
using UnityStandardAssets.Characters.FirstPerson;
public class LightRefillBehavior : MonoBehaviour {
[SerializeField] float oscSpeed;
[SerializeField] float oscAmplitude;
[SerializeField] float distStartMoveToPlayer;
[SerializeField] float moveSpeed;
[SerializeField] bool debugMode;
private float step; // used to step through angles for sin wave functions
private Vector3 startPosition;
private GameObject player = null;
private bool moveToTarget;
// Use this for initialization
void Start () {
startPosition = gameObject.transform.position;
moveToTarget = false;
}
// Update is called once per frame
void Update () {
if (player == null) {
player = GameObject.FindGameObjectWithTag("player");
return;
}
if (!moveToTarget && Vector3.Distance (transform.position, player.transform.position) < distStartMoveToPlayer)
moveToTarget = true;
else
moveToTarget = false;
if (moveToTarget) {
float move = moveSpeed * Time.deltaTime;
Vector3 movePos = Vector3.MoveTowards(transform.position, player.transform.position, move);
transform.position = movePos;
}
Transform t = gameObject.GetComponent<Transform>(); // set this object's transform to 't' for easier coding
Vector3 newPos = new Vector3(t.position.x, t.position.y, t.position.z);
step += oscSpeed * Time.deltaTime;
if (step > 2 * Mathf.PI) step -= 2 * Mathf.PI; // since Mathf is in radians, once step completes a full circle, reset it smoothly
newPos.y = startPosition.y + oscAmplitude * Mathf.Sin(step);
t.position = newPos;
}
void OnTriggerEnter(Collider col) {
if (col.gameObject.tag == "player") {
PlayerLight pLight = player.GetComponent<PlayerLight>();
pLight.lightLeft = pLight.maxLight;
col.GetComponent<FirstPersonController>().ShrinkGunFunction();
if(debugMode) Debug.Log("player light replenished!");
Destroy(gameObject);
}
}
}
|
using Cdiscount.Alm.Sonar.Api.Wrapper.Business;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.Issues.Filters;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.Issues;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.Languages;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.Rules;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.QualityProfiles;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.QualityGates;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.Projects;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.Plugins;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.Users;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.Users.Groups;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.Permissions;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.Metrics;
using Cdiscount.Alm.Sonar.Api.Wrapper.Business.Measures;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.FileExtensions;
using Microsoft.Extensions.Configuration.Json;
using System.Collections.Specialized;
namespace Cdiscount.Alm.Sonar.Api.Wrapper
{
/// <summary>
/// Simple client for calling the Sonar API.
/// note: a cool site to generate json classes: http://json2csharp.com/
/// </summary>
public class SonarApiClient
{
#region attributes
private string _baseAddress;
// used for paged searches
private Issues _issues;
private Business.System.System _system;
private Filters _filters;
private Languages _languages;
private Rules _rules;
private QualityProfiles _qualityProfiles;
private QualityGates _qualityGates;
private Projects _projects;
private Plugins _plugins;
private Users _users;
private UserGroups _userGroups;
private Permissions _permissions;
private Metrics _metrics;
private Measures _measures;
#endregion attributes
#region Constructors
/// <summary>
/// Sonar Api client constructor. One instance per Sonar server address.
/// </summary>
/// <param name="baseAddress">The Uri of the server Sonar API</param>
private void AffectURI(Uri baseAddress)
{
_baseAddress = baseAddress.AbsoluteUri;
_issues = BaseObjectApi<Issues>.CreateObject(this);
_system = BaseObjectApi<Business.System.System>.CreateObject(this);
_filters = BaseObjectApi<Filters>.CreateObject(this);
_languages = BaseObjectApi<Languages>.CreateObject(this);
_rules = BaseObjectApi<Rules>.CreateObject(this);
_qualityProfiles = BaseObjectApi<QualityProfiles>.CreateObject(this);
_qualityGates = BaseObjectApi<QualityGates>.CreateObject(this);
_projects = BaseObjectApi<Projects>.CreateObject(this);
_plugins = BaseObjectApi<Plugins>.CreateObject(this);
_users = BaseObjectApi<Users>.CreateObject(this);
_userGroups = BaseObjectApi<UserGroups>.CreateObject(this);
_permissions = BaseObjectApi<Permissions>.CreateObject(this);
_metrics = BaseObjectApi<Metrics>.CreateObject(this);
_measures = BaseObjectApi<Measures>.CreateObject(this);
}
/// <summary>
/// Sonar Api client constructors. One instance per Sonar server address.
/// </summary>
///
public SonarApiClient(IConfigurationRoot configuration)
{
AffectURI(new Uri(configuration["SonarApiUri"]));
}
public SonarApiClient(NameValueCollection configuration)
{
AffectURI(new Uri(configuration["SonarApiUri"]));
}
public SonarApiClient(Uri baseAddress)
{
AffectURI(baseAddress);
}
#endregion Constructors
#region Properties
public string BaseAddress
{
get { return _baseAddress; }
}
/// <summary>
/// Manage the issues
/// </summary>
public Issues Issues
{
get { return _issues; }
}
public Business.System.System System
{
get { return _system; }
}
/// <summary>
/// Manage issue filters
/// </summary>
public Filters Filters
{
get { return _filters; }
}
/// <summary>
/// Manage programming languages
/// </summary>
public Languages Languages
{
get { return _languages; }
}
/// <summary>
/// Manage sonar rules
/// </summary>
public Rules Rules
{
get { return _rules; }
}
/// <summary>
/// Manage quality profiles
/// </summary>
public QualityProfiles QualityProfiles
{
get { return _qualityProfiles; }
}
/// <summary>
/// Manage quality gates, including conditions and project association
/// </summary>
public QualityGates QualityGates
{
get { return _qualityGates; }
}
/// <summary>
/// Manage projects
/// </summary>
public Projects Projects
{
get { return _projects; }
}
/// <summary>
/// Manage the plugins on the server
/// </summary>
public Plugins Plugins
{
get { return _plugins; }
}
/// <summary>
/// Manage users
/// </summary>
public Users Users
{
get { return _users; }
}
/// <summary>
/// Manage user groups
/// </summary>
public UserGroups UserGroups
{
get { return _userGroups; }
}
/// <summary>
/// Manage permissions
/// </summary>
public Permissions Permissions
{
get { return _permissions; }
}
/// <summary>
/// Manage metrics
/// </summary>
public Metrics Metrics
{
get { return _metrics; }
}
public Measures Measures
{
get { return _measures; }
}
#endregion Properties
#region Methods
#region Synchronous methods
/// <summary>
/// Generic SonarQube API call for getting a list of objects
/// </summary>
/// <typeparam name="T">Typically a class returned by Sonar (cf Sonar classes)</typeparam>
/// <param name="queryUrl">
/// A full query URL (should work in a browser), must target Json, must be compatible with
/// the wanted type T
/// </param>
/// <returns>A list of deserialized T from resulting returned by Sonar</returns>
public static List<T> QueryList<T>(string queryUrl, IConfigurationRoot configuration)
{
using (HttpClient client = GetWebClient(configuration))
{
string json = null;
CallWebApi( () => json = client.GetStringAsync(queryUrl).Result);
var list = JsonConvert.DeserializeObject<List<T>>(json ?? "[]");
return list;
}
}
public static List<T> QueryList<T>(string queryUrl, NameValueCollection configuration)
{
using (HttpClient client = GetWebClient(configuration))
{
string json = null;
CallWebApi(() => json = client.GetStringAsync(queryUrl).Result);
var list = JsonConvert.DeserializeObject<List<T>>(json ?? "[]");
return list;
}
}
/// <summary>
/// Generic SonarQube API call for getting a single object
/// </summary>
/// <typeparam name="T">The class to materialize from the data returned by SonarQube</typeparam>
/// <param name="queryUrl">The full SonarQube query url</param>
/// <returns>An instance of T</returns>
public static T QueryObject<T>(string queryUrl, IConfigurationRoot configuration)
{
using (HttpClient client = GetWebClient(configuration))
{
string json = null;
CallWebApi( () => json = client.GetStringAsync(queryUrl).Result);
T obj = JsonConvert.DeserializeObject<T>(json);
return obj;
}
}
public static T QueryObject<T>(string queryUrl, NameValueCollection configuration)
{
using (HttpClient client = GetWebClient(configuration))
{
string json = null;
CallWebApi(() => json = client.GetStringAsync(queryUrl).Result);
T obj = JsonConvert.DeserializeObject<T>(json);
return obj;
}
}
/// <summary>
/// Method POST data to queryUrl
/// </summary>
/// <param name="queryUrl">The full SonarQube query url where data is post</param>
/// <param name="data">the data to post</param>
public static void Post(string queryUrl, string data, IConfigurationRoot configuration)
{
using (HttpClient client = GetWebClient(configuration))
{
HttpContent content = new StringContent(data);
CallWebApi(() => client.PostAsync(queryUrl, content));
}
}
public static void Post(string queryUrl, string data, NameValueCollection configuration)
{
using (HttpClient client = GetWebClient(configuration))
{
HttpContent content = new StringContent(data);
CallWebApi(() => client.PostAsync(queryUrl, content));
}
}
/// <summary>
/// Method DELETE data to queryUrl
/// </summary>
/// <param name="queryUrl">The full SonarQube query url where data is removed</param>
/// <param name="data">data to removed</param>
/// <returns></returns>
//public static bool Delete(string queryUrl, string data, IConfigurationRoot configuration)
//{
// using (HttpClient client = GetWebClient(configuration))
// {
// HttpContent content = new StringContent(data);
// var result = CallWebApi(() => client.UploadString(queryUrl, "DELETE", data), false);
// return string.IsNullOrEmpty(result);
// }
//}
/// <summary>
/// Calls the web API.
/// </summary>
/// <param name="a">a.</param>
/// <param name="rethrow">if set to <c>true</c> [rethrow].</param>
/// <returns></returns>
/// <exception cref="System.ApplicationException"></exception>
private static string CallWebApi(Action a, bool rethrow = true)
{
string result = null;
try
{
a();
}
catch (WebException ex)
{
if (ex.Response != null)
{
StreamReader reader = new StreamReader(ex.Response.GetResponseStream());
result = reader.ReadToEnd();
if (rethrow)
{
throw new WebException(string.Format("Sonar API error: {0}", result), ex);
}
}
else
{
throw;
}
}
return result;
}
#endregion Synchronous methods
#region Asynchronous methods
/// <summary>
/// Method POST data to queryUrl asynchronously
/// </summary>
/// <param name="queryUrl">The full SonarQube query url where data is post</param>
/// <param name="content">the data to post</param>
/*public async static Task PostAsync(string queryUrl, string data, IConfigurationRoot configuration)
{
using (HttpClient client = GetWebClient(configuration))
{
HttpContent content = new StringContent(data);
await CallWebApiAsync(() => Task.Factory.StartNew(() => client.PostAsync(queryUrl, content)))
.ConfigureAwait(false);
}
}*/
/// <summary>
/// Method DELETE data to queryUrl asynchronously
/// </summary>
/// <param name="queryUrl">The full SonarQube query url where data is removed</param>
/// <param name="data">data to removed</param>
/// <returns></returns>
/*public async static Task<bool> DeleteAsync(string queryUrl, string data)
{
using (var client = new HttpClient())
{
var result = await CallWebApiAsync(() => Task.Factory.StartNew(() => client.UploadString(queryUrl, "DELETE", data)), false)
.ConfigureAwait(false);
return string.IsNullOrEmpty(result);
}
}*/
/// <summary>
/// Generic SonarQube API call for getting a list of objects asynchronously
/// </summary>
/// <typeparam name="T">Typically a class returned by Sonar (cf Sonar classes)</typeparam>
/// <param name="queryUrl">
/// A full query URL (should work in a browser), must target Json, must be compatible with
/// the wanted type T
/// </param>
/// <returns>A list of deserialized T from resulting returned by Sonar</returns>
public async static Task<List<T>> QueryListAsync<T>(string queryUrl, IConfigurationRoot configuration)
{
using (HttpClient client = GetWebClient(configuration))
{
string json = null;
await CallWebApiAsync(async () => await await Task.Factory.StartNew(async () => json = await client.GetStringAsync(queryUrl)))
.ConfigureAwait(false);
var list = JsonConvert.DeserializeObject<List<T>>(json ?? "[]");
return list;
}
}
public async static Task<List<T>> QueryListAsync<T>(string queryUrl, NameValueCollection configuration)
{
using (HttpClient client = GetWebClient(configuration))
{
string json = null;
await CallWebApiAsync(async () => await await Task.Factory.StartNew(async () => json = await client.GetStringAsync(queryUrl)))
.ConfigureAwait(false);
var list = JsonConvert.DeserializeObject<List<T>>(json ?? "[]");
return list;
}
}
/// <summary>
/// Generic SonarQube API call for getting a single object asynchronously
/// </summary>
/// <typeparam name="T">The class to materialize from the data returned by SonarQube</typeparam>
/// <param name="queryUrl">The full SonarQube query url</param>
/// <returns>An instance of T</returns>
public async static Task<T> QueryObjectAsync<T>(string queryUrl, IConfigurationRoot configuration)
{
using (HttpClient client = GetWebClient(configuration))
{
string json = null;
await CallWebApiAsync(async () => await await Task.Factory.StartNew(async () => json = await client.GetStringAsync(queryUrl)))
.ConfigureAwait(false);
T obj = JsonConvert.DeserializeObject<T>(json);
return obj;
}
}
public async static Task<T> QueryObjectAsync<T>(string queryUrl, NameValueCollection configuration)
{
using (HttpClient client = GetWebClient(configuration))
{
string json = null;
await CallWebApiAsync(async () => await await Task.Factory.StartNew(async () => json = await client.GetStringAsync(queryUrl)))
.ConfigureAwait(false);
T obj = JsonConvert.DeserializeObject<T>(json);
return obj;
}
}
/// <summary>
/// Calls the web API asynchronous.
/// </summary>
/// <param name="a">a.</param>
/// <param name="rethrow">if set to <c>true</c> [rethrow].</param>
/// <returns></returns>
/// <exception cref="System.ApplicationException"></exception>
private static async Task<string> CallWebApiAsync(Func<Task<string>> a, bool rethrow = true)
{
string result = null;
try
{
await a().ConfigureAwait(false);
}
catch (WebException ex)
{
if (ex.Response != null)
{
StreamReader reader = new StreamReader(ex.Response.GetResponseStream());
result = reader.ReadToEnd();
if (rethrow)
{
throw new WebException(string.Format("Sonar API error: {0}", result), ex);
}
}
else
{
throw;
}
}
return await Task.Factory.StartNew(() => result).ConfigureAwait(false);
}
#endregion Asynchronous methods
/// <summary>
/// Gets the web client.
/// </summary>
/// <param name="timeOut">The time out.</param>
/// <returns></returns>
/// <exception cref="System.ApplicationException">
/// SonarApiLogin not found in app.config !
/// or
/// SonarApiPassword not found in app.config !
/// </exception>
private static HttpClient GetWebClient(IConfigurationRoot configuration, int timeOut = 0)
{
HttpClient client = (timeOut == 0) ? new HttpClient() : new CustomTimeOutWebClient(timeOut);
//IConfigurationRoot configuration = GetConfig();
string token = configuration["SonarApiToken"];
if (string.IsNullOrEmpty(token))
{
string login = configuration["SonarApiLogin"];
string password = configuration["SonarApiPassword"];
if (String.IsNullOrEmpty(login))
{
throw new ArgumentNullException("SonarApiLogin not found in app.config !");
}
if (String.IsNullOrEmpty(password))
{
throw new ArgumentNullException("SonarApiPassword not found in app.config !");
}
var bytes = Encoding.UTF8.GetBytes(login + ":" + password);
client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
}
else
{
var bytes = Encoding.UTF8.GetBytes(token + ":");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
}
return client;
}
private static HttpClient GetWebClient(NameValueCollection configuration, int timeOut = 0)
{
HttpClient client = (timeOut == 0) ? new HttpClient() : new CustomTimeOutWebClient(timeOut);
//IConfigurationRoot configuration = GetConfig();
string token = configuration["SonarApiToken"];
if (string.IsNullOrEmpty(token))
{
string login = configuration["SonarApiLogin"];
string password = configuration["SonarApiPassword"];
if (String.IsNullOrEmpty(login))
{
throw new ArgumentNullException("SonarApiLogin not found in app.config !");
}
if (String.IsNullOrEmpty(password))
{
throw new ArgumentNullException("SonarApiPassword not found in app.config !");
}
var bytes = Encoding.UTF8.GetBytes(login + ":" + password);
client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
}
else
{
var bytes = Encoding.UTF8.GetBytes(token + ":");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(bytes));
}
return client;
}
#endregion Methods
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria;
using Terraria.ModLoader;
namespace StarlightRiver.Keys
{
class OvergrowKey : Key
{
public OvergrowKey() : base("Overgrowth Key", "StarlightRiver/Keys/OvergrowKey") { }
public override bool ShowCondition => Main.LocalPlayer.GetModPlayer<BiomeHandler>().ZoneOvergrow;
public override void PreDraw(SpriteBatch spriteBatch)
{
spriteBatch.End();
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.Additive);
Texture2D tex = ModContent.GetTexture("StarlightRiver/Keys/Glow");
spriteBatch.Draw(tex, Position + Vector2.One * 16 - Main.screenPosition, tex.Frame(), new Color(255, 255, 200) * 0.3f, LegendWorld.rottime, tex.Frame().Size() / 2, 1 + (float)Math.Cos(LegendWorld.rottime) * 0.25f, 0, 0 );
spriteBatch.Draw(tex, Position + Vector2.One * 16 - Main.screenPosition, tex.Frame(), new Color(255, 255, 200) * 0.5f, LegendWorld.rottime, tex.Frame().Size() / 2, 0.7f + (float)Math.Cos(LegendWorld.rottime + 0.5f) * 0.15f, 0, 0);
spriteBatch.Draw(tex, Position + Vector2.One * 16 - Main.screenPosition, tex.Frame(), new Color(255, 255, 200) * 0.7f, LegendWorld.rottime, tex.Frame().Size() / 2, 0.5f + (float)Math.Cos(LegendWorld.rottime + 1) * 0.1f, 0, 0);
spriteBatch.End();
spriteBatch.Begin();
}
public override void PreUpdate()
{
if(Main.rand.Next(4) == 0)
Dust.NewDust(Position + new Vector2(0, (float)Math.Sin(LegendWorld.rottime) * 5), 32, 32, ModContent.DustType<Dusts.Gold2>(), 0, 0, 0, default, 0.5f);
Lighting.AddLight(Position, new Vector3(1, 1, 0.8f) * 0.6f);
}
public override void OnPickup()
{
CombatText.NewText(Hitbox, Color.White, "Got: Overgrowth Key");
}
}
}
|
using System;
using NLog.Web;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace MediaLibrary
{
class Program
{
// creates static instance of logger
private static NLog.Logger logger = NLogBuilder.ConfigureNLog(Directory.GetCurrentDirectory() + "\\nlog.config").GetCurrentClassLogger();
static void Main(string[] args)
{
logger.Info("Program started");
// sets file path for scrubbed file
string movieFilePath = "movies.scrubbed.csv";
// creates movie file instance
MovieFile movieFile = new MovieFile(movieFilePath);
string choice = "";
do {
// 1 adds movie, 2 displays movie, entering nothing exits program
Console.WriteLine("1) Add movie");
Console.WriteLine("2) Display all movies");
Console.WriteLine("3) Find movie");
Console.WriteLine("Enter to quit");
// takes user input
choice = Console.ReadLine();
// logs users choice
logger.Info("User choice: {choice}", choice);
if(choice == "1"){
// creates Movie object
Movie movie = new Movie();
// asks for title
Console.WriteLine("Enter movie title");
// stores what user entered into movie.title
movie.title = Console.ReadLine();
string input;
do {
// asks for genres or enter done to quit
Console.WriteLine("Enter genre (or done to quit)");
// stores what user entered into variable
input = Console.ReadLine();
// if not done and the user entered something, add it to genre list
if(input != "done" && input.Length > 0)
{
movie.genres.Add(input);
}
// if user didnt enter done, but left it blank, stores no genres listed into list
} while (input != "done");
if (movie.genres.Count == 0){
movie.genres.Add("no genres listed");
}
// asks for directors name
Console.WriteLine("Enter Directors name");
// stores it into movie.director
movie.director = Console.ReadLine();
// asks for running time of movie
Console.WriteLine("Enter running time (h:m:s)");
// parses it into timespan
movie.runningTime = TimeSpan.Parse(Console.ReadLine());
// adds it to the movie file
movieFile.AddMovie(movie);
} else if (choice == "2"){
// foreach loop displays each movie in file
foreach(Movie m in movieFile.Movies){
// calls display method
Console.WriteLine(m.Display());
}
}
else if(choice == "3"){
Console.WriteLine("Enter name of movie or year of movie to search for");
string search = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.Green;
var movieSearch = movieFile.Movies.Where(m => m.title.Contains(search, StringComparison.OrdinalIgnoreCase)).Select(m => m.title);
foreach(string m in movieSearch){
Console.WriteLine($" {m}");
}
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"There are {movieSearch.Count()} movies with {search} in the title: ");
Console.ForegroundColor = ConsoleColor.White;
}
// condition for menu
} while (choice == "1" || choice == "2" || choice == "3");
// {
// mediaId = 123,
// title = "Greatest Movie Ever, The (2020)",
// director = "Jeff Grissom",
// // timespan (hours, minutes, seconds)
// runningTime = new TimeSpan(2, 21, 23),
// genres = { "Comedy", "Romance" }
// };
// Console.WriteLine(movie.Display());
// Album album = new Album
// {
// mediaId = 321,
// title = "Greatest Album Ever, The (2020)",
// artist = "Jeff's Awesome Band",
// recordLabel = "Universal Music Group",
// genres = { "Rock" }
// };
// Console.WriteLine(album.Display());
// Book book = new Book
// {
// mediaId = 111,
// title = "Super Cool Book",
// author = "Jeff Grissom",
// pageCount = 101,
// publisher = "",
// genres = { "Suspense", "Mystery" }
// };
// Console.WriteLine(book.Display());
string scrubbedFile = FileScrubber.ScrubMovies("movies.csv");
logger.Info(scrubbedFile);
logger.Info("Program ended");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gMediaTools.Models.ProcessRunner
{
public class NoNameProcessRunnerParameter : IProcessRunnerParameter
{
public string Name { get; }
public string Value { get; set; }
public string NamePrefix { get; }
public string NameValueSeparator { get; }
public bool ValueNeedsToBeQuoted { get; }
public bool AllowsEmptyValues { get; } = false;
public bool ValueOnlyOutput { get; } = true;
public bool Include { get; set; } = false;
public Func<string, string> ProcessValue { get; set; }
public NoNameProcessRunnerParameter(string name, bool valueNeedsToBeQuoted, Func<string, string> processValue = null)
{
Name = name ?? throw new ArgumentNullException(nameof(name));
ValueNeedsToBeQuoted = valueNeedsToBeQuoted;
ProcessValue = processValue ?? new Func<string, string>((string value) => { return value; });
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneTransition : MonoBehaviour
{
[SerializeField] private string transitionTarget; //遷移先シーンを指定
public void Transition ()
{
SceneManager.LoadScene (transitionTarget); //指定したシーンに遷移
Resources.UnloadUnusedAssets ();
System.GC.Collect ();
}
} |
#region MIT License
/*
* Copyright (c) 2009 University of Jyväskylä, Department of Mathematical
* Information Technology.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
/*
* Original Authors: Tero Jäntti, Tomi Karppinen, Janne Nikkanen.
* Modified for Farseer engine by Mikko Röyskö
*/
namespace Jypeli
{
public partial class PhysicsBody
{
//internal static readonly Coefficients DefaultCoefficients = new Coefficients( 0.5, 0.4, 0.4 );
/// <summary>
/// Lepokitka. Liikkeen alkamista vastustava voima, joka ilmenee kun olio yrittää lähteä liikkeelle
/// toisen olion pinnalta (esim. laatikkoa yritetään työntää eteenpäin).
/// </summary>
public double StaticFriction
{
get { return FSBody.FixtureList[0].Friction; }
set { FSBody.SetFriction((float)value); }
}
// TODO: Liike/lepokitka
/// <summary>
/// Liikekitka. Liikettä vastustava voima joka ilmenee kun kaksi oliota liikkuu toisiaan vasten
/// (esim. laatikko liukuu maata pitkin). Arvot välillä 0.0 (ei kitkaa) ja 1.0 (täysi kitka).
/// </summary>
public double KineticFriction
{
get { return FSBody.FixtureList[0].Friction; }
set { FSBody.SetFriction((float)value); }
}
/// <summary>
/// Olion kimmoisuus. Arvo välillä 0.0-1.0.
/// Arvolla 1.0 olio säilyttää kaiken vauhtinsa törmäyksessä. Mitä pienempi arvo,
/// sitä enemmän olion vauhti hidastuu törmäyksessä.
/// </summary>
public double Restitution
{
get { return FSBody.FixtureList[0].Restitution; }
set { FSBody.SetRestitution((float)value); }
}
}
}
|
using System;
namespace AppStore.Application.Services.Exceptions
{
public class InvalidResourceOperationException : Exception
{
public InvalidResourceOperationException(string message)
: base(message)
{ }
public InvalidResourceOperationException()
: base("It was not possible to complete the request.")
{ }
}
}
|
using System;
using System.Diagnostics;
using Jypeli.Rendering;
using Matrix = System.Numerics.Matrix4x4;
using Vector3 = System.Numerics.Vector3;
namespace Jypeli
{
internal class LineBatch
{
VertexPositionColorTexture[] vertexBuffer;
IShader shader;
Matrix matrix;
int iVertexBuffer = 0;
bool beginHasBeenCalled = false;
public bool LightingEnabled = true;
internal void Initialize()
{
int vertexBufferSize = Game.GraphicsDevice.BufferSize;
vertexBuffer = new VertexPositionColorTexture[vertexBufferSize];
shader = Graphics.BasicColorShader;
}
public void Begin(ref Matrix matrix)
{
Debug.Assert(!beginHasBeenCalled);
beginHasBeenCalled = true;
this.matrix = matrix;
iVertexBuffer = 0;
}
public void End()
{
Debug.Assert(beginHasBeenCalled);
Flush();
beginHasBeenCalled = false;
}
private void Flush()
{
if (iVertexBuffer > 0)
{
shader.Use();
shader.SetUniform("world", matrix * Graphics.ViewProjectionMatrix);
Game.GraphicsDevice.DrawPrimitives(PrimitiveType.OpenGLLines, vertexBuffer, (uint)iVertexBuffer);
}
iVertexBuffer = 0;
}
public void Draw(Vector startPoint, Vector endPoint, Color color)
{
if ((iVertexBuffer + 2) > vertexBuffer.Length)
{
Flush();
}
vertexBuffer[iVertexBuffer++] = new VertexPositionColorTexture(new Vector3((float)startPoint.X, (float)startPoint.Y, 0f), color, Vector.Zero);
vertexBuffer[iVertexBuffer++] = new VertexPositionColorTexture(new Vector3((float)endPoint.X, (float)endPoint.Y, 0f), color, Vector.Zero);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SwitchSprite : MonoBehaviour {
public SpriteRenderer spriteRenderer;
public Sprite[] spritesArrayCloseFront;
public Sprite[] spritesArrayOpenFront;
public Sprite[] spritesArrayCloseLeft;
public Sprite[] spritesArrayOpenLeft;
public DoorTile doorTile;
bool lastState;
public float dirID;
public TilePoint tilePoint;
void Start() {
tilePoint = GetComponentInParent<TilePoint>();
dirID = tilePoint.tileID.x;
if (dirID >= 1 && dirID <= 3) { spriteRenderer.sprite = spritesArrayCloseLeft[doorTile.doorType]; }
if (dirID >= 4 && dirID <= 5) { spriteRenderer.sprite = spritesArrayCloseFront[doorTile.doorType]; transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z); }
if (dirID >= 6 && dirID <= 8) { spriteRenderer.sprite = spritesArrayCloseFront[doorTile.doorType]; }
if (dirID >= 9 && dirID <= 11) { spriteRenderer.sprite = spritesArrayCloseLeft[doorTile.doorType]; transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z); }
}
private void Update() {
if (lastState != doorTile.isOpen) {
if (doorTile.isOpen)
if (dirID >= 1 && dirID <= 3) { spriteRenderer.sprite = spritesArrayCloseLeft[doorTile.doorType]; }
if (dirID >= 4 && dirID <= 5) { spriteRenderer.sprite = spritesArrayCloseFront[doorTile.doorType]; }
if (dirID >= 6 && dirID <= 8) { spriteRenderer.sprite = spritesArrayCloseFront[doorTile.doorType]; }
if (dirID >= 9 && dirID <= 11) { spriteRenderer.sprite = spritesArrayCloseLeft[doorTile.doorType]; }
else
if (doorTile.wasOpen)
if (dirID >= 1 && dirID <= 3) { spriteRenderer.sprite = spritesArrayCloseLeft[doorTile.doorType]; }
if (dirID >= 4 && dirID <= 5) { spriteRenderer.sprite = spritesArrayCloseFront[doorTile.doorType]; }
if (dirID >= 6 && dirID <= 8) { spriteRenderer.sprite = spritesArrayCloseFront[doorTile.doorType]; }
if (dirID >= 9 && dirID <= 11) { spriteRenderer.sprite = spritesArrayCloseLeft[doorTile.doorType]; }
else
if (dirID >= 1 && dirID <= 3) { spriteRenderer.sprite = spritesArrayOpenLeft[doorTile.doorType]; }
if (dirID >= 4 && dirID <= 5) { spriteRenderer.sprite = spritesArrayOpenFront[doorTile.doorType]; }
if (dirID >= 6 && dirID <= 8) { spriteRenderer.sprite = spritesArrayOpenFront[doorTile.doorType]; }
if (dirID >= 9 && dirID <= 11) { spriteRenderer.sprite = spritesArrayOpenLeft[doorTile.doorType]; }
lastState = doorTile.isOpen;
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BaseContainer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void 파일NToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void 창ToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void 새창NToolStripMenuItem_Click(object sender, EventArgs e)
{
BaseGame theGame = new BaseGame();
theGame.MdiParent = this;
theGame.Show();
}
private void 계단식배열ToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.Cascade);
}
private void 가로배열ToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.TileHorizontal);
}
private void 세로배열ToolStripMenuItem_Click(object sender, EventArgs e)
{
LayoutMdi(MdiLayout.TileVertical);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace kindergarden.Models
{
public class gallery
{
public int Id { get; set; }
public string name { get; set; }
public int SchoolId { get; set; }
public virtual School School { get; set; }
public List<galleryImage> images { get; set; }
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.